use f_office_xml::enumeration::{Values, another, own};
use f_office_xml::{Document, NodeId};
use f_office_units::Length;
use crate::body::{
AccentMark, BarMark, BarSide, BorderBoxFlags, CellJustification, Content, DEFAULT_ACCENT,
DEFAULT_GROUP_CHR, GapMinimum, GroupChrMark, GroupChrPlacement, GrownMark, LimitMark,
LimitSide, MathBoxMark, MatrixBase, MatrixMark, MatrixSettings, ROOT_SIGN, RadicalMark,
RowSpacing, Run, RunRecord, RunWrapper, ScriptMark, ScriptSide, SlashKind, SlashMark,
StackMark, read_wrapped,
};
use crate::ns::{M, W};
use crate::on_off;
use crate::props::{Alignment, FontRef, Limit, MathScript, MathStep, MathStyle, RunProps};
use crate::reader::PartReader;
use crate::text::OPERATOR_BREAK_SPACE;
use crate::warnings::Feature;
mod classes;
pub(crate) use classes::ordinary;
use classes::{OperatorClass, operator_class};
pub(crate) const MATH_FONT: &str = "Cambria Math";
pub(crate) const OPERATOR_SPACE: char = '\u{00A0}';
pub(crate) const HAIR_SPACE: char = '\u{200A}';
const RELATION_SPACE: [char; 2] = [OPERATOR_SPACE, HAIR_SPACE];
const THIN_SPACE: char = '\u{2009}';
const PRIME: char = '\u{2032}';
pub(crate) fn read(
reader: &mut PartReader,
node: NodeId,
(script, goes_on): (MathScript, bool),
runs: &mut Vec<Run>,
) {
let doc = reader.doc;
let script = script.with_small_frac(reader.small_frac());
if doc.is(node, M, "oMath") && goes_on {
walk(reader, node, script, runs);
} else if doc.is(node, M, "oMath") {
equation(reader, node, script, runs);
} else {
walk(reader, node, script, runs);
}
}
fn equation(reader: &mut PartReader, node: NodeId, script: MathScript, runs: &mut Vec<Run>) {
let mut own = Vec::new();
walk(reader, node, script, &mut own);
runs.extend(own);
}
fn ends_with_operand(runs: &[Run]) -> bool {
ends_with_operand_past(runs, |c| {
matches!(c, OPERATOR_SPACE | OPERATOR_BREAK_SPACE | HAIR_SPACE | BAR)
})
}
fn ends_with_operand_past_spaces(runs: &[Run]) -> bool {
ends_with_operand_past(runs, |c| {
matches!(
c,
OPERATOR_SPACE | OPERATOR_BREAK_SPACE | HAIR_SPACE | BAR | ' '
)
})
}
fn ends_with_operand_past(runs: &[Run], skipped: fn(char) -> bool) -> bool {
runs.iter()
.rev()
.flat_map(|run| run.content.iter().rev())
.find_map(|content| match content {
Content::Text(text) => text.chars().rev().find(|c| !skipped(*c)).map(ends_operand),
Content::Stack(mark) => Some(*mark == StackMark::End),
Content::Matrix(mark) => Some(*mark == MatrixMark::End),
Content::MathSlash(mark) => Some(*mark == SlashMark::End),
Content::MathLimit(mark) => Some(matches!(mark, LimitMark::End { operand: true })),
Content::GroupChr(mark) => Some(matches!(mark, GroupChrMark::End { operand: true })),
Content::MathBox(mark) => Some(*mark == MathBoxMark::BorderEnd),
Content::LineBreak => Some(false),
_ => None,
})
.unwrap_or(false)
}
const BAR: char = '|';
fn ends_operand(ch: char) -> bool {
!operator(ch) && !matches!(ch, '(' | '[' | '{' | '\u{27E8}')
}
fn ends_with_thin_space(runs: &[Run]) -> bool {
runs.iter()
.rev()
.flat_map(|run| run.content.iter().rev())
.find_map(|content| match content {
Content::Text(text) => text.chars().next_back(),
_ => None,
})
== Some(THIN_SPACE)
}
fn space_after_punctuation(
doc: &Document,
(child, name): (NodeId, &str),
script: MathScript,
runs: &mut [Run],
) {
let next = match name {
"r" => doc
.child_elements(child)
.filter(|t| doc.is(*t, M, "t"))
.find_map(|t| doc.text_content(t).chars().next()),
"nary" | "eqArr" => None,
_ if STRUCTURES.contains(&name) => Some('x'),
_ => None,
};
let Some(next) = next.filter(|&c| c != ' ' && !operator(c)) else {
return;
};
if script.style() >= MathStyle::Script {
return;
}
let Some(Content::Text(text)) = runs.last_mut().and_then(|run| run.content.last_mut()) else {
return;
};
let mut ends = text.chars().rev();
let (Some(mark), before) = (ends.next(), ends.next()) else {
return;
};
let spaced = SPACED_MARKS.contains(&mark) || ELLIPSES.contains(&mark);
if spaced && !decimal(before, mark, next) {
text.push(THIN_SPACE);
}
}
const SPACED_MARKS: [char; 9] = [
',', ';', ':', '.', '?', '!', '\u{203C}', '\u{00A1}', '\u{00BF}',
];
fn decimal(before: Option<char>, mark: char, next: char) -> bool {
matches!(mark, ',' | '.') && before.is_some_and(|c| c.is_ascii_digit()) && next.is_ascii_digit()
}
pub fn is_display(doc: &Document, paragraph: NodeId) -> bool {
doc.child(paragraph, M, "oMathPara").is_some()
}
pub(crate) fn display_alignment(reader: &mut PartReader, paragraph: NodeId) -> Alignment {
let doc = reader.doc;
doc.child(paragraph, M, "oMathPara")
.and_then(|display| doc.child(display, M, "oMathParaPr"))
.and_then(|props| doc.child(props, M, "jc"))
.and_then(|jc| reader.enumeration_in(jc, (Some(M), "val"), DISPLAY_JUSTIFICATION))
.unwrap_or(Alignment::Center)
}
const DISPLAY_JUSTIFICATION: &Values<Alignment> = &Values::new(&[
own("left", Alignment::Start),
own("right", Alignment::End),
own("center", Alignment::Center),
another("centerGroup", Alignment::Center),
]);
pub fn holds_only_equations(doc: &Document, paragraph: NodeId) -> bool {
let mut equations = 0;
for child in doc.child_elements(paragraph) {
if doc.is(child, M, "oMath") {
equations += 1;
} else if !no_content(doc, child) {
return false;
}
}
equations > 0
}
fn no_content(doc: &Document, child: NodeId) -> bool {
doc.is(child, W, "pPr")
|| doc.is(child, W, "bookmarkStart")
|| doc.is(child, W, "bookmarkEnd")
|| (doc.is(child, W, "r") && doc.child_elements(child).all(|c| doc.is(c, W, "rPr")))
}
const STRUCTURES: [&str; 19] = [
"acc",
"bar",
"borderBox",
"box",
"d",
"eqArr",
"f",
"func",
"groupChr",
"limLow",
"limUpp",
"m",
"nary",
"phant",
"rad",
"sPre",
"sSub",
"sSubSup",
"sSup",
];
#[derive(Clone, Copy)]
enum EquationSize {
None,
Inherited(Option<i64>),
}
fn entered(
reader: &mut PartReader,
(child, name, eq_size): (NodeId, &str, EquationSize),
outer: MathScript,
) -> MathScript {
let doc = reader.doc;
if !STRUCTURES.contains(&name) {
return outer;
}
let size = if outer.in_no_structure()
&& let EquationSize::Inherited(size) = eq_size
{
size
} else {
let settings = doc.child(child, M, &format!("{name}Pr"));
control_size(reader, settings)
};
outer.in_structure(size)
}
fn equation_size(reader: &mut PartReader, node: NodeId, children: &[NodeId]) -> EquationSize {
let doc = reader.doc;
if !doc.is(node, M, "oMath") {
return EquationSize::None;
}
let Some(first) = children.iter().copied().find(|&child| {
let name = doc.element(child).map_or("", |e| e.name.local);
if !doc.is(child, M, name) {
return false;
}
if name == "r" {
doc.child_elements(child)
.any(|t| doc.is(t, M, "t") && !doc.text_content(t).is_empty())
} else {
STRUCTURES.contains(&name)
}
}) else {
return EquationSize::None;
};
let name = doc.element(first).map_or("", |e| e.name.local);
let size = if name == "r" {
doc.child(first, W, "rPr")
.and_then(|rpr| RunProps::read(reader, rpr).size)
} else {
let settings = doc.child(first, M, &format!("{name}Pr"));
control_size(reader, settings)
};
EquationSize::Inherited(size)
}
fn walk(reader: &mut PartReader, node: NodeId, outer: MathScript, runs: &mut Vec<Run>) {
walk_in(reader, (node, None), outer, runs);
}
fn walk_in(
reader: &mut PartReader,
(node, enclosing): (NodeId, Option<Fences>),
outer: MathScript,
runs: &mut Vec<Run>,
) {
let doc = reader.doc;
let local = |n: NodeId| doc.element(n).map_or("", |e| e.name.local);
let mut equations = 0;
let children: Vec<NodeId> = doc.child_elements(node).collect();
let eq_size = if outer.in_no_structure() {
equation_size(reader, node, &children)
} else {
EquationSize::None
};
for (index, &child) in children.iter().enumerate() {
if !doc.is(child, M, local(child)) {
outside_math(reader, child, outer, runs);
continue;
}
let name = local(child);
space_after_punctuation(doc, (child, name), outer, runs);
let script = entered(reader, (child, name, eq_size), outer);
match name {
"r" => {
let rest = children.get(index..).unwrap_or(&[]);
grown_space_after(reader, rest, script, runs);
let operand = ends_with_operand(runs);
let followed = followed(doc, children.get(index + 1..).unwrap_or(&[]));
runs.extend(math_run(reader, child, script, (operand, followed)));
}
"sSup" | "sSub" | "sPre" => {
let rest = children.get(index + 1..).unwrap_or(&[]);
script_structure(reader, child, (script, rest), runs);
}
"f" => {
let rest = children.get(index + 1..).unwrap_or(&[]);
fraction(reader, child, (script, rest), runs);
}
"m" => matrix(reader, child, script, runs),
"sSubSup" => {
let rest = children.get(index + 1..).unwrap_or(&[]);
sub_superscript(reader, child, (script, rest), runs);
}
"d" => {
let nested =
enclosing.is_some_and(|outer| beside_same(doc, (&children, index), outer));
delimiter_in(reader, (child, nested), script, runs);
}
"nary" => nary(reader, child, script, runs),
"func" => function(reader, child, script, runs),
"phant" => phantom(reader, child, script, runs),
"rad" => {
let rest = children.get(index + 1..).unwrap_or(&[]);
radical(reader, child, (script, rest), runs);
}
"acc" => accent(reader, child, script, runs),
"bar" => {
let rest = children.get(index + 1..).unwrap_or(&[]);
bar(reader, child, (script, rest), runs);
}
"borderBox" => {
let rest = children.get(index + 1..).unwrap_or(&[]);
border_box(reader, child, (script, rest), runs);
}
"groupChr" => {
let rest = children.get(index + 1..).unwrap_or(&[]);
group_chr(reader, child, (script, rest), runs);
}
"limLow" => {
let is_followed = followed(doc, children.get(index + 1..).unwrap_or(&[]));
limit_structure(reader, child, LimitSide::Lower, (script, is_followed), runs);
}
"limUpp" => {
let is_followed = followed(doc, children.get(index + 1..).unwrap_or(&[]));
limit_structure(reader, child, LimitSide::Upper, (script, is_followed), runs);
}
"eqArr" => equation_array(reader, child, script, runs),
"box" if !laid_out_otherwise(doc, child, name) => {
let mut inner = Vec::new();
walk(reader, child, script, &mut inner);
runs.extend(inner);
}
"oMath" => {
if equations > 0 {
runs.push(text_run(Content::LineBreak, script));
}
equations += 1;
equation(reader, child, script, runs);
}
name if name.ends_with("Pr") => {}
_ => {
warn_of_a_row(reader, child, name);
walk(reader, child, script, runs);
}
}
}
}
fn outside_math(reader: &mut PartReader, node: NodeId, script: MathScript, runs: &mut Vec<Run>) {
let doc = reader.doc;
let local = doc.element(node).map_or("", |e| e.name.local);
let in_w = doc.is(node, W, local);
match RunWrapper::of(local) {
Some(wrapper) if in_w => {
read_wrapped(doc, node, wrapper, runs, |runs| {
walk(reader, node, script, runs);
});
}
_ if (in_w && draws_nothing(local)) || doc.children(node).is_empty() => {}
_ => reader.feature_not_supported(Feature::MathElement),
}
}
fn draws_nothing(local: &str) -> bool {
matches!(
local,
"sdtPr" | "sdtEndPr" | "customXmlPr" | "smartTagPr" | "proofErr" | "permStart" | "permEnd"
) || ["Start", "End"].iter().any(|end| {
local
.strip_suffix(end)
.is_some_and(|start| start == "bookmark" || start.ends_with("Range"))
})
}
fn warn_of_a_row(reader: &mut PartReader, node: NodeId, name: &str) {
if STRUCTURES.contains(&name) && laid_out_otherwise(reader.doc, node, name) {
reader.feature_not_supported(Feature::MathStructure);
}
}
fn laid_out_otherwise(doc: &Document, node: NodeId, name: &str) -> bool {
match name {
"box" => {
let props = doc.child(node, M, "boxPr");
flag(doc, props, "opEmu").unwrap_or(false)
|| props.and_then(|props| doc.child(props, M, "brk")).is_some()
}
_ => true,
}
}
fn border_box(
reader: &mut PartReader,
node: NodeId,
(script, rest): (MathScript, &[NodeId]),
runs: &mut Vec<Run>,
) {
let doc = reader.doc;
let settings = doc.child(node, M, "borderBoxPr");
let flags = border_box_flags(doc, settings);
let content = doc.child(node, M, "e");
if flags.is_empty() {
if let Some(content) = content {
let mut inner = Vec::new();
walk(reader, content, script, &mut inner);
runs.extend(inner);
}
return;
}
fraction_space_before_base(reader, (node, settings), script, runs);
let mark = structure_mark(reader, settings, script);
runs.push(mark(Content::MathBox(MathBoxMark::BorderStart(flags))));
if let Some(content) = content {
walk(reader, content, script, runs);
}
runs.push(mark(Content::MathBox(MathBoxMark::BorderEnd)));
fraction_space_after_base(reader, (node, settings), (script, rest), runs);
}
fn border_box_flags(doc: &Document, settings: Option<NodeId>) -> BorderBoxFlags {
let on = |name: &str| flag(doc, settings, name).unwrap_or(false);
let mut flags = BorderBoxFlags::EMPTY;
for (name, bit) in [
("hideTop", BorderBoxFlags::TOP),
("hideBot", BorderBoxFlags::BOTTOM),
("hideLeft", BorderBoxFlags::LEFT),
("hideRight", BorderBoxFlags::RIGHT),
] {
if !on(name) {
flags = flags.with(bit);
}
}
for (name, bit) in [
("strikeH", BorderBoxFlags::STRIKE_H),
("strikeV", BorderBoxFlags::STRIKE_V),
("strikeBLTR", BorderBoxFlags::STRIKE_BLTR),
("strikeTLBR", BorderBoxFlags::STRIKE_TLBR),
] {
if on(name) {
flags = flags.with(bit);
}
}
flags
}
fn function(reader: &mut PartReader, node: NodeId, script: MathScript, runs: &mut Vec<Run>) {
let doc = reader.doc;
if let Some(name) = doc.child(node, M, "fName") {
walk(reader, name, script, runs);
}
let Some(argument) = doc.child(node, M, "e") else {
return;
};
let delimited = doc
.child_elements(argument)
.find(|n| {
!doc.element(*n)
.is_some_and(|e| e.name.local.ends_with("Pr"))
})
.is_some_and(|first| {
doc.is(first, M, "d")
|| (doc.is(first, M, "r")
&& doc
.child_elements(first)
.filter(|t| doc.is(*t, M, "t"))
.find_map(|t| doc.text_content(t).chars().next())
.is_some_and(|ch| matches!(ch, '(' | '[' | '{' | '\u{27E8}')))
});
if !delimited {
let settings = doc.child(node, M, "funcPr");
runs.push(control_symbol(
reader,
settings,
&THIN_SPACE.to_string(),
script,
));
}
let mut arg = Vec::new();
walk(reader, argument, script, &mut arg);
runs.extend(arg);
}
fn flag(doc: &Document, props: Option<NodeId>, name: &str) -> Option<bool> {
let setting = props.and_then(|p| doc.child(p, M, name))?;
Some(on_off::element(doc, setting, M))
}
fn phantom(reader: &mut PartReader, node: NodeId, script: MathScript, runs: &mut Vec<Run>) {
let doc = reader.doc;
let start = runs.len();
if let Some(content) = doc.child(node, M, "e") {
walk(reader, content, script, runs);
}
let props = doc.child(node, M, "phantPr");
if flag(doc, props, "show").unwrap_or(true) {
return;
}
let no_width = flag(doc, props, "zeroWid").unwrap_or(false);
for run in runs.iter_mut().skip(start) {
if no_width {
run.props.hidden = Some(true);
} else {
run.props.phantom = Some(true);
}
}
}
fn radical(
reader: &mut PartReader,
node: NodeId,
(script, rest): (MathScript, &[NodeId]),
runs: &mut Vec<Run>,
) {
let doc = reader.doc;
let settings = doc.child(node, M, "radPr");
let degree = doc
.child(node, M, "deg")
.filter(|_| !flag(doc, settings, "degHide").unwrap_or(false))
.filter(|deg| doc.child_elements(*deg).any(|n| !doc.is(n, M, "ctrlPr")));
let mark = structure_mark(reader, settings, script);
let step = steps_in(reader, settings, script);
runs.push(mark(Content::Radical(RadicalMark::Start {
degree: degree.is_some(),
})));
if let Some(degree) = degree {
walk(reader, degree, step(MathStep::Degree), runs);
}
let mut sign = control_symbol(reader, settings, &ROOT_SIGN.to_string(), script);
sign.content.insert(0, Content::Radical(RadicalMark::Sign));
runs.push(sign);
runs.push(mark(Content::Radical(RadicalMark::Element)));
if let Some(element) = doc.child(node, M, "e") {
walk(reader, element, script.cramped(), runs);
}
runs.push(mark(Content::Radical(RadicalMark::End)));
fraction_space_after_base(reader, (node, settings), (script, rest), runs);
}
fn accent(reader: &mut PartReader, node: NodeId, script: MathScript, runs: &mut Vec<Run>) {
let doc = reader.doc;
let settings = doc.child(node, M, "accPr");
let character = settings
.and_then(|props| doc.child(props, M, "chr"))
.map_or_else(
|| DEFAULT_ACCENT.to_string(),
|chr| doc.attribute(chr, Some(M), "val").unwrap_or("").to_owned(),
);
let base = doc.child(node, M, "e");
if character.is_empty() {
if let Some(base) = base {
walk(reader, base, script, runs);
}
return;
}
let mark = structure_mark(reader, settings, script);
runs.push(mark(Content::Accent(AccentMark::Start)));
if let Some(base) = base {
walk(reader, base, script.cramped(), runs);
}
let mut glyph = control_symbol(reader, settings, &character, script);
glyph
.content
.insert(0, Content::Accent(AccentMark::Character));
runs.push(glyph);
runs.push(mark(Content::Accent(AccentMark::End)));
}
fn delimiter(reader: &mut PartReader, node: NodeId, script: MathScript, runs: &mut Vec<Run>) {
let doc = reader.doc;
let props = doc.child(node, M, "dPr");
let character = |name: &str, default: &str| -> String {
props
.and_then(|p| doc.child(p, M, name))
.and_then(|c| doc.attribute(c, Some(M), "val"))
.unwrap_or(default)
.to_owned()
};
let (open, separator, close) = (
character("begChr", "("),
character("sepChr", "|"),
character("endChr", ")"),
);
let elements: Vec<NodeId> = doc
.child_elements(node)
.filter(|n| doc.is(*n, M, "e"))
.collect();
let elem_script = if elements.len() > 1 {
script.in_text_style()
} else {
script
};
let base = !flag(doc, props, "grow").unwrap_or(true)
|| (elements.iter().all(|&e| line_high(doc, e)) && !nests(doc, node));
let enclosing = (!base).then(|| fences(doc, node));
let glyph = |reader: &mut PartReader, text: &str| {
let mut run = control_symbol(reader, props, text, script);
run.props.size = script.outermost_size();
if let Some(ch) = text.chars().next() {
if base {
if !SPACED_MARKS.contains(&ch) {
run.props.math_script = Some(script.without_outermost().on_axis(ch));
}
} else {
run.content
.insert(0, Content::Grown(GrownMark::Character(ch)));
}
}
run
};
if !base {
if script.style() < MathStyle::Script
&& ends_with_operand_past_spaces(runs)
&& !ends_with_thin_space(runs)
{
let mut space = control_symbol(reader, props, &THIN_SPACE.to_string(), script);
space.props.size = script.outermost_size();
space.content.push(Content::Grown(GrownMark::SpaceBefore));
runs.push(space);
}
runs.push(text_run(Content::Grown(GrownMark::Start), script));
}
runs.push(glyph(reader, &open));
let mut prev = None;
for e in elements {
if let Some(previous) = prev {
push_delimiter_separator(
reader,
(props, previous, &separator),
(elem_script, script),
&glyph,
runs,
);
}
if prev.is_some() && separator.is_empty() {
let mut part = Vec::new();
walk_in(reader, (e, enclosing), elem_script, &mut part);
runs.extend(part);
} else {
walk_in(reader, (e, enclosing), elem_script, runs);
}
prev = Some(e);
}
runs.push(glyph(reader, &close));
if !base {
let mut end = text_run(Content::Grown(GrownMark::End), script);
end.props.size = script.outermost_size();
runs.push(end);
}
}
fn push_delimiter_separator(
reader: &mut PartReader,
(props, previous, separator): (Option<NodeId>, NodeId, &str),
(elem_script, script): (MathScript, MathScript),
glyph: &impl Fn(&mut PartReader, &str) -> Run,
runs: &mut Vec<Run>,
) {
let Some(sep_ch) = separator.chars().next() else {
return;
};
if elem_script.style() < MathStyle::Script
&& !is_close_fence(sep_ch)
&& !ends_with_thin_space(runs)
&& element_takes_space_before_sep(reader.doc, previous, runs)
{
let mut space = control_symbol(reader, props, &THIN_SPACE.to_string(), elem_script);
space.props.size = script.outermost_size();
runs.push(space);
}
runs.push(glyph(reader, separator));
}
fn element_takes_space_before_sep(doc: &Document, element: NodeId, runs: &[Run]) -> bool {
let last = doc
.child_elements(element)
.filter(|&child| {
let name = doc.element(child).map_or("", |e| e.name.local);
doc.is(child, M, name)
&& !name.ends_with("Pr")
&& (name != "r" || first_non_space_char(doc, child).is_some())
})
.last();
let Some(last) = last else {
return false;
};
match doc.element(last).map_or("", |e| e.name.local) {
"f" | "nary" => true,
"sSup" | "sSub" | "sSubSup" | "sPre" | "bar" | "borderBox" | "groupChr" | "rad" => {
base_ends_with_fraction(doc, last)
}
"d" => runs
.iter()
.rev()
.flat_map(|run| run.content.iter().rev())
.find_map(|content| match content {
Content::Grown(GrownMark::End) => Some(true),
Content::Text(text) if text.is_empty() => None,
_ => Some(false),
})
.unwrap_or(false),
_ => false,
}
}
fn delimiter_in(
reader: &mut PartReader,
(node, nested): (NodeId, bool),
script: MathScript,
runs: &mut Vec<Run>,
) {
let first = runs.len();
delimiter(reader, node, script, runs);
if !nested {
return;
}
if let Some(run) = runs.get_mut(first) {
run.content
.insert(0, Content::Grown(GrownMark::NestedStart));
}
if let Some(run) = runs.last_mut() {
run.content.push(Content::Grown(GrownMark::NestedEnd));
}
}
type Fences<'a> = (&'a str, &'a str);
fn fences(doc: &Document, node: NodeId) -> Fences<'_> {
let character = |name: &str, default: &'static str| {
doc.child(node, M, "dPr")
.and_then(|props| doc.child(props, M, name))
.and_then(|c| doc.attribute(c, Some(M), "val"))
.unwrap_or(default)
};
(character("begChr", "("), character("endChr", ")"))
}
fn nests(doc: &Document, node: NodeId) -> bool {
let outer = fences(doc, node);
doc.child_elements(node)
.filter(|n| doc.is(*n, M, "e"))
.any(|e| {
let children: Vec<NodeId> = doc.child_elements(e).collect();
children.iter().enumerate().any(|(index, &child)| {
doc.is(child, M, "d") && beside_same(doc, (&children, index), outer)
})
})
}
fn beside_same(doc: &Document, (children, index): (&[NodeId], usize), outer: Fences) -> bool {
let Some(&node) = children.get(index) else {
return false;
};
let inner = fences(doc, node);
let properties = |nodes: &[NodeId]| {
nodes
.iter()
.all(|&n| doc.element(n).is_some_and(|e| e.name.local.ends_with("Pr")))
};
(!outer.0.is_empty() && inner.0 == outer.0 && properties(children.get(..index).unwrap_or(&[])))
|| (!outer.1.is_empty()
&& inner.1 == outer.1
&& properties(children.get(index + 1..).unwrap_or(&[])))
}
fn grown_space_after(
reader: &mut PartReader,
rest: &[NodeId],
script: MathScript,
runs: &mut Vec<Run>,
) {
let doc = reader.doc;
let Some(end) = runs
.last()
.filter(|run| run.content.contains(&Content::Grown(GrownMark::End)))
else {
return;
};
let size = end.props.size;
let first = rest
.iter()
.take_while(|node| doc.is(**node, M, "r"))
.flat_map(|node| doc.child_elements(*node))
.filter(|t| doc.is(*t, M, "t"))
.find_map(|t| doc.text_content(t).chars().find(|c| *c != ' '));
let operand = first.is_some_and(|ch| {
ends_operand(ch) && !matches!(ch, ')' | ']' | '}' | '\u{27E9}' | BAR) && !ch.is_whitespace()
});
if operand && script.style() < MathStyle::Script {
let mut space = symbol(&THIN_SPACE.to_string(), script);
space.props.size = size;
space.content.push(Content::Grown(GrownMark::SpaceAfter));
runs.push(space);
}
}
fn line_high(doc: &Document, node: NodeId) -> bool {
doc.child_elements(node).all(|child| {
let name = doc.element(child).map_or("", |e| e.name.local);
if !doc.is(child, M, name) || name == "r" || name.ends_with("Pr") {
return true;
}
matches!(name, "d" | "func" | "e" | "fName")
&& line_high(doc, child)
&& !(name == "d" && nests(doc, child))
})
}
fn nary(reader: &mut PartReader, node: NodeId, script: MathScript, runs: &mut Vec<Run>) {
let doc = reader.doc;
let props = doc.child(node, M, "naryPr");
let operator = props
.and_then(|p| doc.child(p, M, "chr"))
.and_then(|c| doc.attribute(c, Some(M), "val"))
.unwrap_or("\u{222B}");
if script.style() < MathStyle::Script && ends_with_operand(runs) && !ends_with_thin_space(runs)
{
runs.push(control_symbol(
reader,
props,
&THIN_SPACE.to_string(),
script,
));
}
let limit = |hide: &str, name: &str| {
doc.child(node, M, name)
.filter(|_| !flag(doc, props, hide).unwrap_or(false))
};
let limits = (limit("subHide", "sub"), limit("supHide", "sup"));
let outermost = script.style() == MathStyle::Display;
let bare = limits.0.is_none() && limits.1.is_none();
if outermost && bare {
runs.push(large_operator(reader, props, operator, script));
} else if outermost && over_and_under(reader, props, operator) {
limits_over_and_under(reader, props, operator, limits, script, runs);
} else if outermost {
limits_beside(reader, props, operator, limits, script, runs);
} else {
let mut symbol = control_symbol(reader, props, operator, script);
if let Some(ch) = operator.chars().next() {
symbol.props.math_script = Some(script.without_outermost().on_axis(ch));
}
runs.push(symbol);
let drops = integral(operator);
scripts(
reader,
props,
limits,
(script, Marks::Operator { drops }, false),
runs,
);
}
let Some(element) = doc.child(node, M, "e") else {
return;
};
let content = doc
.child_elements(element)
.any(|n| !doc.element(n).is_some_and(|e| e.name.local.ends_with("Pr")));
if content {
runs.push(control_symbol(
reader,
props,
&THIN_SPACE.to_string(),
script,
));
}
walk(reader, element, script, runs);
}
fn over_and_under(reader: &mut PartReader, props: Option<NodeId>, operator: &str) -> bool {
let doc = reader.doc;
let location = props
.and_then(|p| doc.child(p, M, "limLoc"))
.and_then(|l| reader.enumeration_or(l, (Some(M), "val"), LIMIT_LOCATION, "subSup"));
match location {
Some(over) => over,
None => !integral(operator),
}
}
fn integral(operator: &str) -> bool {
operator
.chars()
.next()
.is_some_and(|c| matches!(c, '\u{222B}'..='\u{2233}' | '\u{2A0B}'..='\u{2A1C}'))
}
const LIMIT_LOCATION: &Values<bool> = &Values::new(&[own("undOvr", true), own("subSup", false)]);
fn limits_over_and_under(
reader: &mut PartReader,
settings: Option<NodeId>,
operator: &str,
(sub, sup): (Option<NodeId>, Option<NodeId>),
script: MathScript,
runs: &mut Vec<Run>,
) {
let limit = Limit {
operator: operator.chars().next().unwrap_or('\u{2211}'),
beside: false,
};
let mark = stack_mark(reader, settings, script);
let step = steps_in(reader, settings, script);
let start = StackMark::Start {
bar: None,
centered: true,
};
runs.push(mark(start));
runs.push(mark(start));
if let Some(sup) = sup {
walk(reader, sup, step(MathStep::UpperLimit(limit)), runs);
}
runs.push(mark(StackMark::Middle));
runs.push(large_operator(reader, settings, operator, script));
runs.push(mark(StackMark::End));
runs.push(mark(StackMark::Middle));
if let Some(sub) = sub {
walk(reader, sub, step(MathStep::LowerLimit(limit)), runs);
}
runs.push(mark(StackMark::End));
}
fn limits_beside(
reader: &mut PartReader,
settings: Option<NodeId>,
operator: &str,
(sub, sup): (Option<NodeId>, Option<NodeId>),
script: MathScript,
runs: &mut Vec<Run>,
) {
let limit = Limit {
operator: operator.chars().next().unwrap_or('\u{222B}'),
beside: true,
};
let mark = stack_mark(reader, settings, script);
let step = steps_in(reader, settings, script);
runs.push(large_operator(reader, settings, operator, script));
runs.push(mark(StackMark::StartBeside(limit.operator)));
if let Some(sub) = sub {
walk(reader, sub, step(MathStep::LowerLimit(limit)), runs);
}
runs.push(mark(StackMark::Middle));
if let Some(sup) = sup {
walk(reader, sup, step(MathStep::UpperLimit(limit)), runs);
}
runs.push(mark(StackMark::End));
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FractionKind {
Bar,
NoBar,
Linear,
Skewed,
}
const FRACTION_KIND: &Values<FractionKind> = &Values::new(&[
own("bar", FractionKind::Bar),
own("skw", FractionKind::Skewed),
own("lin", FractionKind::Linear),
own("noBar", FractionKind::NoBar),
]);
const FRACTION_SLASH: &str = "\u{2044}";
fn fraction(
reader: &mut PartReader,
node: NodeId,
(script, rest): (MathScript, &[NodeId]),
runs: &mut Vec<Run>,
) {
let doc = reader.doc;
let settings = doc.child(node, M, "fPr");
let kind = settings
.and_then(|p| doc.child(p, M, "type"))
.and_then(|t| reader.enumeration_or(t, (Some(M), "val"), FRACTION_KIND, "lin"))
.unwrap_or(FractionKind::Bar);
if script.style() < MathStyle::Script && needs_fraction_space_before(runs) {
runs.push(control_symbol(
reader,
settings,
&THIN_SPACE.to_string(),
script,
));
}
match kind {
FractionKind::Bar => stacked_fraction(reader, (node, settings), true, script, runs),
FractionKind::NoBar => stacked_fraction(reader, (node, settings), false, script, runs),
FractionKind::Linear => {
slashed_fraction(reader, (node, settings), SlashKind::Linear, script, runs);
}
FractionKind::Skewed => {
slashed_fraction(reader, (node, settings), SlashKind::Skewed, script, runs);
}
}
if script.style() < MathStyle::Script && needs_fraction_space_after(reader, rest) {
runs.push(control_symbol(
reader,
settings,
&THIN_SPACE.to_string(),
script,
));
}
}
fn stacked_fraction(
reader: &mut PartReader,
(node, settings): (NodeId, Option<NodeId>),
drawn_bar: bool,
script: MathScript,
runs: &mut Vec<Run>,
) {
let doc = reader.doc;
let minimum = if script.style() == MathStyle::Display {
GapMinimum::Display
} else {
GapMinimum::Line
};
let bar = drawn_bar.then_some(minimum);
let mark = stack_mark(reader, settings, script);
let step = steps_in(reader, settings, script);
runs.push(mark(StackMark::Start {
bar,
centered: true,
}));
if let Some(numerator) = doc.child(node, M, "num") {
walk(reader, numerator, step(MathStep::Numerator), runs);
}
runs.push(mark(StackMark::Middle));
if let Some(denominator) = doc.child(node, M, "den") {
walk(reader, denominator, step(MathStep::Denominator), runs);
}
runs.push(mark(StackMark::End));
}
fn is_open_fence(ch: char) -> bool {
matches!(
ch,
'(' | '['
| '{'
| '\u{27E8}'
| '\u{2308}'
| '\u{230A}'
| '\u{27E6}'
| '\u{27EA}'
| '\u{2016}'
)
}
fn is_close_fence(ch: char) -> bool {
matches!(
ch,
')' | ']'
| '}'
| '\u{27E9}'
| '\u{2309}'
| '\u{230B}'
| '\u{27E7}'
| '\u{27EB}'
| '\u{2016}'
)
}
fn needs_fraction_space_before(runs: &[Run]) -> bool {
runs.iter()
.rev()
.flat_map(|run| run.content.iter().rev())
.find_map(fraction_space_after_content)
.unwrap_or(false)
}
fn fraction_space_after_content(content: &Content) -> Option<bool> {
match content {
Content::Text(text) => text
.chars()
.rev()
.find(|&c| c != ' ')
.map(fraction_space_after_char),
Content::Stack(mark) => Some(*mark == StackMark::End),
Content::Matrix(mark) => Some(*mark == MatrixMark::End),
Content::MathSlash(mark) => Some(*mark == SlashMark::End),
Content::MathLimit(mark) => Some(matches!(mark, LimitMark::End { operand: true })),
Content::GroupChr(mark) => Some(matches!(mark, GroupChrMark::End { operand: true })),
Content::MathBox(mark) => Some(*mark == MathBoxMark::BorderEnd),
Content::Radical(mark) => Some(*mark == RadicalMark::End),
Content::Accent(mark) => Some(*mark == AccentMark::End),
Content::MathBar(mark) => Some(*mark == BarMark::End),
Content::Grown(GrownMark::End) => Some(true),
Content::Grown(GrownMark::Start) | Content::LineBreak => Some(false),
_ => None,
}
}
fn fraction_space_after_char(ch: char) -> bool {
!matches!(
ch,
THIN_SPACE | OPERATOR_SPACE | OPERATOR_BREAK_SPACE | HAIR_SPACE
) && !is_open_fence(ch)
&& !leads(ch)
}
fn needs_fraction_space_after(reader: &mut PartReader, rest: &[NodeId]) -> bool {
let doc = reader.doc;
for (pos, &node) in rest.iter().enumerate() {
let name = doc.element(node).map_or("", |e| e.name.local);
if !doc.is(node, M, name) || name.ends_with("Pr") {
continue;
}
if name == "r" {
if let Some((ch, more_in_run)) = first_non_space_char(doc, node) {
let tail = rest.get(pos + 1..).unwrap_or(&[]);
return fraction_space_before_run_char(doc, (node, tail), (ch, more_in_run));
}
continue;
}
return fraction_space_before_structure(reader, node, name);
}
false
}
fn first_non_space_char(doc: &Document, run: NodeId) -> Option<(char, bool)> {
let mut first = None;
for t in doc.child_elements(run).filter(|&t| doc.is(t, M, "t")) {
for ch in doc.text_content(t).chars().filter(|&c| c != ' ') {
if let Some(prev) = first {
return Some((prev, true));
}
first = Some(ch);
}
}
first.map(|ch| (ch, false))
}
fn fraction_space_before_run_char(
doc: &Document,
(run, tail): (NodeId, &[NodeId]),
(ch, more_in_run): (char, bool),
) -> bool {
if is_close_fence(ch) || ch.is_whitespace() {
return false;
}
if SPACED_MARKS.contains(&ch) && !more_in_run && !has_non_space_content(doc, tail) {
return false;
}
let normal = doc
.child(run, M, "rPr")
.and_then(|p| doc.child(p, M, "nor"))
.is_some();
if normal {
return true;
}
let shown = shown(ch);
!operator(shown) && !ELLIPSES.contains(&shown)
}
fn has_non_space_content(doc: &Document, rest: &[NodeId]) -> bool {
rest.iter().any(|&node| {
let name = doc.element(node).map_or("", |e| e.name.local);
if !doc.is(node, M, name) || name.ends_with("Pr") {
return false;
}
name != "r" || first_non_space_char(doc, node).is_some()
})
}
fn fraction_space_before_structure(reader: &mut PartReader, node: NodeId, name: &str) -> bool {
let doc = reader.doc;
match name {
"f" | "nary" | "eqArr" => false,
"limLow" | "limUpp" => doc
.child(node, M, "e")
.and_then(|base| single_operator_base(reader, base))
.is_none(),
"groupChr" => {
let settings = doc.child(node, M, "groupChrPr");
group_chr_operator(reader, settings).is_none()
}
_ => STRUCTURES.contains(&name),
}
}
fn base_edge_is_fraction(doc: &Document, node: NodeId, last: bool) -> bool {
let Some(base) = doc.child(node, M, "e") else {
return false;
};
let mut drawing = doc.child_elements(base).filter(|&child| {
let name = doc.element(child).map_or("", |e| e.name.local);
doc.is(child, M, name)
&& !name.ends_with("Pr")
&& (name != "r" || first_non_space_char(doc, child).is_some())
});
let edge = if last { drawing.last() } else { drawing.next() };
edge.is_some_and(|child| doc.is(child, M, "f"))
}
fn base_starts_with_fraction(doc: &Document, node: NodeId) -> bool {
base_edge_is_fraction(doc, node, false)
}
fn base_ends_with_fraction(doc: &Document, node: NodeId) -> bool {
base_edge_is_fraction(doc, node, true)
}
fn fraction_space_before_base(
reader: &mut PartReader,
(node, settings): (NodeId, Option<NodeId>),
script: MathScript,
runs: &mut Vec<Run>,
) {
if script.style() < MathStyle::Script
&& base_starts_with_fraction(reader.doc, node)
&& needs_fraction_space_before(runs)
{
runs.push(control_symbol(
reader,
settings,
&THIN_SPACE.to_string(),
script,
));
}
}
fn fraction_space_after_base(
reader: &mut PartReader,
(node, settings): (NodeId, Option<NodeId>),
(script, rest): (MathScript, &[NodeId]),
runs: &mut Vec<Run>,
) {
if script.style() < MathStyle::Script
&& base_ends_with_fraction(reader.doc, node)
&& needs_fraction_space_after(reader, rest)
{
runs.push(control_symbol(
reader,
settings,
&THIN_SPACE.to_string(),
script,
));
}
}
fn slashed_fraction(
reader: &mut PartReader,
(node, settings): (NodeId, Option<NodeId>),
kind: SlashKind,
script: MathScript,
runs: &mut Vec<Run>,
) {
let doc = reader.doc;
let mark = structure_mark(reader, settings, script);
runs.push(mark(Content::MathSlash(SlashMark::Start(kind))));
if let Some(numerator) = doc.child(node, M, "num") {
walk(reader, numerator, script, runs);
}
runs.push(mark(Content::MathSlash(SlashMark::Slash)));
runs.push(control_symbol(reader, settings, FRACTION_SLASH, script));
runs.push(mark(Content::MathSlash(SlashMark::Denominator)));
if let Some(denominator) = doc.child(node, M, "den") {
let den_script = match kind {
SlashKind::Skewed => script.cramped(),
SlashKind::Linear => script,
};
walk(reader, denominator, den_script, runs);
}
runs.push(mark(Content::MathSlash(SlashMark::End)));
}
const BAR_SIDE: &Values<BarSide> =
&Values::new(&[own("top", BarSide::Top), own("bot", BarSide::Bottom)]);
fn bar(
reader: &mut PartReader,
node: NodeId,
(script, rest): (MathScript, &[NodeId]),
runs: &mut Vec<Run>,
) {
let doc = reader.doc;
let settings = doc.child(node, M, "barPr");
let side = settings
.and_then(|props| doc.child(props, M, "pos"))
.and_then(|pos| reader.enumeration_in(pos, (Some(M), "val"), BAR_SIDE))
.unwrap_or_default();
fraction_space_before_base(reader, (node, settings), script, runs);
let mark = structure_mark(reader, settings, script);
runs.push(mark(Content::MathBar(BarMark::Start(side))));
if let Some(base) = doc.child(node, M, "e") {
let base_script = match side {
BarSide::Top => script.cramped(),
BarSide::Bottom => script,
};
walk(reader, base, base_script, runs);
}
runs.push(mark(Content::MathBar(BarMark::End)));
fraction_space_after_base(reader, (node, settings), (script, rest), runs);
}
fn group_chr_placement(reader: &mut PartReader, settings: Option<NodeId>) -> GroupChrPlacement {
let doc = reader.doc;
let position = settings
.and_then(|props| doc.child(props, M, "pos"))
.and_then(|pos| reader.enumeration_in(pos, (Some(M), "val"), BAR_SIDE))
.unwrap_or(BarSide::Bottom);
let vertical_align = settings
.and_then(|props| doc.child(props, M, "vertJc"))
.and_then(|jc| reader.enumeration_in(jc, (Some(M), "val"), BAR_SIDE))
.unwrap_or(BarSide::Top);
GroupChrPlacement {
position,
vertical_align,
}
}
fn group_chr_outer_space(
reader: &mut PartReader,
(node, settings): (NodeId, Option<NodeId>),
(script, rest): (MathScript, Option<&[NodeId]>),
(spaced, chr_on_baseline): (bool, bool),
runs: &mut Vec<Run>,
) {
let operator_neighbor = match rest {
None => ends_with_operand(runs),
Some(tail) => followed(reader.doc, tail),
};
if spaced && operator_neighbor {
runs.push(control_symbol(
reader,
settings,
&THIN_SPACE.to_string(),
script,
));
} else if !chr_on_baseline {
match rest {
None => fraction_space_before_base(reader, (node, settings), script, runs),
Some(tail) => fraction_space_after_base(reader, (node, settings), (script, tail), runs),
}
}
}
fn group_chr(
reader: &mut PartReader,
node: NodeId,
(script, rest): (MathScript, &[NodeId]),
runs: &mut Vec<Run>,
) {
let doc = reader.doc;
let settings = doc.child(node, M, "groupChrPr");
let character = settings
.and_then(|props| doc.child(props, M, "chr"))
.map_or_else(
|| DEFAULT_GROUP_CHR.to_string(),
|chr| doc.attribute(chr, Some(M), "val").unwrap_or("").to_owned(),
);
let base = doc.child(node, M, "e");
if character.is_empty() {
if let Some(base) = base {
walk(reader, base, script, runs);
}
return;
}
let placement = group_chr_placement(reader, settings);
let chr_on_baseline = placement.position == placement.vertical_align;
let single_op = group_chr_operator(reader, settings).is_some();
let spaced = single_op && script.style() < MathStyle::Script;
group_chr_outer_space(
reader,
(node, settings),
(script, None),
(spaced, chr_on_baseline),
runs,
);
let mark = structure_mark(reader, settings, script);
let step = steps_in(reader, settings, script);
runs.push(mark(Content::GroupChr(GroupChrMark::Start(placement))));
if let Some(base) = base {
let base_script = if chr_on_baseline {
step(MathStep::Limit {
lower: placement.position == BarSide::Top,
})
} else {
script
};
walk(reader, base, base_script, runs);
}
let mut glyph = control_symbol(reader, settings, &character, script);
glyph
.content
.insert(0, Content::GroupChr(GroupChrMark::Character));
runs.push(glyph);
runs.push(mark(Content::GroupChr(GroupChrMark::End {
operand: !single_op,
})));
group_chr_outer_space(
reader,
(node, settings),
(script, Some(rest)),
(spaced, chr_on_baseline),
runs,
);
}
#[derive(Clone, Copy)]
enum LimitBaseSpace {
Operator(char),
Thin,
}
impl LimitBaseSpace {
fn text(self, script: MathScript, after: bool) -> String {
match self {
Self::Operator(op) if after => space_after_operator(script, op).iter().collect(),
Self::Operator(op) => operator_space(script, op).iter().collect(),
Self::Thin if script.style() < MathStyle::Script => THIN_SPACE.to_string(),
Self::Thin => String::new(),
}
}
}
fn single_operator_base(reader: &mut PartReader, base: NodeId) -> Option<LimitBaseSpace> {
let doc = reader.doc;
let mut children = doc
.child_elements(base)
.filter(|&n| !doc.element(n).is_some_and(|e| e.name.local.ends_with("Pr")));
let node = children.next()?;
if children.next().is_some() {
return None;
}
if doc.is(node, M, "r") {
let text: String = doc
.child_elements(node)
.filter(|&n| doc.is(n, M, "t"))
.map(|t| doc.text_content(t))
.collect();
let mut chars = text.chars().map(shown);
let ch = chars.next()?;
if chars.next().is_some() {
return None;
}
return matches!(
operator_class(ch),
Some(OperatorClass::Relation | OperatorClass::Binary)
)
.then_some(LimitBaseSpace::Operator(ch));
}
if doc.is(node, M, "groupChr") {
let settings = doc.child(node, M, "groupChrPr");
let ch = group_chr_operator(reader, settings)?;
let _ = ch;
return Some(LimitBaseSpace::Thin);
}
None
}
fn group_chr_operator(reader: &mut PartReader, settings: Option<NodeId>) -> Option<char> {
let placement = group_chr_placement(reader, settings);
if placement.position != placement.vertical_align {
return None;
}
let doc = reader.doc;
let character = settings
.and_then(|props| doc.child(props, M, "chr"))
.map_or_else(
|| DEFAULT_GROUP_CHR.to_string(),
|chr| doc.attribute(chr, Some(M), "val").unwrap_or("").to_owned(),
);
let mut chars = character.chars();
let ch = shown(chars.next()?);
if chars.next().is_some() {
return None;
}
operator_class(ch).map(|_| ch)
}
fn limit_structure(
reader: &mut PartReader,
node: NodeId,
side: LimitSide,
(script, followed): (MathScript, bool),
runs: &mut Vec<Run>,
) {
let doc = reader.doc;
let props_name = match side {
LimitSide::Lower => "limLowPr",
LimitSide::Upper => "limUppPr",
};
let settings = doc.child(node, M, props_name);
let base = doc.child(node, M, "e");
let base_op = base.and_then(|b| single_operator_base(reader, b));
if let Some(kind) = base_op
&& ends_with_operand(runs)
{
let before = kind.text(script, false);
if !before.is_empty() {
runs.push(control_symbol(reader, settings, &before, script));
}
}
let mark = structure_mark(reader, settings, script);
let step = steps_in(reader, settings, script);
runs.push(mark(Content::MathLimit(LimitMark::Start(side))));
if let Some(base) = base {
walk(reader, base, script, runs);
}
runs.push(mark(Content::MathLimit(LimitMark::Limit)));
if let Some(lim) = doc.child(node, M, "lim") {
let lower = side == LimitSide::Lower;
walk(reader, lim, step(MathStep::Limit { lower }), runs);
}
runs.push(mark(Content::MathLimit(LimitMark::End {
operand: base_op.is_none(),
})));
if let Some(kind) = base_op
&& followed
{
let after = kind.text(script, true);
if !after.is_empty() {
runs.push(control_symbol(reader, settings, &after, script));
}
}
}
const MATRIX_BASE: &Values<MatrixBase> = &Values::new(&[
own("top", MatrixBase::Top),
own("center", MatrixBase::Center),
own("bot", MatrixBase::Bottom),
]);
const CELL_JUSTIFICATION: &Values<CellJustification> = &Values::new(&[
own("left", CellJustification::Left),
own("center", CellJustification::Center),
own("right", CellJustification::Right),
another("inside", CellJustification::Center),
another("outside", CellJustification::Center),
]);
fn matrix(reader: &mut PartReader, node: NodeId, script: MathScript, runs: &mut Vec<Run>) {
let doc = reader.doc;
let settings = doc.child(node, M, "mPr");
let columns = column_justifications(reader, settings);
let rows = doc
.child_elements(node)
.filter(|n| doc.is(*n, M, "mr"))
.map(|row| {
doc.child_elements(row)
.filter(|n| doc.is(*n, M, "e"))
.enumerate()
.map(|(column, cell)| (columns.get(column).copied().unwrap_or_default(), cell))
.collect()
})
.collect();
grid(reader, settings, (rows, script), runs);
}
fn equation_array(reader: &mut PartReader, node: NodeId, script: MathScript, runs: &mut Vec<Run>) {
let doc = reader.doc;
let rows = doc
.child_elements(node)
.filter(|n| doc.is(*n, M, "e"))
.map(|row| vec![(CellJustification::Center, row)])
.collect();
grid(reader, doc.child(node, M, "eqArrPr"), (rows, script), runs);
}
fn grid(
reader: &mut PartReader,
settings: Option<NodeId>,
(rows, script): (Vec<Vec<(CellJustification, NodeId)>>, MathScript),
runs: &mut Vec<Run>,
) {
let start = matrix_settings(reader, settings);
let mark = structure_mark(reader, settings, script);
runs.push(mark(Content::Matrix(MatrixMark::Start(start))));
for (index, row) in rows.into_iter().enumerate() {
if index > 0 {
runs.push(mark(Content::Matrix(MatrixMark::Row)));
}
for (justification, cell) in row {
runs.push(mark(Content::Matrix(MatrixMark::Cell(justification))));
walk(reader, cell, script, runs);
}
}
runs.push(mark(Content::Matrix(MatrixMark::End)));
}
#[derive(Clone, Copy)]
enum RowRule {
Single,
OneAndAHalf,
Double,
Exactly,
HalfLines,
}
const ROW_RULES: [RowRule; 5] = [
RowRule::Single,
RowRule::OneAndAHalf,
RowRule::Double,
RowRule::Exactly,
RowRule::HalfLines,
];
fn matrix_settings(reader: &mut PartReader, settings: Option<NodeId>) -> MatrixSettings {
let doc = reader.doc;
let setting = |name: &str| settings.and_then(|p| doc.child(p, M, name));
let base = setting("baseJc")
.and_then(|n| reader.enumeration_in(n, (Some(M), "val"), MATRIX_BASE))
.unwrap_or_default();
let number = |reader: &mut PartReader, name: &str| {
setting(name)
.and_then(|n| reader.or_missing_in(n, (Some(M), "val"), crate::numbers::decimal))
};
let distance = number(reader, "rSp").unwrap_or(0).max(0);
let rule = number(reader, "rSpRule")
.and_then(|value| usize::try_from(value).ok())
.and_then(|value| ROW_RULES.get(value));
let rows = match rule {
Some(RowRule::OneAndAHalf) => RowSpacing::OneAndAHalf,
Some(RowRule::Double) => RowSpacing::Double,
Some(RowRule::Exactly) => {
Length::from_twips(distance).map_or(RowSpacing::Single, RowSpacing::Exactly)
}
Some(RowRule::HalfLines) => RowSpacing::HalfLines(distance),
Some(RowRule::Single) | None => RowSpacing::Single,
};
let column_width = number(reader, "cSp")
.and_then(|twips| Length::from_twips(twips.max(0)))
.unwrap_or(Length::ZERO);
MatrixSettings {
base,
rows,
column_width,
}
}
fn column_justifications(
reader: &mut PartReader,
settings: Option<NodeId>,
) -> Vec<CellJustification> {
let doc = reader.doc;
let Some(columns) = settings.and_then(|p| doc.child(p, M, "mcs")) else {
return Vec::new();
};
let mut out = Vec::new();
for column in doc.child_elements(columns).filter(|n| doc.is(*n, M, "mc")) {
let props = doc.child(column, M, "mcPr");
let setting = |name: &str| props.and_then(|p| doc.child(p, M, name));
let count = setting("count")
.and_then(|n| reader.or_missing_in(n, (Some(M), "val"), crate::numbers::decimal))
.unwrap_or(1)
.clamp(1, crate::params::MATH_MATRIX_COLUMNS);
let justification = setting("mcJc")
.and_then(|n| reader.enumeration_in(n, (Some(M), "val"), CELL_JUSTIFICATION))
.unwrap_or_default();
let count = usize::try_from(count).unwrap_or(1);
out.extend(std::iter::repeat_n(justification, count));
}
out
}
fn sub_superscript(
reader: &mut PartReader,
node: NodeId,
(script, rest): (MathScript, &[NodeId]),
runs: &mut Vec<Run>,
) {
let doc = reader.doc;
let followed = followed(doc, rest);
let settings = doc.child(node, M, "sSubSupPr");
let start = box_start(doc, node);
let boxed = start.is_some();
if let Some(start) = start {
let mark = structure_mark(reader, settings, script);
runs.push(mark(Content::Scripts(start)));
}
if let Some(base) = doc.child(node, M, "e") {
walk(reader, base, script, runs);
}
let parts = (doc.child(node, M, "sub"), doc.child(node, M, "sup"));
scripts(
reader,
settings,
parts,
(script, Marks::Base { boxed }, followed),
runs,
);
fraction_space_after_base(reader, (node, settings), (script, rest), runs);
}
fn box_start(doc: &Document, node: NodeId) -> Option<ScriptMark> {
let base = doc.child(node, M, "e")?;
let structures: Vec<(&str, NodeId)> = doc
.child_elements(base)
.filter_map(|child| {
let name = doc.element(child).map_or("", |e| e.name.local);
(doc.is(child, M, name) && !name.ends_with("Pr")).then_some((name, child))
})
.collect();
let boxes = |&(name, child): &(&str, NodeId)| match name {
"rad" | "f" => true,
"bar" => overbar(doc, child),
_ => false,
};
if structures.iter().any(boxes) {
Some(ScriptMark::BoxStart { delimited: false })
} else {
(structures.last().map(|&(name, _)| name) == Some("d"))
.then_some(ScriptMark::BoxStart { delimited: true })
}
}
fn overbar(doc: &Document, node: NodeId) -> bool {
doc.child(node, M, "barPr")
.and_then(|props| doc.child(props, M, "pos"))
.and_then(|pos| doc.attribute(pos, Some(M), "val"))
== Some("top")
}
#[derive(Clone, Copy)]
enum Marks {
Base { boxed: bool },
Operator { drops: bool },
}
fn scripts(
reader: &mut PartReader,
settings: Option<NodeId>,
(sub, sup): (Option<NodeId>, Option<NodeId>),
(script, marks, followed): (MathScript, Marks, bool),
runs: &mut Vec<Run>,
) {
let stacked = sub.is_some() && sup.is_some();
let mark = stack_mark(reader, settings, script);
let script_mark = structure_mark(reader, settings, script);
let script_mark = |mark: ScriptMark| script_mark(Content::Scripts(mark));
let step = steps_in(reader, settings, script);
runs.push(script_mark(match marks {
Marks::Operator { drops } => ScriptMark::Operator { stacked, drops },
Marks::Base { boxed } => ScriptMark::Base {
stacked,
followed,
boxed,
},
}));
if stacked {
runs.push(mark(StackMark::Start {
bar: None,
centered: false,
}));
}
if let Some(sub) = sub {
runs.push(script_mark(ScriptMark::Start(ScriptSide::Sub)));
walk(reader, sub, step(MathStep::Subscript), runs);
runs.push(script_mark(ScriptMark::End));
}
if stacked {
runs.push(mark(StackMark::Middle));
}
let upper = if stacked {
MathStep::SuperscriptBesideSubscript
} else {
MathStep::Superscript
};
if let Some(sup) = sup {
runs.push(script_mark(ScriptMark::Start(ScriptSide::Sup)));
walk(reader, sup, step(upper), runs);
runs.push(script_mark(ScriptMark::End));
}
if stacked {
runs.push(mark(StackMark::End));
}
runs.push(script_mark(ScriptMark::After));
}
fn script_structure(
reader: &mut PartReader,
node: NodeId,
(script, rest): (MathScript, &[NodeId]),
runs: &mut Vec<Run>,
) {
let doc = reader.doc;
let followed = followed(doc, rest);
let local = doc.element(node).map_or("", |e| e.name.local);
let attached = matches!(local, "sSub" | "sSup");
let settings = doc.child(node, M, &format!("{local}Pr"));
let upper = if doc.child(node, M, "sub").is_some() {
MathStep::SuperscriptBesideSubscript
} else {
MathStep::Superscript
};
let size = control_size(reader, settings);
let start = box_start(doc, node).filter(|_| attached);
let boxed = start.is_some();
let mark = structure_mark(reader, settings, script);
let marks = |marks: [ScriptMark; 2], runs: &mut Vec<Run>| {
if attached {
runs.extend(marks.map(|m| mark(Content::Scripts(m))));
}
};
for child in doc.child_elements(node) {
let (script_side, step) = if doc.is(child, M, "sup") {
(ScriptSide::Sup, upper)
} else if doc.is(child, M, "sub") {
(ScriptSide::Sub, MathStep::Subscript)
} else {
if doc.is(child, M, "e") {
if let Some(start) = start {
runs.push(mark(Content::Scripts(start)));
}
walk(reader, child, script, runs);
}
continue;
};
marks(
[
ScriptMark::Base {
stacked: false,
followed,
boxed,
},
ScriptMark::Start(script_side),
],
runs,
);
walk(reader, child, script.inside(step, size), runs);
marks([ScriptMark::End, ScriptMark::After], runs);
}
fraction_space_after_base(reader, (node, settings), (script, rest), runs);
}
fn followed(doc: &Document, rest: &[NodeId]) -> bool {
rest.iter().any(|&node| {
let name = doc.element(node).map_or("", |e| e.name.local);
if !doc.is(node, M, name) || name.ends_with("Pr") {
return false;
}
name != "r"
|| doc
.child_elements(node)
.any(|t| doc.is(t, M, "t") && !doc.text_content(t).is_empty())
})
}
fn control_size(reader: &mut PartReader, settings: Option<NodeId>) -> Option<i64> {
let doc = reader.doc;
settings
.and_then(|p| doc.child(p, M, "ctrlPr"))
.and_then(|c| doc.child(c, W, "rPr"))
.and_then(|rpr| RunProps::read(reader, rpr).size)
}
fn steps_in(
reader: &mut PartReader,
settings: Option<NodeId>,
script: MathScript,
) -> impl Fn(MathStep) -> MathScript + use<> {
let size = control_size(reader, settings);
move |step| script.inside(step, size)
}
fn stack_mark(
reader: &mut PartReader,
settings: Option<NodeId>,
script: MathScript,
) -> impl Fn(StackMark) -> Run + use<> {
let mark = structure_mark(reader, settings, script);
move |stack| mark(Content::Stack(stack))
}
fn structure_mark(
reader: &mut PartReader,
settings: Option<NodeId>,
script: MathScript,
) -> impl Fn(Content) -> Run + use<> {
let props = control_props(reader, settings, script);
move |mark| Run {
style: None,
props: props.clone(),
content: vec![mark],
revisions: Default::default(),
starts_buffer: false,
buffer_only: crate::body::BufferOnly::default(),
record: RunRecord::default(),
code_format: None,
links: Vec::new(),
}
}
fn control_props(
reader: &mut PartReader,
settings: Option<NodeId>,
script: MathScript,
) -> RunProps {
let doc = reader.doc;
let mut props = settings
.and_then(|p| doc.child(p, M, "ctrlPr"))
.and_then(|c| doc.child(c, W, "rPr"))
.map_or_default(|rpr| RunProps::read(reader, rpr));
props.size = script.outermost_size().or(props.size);
props.apply(&math_props(script));
props
}
fn large_operator(
reader: &mut PartReader,
settings: Option<NodeId>,
operator: &str,
script: MathScript,
) -> Run {
let mut run = control_symbol(reader, settings, operator, script);
run.props.math_script = Some(script.without_outermost().large());
run
}
fn control_symbol(
reader: &mut PartReader,
settings: Option<NodeId>,
text: &str,
script: MathScript,
) -> Run {
Run {
style: None,
props: control_props(reader, settings, script),
content: vec![Content::Text(text.to_owned())],
revisions: Default::default(),
starts_buffer: false,
buffer_only: crate::body::BufferOnly::default(),
record: RunRecord::default(),
code_format: None,
links: Vec::new(),
}
}
fn apply_math_run_font(props: &mut RunProps, style: LetterStyle) {
let default = || FontRef::Name(MATH_FONT.to_owned());
let own_other = |slot: &Option<FontRef>| {
slot.as_ref().is_some_and(
|font| !matches!(font, FontRef::Name(name) if name.eq_ignore_ascii_case(MATH_FONT)),
)
};
let has_slot = props.font_ascii.is_some() || props.font_hansi.is_some();
if !has_slot {
props.font_ascii = Some(default());
props.font_hansi = Some(default());
}
let may_use_other = own_other(&props.font_ascii)
|| own_other(&props.font_hansi)
|| (has_slot && (props.font_ascii.is_none() || props.font_hansi.is_none()));
props.math = Some(true);
if may_use_other {
if matches!(style, LetterStyle::Bold | LetterStyle::BoldItalic) {
props.bold = Some(true);
}
if matches!(style, LetterStyle::Italic | LetterStyle::BoldItalic) {
props.italic = Some(true);
}
}
}
fn math_props(script: MathScript) -> RunProps {
let font = FontRef::Name(MATH_FONT.to_owned());
RunProps {
font_ascii: Some(font.clone()),
font_hansi: Some(font),
math_script: in_script(script),
math: Some(true),
..RunProps::default()
}
}
fn in_script(script: MathScript) -> Option<MathScript> {
(script.depth() > 0).then_some(script.without_outermost())
}
fn text_run(content: Content, script: MathScript) -> Run {
Run {
style: None,
props: math_props(script),
content: vec![content],
revisions: Default::default(),
starts_buffer: false,
buffer_only: crate::body::BufferOnly::default(),
record: RunRecord::default(),
code_format: None,
links: Vec::new(),
}
}
fn symbol(text: &str, script: MathScript) -> Run {
text_run(Content::Text(text.to_owned()), script)
}
fn math_run(
reader: &mut PartReader,
node: NodeId,
script: MathScript,
ends: (bool, bool),
) -> Option<Run> {
let doc = reader.doc;
let text: String = doc
.child_elements(node)
.filter(|t| doc.is(*t, M, "t"))
.map(|t| doc.text_content(t))
.collect();
if text.is_empty() {
return None;
}
let math = doc.child(node, M, "rPr");
let normal = math.and_then(|p| doc.child(p, M, "nor")).is_some();
let style = math
.and_then(|p| doc.child(p, M, "sty"))
.and_then(|s| reader.enumeration_or(s, (Some(M), "val"), LETTER_STYLE, "p"))
.unwrap_or(LetterStyle::Italic);
let mut props = doc
.child(node, W, "rPr")
.map_or_default(|rpr| RunProps::read(reader, rpr));
if normal {
props.math = Some(false);
} else {
apply_math_run_font(&mut props, style);
}
if script.depth() > 0 {
props.math_script = Some(script.without_outermost());
}
let shown = if normal {
text
} else {
styled(&text, style, ends, script)
};
Some(Run {
style: None,
props,
content: vec![Content::Text(shown)],
revisions: Default::default(),
starts_buffer: false,
buffer_only: crate::body::BufferOnly::default(),
record: RunRecord::default(),
code_format: None,
links: Vec::new(),
})
}
fn operator_space(script: MathScript, ch: char) -> &'static [char] {
if script.style() >= MathStyle::Script {
&[]
} else if relation(ch) {
&RELATION_SPACE
} else {
&[OPERATOR_SPACE]
}
}
fn space_after_operator(script: MathScript, ch: char) -> &'static [char] {
let space = operator_space(script, ch);
if space.is_empty() || script.is_display() || !script.in_no_structure() {
space
} else if relation(ch) {
&[HAIR_SPACE, OPERATOR_BREAK_SPACE]
} else {
&[OPERATOR_BREAK_SPACE]
}
}
fn styled(
text: &str,
style: LetterStyle,
(operand, followed): (bool, bool),
script: MathScript,
) -> String {
let chars: Vec<char> = text.chars().map(shown).collect();
let mut out = String::new();
let mut after_operand = operand;
for (index, &ch) in chars.iter().enumerate() {
let next = chars.get(index + 1).copied();
match operator_class(ch) {
Some(class) if after_operand => between(&mut out, script, (ch, class), next),
Some(OperatorClass::Binary | OperatorClass::Relation) => {
leading(&mut out, script, ch, next.is_some() || followed);
}
_ => operand_char(&mut out, (style, script), &chars, index, after_operand),
}
if ch != BAR {
after_operand = ends_operand(ch);
}
}
out
}
fn shown(ch: char) -> char {
match ch {
'*' => '\u{2217}',
'-' => '\u{2212}',
'\'' => PRIME,
other => other,
}
}
const HELD_LEADING: char = '\u{00D7}';
fn leading(out: &mut String, script: MathScript, ch: char, more: bool) {
out.push(ch);
if !more {
return;
}
if ch == HELD_LEADING {
out.extend(operator_space(script, ch));
} else {
out.extend(space_after_operator(script, ch));
}
}
fn between(
out: &mut String,
script: MathScript,
(ch, class): (char, OperatorClass),
next: Option<char>,
) {
let pair = next.is_some_and(leads);
if !(class == OperatorClass::Sign && next.is_some_and(relation)) {
out.extend(operator_space(script, ch));
}
out.push(ch);
if !pair {
out.extend(space_after_operator(script, ch));
}
}
fn leads(ch: char) -> bool {
matches!(
operator_class(ch),
Some(OperatorClass::Binary | OperatorClass::Relation)
)
}
const ELLIPSES: [char; 2] = ['\u{22EF}', '\u{2026}'];
fn operand_char(
out: &mut String,
(style, script): (LetterStyle, MathScript),
chars: &[char],
index: usize,
after_operand: bool,
) {
let Some(&ch) = chars.get(index) else {
return;
};
let ellipsis = ELLIPSES.contains(&ch) && script.style() < MathStyle::Script;
let punctuation_before = index
.checked_sub(1)
.and_then(|before| chars.get(before))
.is_some_and(|c| SPACED_MARKS.contains(c));
if ellipsis && after_operand && !punctuation_before {
out.push(THIN_SPACE);
}
out.push(letter(ch, style));
let operand_after = chars
.get(index + 1)
.is_some_and(|&next| next != ' ' && !operator(next));
if (ellipsis && operand_after) || punctuation_space(script, chars, index) {
out.push(THIN_SPACE);
}
}
fn punctuation_space(script: MathScript, chars: &[char], index: usize) -> bool {
let (Some(&ch), Some(&next)) = (chars.get(index), chars.get(index + 1)) else {
return false;
};
if script.style() >= MathStyle::Script || !SPACED_MARKS.contains(&ch) || next == ' ' {
return false;
}
let before = index.checked_sub(1).and_then(|before| chars.get(before));
!decimal(before.copied(), ch, next)
}
fn operator(ch: char) -> bool {
operator_class(ch).is_some()
}
fn relation(ch: char) -> bool {
operator_class(ch) == Some(OperatorClass::Relation)
}
fn letter(ch: char, style: LetterStyle) -> char {
if let Some(greek) = greek(ch, style) {
return greek;
}
let offset = |base: char, first: char| {
char::from_u32(u32::from(base) + (u32::from(ch) - u32::from(first))).unwrap_or(ch)
};
match (style, ch) {
(LetterStyle::Bold, 'a'..='z') => offset('\u{1D41A}', 'a'),
(LetterStyle::Bold, 'A'..='Z') => offset('\u{1D400}', 'A'),
(LetterStyle::Bold | LetterStyle::BoldItalic, '0'..='9') => offset('\u{1D7CE}', '0'),
(LetterStyle::BoldItalic, 'a'..='z') => offset('\u{1D482}', 'a'),
(LetterStyle::BoldItalic, 'A'..='Z') => offset('\u{1D468}', 'A'),
(LetterStyle::Italic, 'h') => '\u{210E}',
(LetterStyle::Italic, 'a'..='z') => offset('\u{1D44E}', 'a'),
(LetterStyle::Italic, 'A'..='Z') => offset('\u{1D434}', 'A'),
_ => ch,
}
}
const GREEK_VARIANTS: [char; 6] = [
'\u{03F5}', '\u{03D1}', '\u{03F0}', '\u{03D5}', '\u{03F1}', '\u{03D6}',
];
struct GreekForms {
capitals: char,
nabla: char,
small: char,
partial: char,
variants: char,
}
const BOLD_GREEK: GreekForms = GreekForms {
capitals: '\u{1D6A8}',
nabla: '\u{1D6C1}',
small: '\u{1D6C2}',
partial: '\u{1D6DB}',
variants: '\u{1D6DC}',
};
const ITALIC_GREEK: GreekForms = GreekForms {
capitals: '\u{1D6E2}',
nabla: '\u{1D6FB}',
small: '\u{1D6FC}',
partial: '\u{1D715}',
variants: '\u{1D716}',
};
const BOLD_ITALIC_GREEK: GreekForms = GreekForms {
capitals: '\u{1D71C}',
nabla: '\u{1D735}',
small: '\u{1D736}',
partial: '\u{1D74F}',
variants: '\u{1D750}',
};
fn greek(ch: char, style: LetterStyle) -> Option<char> {
let forms = match style {
LetterStyle::Plain => return None,
LetterStyle::Bold => &BOLD_GREEK,
LetterStyle::Italic => &ITALIC_GREEK,
LetterStyle::BoldItalic => &BOLD_ITALIC_GREEK,
};
let after = |first: char, steps: u32| char::from_u32(u32::from(first) + steps);
let from = |first: char, start: char| after(first, u32::from(ch) - u32::from(start));
match ch {
'\u{0391}'..='\u{03A1}' | '\u{03A3}'..='\u{03A9}' => from(forms.capitals, '\u{0391}'),
'\u{2207}' => Some(forms.nabla),
'\u{03B1}'..='\u{03C9}' => from(forms.small, '\u{03B1}'),
'\u{2202}' => Some(forms.partial),
_ => {
let place = GREEK_VARIANTS.iter().position(|&v| v == ch)?;
after(forms.variants, u32::try_from(place).ok()?)
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LetterStyle {
Plain,
Bold,
Italic,
BoldItalic,
}
const LETTER_STYLE: &Values<LetterStyle> = &Values::new(&[
own("p", LetterStyle::Plain),
own("b", LetterStyle::Bold),
own("i", LetterStyle::Italic),
own("bi", LetterStyle::BoldItalic),
]);
#[cfg(test)]
mod tests;