use std::fmt::Write as _;
use super::from_docx::Element;
use super::xml::{FormatMark, StyleChangeKind, escape};
pub(super) fn with_style_changes(
styles: &str,
changes: &[(String, Vec<(StyleChangeKind, FormatMark)>)],
) -> String {
let mut out = styles.to_string();
for (holder, marks) in changes {
if holder == "docDefaults" {
continue;
}
let paragraph = marks
.iter()
.find(|(kind, _)| *kind == StyleChangeKind::Paragraph)
.map(|(_, mark)| mark);
let run = marks
.iter()
.find(|(kind, _)| *kind == StyleChangeKind::Run)
.map(|(_, mark)| mark);
if paragraph.is_none() && run.is_none() {
continue;
}
let key = format!("w:styleId=\"{}\"", escape(holder));
let Some(at) = out.find(&key) else {
continue;
};
let Some(end) = out[at..].find("</w:style>").map(|i| at + i) else {
continue;
};
let mut block = out[at..end].to_string();
if let Some(mark) = paragraph {
place(&mut block, "pPr", &carrier(mark, "pPr"));
}
if let Some(mark) = run {
place(&mut block, "rPr", &carrier(mark, "rPr"));
}
out.replace_range(at..end, &block);
}
out
}
pub(super) fn style_change_warnings(
changes: &[(String, Vec<(StyleChangeKind, FormatMark)>)],
legacy: &[(String, Vec<String>)],
) -> Vec<String> {
let mut out = Vec::new();
for (holder, tags) in legacy {
if tags.is_empty() || holder == "docDefaults" {
continue;
}
let verb = if tags.len() == 1 { "has" } else { "have" };
out.push(format!(
"style_changes: {holder}: {} {verb} no kind; written as rPr",
tags.join("; ")
));
}
for (holder, marks) in changes {
if holder == "docDefaults" {
let count = marks.len();
if count == 1 {
out.push(
"style_changes: docDefaults: the document defaults have no change slot; 1 change is not written"
.to_string(),
);
} else if count > 1 {
out.push(format!(
"style_changes: docDefaults: the document defaults have no change slot; {count} changes are not written"
));
}
continue;
}
let paragraph = marks
.iter()
.filter(|(kind, _)| *kind == StyleChangeKind::Paragraph)
.count();
let run = marks
.iter()
.filter(|(kind, _)| *kind == StyleChangeKind::Run)
.count();
let other = marks
.iter()
.filter(|(kind, _)| *kind == StyleChangeKind::Other)
.count();
if paragraph > 1 {
out.push(format!(
"style_changes: {holder}: {paragraph} pPr changes for one slot; the rest are not written"
));
}
if run > 1 {
out.push(format!(
"style_changes: {holder}: {run} rPr changes for one slot; the rest are not written"
));
}
if other == 1 {
out.push(format!(
"style_changes: {holder}: 1 other change is not written"
));
} else if other > 1 {
out.push(format!(
"style_changes: {holder}: {other} other changes are not written"
));
}
}
out
}
fn carrier(mark: &FormatMark, inner: &str) -> String {
let date = super::xml::date_attribute(&mark.date);
let id = mark
.id
.map_or_else(String::new, |id| format!(" w:id=\"{id}\""));
format!(
"<w:{inner}Change{id} w:author=\"{}\"{date}><w:{inner}/></w:{inner}Change>",
escape(&mark.author)
)
}
fn place(block: &mut String, property: &str, change: &str) {
match if property == "pPr" {
own_ppr(block)
} else {
own_rpr(block)
} {
Some(own) if own.empty() => {
block.replace_range(
own.start..own.end,
&format!("<w:{property}>{change}</w:{property}>"),
);
}
Some(own) => {
if let Some(span) = direct_child_span(block, &own, &format!("{property}Change")) {
block.replace_range(span, change);
} else if let Some(close) = own.close {
block.insert_str(close, change);
}
}
None if property == "pPr" => {
let at = own_rpr(block).map_or(block.len(), |run| run.start);
block.insert_str(at, &format!("<w:pPr>{change}</w:pPr>"));
}
None => block.push_str(&format!("<w:rPr>{change}</w:rPr>")),
}
}
struct OpenTag {
start: usize,
end: usize,
empty: bool,
}
fn open_tag(xml: &str, name: &str, range: std::ops::Range<usize>) -> Option<OpenTag> {
let tag = format!("<w:{name}");
let mut from = range.start;
while let Some(at) = xml[from..range.end].find(&tag).map(|i| from + i) {
let after = at + tag.len();
if xml[after..].starts_with([' ', '>', '/', '\t', '\n', '\r']) {
let end = after + xml[after..].find('>')? + 1;
return Some(OpenTag {
start: at,
end,
empty: xml[..end - 1].ends_with('/'),
});
}
from = after;
}
None
}
struct Own {
start: usize,
end: usize,
close: Option<usize>,
}
impl Own {
fn empty(&self) -> bool {
self.close.is_none()
}
}
fn own(block: &str, name: &str, from: usize) -> Option<Own> {
let open = open_tag(block, name, from..block.len())?;
if open.empty {
return Some(Own {
start: open.start,
end: open.end,
close: None,
});
}
let close = close_at(block, name, open.end)?;
let tag = format!("</w:{name}>");
Some(Own {
start: open.start,
end: close + tag.len(),
close: Some(close),
})
}
fn close_at(block: &str, name: &str, open_end: usize) -> Option<usize> {
let tag = format!("</w:{name}>");
let mut depth = 1usize;
let mut at = open_end;
while let Some(close) = block[at..].find(&tag).map(|i| i + at) {
depth += usize::from(open_tag(block, name, at..close).is_some_and(|open| !open.empty));
depth = depth.checked_sub(1)?;
if depth == 0 {
return Some(close);
}
at = close + tag.len();
}
None
}
fn own_ppr(block: &str) -> Option<Own> {
own(block, "pPr", 0)
}
fn own_rpr(block: &str) -> Option<Own> {
own(block, "rPr", own_ppr(block).map_or(0, |ppr| ppr.end))
}
fn direct_child_span(block: &str, own: &Own, local: &str) -> Option<std::ops::Range<usize>> {
let open_end = own.start + block[own.start..].find('>')? + 1;
let close = own.close?;
let mut at = open_end;
while at < close {
let rest = &block[at..close];
let Some(rel) = rest.find('<') else {
break;
};
let start = at + rel;
if block.as_bytes().get(start + 1) == Some(&b'/') {
break;
}
let tag_end = start + block[start..close].find('>')?;
let raw = &block[start + 1..tag_end];
let empty = raw.ends_with('/');
let token = raw.trim_end_matches('/').split_whitespace().next()?;
let name = token.rsplit(':').next().unwrap_or(token);
let element_end = if empty {
tag_end + 1
} else {
let close_at = close_at(block, name, tag_end + 1)?;
close_at + format!("</w:{name}>").len()
};
if name == local {
return Some(start..element_end);
}
at = element_end;
}
None
}
#[derive(Clone, Debug, PartialEq)]
#[doc(hidden)]
pub struct StyleSpec {
pub id: String,
pub name: Option<String>,
pub character: bool,
pub heading: Option<u32>,
pub default: bool,
pub font: String,
pub bold: bool,
pub italic: bool,
pub size: u32,
pub before: Option<u32>,
pub after: Option<u32>,
pub line: Option<(u32, &'static str)>,
pub keep_next: bool,
pub keep_lines: bool,
pub left: Option<i64>,
pub right: Option<i64>,
pub first_line: Option<i64>,
pub hanging: Option<i64>,
pub contextual_spacing: bool,
pub align: Option<&'static str>,
}
const MOST_POINTS: f64 = 1638.0;
fn points(value: &str, scale: f64) -> Option<u32> {
let n: f64 = value.strip_suffix("pt")?.parse().ok()?;
(n.is_finite() && (0.0..=MOST_POINTS).contains(&n)).then(|| (n * scale).round() as u32)
}
pub(super) fn twips_in(value: &str) -> Option<i64> {
let n: f64 = value.strip_suffix("in")?.parse().ok()?;
if !n.is_finite() {
return None;
}
let twips = (n * 1440.0).round();
(twips.is_finite() && twips.abs() <= 31680.0).then_some(twips as i64)
}
fn font_clause(clause: &str) -> Option<(String, bool, bool, u32)> {
let (rest, size) = clause.rsplit_once(' ')?;
let size = points(size, 2.0)?;
let mut rest = rest;
let mut italic = false;
let mut bold = false;
if let Some(r) = rest.strip_suffix(" italic") {
italic = true;
rest = r;
}
if let Some(r) = rest.strip_suffix(" bold") {
bold = true;
rest = r;
}
(!rest.is_empty()).then(|| (rest.to_string(), bold, italic, size))
}
fn spec(id: &str, heading: Option<u32>, default: bool, value: &str) -> Option<StyleSpec> {
let (value, name) = match value.rsplit_once(", named ") {
Some((value, name)) => (value, Some(name.to_string())),
None => (value, None),
};
let mut clauses = value.split(", ").peekable();
let character = !default && clauses.next_if(|c| *c == "character").is_some();
let (font, bold, italic, size) = font_clause(clauses.next()?)?;
let mut spec = StyleSpec {
id: id.to_string(),
name,
character,
heading,
default,
font,
bold,
italic,
size,
before: None,
after: None,
line: None,
keep_next: false,
keep_lines: false,
left: None,
right: None,
first_line: None,
hanging: None,
contextual_spacing: false,
align: None,
};
for clause in clauses {
match clause.split_once(' ') {
Some(("before", v)) => spec.before = Some(points(v, 20.0)?),
Some(("after", v)) => spec.after = Some(points(v, 20.0)?),
Some(("indent", v)) => spec.left = Some(twips_in(v)?),
Some(("right", v)) => spec.right = Some(twips_in(v)?),
Some(("first-line", v)) => spec.first_line = Some(twips_in(v)?),
Some(("hanging", v)) => spec.hanging = Some(twips_in(v)?),
Some(("contextual", "spacing")) => spec.contextual_spacing = true,
Some(("line", v)) => {
spec.line = Some(match v.split_once(' ') {
Some((height, "exact")) => (points(height, 20.0)?, "exact"),
Some((height, "atLeast")) => (points(height, 20.0)?, "atLeast"),
Some(_) => return None,
None => {
let ratio: f64 = v.parse().ok()?;
if !(ratio.is_finite() && (0.0..=132.0).contains(&ratio)) {
return None;
}
((ratio * 240.0).round() as u32, "auto")
}
});
}
None if clause == "keep-next" => spec.keep_next = true,
None if clause == "keep-lines" => spec.keep_lines = true,
None => {
spec.align = Some(match clause {
"left" => "left",
"center" => "center",
"right" => "right",
"justify" => "both",
_ => return None,
});
}
Some(_) => return None,
}
}
Some(spec)
}
pub(super) fn without_comment(line: &str) -> &str {
let mut quoted = false;
let mut escaped = false;
let mut spaces = 0;
for (at, c) in line.char_indices() {
match c {
_ if escaped => escaped = false,
'\\' if quoted => escaped = true,
'"' => quoted = !quoted,
'#' if spaces >= 2 && !quoted => return &line[..at],
_ => {}
}
spaces = if c == ' ' { spaces + 1 } else { 0 };
}
line
}
fn unquote(value: &str) -> Option<String> {
if value.starts_with('"') {
serde_json::from_str(value).ok()
} else {
Some(value.to_string())
}
}
#[derive(Clone, Debug, PartialEq)]
#[doc(hidden)]
pub enum TableBorders {
All(u32),
Sides(Vec<BorderSide>),
}
#[derive(Clone, Debug, PartialEq)]
#[doc(hidden)]
pub struct BorderSide {
pub side: String,
pub val: String,
pub size: Option<u32>,
pub color: Option<String>,
pub space: Option<u32>,
}
pub(crate) const TABLE_BORDER_SIDES: [&str; 6] =
["top", "left", "bottom", "right", "insideH", "insideV"];
fn border_sides(clause: &str) -> Option<Vec<BorderSide>> {
let mut tokens = clause.strip_prefix("borders ")?.split(' ').peekable();
let mut sides: Vec<BorderSide> = Vec::new();
while let Some(side) = tokens.next() {
if !TABLE_BORDER_SIDES.contains(&side) || sides.iter().any(|s| s.side == side) {
return None;
}
let val = tokens
.next()
.filter(|v| !v.is_empty() && v.chars().all(|c| c.is_ascii_alphanumeric()))?;
let mut border = BorderSide {
side: side.to_string(),
val: val.to_string(),
size: None,
color: None,
space: None,
};
while let Some(&token) = tokens.peek() {
if TABLE_BORDER_SIDES.contains(&token) {
break;
}
tokens.next();
if let Some(pt) = token.strip_suffix("pt").filter(|_| border.size.is_none()) {
let pt = pt
.parse::<f64>()
.ok()
.filter(|pt| (0.0..=255.0).contains(pt))?;
border.size = Some((pt * 8.0).round() as u32);
} else if let Some(hex) = token.strip_prefix('#').filter(|_| border.color.is_none()) {
(hex.len() == 6 && hex.chars().all(|c| c.is_ascii_hexdigit())).then_some(())?;
border.color = Some(hex.to_string());
} else if token == "space" && border.space.is_none() {
let pt = tokens.next()?.strip_suffix("pt")?.parse::<u32>().ok()?;
border.space = Some(pt);
} else {
return None;
}
}
sides.push(border);
}
(!sides.is_empty()).then_some(sides)
}
pub(super) fn table_style(yaml: &str) -> Option<(String, Option<TableBorders>, Option<String>)> {
legend_line(yaml, "table: ")
.as_deref()
.and_then(table_style_entry)
.map(|(entry, _)| entry)
}
pub(super) fn table_legend(
yaml: &str,
) -> std::collections::BTreeMap<String, (Option<TableBorders>, Option<String>)> {
let mut out = std::collections::BTreeMap::new();
let Some(value) = legend_line(yaml, "tables: ") else {
return out;
};
let mut rest = value.as_str();
while let Some(((id, border, name), next)) = table_style_entry(rest) {
out.insert(id, (border, name));
rest = next;
}
out
}
fn legend_line(yaml: &str, key: &str) -> Option<String> {
let mut inside = false;
for line in yaml.lines() {
if !line.starts_with(' ') {
inside = line.trim_end() == "styles:";
continue;
}
if let Some(value) = without_comment(line)
.trim()
.strip_prefix(key)
.filter(|_| inside)
.and_then(|v| unquote(v.trim()))
{
return Some(value);
}
}
None
}
type TableStyleEntry = (String, Option<TableBorders>, Option<String>);
fn table_style_entry(value: &str) -> Option<(TableStyleEntry, &str)> {
let (id, mut rest) = take_clause(value);
let id = unquote(id.trim()).filter(|id| !id.is_empty())?;
let mut border = None;
let mut name = None;
while !rest.is_empty() {
let (clause, next) = take_clause(rest);
if border.is_none()
&& let Some(pt) = clause
.strip_prefix("all borders ")
.and_then(|pt| pt.strip_suffix("pt"))
.and_then(|pt| pt.parse::<f64>().ok())
.filter(|pt| (0.25..=6.0).contains(pt))
{
border = Some(TableBorders::All((pt * 8.0).round() as u32));
} else if border.is_none()
&& let Some(sides) = border_sides(&clause)
{
border = Some(TableBorders::Sides(sides));
} else if name.is_none()
&& let Some(named) = clause
.strip_prefix("named ")
.and_then(|named| unquote(named.trim()))
{
name = Some(named);
} else if clause != "borders vary" {
return Some(((id, border, name), rest));
}
rest = next;
}
Some(((id, border, name), ""))
}
fn take_clause(value: &str) -> (String, &str) {
let (mut quoted, mut escaped) = (false, false);
for (i, c) in value.char_indices() {
match c {
_ if escaped => escaped = false,
'\\' if quoted => escaped = true,
'"' => quoted = !quoted,
',' if !quoted && value[i + 1..].starts_with(' ') => {
return (value[..i].to_string(), &value[i + 2..]);
}
_ => {}
}
}
(value.to_string(), "")
}
pub(super) fn legend(yaml: &str) -> Vec<StyleSpec> {
let mut specs = Vec::new();
let mut inside = false;
for line in yaml.lines() {
if !line.starts_with(' ') {
inside = line.trim_end() == "styles:";
continue;
}
if !inside {
continue;
}
let line = without_comment(line).trim();
let Some((key, value)) = line.split_once(": ") else {
continue;
};
let (Some(key), Some(value)) = (unquote(key), unquote(value.trim())) else {
continue;
};
let spec = if key.bytes().all(|b| b == b'#') {
let level = u32::try_from(key.len())
.ok()
.filter(|n| (1..=6).contains(n));
level.and_then(|level| {
let (id, rest) = value.split_once(", ")?;
spec(&unquote(id)?, Some(level), false, rest)
})
} else if matches!(key.as_str(), "table" | "tables" | "changes") {
None
} else {
let default = !specs.iter().any(|s: &StyleSpec| s.default);
spec(&key, None, default, &value)
};
specs.extend(spec);
}
specs
}
pub(super) fn apply(styles: &str, specs: &[StyleSpec]) -> String {
let mut defaults = document_defaults(styles);
let mut out = styles.to_string();
let base = specs.iter().find(|s| s.default);
let from_base = base.map(effective);
if let Some(look) = &from_base {
out = out.replace(
"w:type=\"paragraph\" w:default=\"1\"",
"w:type=\"paragraph\"",
);
with_default_spacing(&mut out, look);
defaults.before = look.before;
defaults.after = look.after;
defaults.line_twips = look.line_twips;
defaults.line_rule.clone_from(&look.line_rule);
}
for spec in specs {
out = without_style(&out, &spec.id);
let inherited = if spec.default || spec.character {
&defaults
} else {
from_base.as_ref().unwrap_or(&defaults)
};
let parent = base.filter(|_| !spec.character).map(|b| b.id.as_str());
let definition = definition(spec, parent, inherited);
if let Some(at) = out.rfind("</w:styles>") {
out.insert_str(at, &definition);
}
}
out
}
const AFTER_SPACING: [&str; 11] = [
"ind",
"contextualSpacing",
"mirrorIndents",
"suppressOverlap",
"jc",
"textDirection",
"textAlignment",
"textboxTightWrap",
"outlineLvl",
"divId",
"cnfStyle",
];
fn with_default_spacing(out: &mut String, look: &Given) {
let mut spacing = String::from("<w:spacing");
if look.before > 0 {
let _ = write!(spacing, " w:before=\"{}\"", look.before);
}
let _ = write!(
spacing,
" w:after=\"{}\" w:line=\"{}\" w:lineRule=\"{}\"/>",
look.after, look.line_twips, look.line_rule
);
let ppr = format!("<w:pPr>{spacing}</w:pPr>");
let default = format!("<w:pPrDefault>{ppr}</w:pPrDefault>");
let Some(defaults) = open_tag(out, "docDefaults", 0..out.len()) else {
if let Some(styles) = open_tag(out, "styles", 0..out.len()).filter(|t| !t.empty) {
out.insert_str(
styles.end,
&format!("<w:docDefaults>{default}</w:docDefaults>"),
);
}
return;
};
if defaults.empty {
out.replace_range(
defaults.start..defaults.end,
&format!("<w:docDefaults>{default}</w:docDefaults>"),
);
return;
}
let Some(close) = out[defaults.end..]
.find("</w:docDefaults>")
.map(|at| defaults.end + at)
else {
return;
};
let Some(ppr_default) = open_tag(out, "pPrDefault", defaults.end..close) else {
out.insert_str(close, &default);
return;
};
if ppr_default.empty {
out.replace_range(ppr_default.start..ppr_default.end, &default);
return;
}
let Some(default_close) = out[ppr_default.end..close]
.find("</w:pPrDefault>")
.map(|at| ppr_default.end + at)
else {
return;
};
let Some(own) = open_tag(out, "pPr", ppr_default.end..default_close) else {
out.insert_str(ppr_default.end, &ppr);
return;
};
if own.empty {
out.replace_range(own.start..own.end, &ppr);
return;
}
let Some(mut own_close) = out[own.end..default_close]
.rfind("</w:pPr>")
.map(|at| own.end + at)
else {
return;
};
if let Some(old) = open_tag(out, "spacing", own.end..own_close) {
let end = if old.empty {
old.end
} else {
out[old.end..own_close]
.find("</w:spacing>")
.map_or(old.end, |at| old.end + at + "</w:spacing>".len())
};
out.replace_range(old.start..end, "");
own_close -= end - old.start;
}
let at = AFTER_SPACING
.iter()
.filter_map(|name| open_tag(out, name, own.end..own_close).map(|t| t.start))
.min()
.unwrap_or(own_close);
out.insert_str(at, &spacing);
}
fn without_style(styles: &str, id: &str) -> String {
let key = format!("w:styleId=\"{}\"", escape(id));
let mut out = String::with_capacity(styles.len());
let mut rest = styles;
while let Some(at) = rest.find("<w:style ") {
let Some(tag_end) = rest[at..].find('>').map(|i| at + i) else {
break;
};
let Some(end) = rest[tag_end..].find("</w:style>").map(|i| tag_end + i + 10) else {
break;
};
out.push_str(&rest[..at]);
if !rest[at..tag_end].contains(&key) {
out.push_str(&rest[at..end]);
}
rest = &rest[end..];
}
out.push_str(rest);
out
}
struct Given {
font: Option<String>,
size: Option<u32>,
bold: bool,
italic: bool,
before: u32,
after: u32,
line_twips: u32,
line_rule: String,
align: String,
keep_next: bool,
keep_lines: bool,
contextual: bool,
left: Option<i64>,
right: Option<i64>,
first_line: Option<i64>,
hanging: Option<i64>,
}
impl Given {
fn implicit() -> Self {
Self {
font: None,
size: None,
bold: false,
italic: false,
before: 0,
after: 0,
line_twips: 240,
line_rule: "auto".to_string(),
align: "left".to_string(),
keep_next: false,
keep_lines: false,
contextual: false,
left: None,
right: None,
first_line: None,
hanging: None,
}
}
}
fn effective(spec: &StyleSpec) -> Given {
let (line_twips, line_rule) = spec.line.unwrap_or((240, "auto"));
Given {
font: Some(spec.font.clone()),
size: Some(spec.size),
bold: spec.bold,
italic: spec.italic,
before: spec.before.unwrap_or(0),
after: spec.after.unwrap_or(0),
line_twips,
line_rule: line_rule.to_string(),
align: spec.align.unwrap_or("left").to_string(),
keep_next: spec.keep_next,
keep_lines: spec.keep_lines,
contextual: spec.contextual_spacing,
left: spec.left,
right: spec.right,
first_line: spec.first_line,
hanging: spec.hanging,
}
}
fn whole(element: &Element, attr: &str) -> Option<u32> {
let n: f64 = element.attr(attr)?.parse().ok()?;
let n = n.round();
(n.is_finite() && (0.0..=u32::MAX as f64).contains(&n)).then_some(n as u32)
}
fn signed(element: &Element, attr: &str) -> Option<i64> {
let n: f64 = element.attr(attr)?.parse().ok()?;
let n = n.round();
(n.is_finite() && n.abs() <= 1.0e15).then_some(n as i64)
}
fn document_defaults(styles: &str) -> Given {
let mut given = Given::implicit();
let Ok(root) = super::from_docx::parse_xml(styles.as_bytes()) else {
return given;
};
let Some(defaults) = root.child("docDefaults") else {
return given;
};
if let Some(rpr) = defaults.path(&["rPrDefault", "rPr"]) {
if let Some(fonts) = rpr.child("rFonts") {
given.font = fonts
.attr("asciiTheme")
.is_none()
.then(|| fonts.attr("ascii").or_else(|| fonts.attr("hAnsi")))
.flatten()
.map(str::to_string);
}
if let Some(size) = rpr.child("sz").and_then(|sz| whole(sz, "val")) {
given.size = Some(size);
}
if let Some(bold) = rpr.toggle("b") {
given.bold = bold;
}
if let Some(italic) = rpr.toggle("i") {
given.italic = italic;
}
}
if let Some(ppr) = defaults.path(&["pPrDefault", "pPr"]) {
if let Some(spacing) = ppr.child("spacing") {
if let Some(before) = whole(spacing, "before") {
given.before = before;
}
if let Some(after) = whole(spacing, "after") {
given.after = after;
}
if let Some(line) = whole(spacing, "line") {
given.line_twips = line;
given.line_rule = spacing.attr("lineRule").unwrap_or("auto").to_string();
}
}
if let Some(ind) = ppr.child("ind") {
if let Some(left) = signed(ind, "left").or_else(|| signed(ind, "start")) {
given.left = Some(left);
}
if let Some(right) = signed(ind, "right").or_else(|| signed(ind, "end")) {
given.right = Some(right);
}
if let Some(first) = signed(ind, "firstLine") {
given.first_line = Some(first);
}
if let Some(hanging) = signed(ind, "hanging") {
given.hanging = Some(hanging);
}
}
if let Some(on) = ppr.toggle("keepNext") {
given.keep_next = on;
}
if let Some(on) = ppr.toggle("keepLines") {
given.keep_lines = on;
}
if let Some(on) = ppr.toggle("contextualSpacing") {
given.contextual = on;
}
if let Some(align) = ppr.child("jc").and_then(|jc| jc.attr("val")) {
given.align = align.to_string();
}
}
given
}
fn indent_attr(spec: Option<i64>, inherited: Option<i64>) -> Option<i64> {
spec.filter(|value| Some(*value) != inherited)
}
fn gallery_flags(id: &str, name: &str) -> String {
let Some(builtin) = super::xml::style_definition(id) else {
return String::new();
};
if !builtin.contains(&format!("<w:name w:val=\"{name}\"/>")) {
return String::new();
}
let mut out = String::new();
for flag in [
"<w:uiPriority ",
"<w:semiHidden/>",
"<w:unhideWhenUsed/>",
"<w:qFormat/>",
] {
if let Some(at) = builtin.find(flag) {
let end = builtin[at..]
.find("/>")
.map_or(builtin.len(), |e| at + e + 2);
out.push_str(&builtin[at..end]);
}
}
out
}
fn definition(spec: &StyleSpec, base: Option<&str>, inherited: &Given) -> String {
let id = escape(&spec.id);
let name = match (&spec.name, spec.heading, spec.id.strip_prefix("Heading")) {
(Some(name), ..) => escape(name).to_string(),
(None, Some(_), Some(n)) if n.parse::<u32>().is_ok() => format!("heading {n}"),
_ => id.to_string(),
};
let name = name.replace(',', " ");
let mut out = if spec.default {
format!(
"<w:style w:type=\"paragraph\" w:default=\"1\" w:styleId=\"{id}\"><w:name w:val=\"{name}\"/><w:qFormat/>"
)
} else {
let mut out = format!(
"<w:style w:type=\"{}\" w:styleId=\"{id}\"><w:name w:val=\"{name}\"/>",
if spec.character {
"character"
} else {
"paragraph"
}
);
if let Some(base) = base.filter(|b| *b != spec.id) {
out.push_str(&format!("<w:basedOn w:val=\"{}\"/>", escape(base)));
if spec.heading.is_some() {
out.push_str(&format!("<w:next w:val=\"{}\"/>", escape(base)));
}
}
if spec.heading.is_some() {
out.push_str("<w:uiPriority w:val=\"9\"/><w:qFormat/>");
} else {
out.push_str(&gallery_flags(&spec.id, &name));
}
out
};
let mut ppr = String::new();
if spec.keep_next && !inherited.keep_next {
ppr.push_str("<w:keepNext/>");
}
if spec.keep_lines && !inherited.keep_lines {
ppr.push_str("<w:keepLines/>");
}
let before = if spec.default {
spec.before.or(Some(0))
} else {
spec.before
};
let after = if spec.default {
spec.after.or(Some(0))
} else {
spec.after
};
let line = if spec.default {
spec.line.or(Some((240, "auto")))
} else {
spec.line
};
let write_before = before.is_some_and(|value| value != inherited.before);
let write_after = after.is_some_and(|value| value != inherited.after);
let write_line = line
.is_some_and(|(twips, rule)| twips != inherited.line_twips || rule != inherited.line_rule);
if write_before || write_after || write_line {
ppr.push_str("<w:spacing");
if write_before {
ppr.push_str(&format!(" w:before=\"{}\"", before.unwrap_or(0)));
}
if write_after {
ppr.push_str(&format!(" w:after=\"{}\"", after.unwrap_or(0)));
}
if write_line {
let (twips, rule) = line.unwrap_or((240, "auto"));
ppr.push_str(&format!(" w:line=\"{twips}\" w:lineRule=\"{rule}\""));
}
ppr.push_str("/>");
}
let indent = |value: Option<i64>, given: Option<i64>| {
if spec.default {
indent_attr(value.or(Some(0)), Some(given.unwrap_or(0)))
} else {
indent_attr(value, given)
}
};
let left = indent(spec.left, inherited.left);
let right = indent(spec.right, inherited.right);
let first = indent(spec.first_line, inherited.first_line);
let hanging = indent(spec.hanging, inherited.hanging);
if left.is_some() || right.is_some() || first.is_some() || hanging.is_some() {
ppr.push_str("<w:ind");
if let Some(value) = left {
ppr.push_str(&format!(" w:left=\"{value}\""));
}
if let Some(value) = right {
ppr.push_str(&format!(" w:right=\"{value}\""));
}
if let Some(value) = first {
ppr.push_str(&format!(" w:firstLine=\"{value}\""));
}
if let Some(value) = hanging {
ppr.push_str(&format!(" w:hanging=\"{value}\""));
}
ppr.push_str("/>");
}
if spec.contextual_spacing && !inherited.contextual {
ppr.push_str("<w:contextualSpacing/>");
}
let align = if spec.default {
spec.align.or(Some("left"))
} else {
spec.align
};
if let Some(align) = align.filter(|value| *value != inherited.align) {
ppr.push_str(&format!("<w:jc w:val=\"{align}\"/>"));
}
if let Some(level) = spec.heading {
ppr.push_str(&format!("<w:outlineLvl w:val=\"{}\"/>", level - 1));
}
if !ppr.is_empty() {
out.push_str(&format!("<w:pPr>{ppr}</w:pPr>"));
}
let mut rpr = String::new();
if inherited.font.as_deref() != Some(spec.font.as_str()) {
let font = escape(&spec.font);
rpr.push_str(&format!(
"<w:rFonts w:ascii=\"{font}\" w:hAnsi=\"{font}\" w:eastAsia=\"{font}\" w:cs=\"{font}\"/>"
));
}
let toggle = |on: bool, name: &str| {
if on {
format!("<w:{name}/><w:{name}Cs/>")
} else {
format!("<w:{name} w:val=\"0\"/><w:{name}Cs w:val=\"0\"/>")
}
};
if spec.bold != inherited.bold {
rpr.push_str(&toggle(spec.bold, "b"));
}
if spec.italic != inherited.italic {
rpr.push_str(&toggle(spec.italic, "i"));
}
if inherited.size != Some(spec.size) {
rpr.push_str(&format!(
"<w:sz w:val=\"{size}\"/><w:szCs w:val=\"{size}\"/>",
size = spec.size
));
}
if !rpr.is_empty() {
out.push_str(&format!("<w:rPr>{rpr}</w:rPr>"));
}
out.push_str("</w:style>");
out
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod tests {
use super::*;
fn defaults_change(styles: &str) -> String {
let mark = FormatMark {
id: Some(7),
author: "Ana".to_string(),
date: String::new(),
};
with_style_changes(
styles,
&[(
"docDefaults".to_string(),
vec![(StyleChangeKind::Run, mark)],
)],
)
}
#[test]
fn a_defaults_change_leaves_the_defaults_unchanged() {
for styles in [
"<w:styles xmlns:w=\"W\"><w:style w:styleId=\"A\"><w:rPr><w:b/></w:rPr></w:style></w:styles>",
"<w:styles><w:docDefaults><w:pPrDefault><w:pPr/></w:pPrDefault></w:docDefaults></w:styles>",
"<w:styles><w:docDefaults/></w:styles>",
"<w:styles><w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val=\"22\"/></w:rPr></w:rPrDefault>\
</w:docDefaults><w:style w:styleId=\"A\"><w:rPr><w:b/></w:rPr></w:style></w:styles>",
] {
assert_eq!(defaults_change(styles), styles);
}
}
#[test]
fn style_change_carrier_first_mark_of_each_kind_is_written() {
let styles = "<w:styles><w:style w:styleId=\"Normal\"><w:name w:val=\"Normal\"/></w:style></w:styles>";
let mark = |id: u32, author: &str| FormatMark {
id: Some(id),
author: author.to_string(),
date: String::new(),
};
let out = with_style_changes(
styles,
&[(
"Normal".to_string(),
vec![
(StyleChangeKind::Paragraph, mark(7, "Ana")),
(StyleChangeKind::Paragraph, mark(8, "Ana")),
(StyleChangeKind::Paragraph, mark(9, "Bob")),
(StyleChangeKind::Run, mark(3, "Ana")),
(StyleChangeKind::Other, mark(4, "Ana")),
],
)],
);
assert_eq!(out.matches("<w:pPrChange").count(), 1, "{out}");
assert_eq!(out.matches("<w:rPrChange").count(), 1, "{out}");
assert!(out.contains("w:id=\"7\""), "{out}");
assert!(out.contains("w:id=\"3\""), "{out}");
assert!(!out.contains("w:id=\"8\""), "{out}");
assert!(!out.contains("w:id=\"4\""), "{out}");
let ppr = out.find("<w:pPr>").expect("pPr");
let rpr = out.find("<w:rPr>").expect("rPr");
assert!(ppr < rpr, "{out}");
}
#[test]
fn style_change_carrier_replaces_a_nested_run_change() {
let styles = "<w:styles><w:style w:styleId=\"Normal\"><w:rPr><w:b/>\
<w:rPrChange w:id=\"1\" w:author=\"Old\"><w:rPr><w:i/></w:rPr></w:rPrChange>\
</w:rPr></w:style></w:styles>";
let out = with_style_changes(
styles,
&[(
"Normal".to_string(),
vec![(
StyleChangeKind::Run,
FormatMark {
id: Some(9),
author: "Ana".to_string(),
date: String::new(),
},
)],
)],
);
assert_eq!(out.matches("<w:rPrChange").count(), 1, "{out}");
assert!(out.contains("w:id=\"9\""), "{out}");
assert!(out.contains("<w:b/>"), "{out}");
assert!(!out.contains("w:author=\"Old\""), "{out}");
assert!(!out.contains("<w:i/>"), "{out}");
}
#[test]
fn style_change_carrier_expands_an_empty_run_holder() {
let styles = "<w:styles><w:style w:styleId=\"Normal\"><w:rPr/></w:style></w:styles>";
let mark = FormatMark {
id: Some(4),
author: "Ana".to_string(),
date: String::new(),
};
let out = with_style_changes(
styles,
&[(
"Normal".to_string(),
vec![
(StyleChangeKind::Run, mark.clone()),
(StyleChangeKind::Paragraph, mark),
],
)],
);
let ppr = out.find("<w:pPr>").expect("pPr");
let rpr = out.find("<w:rPr>").expect("rPr");
assert!(ppr < rpr, "{out}");
assert!(out.contains("<w:pPr><w:pPrChange"), "{out}");
assert!(out.contains("<w:rPr><w:rPrChange"), "{out}");
}
#[test]
fn a_style_change_lands_in_the_styles_own_ppr_and_rpr() {
let mark = FormatMark {
id: Some(9),
author: "Ana".to_string(),
date: String::new(),
};
let styles = "<w:styles><w:style w:styleId=\"Heading1\"><w:name w:val=\"heading 1\"/>\
<w:pPr><w:keepNext/><w:rPr><w:i/></w:rPr></w:pPr>\
<w:rPr><w:sz w:val=\"32\"/></w:rPr></w:style></w:styles>";
assert_eq!(
with_style_changes(
styles,
&[(
"Heading1".to_string(),
vec![
(StyleChangeKind::Paragraph, mark.clone()),
(StyleChangeKind::Run, mark),
],
)],
),
"<w:styles><w:style w:styleId=\"Heading1\"><w:name w:val=\"heading 1\"/>\
<w:pPr><w:keepNext/><w:rPr><w:i/></w:rPr>\
<w:pPrChange w:id=\"9\" w:author=\"Ana\"><w:pPr/></w:pPrChange></w:pPr>\
<w:rPr><w:sz w:val=\"32\"/><w:rPrChange w:id=\"9\" w:author=\"Ana\"><w:rPr/></w:rPrChange>\
</w:rPr></w:style></w:styles>"
);
}
const YAML: &str = "view: tracked\nstyles:\n Normal: Times New Roman 11pt, after 6pt, line 12pt atLeast, left # default; unannotated paragraphs use it\n \"#\": Heading1, Times New Roman bold 24pt, before 24pt, keep-next\n \"##\": Heading2, Arial bold italic 13.5pt, line 1.08, center\n table: TableGrid, all borders 0.5pt\nbody: p0-p2\n";
#[test]
fn every_other_style_and_its_name_read_and_are_defined() {
let specs = legend(
"styles:\n Normal: Arial 12pt, left # default\n \
\"#\": Heading1, Arial bold 16pt, named Heading 1\n \
TextHeading2: Times New Roman 12pt, after 6pt, named Text Heading 2\n \
TOC2: Arial 11pt\n",
);
let ids: Vec<(&str, Option<&str>, bool)> = specs
.iter()
.map(|s| (s.id.as_str(), s.name.as_deref(), s.default))
.collect();
assert_eq!(
ids,
[
("Normal", None, true),
("Heading1", Some("Heading 1"), false),
("TextHeading2", Some("Text Heading 2"), false),
("TOC2", None, false),
]
);
let styles = apply("<w:styles></w:styles>", &specs);
assert!(
styles.contains(
r#"<w:style w:type="paragraph" w:styleId="TextHeading2"><w:name w:val="Text Heading 2"/><w:basedOn w:val="Normal"/><w:pPr><w:spacing w:after="120"/></w:pPr><w:rPr><w:rFonts w:ascii="Times New Roman""#
),
"{styles}"
);
assert!(
styles.contains(r#"<w:name w:val="Heading 1"/>"#),
"{styles}"
);
assert!(
styles.contains(r#"w:styleId="TOC2"><w:name w:val="TOC2"/>"#),
"{styles}"
);
assert_eq!(styles.matches("w:default=\"1\"").count(), 1, "{styles}");
}
#[test]
fn a_character_style_comes_back_as_one() {
let specs = legend(
"styles:\n Normal: Calibri 11pt, left\n \
LineNumber: character, Calibri 11pt, named line number\n",
);
assert_eq!(specs.len(), 2, "the character style must be read");
let styles = apply("<w:styles></w:styles>", &specs);
assert!(
styles.contains(r#"<w:style w:type="character" w:styleId="LineNumber"><w:name w:val="line number"/>"#),
"{styles}"
);
assert_eq!(legend("styles:\n Normal: character, Calibri 11pt\n"), []);
}
#[test]
fn a_character_style_keeps_its_font_without_a_paragraph_base() {
let specs = legend(
"styles:\n Normal: Calibri bold italic 11pt, after 8pt, left\n \
LineNumber: character, Calibri bold italic 11pt, named line number\n",
);
let styles = apply("<w:styles></w:styles>", &specs);
let character = styles
.split(r#"<w:style w:type="character""#)
.nth(1)
.expect("a character style is written")
.split("</w:style>")
.next()
.unwrap();
assert!(!character.contains("<w:basedOn"), "{character}");
assert!(!character.contains("<w:pPr"), "{character}");
assert!(character.contains(r#"w:ascii="Calibri""#), "{character}");
assert!(character.contains(r#"<w:sz w:val="22"/>"#), "{character}");
assert!(
character.contains("<w:b/>") && character.contains("<w:i/>"),
"{character}"
);
}
#[test]
fn the_legend_reads() {
let specs = legend(YAML);
assert_eq!(specs.len(), 3, "{specs:?}");
assert_eq!(
(
specs[0].font.as_str(),
specs[0].size,
specs[0].after,
specs[0].line,
specs[0].align
),
(
"Times New Roman",
22,
Some(120),
Some((240, "atLeast")),
Some("left")
)
);
assert_eq!(
(specs[1].heading, specs[1].bold, specs[1].before),
(Some(1), true, Some(480))
);
assert!(specs[1].keep_next);
assert!(!specs[0].keep_lines);
assert!(!specs[0].contextual_spacing);
assert_eq!(specs[0].left, None);
assert_eq!(
(specs[2].italic, specs[2].size, specs[2].line),
(true, 27, Some((259, "auto")))
);
assert_eq!(specs[2].align, Some("center"));
}
#[test]
fn a_comment_ends_at_a_hash_outside_quotes() {
assert_eq!(without_comment(" a: b # c"), " a: b ");
assert_eq!(without_comment("title: Issue #5"), "title: Issue #5");
assert_eq!(
without_comment(" a: \"x #1 \\\" #\" # c"),
" a: \"x #1 \\\" #\" "
);
assert_eq!(without_comment(" \"#\": H1, A 1pt"), " \"#\": H1, A 1pt");
}
#[test]
fn what_does_not_read_is_left_out() {
assert_eq!(
legend("styles:\n Normal: 11pt\n \"#\": Heading1, Arial bold 99999pt\n"),
[]
);
assert_eq!(legend("styles:\n \"#######\": Heading7, Arial 11pt\n"), []);
assert_eq!(legend("styles:\n table: TableGrid\n"), []);
assert_eq!(
legend("styles:\n Normal: Calibri 11pt, indent 99in, left\n"),
[]
);
assert_eq!(
legend("styles:\n Normal: Calibri 11pt, indent 0.5, left\n"),
[]
);
assert_eq!(
legend("styles:\n Normal: Calibri 11pt, contextual wide, left\n"),
[]
);
}
#[test]
fn a_default_style_with_another_id_takes_the_default() {
let specs = legend(
"styles:\n \"1\": Arial 12pt, left # default\n \"#\": 2, Calibri bold 16pt, before 12pt\n",
);
assert_eq!(
specs.iter().map(|s| s.id.as_str()).collect::<Vec<_>>(),
["1", "2"]
);
let styles = "<w:styles><w:style w:type=\"paragraph\" w:default=\"1\" w:styleId=\"Normal\"><w:name w:val=\"Normal\"/></w:style></w:styles>";
let out = apply(styles, &specs);
assert_eq!(out.matches("w:default=\"1\"").count(), 1, "{out}");
assert!(out.contains("w:default=\"1\" w:styleId=\"1\""), "{out}");
assert!(
out.contains("<w:name w:val=\"2\"/><w:basedOn w:val=\"1\"/>"),
"{out}"
);
}
#[test]
fn a_definition_replaces_the_styles_own() {
let styles = "<w:styles><w:style w:type=\"paragraph\" w:default=\"1\" w:styleId=\"Normal\"><w:name w:val=\"Normal\"/></w:style><w:style w:type=\"paragraph\" w:styleId=\"Quote\"><w:name w:val=\"Quote\"/></w:style></w:styles>";
let out = apply(styles, &legend(YAML));
assert_eq!(out.matches("w:styleId=\"Normal\"").count(), 1, "{out}");
assert!(out.contains("w:styleId=\"Quote\""), "{out}");
let normal = style_element(&out, "Normal");
assert!(
out.starts_with(
"<w:styles><w:docDefaults><w:pPrDefault><w:pPr>\
<w:spacing w:after=\"120\" w:line=\"240\" w:lineRule=\"atLeast\"/>\
</w:pPr></w:pPrDefault></w:docDefaults>"
),
"{out}"
);
assert!(!normal.contains("<w:spacing"), "{normal}");
assert!(!normal.contains("<w:jc"), "{normal}");
assert!(!normal.contains("<w:b"), "{normal}");
assert!(
normal.contains(
"<w:rFonts w:ascii=\"Times New Roman\" w:hAnsi=\"Times New Roman\" \
w:eastAsia=\"Times New Roman\" w:cs=\"Times New Roman\"/>"
),
"{normal}"
);
assert!(
normal.contains("<w:sz w:val=\"22\"/><w:szCs w:val=\"22\"/>"),
"{normal}"
);
assert!(
out.contains("<w:name w:val=\"heading 1\"/><w:basedOn w:val=\"Normal\"/>"),
"{out}"
);
}
fn style_element(styles: &str, id: &str) -> String {
let key = format!("w:styleId=\"{id}\"");
let at = styles
.find(&key)
.unwrap_or_else(|| panic!("no {id} in {styles}"));
let start = styles[..at].rfind("<w:style ").unwrap_or(at);
let end = styles[at..]
.find("</w:style>")
.map(|i| at + i + "</w:style>".len())
.unwrap_or(styles.len());
styles[start..end].to_string()
}
#[test]
fn an_indent_contextual_spacing_and_keep_lines_are_written() {
let specs = legend(
"styles:\n \
Normal: Times New Roman 11pt, indent -0.0035in, hanging 0.007in, justify\n \
\"#\": Heading1, Times New Roman bold 16pt, keep-next, keep-lines\n \
ListParagraph: Times New Roman 11pt, indent 0.5in, first-line 0.25in, \
contextual spacing, named List Paragraph\n",
);
assert_eq!(specs[0].left, Some(-5));
assert_eq!(specs[0].hanging, Some(10));
assert!(specs[1].keep_lines);
assert_eq!(specs[2].left, Some(720));
assert_eq!(specs[2].first_line, Some(360));
assert!(specs[2].contextual_spacing);
let out = apply("<w:styles></w:styles>", &specs);
let list = style_element(&out, "ListParagraph");
assert!(
list.contains("<w:ind w:left=\"720\" w:firstLine=\"360\"/>"),
"{list}"
);
assert!(list.contains("<w:contextualSpacing/>"), "{list}");
assert!(!list.contains("<w:rPr"), "{list}");
let heading = style_element(&out, "Heading1");
assert!(heading.contains("<w:keepNext/><w:keepLines/>"), "{heading}");
let normal = style_element(&out, "Normal");
assert!(
normal.contains("<w:ind w:left=\"-5\" w:hanging=\"10\"/>"),
"{normal}"
);
}
#[test]
fn a_right_indent_is_written_and_a_bare_right_still_aligns() {
let specs = legend(
"styles:\n \
Normal: Times New Roman 11pt, left\n \
Quote: Times New Roman 11pt, indent 0.5in, right 0.5in, named Quote Text\n \
Flush: Times New Roman 11pt, right\n \
Back: Times New Roman 11pt, right 0in\n",
);
assert_eq!(specs[1].right, Some(720));
assert_eq!(specs[2].right, None);
assert_eq!(specs[2].align, Some("right"));
assert_eq!(specs[3].right, Some(0));
let out = apply("<w:styles></w:styles>", &specs);
let quote = style_element(&out, "Quote");
assert!(
quote.contains("<w:ind w:left=\"720\" w:right=\"720\"/>"),
"{quote}"
);
let flush = style_element(&out, "Flush");
assert!(flush.contains("<w:jc w:val=\"right\"/>"), "{flush}");
assert!(!flush.contains("<w:ind"), "{flush}");
let back = style_element(&out, "Back");
assert!(back.contains("<w:ind w:right=\"0\"/>"), "{back}");
}
#[test]
fn a_theme_font_in_the_defaults_is_not_the_named_font() {
let styles = "<w:styles><w:docDefaults><w:rPrDefault><w:rPr>\
<w:rFonts w:ascii=\"Aptos\" w:hAnsi=\"Aptos\" w:asciiTheme=\"minorHAnsi\" w:hAnsiTheme=\"minorHAnsi\"/>\
<w:sz w:val=\"22\"/></w:rPr></w:rPrDefault></w:docDefaults></w:styles>";
let out = apply(styles, &legend("styles:\n Normal: Aptos 11pt, left\n"));
let normal = style_element(&out, "Normal");
assert!(normal.contains("<w:rFonts w:ascii=\"Aptos\""), "{normal}");
}
#[test]
fn a_style_omits_properties_the_defaults_already_give() {
let styles = "<w:styles><w:docDefaults><w:rPrDefault><w:rPr>\
<w:rFonts w:ascii=\"Calibri\" w:hAnsi=\"Calibri\" w:eastAsia=\"Calibri\" w:cs=\"Calibri\"/>\
<w:sz w:val=\"22\"/><w:szCs w:val=\"22\"/></w:rPr></w:rPrDefault>\
<w:pPrDefault><w:pPr><w:spacing w:after=\"160\" w:line=\"259\" w:lineRule=\"auto\"/>\
</w:pPr></w:pPrDefault></w:docDefaults></w:styles>";
let specs = legend(
"styles:\n \
Normal: Calibri 11pt, after 8pt, line 1.08, left\n \
\"#\": Heading1, Calibri bold 16pt, before 12pt, after 4pt, keep-next, keep-lines\n \
ListParagraph: Calibri 11pt, indent 0.5in, contextual spacing, named List Paragraph\n \
Quote: Calibri 11pt, left\n",
);
let out = apply(styles, &specs);
assert!(
out.contains(
"<w:style w:type=\"paragraph\" w:default=\"1\" w:styleId=\"Normal\">\
<w:name w:val=\"Normal\"/><w:qFormat/></w:style>"
),
"{out}"
);
let list = style_element(&out, "ListParagraph");
assert!(list.contains("<w:ind w:left=\"720\"/>"), "{list}");
assert!(list.contains("<w:contextualSpacing/>"), "{list}");
assert!(!list.contains("<w:rPr"), "{list}");
assert!(
list.contains("<w:name w:val=\"List Paragraph\"/>"),
"{list}"
);
assert!(
list.contains(
"<w:basedOn w:val=\"Normal\"/><w:uiPriority w:val=\"34\"/><w:qFormat/><w:pPr>"
),
"{list}"
);
assert!(
style_element(&out, "Quote").contains("<w:uiPriority w:val=\"29\"/><w:qFormat/>"),
"{out}"
);
let heading = style_element(&out, "Heading1");
assert!(
heading.contains(
"<w:pPr><w:keepNext/><w:keepLines/><w:spacing w:before=\"240\" w:after=\"80\"/>\
<w:outlineLvl w:val=\"0\"/></w:pPr>"
),
"{heading}"
);
assert!(
heading.contains(
"<w:rPr><w:b/><w:bCs/><w:sz w:val=\"32\"/><w:szCs w:val=\"32\"/></w:rPr>"
),
"{heading}"
);
let quote = style_element(&out, "Quote");
assert!(!quote.contains("<w:rPr"), "{quote}");
assert!(!quote.contains("<w:pPr"), "{quote}");
}
#[test]
fn the_default_style_s_omitted_indent_is_none() {
let styles = "<w:styles><w:docDefaults><w:pPrDefault><w:pPr>\
<w:ind w:left=\"360\" w:right=\"720\" w:hanging=\"360\"/>\
</w:pPr></w:pPrDefault></w:docDefaults></w:styles>";
let out = apply(
styles,
&legend("styles:\n Normal: Calibri 11pt, left\n Quote: Calibri 11pt, left\n"),
);
let normal = style_element(&out, "Normal");
assert!(
normal.contains("<w:ind w:left=\"0\" w:right=\"0\" w:hanging=\"0\"/>"),
"{normal}"
);
assert!(!style_element(&out, "Quote").contains("<w:ind"), "{out}");
let out = apply(
"<w:styles></w:styles>",
&legend("styles:\n Normal: Calibri 11pt, left\n"),
);
assert!(!style_element(&out, "Normal").contains("<w:ind"), "{out}");
}
#[test]
fn a_run_property_is_written_when_it_differs_from_the_base() {
let specs =
legend("styles:\n Normal: Calibri bold 11pt, left\n Quote: Calibri 11pt, left\n");
let out = apply("<w:styles></w:styles>", &specs);
let quote = style_element(&out, "Quote");
assert!(
quote.contains("<w:b w:val=\"0\"/><w:bCs w:val=\"0\"/>"),
"{quote}"
);
assert!(!quote.contains("w:rFonts"), "{quote}");
assert!(!quote.contains("<w:sz"), "{quote}");
assert!(!quote.contains("<w:jc"), "{quote}");
}
fn paragraph_defaults(styles: &str) -> &str {
let Some(start) = styles.find("<w:pPrDefault") else {
return "";
};
let end = styles[start..]
.find("</w:pPrDefault>")
.map_or(styles.len(), |i| start + i + "</w:pPrDefault>".len());
&styles[start..end]
}
#[test]
fn the_default_style_s_spacing_is_the_documents_default() {
let styles = "<w:styles><w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val=\"22\"/></w:rPr></w:rPrDefault>\
<w:pPrDefault><w:pPr><w:spacing w:after=\"160\" w:line=\"259\" w:lineRule=\"auto\"/></w:pPr></w:pPrDefault>\
</w:docDefaults></w:styles>";
let out = apply(
styles,
&legend(
"styles:\n Normal: Calibri 11pt, after 10pt, line 1.15, left\n \
Quote: Calibri 11pt, before 6pt, left\n",
),
);
assert_eq!(
paragraph_defaults(&out),
"<w:pPrDefault><w:pPr><w:spacing w:after=\"200\" w:line=\"276\" w:lineRule=\"auto\"/>\
</w:pPr></w:pPrDefault>",
"{out}"
);
let normal = style_element(&out, "Normal");
assert!(!normal.contains("<w:spacing"), "{normal}");
let quote = style_element(&out, "Quote");
assert!(quote.contains("<w:spacing w:before=\"120\"/>"), "{quote}");
let out = apply(styles, &legend("styles:\n Normal: Calibri 11pt, left\n"));
assert_eq!(
paragraph_defaults(&out),
"<w:pPrDefault><w:pPr><w:spacing w:after=\"0\" w:line=\"240\" w:lineRule=\"auto\"/>\
</w:pPr></w:pPrDefault>",
"{out}"
);
assert!(
!style_element(&out, "Normal").contains("<w:spacing"),
"{out}"
);
}
#[test]
fn the_default_spacing_lands_where_the_schema_puts_it() {
let specs = legend(
"styles:\n Normal: Calibri 11pt, before 3pt, after 6pt, line 12pt exact, left\n",
);
let spacing =
"<w:spacing w:before=\"60\" w:after=\"120\" w:line=\"240\" w:lineRule=\"exact\"/>";
let out = apply("<w:styles><w:latentStyles/></w:styles>", &specs);
assert!(
out.starts_with(&format!(
"<w:styles><w:docDefaults><w:pPrDefault><w:pPr>{spacing}</w:pPr></w:pPrDefault>\
</w:docDefaults><w:latentStyles/>"
)),
"{out}"
);
let out = apply(
"<w:styles><w:docDefaults><w:rPrDefault><w:rPr/></w:rPrDefault></w:docDefaults></w:styles>",
&specs,
);
assert!(
out.contains(&format!(
"<w:rPrDefault><w:rPr/></w:rPrDefault><w:pPrDefault><w:pPr>{spacing}</w:pPr>\
</w:pPrDefault></w:docDefaults>"
)),
"{out}"
);
let out = apply(
"<w:styles><w:docDefaults><w:pPrDefault><w:pPr><w:widowControl/>\
<w:spacing w:after=\"160\" w:line=\"259\" w:lineRule=\"auto\"/><w:ind w:left=\"0\"/></w:pPr>\
</w:pPrDefault></w:docDefaults></w:styles>",
&specs,
);
assert_eq!(
paragraph_defaults(&out),
format!(
"<w:pPrDefault><w:pPr><w:widowControl/>{spacing}<w:ind w:left=\"0\"/></w:pPr></w:pPrDefault>"
),
"{out}"
);
let out = apply(
"<w:styles><w:docDefaults><w:pPrDefault><w:pPr><w:jc w:val=\"left\"/></w:pPr>\
</w:pPrDefault></w:docDefaults></w:styles>",
&specs,
);
assert_eq!(
paragraph_defaults(&out),
format!("<w:pPrDefault><w:pPr>{spacing}<w:jc w:val=\"left\"/></w:pPr></w:pPrDefault>"),
"{out}"
);
for empty in [
"<w:pPrDefault/>",
"<w:pPrDefault></w:pPrDefault>",
"<w:pPrDefault><w:pPr/></w:pPrDefault>",
] {
let out = apply(
&format!("<w:styles><w:docDefaults>{empty}</w:docDefaults></w:styles>"),
&specs,
);
assert_eq!(
paragraph_defaults(&out),
format!("<w:pPrDefault><w:pPr>{spacing}</w:pPr></w:pPrDefault>"),
"{out}"
);
}
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod branch_tests {
use super::*;
const W: &str = "xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"";
fn mark(id: Option<u32>) -> FormatMark {
FormatMark {
id,
author: "Ana".to_string(),
date: "2026-01-01T00:00:00Z".to_string(),
}
}
#[test]
fn style_changes_land_in_the_styles_own_properties() {
let styles = format!(
"<w:styles {W}><w:style w:styleId=\"A\"><w:pPr/><w:rPr><w:b/><w:rPrChange w:id=\"1\" w:author=\"Old\"><w:rPr/></w:rPrChange></w:rPr></w:style><w:style w:styleId=\"B\"><w:rPr><w:i/></w:rPr></w:style><w:style w:styleId=\"C\"><w:name w:val=\"C\"/></w:style><w:style w:styleId=\"Open\">"
);
let changes = vec![
(
"A".to_string(),
vec![
(StyleChangeKind::Paragraph, mark(Some(2))),
(StyleChangeKind::Run, mark(None)),
],
),
(
"B".to_string(),
vec![(StyleChangeKind::Paragraph, mark(Some(3)))],
),
("C".to_string(), vec![(StyleChangeKind::Run, mark(Some(4)))]),
("D".to_string(), vec![(StyleChangeKind::Run, mark(Some(5)))]),
(
"B".to_string(),
vec![(StyleChangeKind::Other, mark(Some(6)))],
),
(
"Open".to_string(),
vec![(StyleChangeKind::Run, mark(Some(7)))],
),
(
"docDefaults".to_string(),
vec![(StyleChangeKind::Run, mark(Some(8)))],
),
];
let out = with_style_changes(&styles, &changes);
assert!(
out.contains(
"<w:style w:styleId=\"A\"><w:pPr><w:pPrChange w:id=\"2\" w:author=\"Ana\""
),
"{out}"
);
assert!(!out.contains("Old"), "{out}");
assert!(
out.contains("<w:style w:styleId=\"B\"><w:pPr><w:pPrChange w:id=\"3\""),
"{out}"
);
assert!(
out.contains("<w:name w:val=\"C\"/><w:rPr><w:rPrChange w:id=\"4\""),
"{out}"
);
assert!(
!out.contains("w:id=\"5\"")
&& !out.contains("w:id=\"6\"")
&& !out.contains("w:id=\"7\"")
);
assert!(!out.contains("w:id=\"8\""));
}
#[test]
fn style_change_warnings_count_what_is_not_written() {
let changes = vec![
(
"docDefaults".to_string(),
vec![(StyleChangeKind::Run, mark(Some(1)))],
),
(
"docDefaults".to_string(),
vec![
(StyleChangeKind::Run, mark(Some(1))),
(StyleChangeKind::Paragraph, mark(Some(2))),
],
),
("docDefaults".to_string(), vec![]),
(
"A".to_string(),
vec![
(StyleChangeKind::Paragraph, mark(Some(1))),
(StyleChangeKind::Paragraph, mark(Some(2))),
(StyleChangeKind::Run, mark(Some(3))),
(StyleChangeKind::Run, mark(Some(4))),
(StyleChangeKind::Other, mark(Some(5))),
],
),
(
"B".to_string(),
vec![
(StyleChangeKind::Other, mark(Some(6))),
(StyleChangeKind::Other, mark(Some(7))),
],
),
];
let legacy = vec![
("A".to_string(), vec!["r1 @A".to_string()]),
(
"B".to_string(),
vec!["r2 @A".to_string(), "r3 @A".to_string()],
),
("C".to_string(), vec![]),
("docDefaults".to_string(), vec!["r4 @A".to_string()]),
];
assert_eq!(
style_change_warnings(&changes, &legacy),
[
"style_changes: A: r1 @A has no kind; written as rPr",
"style_changes: B: r2 @A; r3 @A have no kind; written as rPr",
"style_changes: docDefaults: the document defaults have no change slot; 1 change is not written",
"style_changes: docDefaults: the document defaults have no change slot; 2 changes are not written",
"style_changes: A: 2 pPr changes for one slot; the rest are not written",
"style_changes: A: 2 rPr changes for one slot; the rest are not written",
"style_changes: A: 1 other change is not written",
"style_changes: B: 2 other changes are not written",
]
);
}
#[test]
fn nested_property_elements_close_at_their_own_close() {
let block = "<w:style><w:pPr><w:jc/><w:pPrChange><w:pPr><w:ind/></w:pPr></w:pPrChange></w:pPr><w:rPr><w:b/></w:rPr>";
let ppr = own_ppr(block).expect("pPr");
assert_eq!(
&block[ppr.start..ppr.end],
"<w:pPr><w:jc/><w:pPrChange><w:pPr><w:ind/></w:pPr></w:pPrChange></w:pPr>"
);
let span = direct_child_span(block, &ppr, "pPrChange").expect("change");
assert!(block[span].starts_with("<w:pPrChange>"));
assert!(direct_child_span(block, &ppr, "missing").is_none());
assert!(open_tag("<w:pPrX/><w:pPr\t/>", "pPr", 0..18).is_some_and(|t| t.empty));
assert!(open_tag("<w:pPr", "pPr", 0..6).is_none());
assert!(close_at("<w:pPr>", "pPr", 7).is_none());
assert!(own("<w:pPr><w:b/>", "pPr", 0).is_none());
let open = own("<w:rPr><w:b/></w:rPr>", "rPr", 0).expect("rPr");
assert!(direct_child_span("<w:rPr><w:b/></w:rPr>", &open, "x").is_none());
let text = "<w:rPr>text</w:rPr>";
let open = own(text, "rPr", 0).expect("rPr");
assert!(direct_child_span(text, &open, "x").is_none());
}
#[test]
fn legend_values_refuse_what_word_cannot_hold() {
assert_eq!(points("2000pt", 20.0), None);
assert_eq!(points("-1pt", 20.0), None);
assert_eq!(points("NaNpt", 20.0), None);
assert_eq!(twips_in("infin"), None);
assert_eq!(twips_in("30in"), None);
assert_eq!(twips_in("-0.5in"), Some(-720));
assert_eq!(font_clause(" bold 11pt"), None);
assert_eq!(
font_clause("Arial bold italic 11pt"),
Some(("Arial".to_string(), true, true, 22))
);
for bad in [
"Arial 11pt, line 200",
"Arial 11pt, line NaN",
"Arial 11pt, line 12pt sometimes",
"Arial 11pt, sideways",
"Arial 11pt, tilt 3",
"Arial 11pt, before 9999pt",
] {
assert!(spec("S", None, false, bad).is_none(), "{bad}");
}
let good = spec("S", None, false, "character, Arial 11pt, line 12pt atLeast, right 0.5in, first-line 0.25in, hanging 0.1in, indent 1in, contextual spacing, keep-next, keep-lines, justify, named My S").expect("spec");
assert!(good.character && good.keep_next && good.keep_lines && good.contextual_spacing);
assert_eq!(good.align, Some("both"));
assert_eq!(good.name.as_deref(), Some("My S"));
assert_eq!(
without_comment("text: \"a # b\\\" c\" # note"),
"text: \"a # b\\\" c\" "
);
assert_eq!(unquote("\"bad"), None);
}
#[test]
fn table_legends_read_borders_names_and_stop_at_unknown_clauses() {
assert_eq!(
border_sides("borders top double 0.75pt #FF0000 space 4pt left single"),
Some(vec![
BorderSide {
side: "top".into(),
val: "double".into(),
size: Some(6),
color: Some("FF0000".into()),
space: Some(4)
},
BorderSide {
side: "left".into(),
val: "single".into(),
size: None,
color: None,
space: None
},
])
);
for bad in [
"borders middle single",
"borders top single top double",
"borders top s!ngle",
"borders top",
"borders top single 300pt",
"borders top single #FF00",
"borders top single #GGGGGG",
"borders top single space x",
"borders top single space",
"borders top single 1pt 2pt",
"borders top single wavy",
"frames top single",
] {
assert_eq!(border_sides(bad), None, "{bad}");
}
let yaml = "styles:\n table: Grid, all borders 1.5pt, named \"My, Grid\", borders vary # c\n tables: A, all borders 9pt, B, borders top single, named Bee, C, D, extra\nother:\n table: Ignored\n";
assert_eq!(
table_style(yaml),
Some((
"Grid".to_string(),
Some(TableBorders::All(12)),
Some("My, Grid".to_string())
))
);
assert_eq!(
table_style("styles:\n table: \"Q, named Z\"\n"),
Some(("Q".to_string(), None, Some("Z".to_string())))
);
let legend = table_legend(yaml);
let keys: Vec<&str> = legend.keys().map(String::as_str).collect();
assert_eq!(keys, ["A", "B", "C", "D", "all borders 9pt", "extra"]);
assert!(table_legend("styles:\n Normal: Arial 11pt\n").is_empty());
assert_eq!(table_style("styles:\n table: \"\"\n"), None);
assert_eq!(
take_clause("\"a, \\\"b\", c"),
("\"a, \\\"b\"".to_string(), "c")
);
}
#[test]
fn the_legend_skips_unreadable_keys_and_headings_out_of_range() {
let specs = legend(
"styles:\n no separator\n \"open: Arial 11pt\n \"#######\": Heading7, Arial 11pt\n \"#\": NoComma\n \"##\": Heading2, Arial bold 13pt\n changes: x\n Normal: Arial 11pt\n Body: Arial 10pt\nother:\n Skip: Arial 9pt\n",
);
let ids: Vec<(&str, bool, Option<u32>)> = specs
.iter()
.map(|s| (s.id.as_str(), s.default, s.heading))
.collect();
assert_eq!(
ids,
[
("Heading2", false, Some(2)),
("Normal", true, None),
("Body", false, None)
]
);
}
}