Merge branch 'main' into feat/audio-dsp

This commit is contained in:
Dylan M. Taylor
2026-11-20 00:26:12 -05:00
committed by GitHub
33 changed files with 2566 additions and 43 deletions
Generated
+1
View File
@@ -2573,6 +2573,7 @@ version = "0.1.0"
dependencies = [
"craft-xml",
"proptest",
"roxmltree 0.21.2",
"serde",
"serde_json",
]
+35 -1
View File
@@ -448,7 +448,13 @@ fn one_element(s: &str) -> bool {
r.config_mut().check_comments = true;
let (mut depth, mut roots) = (0usize, 0usize);
loop {
let attrs_ok = |e: &BytesStart| e.attributes().all(|a| a.is_ok());
// Each attribute parses and its value unescapes: an undeclared entity (`x="&no;"`) isn't
// well-formed, and the reader would keep it raw (#6072).
// Names must be XML names too: the reader takes `<a?b>` and `x?="1"` without complaint.
let attrs_ok = |e: &BytesStart| {
is_qname(e.name().as_ref())
&& e.attributes().all(|a| a.is_ok_and(|a| is_qname(a.key.as_ref()) && a.normalized_value(quick_xml::XmlVersion::Explicit1_0).is_ok()))
};
match r.read_event() {
Ok(Event::Start(e)) => {
if !attrs_ok(&e) || (depth == 0 && roots > 0) {
@@ -480,6 +486,28 @@ fn one_element(s: &str) -> bool {
}
}
/// Whether `name` is an XML name with at most one colon, neither first nor last: a qualified name
/// in Namespaces in XML 1.0 (§4), with the name characters of XML 1.0 (Fifth Edition) §2.3.
fn is_qname(name: &[u8]) -> bool {
fn start(c: char) -> bool {
matches!(c, 'A'..='Z' | '_' | 'a'..='z' | '\u{C0}'..='\u{D6}' | '\u{D8}'..='\u{F6}' | '\u{F8}'..='\u{2FF}' | '\u{370}'..='\u{37D}'
| '\u{37F}'..='\u{1FFF}' | '\u{200C}'..='\u{200D}' | '\u{2070}'..='\u{218F}' | '\u{2C00}'..='\u{2FEF}' | '\u{3001}'..='\u{D7FF}'
| '\u{F900}'..='\u{FDCF}' | '\u{FDF0}'..='\u{FFFD}' | '\u{10000}'..='\u{EFFFF}')
}
fn more(c: char) -> bool {
start(c) || matches!(c, '-' | '.' | '0'..='9' | '\u{B7}' | '\u{300}'..='\u{36F}' | '\u{203F}'..='\u{2040}')
}
let ncname = |p: &str| {
let mut cs = p.chars();
cs.next().is_some_and(start) && cs.all(more)
};
let Ok(name) = std::str::from_utf8(name) else { return false };
match name.split_once(':') {
Some((prefix, local)) => ncname(prefix) && ncname(local),
None => ncname(name),
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -587,6 +615,12 @@ mod tests {
"<a></a></pkg:xmlData>",
"<a><!-- x -- y --></a>",
"<a/><!-- x--->",
"<a x=\"&no;\"/>",
"<a><b x=\"&no;\"/></a>",
"<a?b/>",
"<a x?=\"1\"/>",
"<a><b:c:d/></a>",
"<a :x=\"1\"/>",
] {
assert!(xml_fragment(ct, bad.as_bytes()).is_none(), "{bad}");
}
+5 -2
View File
@@ -616,8 +616,11 @@ fn vml_float(shape: &El, style: &str, in_hf: bool) -> Float {
dist_bottom: dist("mso-wrap-distance-bottom"),
hidden,
// Word for Mac draws a VML shape anchored in a header table cell on the page whatever
// `o:allowincell` says (user-checked), as for Word's picture and text watermarks.
outside_cell: in_hf,
// `o:allowincell` says (user-checked), as for Word's picture and text watermarks. In the
// body, Layout in table cell off (`o:allowincell="f"`) places the shape outside its cell,
// and the cell's text doesn't wrap around it (user-checked in Word for Windows); without
// the attribute the shape is laid out in its cell.
outside_cell: in_hf || shape.attr("o:allowincell").is_some_and(|v| matches!(v.trim(), "f" | "false" | "0")),
..Float::default()
};
f.set_spin(vml_spin(style));
+33
View File
@@ -1641,6 +1641,39 @@ fn body_cell_vml_picture_stays_in_its_cell() {
assert_eq!(floats, vec![false]);
}
/// A VML shape in a body table cell with Layout in table cell off (`o:allowincell="f"`, which
/// Word writes for such a shape in a document in Word 2003 compatibility mode, user-checked) is
/// placed outside its cell, as Word draws it: beside the table, and the cell's text doesn't wrap
/// around it. Without the attribute, or with it on, the shape stays laid out in its cell. Both
/// survive save and reopen.
#[test]
fn body_cell_vml_shape_with_layout_in_cell_off_is_placed_outside_the_cell() {
let shape = |allow: &str| {
format!(
r##"<w:r><w:pict><v:shape id="Box1" type="#_x0000_t202" style="position:absolute;margin-left:-60pt;margin-top:4pt;width:48pt;height:40pt;z-index:251659264;mso-position-horizontal-relative:text;mso-position-vertical-relative:text" {allow} filled="f"><v:textbox><w:txbxContent><w:p><w:r><w:t>ICON</w:t></w:r></w:p></w:txbxContent></v:textbox><w10:wrap xmlns:w10="urn:schemas-microsoft-com:office:word" type="topAndBottom"/></v:shape></w:pict></w:r>"##
)
};
let floats = |d: &Document| -> Vec<(bool, Wrap)> {
let Block::Table(t) = &*d.body[0] else { panic!("table first") };
t.rows[0].cells[0]
.blocks
.iter()
.filter_map(|b| b.as_para())
.flat_map(|p| p.objects.iter().filter_map(|o| o.frame()).map(|(_, _, f)| (f.outside_cell, f.wrap)))
.collect()
};
for (allow, outside) in [(r#"o:allowincell="f""#, true), (r#"o:allowincell="false""#, true), (r#"o:allowincell="t""#, false), ("", false)] {
let run = shape(allow);
let body = format!(
r#"<w:tbl><w:tblGrid><w:gridCol w:w="7200"/></w:tblGrid><w:tr><w:tc><w:p>{run}<w:r><w:t>Box title</w:t></w:r></w:p><w:p><w:r><w:t>Box text</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p/>"#
);
let d = craft_docx::read(&docx(&body, &[], &[])).unwrap();
assert_eq!(floats(&d), vec![(outside, Wrap::TopAndBottom)], "{allow}");
let d2 = craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap();
assert_eq!(floats(&d2), vec![(outside, Wrap::TopAndBottom)], "saved: {allow}");
}
}
/// Issue #149: an absolutely positioned VML text box in a header floats where its style puts it
/// (relative to the page here, behind the text at a negative z-index, no wrapping) instead of
/// sitting inline in the header's flow, and it keeps that placement when saved and read back.
+109
View File
@@ -0,0 +1,109 @@
//! An equation's kept source OMML is written back verbatim only when it is exactly one well-formed
//! `m:oMath` (#6072). `Math::omml` also comes from `.json` documents, so anything else must not
//! reach `document.xml`: it is written from the equation's nodes instead.
use craft_math::math::{MNode, MRun, Math};
use craft_wordmodel::para::{InlineObject, OBJ};
use craft_wordmodel::props::CharProps;
use craft_wordmodel::{Document, Paragraph, para_block};
/// Save a one-equation document whose equation keeps `omml` and has the nodes `NODES`.
fn save(omml: &str, display: bool) -> (String, Document) {
let math = Math { nodes: vec![MNode::Run(MRun::new("NODES"))], omml: omml.into(), ..Default::default() };
let mut p = Paragraph::new();
p.insert_object(0, InlineObject::Equation { linear: "NODES".into(), display, math }, &CharProps::default()).unwrap();
let mut doc = Document::new();
doc.body = vec![para_block(p)];
let bytes = craft_docx::write(&doc).unwrap();
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
// The saved file must open again (the main part is read strictly).
let back = craft_docx::read(&bytes).unwrap_or_else(|e| panic!("{omml:?} doesn't reopen: {e}"));
(xml, back)
}
/// The text of the reopened document's equations and paragraphs.
fn texts(doc: &Document) -> Vec<String> {
let mut out = Vec::new();
for b in &doc.body {
let Some(p) = b.as_para() else { continue };
for o in &p.objects {
if let InlineObject::Equation { math, .. } = o {
out.push(craft_math::math::to_linear(&math.nodes));
}
}
let text: String = p.text.chars().filter(|c| *c != OBJ).collect();
if !text.trim().is_empty() {
out.push(text);
}
}
out
}
#[test]
fn well_formed_kept_omml_is_written_back_unchanged() {
let kept = "<m:oMath><m:r><m:t>KEPT</m:t></m:r></m:oMath>";
let (xml, back) = save(kept, false);
assert!(xml.contains(kept), "{xml}");
assert_eq!(texts(&back), vec!["KEPT".to_string()]);
}
#[test]
fn xml_whitespace_after_the_element_name_is_kept() {
// XML allows any of space, tab, carriage return and line feed between a name and `>`.
for ws in [" ", "\t", "\r", "\n", "\r\n "] {
let kept = format!("<m:oMath{ws}><m:r><m:t>KEPT</m:t></m:r></m:oMath>");
let (xml, back) = save(&kept, false);
assert!(xml.contains(&kept), "{ws:?}: {xml}");
assert_eq!(texts(&back), vec!["KEPT".to_string()], "{ws:?}");
}
}
#[test]
fn malformed_kept_omml_is_written_from_the_nodes() {
for kept in [
// Unclosed, mismatched, an undefined entity.
"<m:oMath><m:r>",
"<m:oMath></m:r>",
"<m:oMath><m:r><m:t>&bad;</m:t></m:r></m:oMath>",
// Markup after the element, text after it, a second element.
"<m:oMath></m:oMath></w:p><w:p><w:r><w:t>INJECTED</w:t></w:r></w:p><w:p>",
"<m:oMath></m:oMath>INJECTED",
"<m:oMath></m:oMath><w:r><w:t>INJECTED</w:t></w:r>",
// Not an m:oMath.
"<m:r><m:t>INJECTED</m:t></m:r>",
// An m:oMath in another namespace, and an unknown entity in an attribute.
"<m:oMath xmlns:m=\"urn:other\"><m:r><m:t>INJECTED</m:t></m:r></m:oMath>",
"<m:oMath><m:r bad=\"&missing;\"><m:t>INJECTED</m:t></m:r></m:oMath>",
// Names that aren't XML names, and prefixes that aren't declared.
"<m:oMath bad?=\"1\"><m:r><m:t>INJECTED</m:t></m:r></m:oMath>",
"<m:oMath><m:r><m:t a:b:c=\"1\">INJECTED</m:t></m:r></m:oMath>",
"<m:oMath><m:r><m:t>INJECTED</m:t></m:r><m:r?/></m:oMath>",
"<m:oMath missing:x=\"1\"><m:r><m:t>INJECTED</m:t></m:r></m:oMath>",
"<m:oMath><missing:r><m:t>INJECTED</m:t></missing:r></m:oMath>",
// Two attributes with one expanded name (Namespaces in XML §6.3).
"<m:oMath xmlns:p=\"urn:x\" xmlns:q=\"urn:x\" p:a=\"1\" q:a=\"2\"><m:r><m:t>INJECTED</m:t></m:r></m:oMath>",
// A `<` in an attribute value, `]]>` in text.
"<m:oMath bad=\"<\"><m:r><m:t>INJECTED</m:t></m:r></m:oMath>",
"<m:oMath><m:r><m:t>INJECTED]]></m:t></m:r></m:oMath>",
// Characters XML 1.0 doesn't allow, as references or as they are.
"<m:oMath bad=\"&#1;\"><m:r><m:t>INJECTED</m:t></m:r></m:oMath>",
"<m:oMath><m:r><m:t>INJECTED&#1;</m:t></m:r></m:oMath>",
"<m:oMath><m:r><m:t>INJECTED&#xFFFF;</m:t></m:r></m:oMath>",
"<m:oMath bad=\"\u{1}\"><m:r><m:t>INJECTED</m:t></m:r></m:oMath>",
"<m:oMath><m:r><m:t>INJECTED\u{1}</m:t></m:r></m:oMath>",
] {
let (xml, back) = save(kept, false);
assert!(!xml.contains("INJECTED") && !xml.contains("&bad;"), "{kept:?} was written: {xml}");
assert_eq!(texts(&back), vec!["NODES".to_string()], "{kept:?}");
}
}
#[test]
fn a_kept_omath_para_is_not_nested_in_another() {
let kept = "<m:oMathPara><m:oMath><m:r><m:t>P</m:t></m:r></m:oMath></m:oMathPara>";
let (xml, back) = save(kept, true);
assert!(!xml.contains("<m:oMathPara><m:oMathPara>"), "{xml}");
assert_eq!(texts(&back), vec!["NODES".to_string()]);
}
+2
View File
@@ -23,12 +23,14 @@ mod font_table;
mod glossary;
mod heading_levels;
mod kashida;
mod kept_omml_check;
mod latin_theme_slots;
mod legacy_forms;
mod ligatures;
mod line_numbering;
mod locked_canvas;
mod malformed;
mod math_normal_text;
mod missing_pictures;
mod nested_block_controls;
mod note_comments;
+66
View File
@@ -0,0 +1,66 @@
//! Normal text in an equation (`m:nor`) is saved without `m:scr`/`m:sty` (#6073). In the OMML
//! schema `CT_RPR` holds `m:nor` or `m:scr`/`m:sty`, not both, and Word keeps only the `m:nor` of
//! such a run, so the bold or italic of normal text goes in `w:rPr` (`w:b`/`w:i`), which the
//! reader takes back for normal text.
use craft_math::math::{MNode, MRun, MScr, MSty, Math};
use craft_wordmodel::InlineObject;
use craft_wordmodel::props::CharProps;
use craft_wordmodel::{Document, Paragraph, para_block};
/// Save an equation holding one normal-text run; the run's `m:r` XML and the reopened run.
fn save(run: MRun) -> (String, MRun) {
let math = Math { nodes: vec![MNode::Run(run)], ..Default::default() };
let mut p = Paragraph::new();
p.insert_object(0, InlineObject::Equation { linear: String::new(), display: false, math }, &CharProps::default()).unwrap();
let mut doc = Document::new();
doc.body = vec![para_block(p)];
let bytes = craft_docx::write(&doc).unwrap();
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
let mut xml = String::new();
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
let start = xml.find("<m:r>").unwrap();
let end = start + xml[start..].find("</m:r>").unwrap() + "</m:r>".len();
let back = craft_docx::read(&bytes).unwrap();
let math = back.body.iter().filter_map(|b| b.as_para()).flat_map(|p| p.objects.iter()).find_map(|o| match o {
InlineObject::Equation { math, .. } => Some(math.clone()),
_ => None,
});
let Some(MNode::Run(r)) = math.unwrap().nodes.into_iter().next() else { panic!("no run") };
(xml[start..end].to_string(), r)
}
fn normal(sty: Option<MSty>) -> MRun {
MRun { nor: true, sty, font: Some("Arial".into()), ..MRun::new("normal text") }
}
#[test]
fn normal_text_has_no_math_style() {
for sty in [None, Some(MSty::Plain), Some(MSty::Bold), Some(MSty::Italic), Some(MSty::BoldItalic)] {
let (run, _) = save(normal(sty));
assert!(run.contains("<m:nor/>"), "{sty:?}: {run}");
assert!(!run.contains("m:sty") && !run.contains("m:scr"), "{sty:?}: {run}");
}
// A script style isn't written for normal text either.
let (run, _) = save(MRun { scr: MScr::Fraktur, ..normal(None) });
assert!(!run.contains("m:scr"), "{run}");
}
#[test]
fn bold_and_italic_normal_text_survive_a_save() {
for (sty, b, i) in [(MSty::Bold, true, false), (MSty::Italic, false, true), (MSty::BoldItalic, true, true)] {
let (run, back) = save(normal(Some(sty)));
assert_eq!((run.contains("<w:b/>"), run.contains("<w:i/>")), (b, i), "{sty:?}: {run}");
assert_eq!(back, normal(Some(sty)), "{sty:?}");
}
}
#[test]
fn math_runs_keep_their_style() {
for sty in [MSty::Plain, MSty::Bold, MSty::Italic, MSty::BoldItalic] {
let math = MRun { sty: Some(sty), ..MRun::new("x") };
let (run, back) = save(math.clone());
assert!(run.contains("m:sty") && !run.contains("<w:b/>"), "{sty:?}: {run}");
assert_eq!(back, math);
}
}
+136
View File
@@ -33,6 +33,36 @@ pub struct TocStyleValues {
pub entries: Vec<TocStyleEntryValues>,
}
impl TocStyleValues {
/// Emits a `TOCStyle` element and its `TOCStyleEntry` children.
pub fn to_el(&self, name: &str, mut fresh: impl FnMut() -> String) -> El {
let mut el = El::new("TOCStyle")
.with_attr("Self", self.self_id.as_deref().unwrap_or("TOCStyle/Table of Contents"))
.with_attr("Name", name)
.with_attr("Title", self.title.as_deref().unwrap_or(""))
.with_attr("TitleStyle", self.title_style.as_deref().unwrap_or("ParagraphStyle/$ID/NormalParagraphStyle"))
.with_attr("RunIn", "false")
.with_attr("IncludeHidden", "false")
.with_attr("IncludeBookDocuments", "false")
.with_attr("CreateBookmarks", bool_str(self.create_bookmarks.unwrap_or(false)));
for entry in &self.entries {
el.push(
El::new("TOCStyleEntry")
.with_attr("Self", fresh())
.with_attr("Name", entry.style.as_deref().unwrap_or(""))
.with_attr("FormatStyle", entry.entry_style.as_deref().unwrap_or(""))
.with_attr("Level", entry.level.unwrap_or(1).to_string())
.with_attr("PageNumberPosition", entry.page_number_position.as_deref().unwrap_or("AfterEntry"))
.with_attr("Separator", entry.separator.as_deref().unwrap_or("\t"))
.with_attr("PageNumberStyle", entry.page_number_style.as_deref().unwrap_or("CharacterStyle/$ID/[No character style]"))
.with_attr("SeparatorStyle", entry.separator_style.as_deref().unwrap_or("CharacterStyle/$ID/[No character style]"))
.with_attr("Sort", bool_str(entry.sort.unwrap_or(false))),
);
}
el
}
}
/// Date-based IDML text variable kinds.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TextDateKind {
@@ -259,6 +289,54 @@ impl CellStyleValues {
edge_strokes: ["TopEdge", "LeftEdge", "BottomEdge", "RightEdge"].map(|edge| values.stroke_values(edge)),
}
}
/// Emits a `CellStyle` element from these values.
pub fn to_el(&self) -> El {
let mut el = El::new("CellStyle");
if let Some(self_id) = &self.self_id {
el.attrs.push(("Self".into(), self_id.clone()));
}
if let Some(name) = &self.name {
el.attrs.push(("Name".into(), name.clone()));
}
if let Some(fill) = &self.fill {
el.attrs.push(("FillColor".into(), fill.clone()));
}
if let Some(tint) = self.fill_tint {
el.attrs.push(("FillTint".into(), num(tint)));
}
for ((text, legacy), value) in
[("TextTopInset", "TopInset"), ("TextLeftInset", "LeftInset"), ("TextBottomInset", "BottomInset"), ("TextRightInset", "RightInset")]
.iter()
.zip(self.insets)
{
if let Some(value) = value {
let s = num(value);
el.attrs.push(((*text).into(), s.clone()));
el.attrs.push(((*legacy).into(), s));
}
}
if let Some(vj) = &self.vertical_justification {
el.attrs.push(("VerticalJustification".into(), vj.clone()));
}
if let Some(fb) = &self.first_baseline {
el.attrs.push(("FirstBaselineOffset".into(), fb.clone()));
}
if let Some(min) = self.first_baseline_min {
el.attrs.push(("MinimumFirstBaselineOffset".into(), num(min)));
}
for (side, stroke) in ["TopEdge", "LeftEdge", "BottomEdge", "RightEdge"].iter().zip(&self.edge_strokes) {
stroke.push_prefixed_attrs(&mut el, side, false);
}
if let Some(ps) = &self.paragraph_style {
el.attrs.push(("AppliedParagraphStyle".into(), ps.clone()));
}
let based_on = match &self.based_on {
Some(base) if base != "$ID/[None]" => prop("BasedOn", "object", base.clone()),
_ => prop("BasedOn", "string", "$ID/[None]"),
};
with_props(el, vec![based_on])
}
}
/// Parsed table-style assignments that are independent of DesignCraft's style resolution.
@@ -309,6 +387,57 @@ impl TableStyleValues {
column_strokes: values.alternating_stroke_values("Column"),
}
}
/// Emits a `TableStyle` element from these values.
pub fn to_el(&self, self_id: &str) -> El {
let mut el = El::new("TableStyle").with_attr("Self", self_id);
if let Some(name) = &self.name {
el.attrs.push(("Name".into(), name.clone()));
}
for (key, value) in [
("HeaderRegionCellStyle", &self.header_cell_style),
("BodyRegionCellStyle", &self.body_cell_style),
("FooterRegionCellStyle", &self.footer_cell_style),
("LeftColumnRegionCellStyle", &self.left_column_cell_style),
("RightColumnRegionCellStyle", &self.right_column_cell_style),
] {
if let Some(value) = value {
el.attrs.push((key.into(), value.clone()));
}
}
for (key, value) in [
("HeaderRegionSameAsBodyRegion", self.header_same_as_body),
("FooterRegionSameAsBodyRegion", self.footer_same_as_body),
("LeftColumnRegionSameAsBodyRegion", self.left_column_same_as_body),
("RightColumnRegionSameAsBodyRegion", self.right_column_same_as_body),
] {
if let Some(value) = value {
el.attrs.push((key.into(), bool_str(value).into()));
}
}
for (side, stroke) in ["TopBorder", "LeftBorder", "BottomBorder", "RightBorder"].iter().zip(&self.border_strokes) {
stroke.push_prefixed_attrs(&mut el, side, false);
}
self.row_fills.push_attrs(&mut el, "Row");
self.column_fills.push_attrs(&mut el, "Column");
self.row_strokes.push_attrs(&mut el, "Row");
self.column_strokes.push_attrs(&mut el, "Column");
if let Some(value) = self.space_before {
el.attrs.push(("SpaceBefore".into(), num(value)));
}
if let Some(value) = self.space_after {
el.attrs.push(("SpaceAfter".into(), num(value)));
}
let mut props = Vec::new();
if let Some(base) = &self.based_on {
props.push(if base == "$ID/[No table style]" {
prop("BasedOn", "string", "$ID/[No table style]")
} else {
prop("BasedOn", "object", base.clone())
});
}
with_props(el, props)
}
}
impl NumberingListValues {
@@ -342,6 +471,13 @@ impl EpubSplitValues {
let values = Values::of(el);
Self { break_document: values.boolean("BreakDocument") == Some(true), paragraph_style: values.get("ParagraphStyleName").map(str::to_owned) }
}
/// Emits an `EPubExportPreference` element.
pub fn to_el(&self) -> El {
El::new("EPubExportPreference")
.with_attr("BreakDocument", bool_str(self.break_document))
.with_attr("ParagraphStyleName", self.paragraph_style.as_deref().unwrap_or(""))
}
}
impl TextVariableValues {
+83 -5
View File
@@ -31,7 +31,10 @@ pub use effects::{
DirectionalFeatherValues, DropShadowValues, FeatherValues, GradientFeatherValues, ObjectStyleStack, OpacityStopValues, TransparencySetting,
};
pub use geometry::{MAX_PATH_POINTS, PathGeometry, PathGeometryError, PathPoint, SubPath};
pub use preferences::{DocumentPreferences, FootnotePreferences, GridPreferences, TextFramePreferences};
pub use preferences::{
DocumentPreferences, FootnotePreferences, GridPreferences, TextFramePreferences, TextPreferenceValues, ViewPreferenceValues,
pasteboard_preference_el, transparency_preference_el,
};
pub use resources::{
CharacterAppearanceValues, CharacterSpecialValues, CharacterTypographyValues, CjkCharacterValues, CjkParagraphValues, ColorDefinition,
ColorGroup, ColorGroupDefinition, ColorGroupMember, ColorSpace, CompositeFontDefinition, CompositeFontEntryDefinition, EpubExportTagMap,
@@ -39,18 +42,19 @@ pub use resources::{
GrepStyleValue, Ink, InkDefinition, MojikumiRow, NestedLineStyleValue, NestedStyleValue, NestedStyleValues, ObjectStyleValues,
OpenTypeFeatureValues, ParagraphAlignmentValues, ParagraphBoxValues, ParagraphFlowValues, ParagraphListValues, ParagraphSpanValues, RubyValues,
StrokeDefinition, StrokeStyle, StrokeStyleKind, Style, StyleGroup, StyleGroupWriter, StyleKind, StyleNode, Swatch, SwatchKind, TabStopValues,
TextDecorationValues, TintDefinition, color_groups, inks, named, preference, stroke_styles, style_groups, swatches,
TextDecorationValues, TintDefinition, color_groups, inks, named, object_style_effects_category_settings, preference, stroke_styles, style_groups,
swatches,
};
pub use spread::{
BaselineFrameGridOption, BaselineFrameGridRelative, ClippingPathValues, FrameFittingOption, Graphic, GraphicChild, GraphicKind,
GraphicLayerOptions, Guide, ItemChild, ItemKind, Link, MarginPreference, Page, PageChild, PageItem, PdfAttribute, Spread, SpreadChild, TextPath,
TextWrapPreference, spreads,
GraphicLayerOptions, Guide, GuideValues, ItemChild, ItemKind, Link, MarginPreference, Page, PageChild, PageItem, PdfAttribute, Spread,
SpreadChild, TextPath, TextWrapPreference, spreads,
};
pub use story::{
Ace, AnchoredObjectSetting, AnchoredObjectValues, CONTAINERS, Cell, CellOptions, Container, ContainerKind, ContentPart, CrossReferenceSource,
IndexCrossReferenceValues, IndexDocument, IndexReference, IndexTopicPath, IndexValues, PageReference, Range, SavedCrossReference,
SavedCrossReferencePart, Story, StoryAnchor, StoryPreference, Table, TableChild, TableColumn, TableLayout, TableRow, TextNode, TrackedChangeKind,
stories,
stories, text_variable_instance_el, tracked_change_el,
};
use crate::value::{matrix, nums};
@@ -145,6 +149,30 @@ impl StrokeValues {
}
result
}
/// Writes prefixed cell/table stroke attributes onto `el`. When `line_style_for_kind` is
/// true, `kind` is written as `{prefix}LineStyle` (used for `EndColumnLineStyle`).
pub fn push_prefixed_attrs(&self, el: &mut El, prefix: &str, line_style_for_kind: bool) {
if let Some(value) = self.weight {
el.attrs.push((format!("{prefix}StrokeWeight"), crate::value::num(value)));
}
if let Some(value) = &self.color {
el.attrs.push((format!("{prefix}StrokeColor"), value.clone()));
}
if let Some(value) = self.tint {
el.attrs.push((format!("{prefix}StrokeTint"), crate::value::num(value)));
}
if let Some(value) = &self.kind {
let key = if line_style_for_kind { format!("{prefix}LineStyle") } else { format!("{prefix}StrokeType") };
el.attrs.push((key, value.clone()));
}
if let Some(value) = &self.gap_color {
el.attrs.push((format!("{prefix}StrokeGapColor"), value.clone()));
}
if let Some(value) = self.gap_tint {
el.attrs.push((format!("{prefix}StrokeGapTint"), crate::value::num(value)));
}
}
}
/// Raw fill properties before a caller resolves swatch names to its own colour model.
@@ -201,6 +229,56 @@ pub struct AlternatingStrokeValues {
pub skip_last: Option<f64>,
}
impl AlternatingFillValues {
/// Writes alternating row/column fill attributes onto `el`.
pub fn push_attrs(&self, el: &mut El, kind: &str) {
if let Some(value) = self.first_count {
el.attrs.push((format!("Start{kind}FillCount"), crate::value::num(value)));
}
if let Some(value) = &self.first_color {
el.attrs.push((format!("Start{kind}FillColor"), value.clone()));
}
if let Some(value) = self.first_tint {
el.attrs.push((format!("Start{kind}FillTint"), crate::value::num(value)));
}
if let Some(value) = self.next_count {
el.attrs.push((format!("End{kind}FillCount"), crate::value::num(value)));
}
if let Some(value) = &self.next_color {
el.attrs.push((format!("End{kind}FillColor"), value.clone()));
}
if let Some(value) = self.next_tint {
el.attrs.push((format!("End{kind}FillTint"), crate::value::num(value)));
}
if let Some(value) = self.skip_first {
el.attrs.push((format!("SkipFirstAlternatingFill{kind}s"), crate::value::num(value)));
}
if let Some(value) = self.skip_last {
el.attrs.push((format!("SkipLastAlternatingFill{kind}s"), crate::value::num(value)));
}
}
}
impl AlternatingStrokeValues {
/// Writes alternating row/column stroke attributes onto `el`.
pub fn push_attrs(&self, el: &mut El, kind: &str) {
if let Some(value) = self.first_count {
el.attrs.push((format!("Start{kind}StrokeCount"), crate::value::num(value)));
}
if let Some(value) = self.next_count {
el.attrs.push((format!("End{kind}StrokeCount"), crate::value::num(value)));
}
self.first.push_prefixed_attrs(el, &format!("Start{kind}"), false);
self.next.push_prefixed_attrs(el, &format!("End{kind}"), kind == "Column");
if let Some(value) = self.skip_first {
el.attrs.push((format!("SkipFirstAlternatingStroke{kind}s"), crate::value::num(value)));
}
if let Some(value) = self.skip_last {
el.attrs.push((format!("SkipLastAlternatingStroke{kind}s"), crate::value::num(value)));
}
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TableOptions {
pub direction: Option<String>,
+51
View File
@@ -418,3 +418,54 @@ fn inset(elements: &[&El]) -> Option<[f64; 4]> {
None
}
}
/// Document view-unit and ruler-origin preferences.
#[derive(Clone, Debug, PartialEq)]
pub struct ViewPreferenceValues {
pub horizontal_units: String,
pub vertical_units: String,
pub ruler_origin: String,
pub cursor_key_increment: f64,
}
impl ViewPreferenceValues {
/// Emits a canonical `ViewPreference` element.
pub fn to_el(&self) -> El {
El::new("ViewPreference")
.with_attr("HorizontalMeasurementUnits", &self.horizontal_units)
.with_attr("VerticalMeasurementUnits", &self.vertical_units)
.with_attr("RulerOrigin", &self.ruler_origin)
.with_attr("CursorKeyIncrement", crate::value::num(self.cursor_key_increment))
.with_attr("PointsPerInch", "72")
}
}
/// Document superscript and subscript text preferences.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TextPreferenceValues {
pub superscript_size: f64,
pub superscript_position: f64,
pub subscript_size: f64,
pub subscript_position: f64,
}
impl TextPreferenceValues {
/// Emits a canonical `TextPreference` element.
pub fn to_el(&self) -> El {
El::new("TextPreference")
.with_attr("SuperscriptSize", crate::value::num(self.superscript_size))
.with_attr("SuperscriptPosition", crate::value::num(self.superscript_position))
.with_attr("SubscriptSize", crate::value::num(self.subscript_size))
.with_attr("SubscriptPosition", crate::value::num(self.subscript_position))
}
}
/// Emits a `PasteboardPreference` element with horizontal and vertical margins in points.
pub fn pasteboard_preference_el(horizontal: f64, vertical: f64) -> El {
El::new("PasteboardPreference").with_attr("PasteboardMargins", format!("{} {}", crate::value::num(horizontal), crate::value::num(vertical)))
}
/// Emits a `TransparencyPreference` element for the given blending space (`"CMYK"` or `"RGB"`).
pub fn transparency_preference_el(blending_space: &str) -> El {
El::new("TransparencyPreference").with_attr("BlendingSpace", blending_space)
}
+16
View File
@@ -1406,6 +1406,22 @@ impl ObjectStyleValues {
}
}
/// Emits an `ObjectStyleObjectEffectsCategorySettings` element for an object style.
pub fn object_style_effects_category_settings(enable_drop_shadow: bool, enable_feather: bool) -> El {
let bool_s = |b: bool| if b { "true" } else { "false" };
El::new("ObjectStyleObjectEffectsCategorySettings")
.with_attr("EnableTransparency", "false")
.with_attr("EnableDropShadow", bool_s(enable_drop_shadow))
.with_attr("EnableFeather", bool_s(enable_feather))
.with_attr("EnableInnerShadow", "false")
.with_attr("EnableOuterGlow", "false")
.with_attr("EnableInnerGlow", "false")
.with_attr("EnableBevelEmboss", "false")
.with_attr("EnableSatin", "false")
.with_attr("EnableDirectionalFeather", "false")
.with_attr("EnableGradientFeather", "false")
}
impl StyleGroup {
/// The root group `el`; `None` when `el` is no root style group.
pub fn from_el(el: &El) -> Option<StyleGroup> {
+47
View File
@@ -236,6 +236,20 @@ impl MarginPreference {
let values: Option<Vec<f64>> = source.split_whitespace().take(limit).map(|v| v.parse::<f64>().ok().filter(|v| v.is_finite())).collect();
values.filter(|values| !values.is_empty())
}
/// Emits a `MarginPreference` element from resolved column and margin geometry.
pub fn to_el(column_count: usize, column_gutter: f64, top: f64, bottom: f64, left: f64, right: f64, columns_positions: &[f64]) -> El {
let positions: Vec<String> = columns_positions.iter().copied().map(crate::value::num).collect();
El::new("MarginPreference")
.with_attr("ColumnCount", column_count.max(1))
.with_attr("ColumnGutter", crate::value::num(column_gutter))
.with_attr("Top", crate::value::num(top))
.with_attr("Bottom", crate::value::num(bottom))
.with_attr("Left", crate::value::num(left))
.with_attr("Right", crate::value::num(right))
.with_attr("ColumnDirection", "Horizontal")
.with_attr("ColumnsPositions", positions.join(" "))
}
}
/// A child of a page, in document order.
@@ -324,6 +338,39 @@ pub struct Guide {
pub rest: Vec<El>,
}
/// Values for emitting an IDML `Guide` element.
#[derive(Clone, Debug, PartialEq)]
pub struct GuideValues {
pub self_id: String,
pub horizontal: bool,
pub location: f64,
pub fit_to_page: bool,
pub locked: bool,
pub page_index: usize,
pub liquid: bool,
pub item_layer: Option<String>,
}
impl GuideValues {
/// Emits a `Guide` element.
pub fn to_el(&self) -> El {
let bool_s = |b: bool| if b { "true" } else { "false" };
let mut el = El::new("Guide")
.with_attr("Self", &self.self_id)
.with_attr("Orientation", if self.horizontal { "Horizontal" } else { "Vertical" })
.with_attr("Location", crate::value::num(self.location))
.with_attr("FitToPage", bool_s(self.fit_to_page))
.with_attr("ViewThreshold", "5")
.with_attr("Locked", bool_s(self.locked))
.with_attr("PageIndex", self.page_index.to_string())
.with_attr("GuideType", if self.liquid { "Liquid" } else { "Ruler" });
if let Some(layer) = &self.item_layer {
el.attrs.push(("ItemLayer".into(), layer.clone()));
}
el
}
}
impl Guide {
/// `Orientation` is `Horizontal`; a guide is vertical otherwise.
pub fn horizontal(&self) -> bool {
+16
View File
@@ -351,6 +351,22 @@ impl CrossReferenceSource {
}
}
/// Emits a `TextVariableInstance` element inside a story character range.
pub fn text_variable_instance_el(self_id: &str, name: &str, result_text: &str, associated_var: &str) -> El {
El::new("TextVariableInstance")
.with_attr("Self", self_id)
.with_attr("Name", name)
.with_attr("ResultText", result_text)
.with_attr("AssociatedTextVariable", associated_var)
}
/// Emits a tracked-change `<Change>` element wrapping its story nodes.
pub fn tracked_change_el(self_id: &str, change_type: &str, children: Vec<Node>) -> El {
let mut el = El::new("Change").with_attr("Self", self_id).with_attr("ChangeType", change_type);
el.children = children;
el
}
#[derive(Clone, Debug, PartialEq)]
pub enum SavedCrossReferencePart {
Text(String),
+112
View File
@@ -408,3 +408,115 @@ fn designmap_layers_sections_and_hyperlinks_roundtrip_expected_attributes() {
assert_eq!(cg.attr("IsRootColorGroup"), Some("true"));
assert_eq!(cg.elements().count(), 2);
}
#[test]
fn preferences_styles_spread_and_story_schema_helpers_roundtrip() {
use craft_idml::Node;
use craft_idml::model::{
CellStyleValues, EpubSplitValues, GuideValues, MarginPreference, StrokeValues, TableStyleValues, TextPreferenceValues, TocStyleEntryValues,
TocStyleValues, ViewPreferenceValues, object_style_effects_category_settings, pasteboard_preference_el, text_variable_instance_el,
tracked_change_el, transparency_preference_el,
};
let view = ViewPreferenceValues {
horizontal_units: "Points".into(),
vertical_units: "Points".into(),
ruler_origin: "SpreadOrigin".into(),
cursor_key_increment: 1.0,
}
.to_el();
assert_eq!(view.attr("HorizontalMeasurementUnits"), Some("Points"));
assert_eq!(view.attr("PointsPerInch"), Some("72"));
let text_pref =
TextPreferenceValues { superscript_size: 58.3, superscript_position: 33.3, subscript_size: 58.3, subscript_position: 33.3 }.to_el();
assert_eq!(text_pref.attr("SuperscriptSize"), Some("58.3"));
assert_eq!(pasteboard_preference_el(72.0, 36.0).attr("PasteboardMargins"), Some("72 36"));
assert_eq!(transparency_preference_el("CMYK").attr("BlendingSpace"), Some("CMYK"));
let epub = EpubSplitValues { break_document: true, paragraph_style: Some("ParagraphStyle/H1".into()) };
assert_eq!(EpubSplitValues::from_el(&epub.to_el()), epub);
let margin = MarginPreference::to_el(2, 12.0, 36.0, 36.0, 36.0, 36.0, &[0.0, 200.0, 212.0, 412.0]);
let parsed_margin = MarginPreference::from_el(&margin);
assert_eq!(parsed_margin.column_count(), Some(2.0));
assert_eq!(parsed_margin.column_positions(4), Some(vec![0.0, 200.0, 212.0, 412.0]));
let guide = GuideValues {
self_id: "u1g0".into(),
horizontal: true,
location: 100.0,
fit_to_page: true,
locked: false,
page_index: 0,
liquid: false,
item_layer: Some("u2".into()),
}
.to_el();
assert_eq!(guide.attr("Orientation"), Some("Horizontal"));
assert_eq!(guide.attr("ItemLayer"), Some("u2"));
let cell_style = CellStyleValues {
self_id: Some("CellStyle/Header".into()),
name: Some("Header".into()),
based_on: Some("$ID/[None]".into()),
fill: Some("Color/Black".into()),
fill_tint: Some(20.0),
insets: [Some(4.0), Some(6.0), Some(4.0), Some(6.0)],
edge_strokes: [
StrokeValues { weight: Some(1.0), color: Some("Color/Black".into()), ..StrokeValues::default() },
StrokeValues::default(),
StrokeValues::default(),
StrokeValues::default(),
],
..CellStyleValues::default()
};
let parsed_cell = CellStyleValues::from_el(&cell_style.to_el());
assert_eq!(parsed_cell.insets, cell_style.insets);
assert_eq!(parsed_cell.edge_strokes[0].weight, Some(1.0));
let mut table_style = TableStyleValues {
name: Some("Grid".into()),
based_on: Some("$ID/[No table style]".into()),
space_before: Some(6.0),
..TableStyleValues::default()
};
table_style.column_strokes.next.kind = Some("Solid".into());
let table_el = table_style.to_el("TableStyle/Grid");
assert_eq!(table_el.attr("EndColumnLineStyle"), Some("Solid"));
assert_eq!(TableStyleValues::from_el(&table_el).column_strokes.next.kind.as_deref(), Some("Solid"));
let mut n = 0;
let toc = TocStyleValues {
self_id: Some("TOCStyle/Table of Contents".into()),
title: Some("Contents".into()),
title_style: Some("ParagraphStyle/Title".into()),
create_bookmarks: Some(true),
entries: vec![TocStyleEntryValues {
style: Some("Heading 1".into()),
level: Some(1),
page_number_position: Some("AfterEntry".into()),
separator: Some("\t".into()),
entry_style: Some("ParagraphStyle/TOC 1".into()),
page_number_style: None,
separator_style: None,
sort: Some(false),
}],
}
.to_el("Table of Contents", || {
n += 1;
format!("u{n}")
});
assert_eq!(toc.attr("CreateBookmarks"), Some("true"));
assert_eq!(toc.elements().count(), 1);
let obj_fx = object_style_effects_category_settings(true, false);
assert_eq!(obj_fx.attr("EnableDropShadow"), Some("true"));
assert_eq!(obj_fx.attr("EnableFeather"), Some("false"));
let tv = text_variable_instance_el("u9", "Chapter", "1", "dTextVariablenChapter");
assert_eq!(tv.attr("ResultText"), Some("1"));
let ch = tracked_change_el("u10", "InsertedText", vec![Node::El(craft_idml::El::new("Content"))]);
assert_eq!(ch.attr("ChangeType"), Some("InsertedText"));
}
+22 -2
View File
@@ -305,9 +305,29 @@ pub struct Attribute {
}
impl Attribute {
/// The first value as text.
/// The first value as text, including textWithLanguage and nameWithLanguage.
/// Malformed language framing, like a missing value, yields an empty string.
pub fn text(&self) -> String {
self.values.first().map(|v| String::from_utf8_lossy(v).into_owned()).unwrap_or_default()
self.values
.first()
.and_then(|value| {
let text = if matches!(self.tag, 0x35 | 0x36) {
// RFC 8010 section 3.9: two nonnegative SIGNED-SHORT lengths frame the language and text.
let language_len = i16::from_be_bytes(value.get(..2)?.try_into().ok()?);
let length_at = 2usize.checked_add(usize::try_from(language_len).ok()?)?;
let text_at = length_at.checked_add(2)?;
let text_len = i16::from_be_bytes(value.get(length_at..text_at)?.try_into().ok()?);
let text = value.get(text_at..)?;
if text.len() != usize::try_from(text_len).ok()? {
return None;
}
text
} else {
value.as_slice()
};
Some(String::from_utf8_lossy(text).into_owned())
})
.unwrap_or_default()
}
/// The first value as a big-endian integer.
pub fn int(&self) -> Option<i32> {
+70
View File
@@ -686,3 +686,73 @@ fn a_header_trickled_a_byte_at_a_time_is_found() {
assert!(raw.ends_with(b"\r\n\r\nok"), "{:?}", String::from_utf8_lossy(&raw));
server.join().unwrap();
}
fn language_value(language: &str, text: &[u8]) -> Vec<u8> {
let mut value = (language.len() as u16).to_be_bytes().to_vec();
value.extend_from_slice(language.as_bytes());
value.extend_from_slice(&(text.len() as u16).to_be_bytes());
value.extend_from_slice(text);
value
}
#[test]
fn language_tagged_text_uses_byte_lengths_and_keeps_plain_text_lossy() {
for tag in [0x35, 0x36] {
let value = language_value("de", "Büro 東京".as_bytes());
let attribute = Attribute { group: TAG_PRINTER_GROUP, tag, name: "text".into(), values: vec![value, b"ignored".to_vec()] };
assert_eq!(attribute.text(), "Büro 東京");
let attribute = Attribute { values: vec![language_value("en", b"bad\xfftext")], ..attribute };
assert_eq!(attribute.text(), "bad\u{fffd}text");
}
for tag in [TAG_TEXT, TAG_NAME] {
let attribute = Attribute { group: TAG_PRINTER_GROUP, tag, name: "text".into(), values: vec![b"plain\xfftext".to_vec()] };
assert_eq!(attribute.text(), "plain\u{fffd}text");
assert_eq!(Attribute { values: Vec::new(), ..attribute }.text(), "");
}
}
#[test]
fn malformed_language_lengths_do_not_become_printer_text() {
let malformed: &[&[u8]] = &[
b"",
b"\0",
b"\xff\xff",
b"\x80\0",
b"\0\x02e",
b"\0\x02en",
b"\0\x02en\0",
b"\0\x02en\xff\xff",
b"\0\x02en\x80\0",
b"\0\x02en\0\x02x",
b"\0\x02en\0\x01xy",
b"\x7f\xffen\0\0",
b"\0\x02en\x7f\xffx",
];
for tag in [0x35, 0x36] {
for value in malformed {
let attribute = Attribute { group: TAG_PRINTER_GROUP, tag, name: "text".into(), values: vec![value.to_vec()] };
assert_eq!(attribute.text(), "", "tag {tag:#x}: {value:?}");
}
let attribute = Attribute { group: TAG_PRINTER_GROUP, tag, name: "text".into(), values: vec![language_value("en", b"")] };
assert_eq!(attribute.text(), "");
}
}
#[test]
fn localized_queue_default_and_status_text_reach_callers() {
let name = language_value("en", b"Office");
let info = language_value("fr", "Imprimante générale".as_bytes());
let body = ipp(0, &[ok_header(), (TAG_PRINTER_GROUP, &[(0x36, "printer-name", &[&name]), (0x35, "printer-info", &[&info])])]);
for chunked in [false, true] {
let (ep, _rx) = fake(body.clone(), chunked, 200);
let list = queues(&ep, OP_CUPS_GET_PRINTERS, false).unwrap();
assert_eq!(list.len(), 1);
assert_eq!(list[0].name, "Office");
assert_eq!(list[0].info, "Imprimante générale");
assert_eq!(queue_path(&list[0].name, false).unwrap(), "/printers/Office");
let (ep, _rx) = fake(body.clone(), chunked, 200);
assert_eq!(default_printer(&ep).unwrap().as_deref(), Some("Office"));
let reply = ipp(0x0506, &[ok_header(), (TAG_OPERATION_GROUP, &[(0x35, "status-message", &[&info])])]);
let (ep, _rx) = fake(reply, chunked, 200);
assert_eq!(queues(&ep, OP_CUPS_GET_PRINTERS, false), Err(Error::Status(0x0506, "Imprimante générale".into())));
}
}
+22
View File
@@ -657,6 +657,28 @@ fn a_tabular_row_keeps_the_cells_a_table_row_holds() {
assert_eq!(t.rows.get(1).map(Vec::len), Some(2));
}
#[test]
fn a_script_on_a_script_exports_as_a_tex_group() {
use craft_math::math::{MNode, MRun, ScriptKind, to_linear};
let a = |t: &str| vec![MNode::Run(MRun::new(t))];
let sup = |base, s| MNode::Script { kind: ScriptKind::Sup, base, sub: Vec::new(), sup: s };
// sSup(sSup(a, b), c), as Word files hold it: the docx reader keeps `to_linear` of it.
let linear = to_linear(&[sup(vec![sup(a("a"), a("b"))], a("c"))]);
assert_eq!(linear, "〖a^b〗^c");
let mut d = Document::new();
let mut p = craft_wordmodel::Paragraph::new();
p.insert_object(0, craft_wordmodel::para::InlineObject::Equation { linear, display: false, math: Default::default() }, &Default::default())
.unwrap();
d.body = vec![craft_wordmodel::para_block(p)];
let tex = export(&d);
// The preamble sets up no Unicode math font, so `〖` would stop pdflatex.
assert!(tex.contains("${a^b}^c$") && !tex.contains('〖') && !tex.contains('〗'), "{tex}");
// Invisible brackets anywhere are a TeX group; one left unmatched is dropped.
for (linear, tex) in [("〖a+b〗^2", "{a+b}^2"), ("x^〖a〗", "x^{a}"), ("〖〖a〗^b〗^c", "{{a}^b}^c"), ("a〗b〖c", "abc")] {
assert_eq!(linear_to_latex(linear), tex, "{linear}");
}
}
#[test]
fn a_starred_line_break_shows_no_star() {
// `\\*` (a line break with no page break after it) left its `*` in the text.
+3
View File
@@ -12,6 +12,9 @@ workspace = true
[dependencies]
craft-xml = { workspace = true }
# A conforming XML parser (names, namespaces, characters), for checking kept OMML before it is
# written verbatim; already in the lock as a dependency of other crates.
roxmltree = "0.21"
serde = { workspace = true }
[dev-dependencies]
+53 -2
View File
@@ -235,7 +235,11 @@ pub fn linear_to_latex(linear: &str) -> String {
fn linear_to_latex_at(linear: &str, depth: usize) -> String {
let chars: Vec<char> = linear.chars().collect();
let parens = closers(&chars, '(', ')');
let brackets = closers(&chars, '〖', '〗');
let mut o = String::new();
// Where the output ended after the last plain letter written below: while it still ends
// there, its trailing letters are plain text, not a control word, and needn't be scanned.
let mut plain_end = usize::MAX;
let mut i = 0;
let sub = |s: &str| if depth < MAX_NEST { linear_to_latex_at(s, depth + 1) } else { escape_math_text(s) };
while let Some(&c) = chars.get(i) {
@@ -309,6 +313,16 @@ fn linear_to_latex_at(linear: &str, depth: usize) -> String {
o.push('\\');
o.push(c);
}
// Invisible brackets (`〖a^b〗^c`, a script base that isn't simple) only group: a TeX
// group. One without its partner shows nothing and is dropped.
'〖' => {
if let Some((inner, end)) = balanced(&chars, &brackets, i) {
o.push_str(&format!("{{{}}}", sub(&inner)));
i = end;
continue;
}
}
'〗' => {}
'{' => o.push_str("\\{"),
'}' => o.push_str("\\}"),
'~' => o.push_str("\\sim "),
@@ -322,7 +336,20 @@ fn linear_to_latex_at(linear: &str, depth: usize) -> String {
}
}
None if c.is_control() => {}
None => o.push(c),
None => {
// A letter after a control word would extend it. The lookahead above only sees
// the next input character, so a character dropped in between (an unmatched
// `〖` or `〗`, a control character) would join `\in` and `put` into `\input`.
// Scanning only when other output came since the last plain letter keeps a long
// run of letters linear.
if c.is_ascii_alphabetic() && o.len() != plain_end && ends_with_control_word(&o) {
o.push(' ');
}
o.push(c);
if c.is_ascii_alphabetic() {
plain_end = o.len();
}
}
},
}
i += 1;
@@ -330,9 +357,15 @@ fn linear_to_latex_at(linear: &str, depth: usize) -> String {
o.trim().to_string()
}
/// Does `o` end in a control word (`\` and letters), which a following letter would extend?
fn ends_with_control_word(o: &str) -> bool {
let head = o.trim_end_matches(|c: char| c.is_ascii_alphabetic());
head.len() < o.len() && head.ends_with('\\')
}
fn escape_math_text(s: &str) -> String {
let mut o = String::new();
for c in s.chars().filter(|c| !matches!(c, '{' | '}' | '\\' | '$' | '%' | '#' | '&') && !c.is_control()) {
for c in s.chars().filter(|c| !matches!(c, '{' | '}' | '\\' | '$' | '%' | '#' | '&' | '〖' | '〗') && !c.is_control()) {
// Never `^^` (see `linear_to_latex_at`).
if c == '^' && o.ends_with('^') {
continue;
@@ -626,4 +659,22 @@ mod tests {
assert!(!linear_to_latex(linear).contains("^^"), "{linear}");
}
}
/// A character the export drops (an unmatched invisible bracket, a control character) must not
/// join a control word to the letters after it: `\in〗put` would otherwise be `\input`.
#[test]
fn a_dropped_character_does_not_join_a_command_to_the_next_letters() {
for linear in ["\\in〗put x", "\\in〖put x", "∈〗put x", "∈〖put x", "\\in\u{1}put x", "∈\u{1}put x", "\\in〗〗〖put"] {
let tex = linear_to_latex(linear);
assert!(!tex.contains("\\input"), "{linear:?} → {tex}");
assert!(tex.starts_with("\\in put"), "{linear:?} → {tex}");
}
// A command followed by a letter directly is still separated, and grouping still works.
assert_eq!(linear_to_latex("∈x"), "\\in x");
assert_eq!(linear_to_latex("〖a+b〗^2"), "{a+b}^2");
// The check stays linear: a long run of letters, plain or after a command, is one pass.
let letters = "a".repeat(400_000);
assert_eq!(linear_to_latex(&letters).len(), 400_000);
assert_eq!(linear_to_latex(&format!("∈〗{letters}")), format!("\\in {letters}"));
}
}
+63 -11
View File
@@ -499,7 +499,12 @@ fn lin_arg(a: &[MNode], s: &mut String, depth: usize) {
// A bare script or limit ends at a space: a letter, digit or period after it is its own item.
if matches!(n, MNode::Script { kind, .. } if *kind != ScriptKind::Pre) || matches!(n, MNode::Lim { .. }) {
let ends_bare = s.chars().next_back().is_some_and(|c| c.is_alphanumeric() || c == '.');
if ends_bare && a.get(i + 1).and_then(first_lin_char).is_some_and(|c| c.is_alphanumeric() || c == '.') {
// So does a `,` before a digit: a number script reads it as part of the number (`x^2,3`).
let comma_digit = || {
let mut cs = a[i + 1..].iter().map_while(|n| if let MNode::Run(r) = n { Some(r.text.chars()) } else { None }).flatten();
cs.next() == Some(',') && cs.next().is_some_and(|c| c.is_ascii_digit())
};
if ends_bare && (a.get(i + 1).and_then(first_lin_char).is_some_and(|c| c.is_alphanumeric() || c == '.') || comma_digit()) {
s.push(' ');
}
}
@@ -518,11 +523,20 @@ fn first_lin_char(n: &MNode) -> Option<char> {
}
}
/// An argument as an operand: bare when it's a single simple atom, parenthesised otherwise.
fn lin_operand(a: &[MNode], s: &mut String, depth: usize) {
let mut inner = String::new();
lin_arg(a, &mut inner, depth);
let simple = match a {
/// Whether `t` is one number as the linear-format parser reads it (`number_len`): digits, where a
/// `.` or `,` continues it only before a digit (`2.5`, `1,000`), and a leading `.` before a digit
/// starts one (`.5`). `2.` isn't one: the parser leaves the point out.
fn is_number(t: &str) -> bool {
// Every character of a number is ASCII, so the bytes do.
let b = t.as_bytes();
let digit = |k: usize| b.get(k).is_some_and(u8::is_ascii_digit);
(digit(0) || (b.first() == Some(&b'.') && digit(1)))
&& b.iter().enumerate().all(|(k, &c)| c.is_ascii_digit() || (matches!(c, b'.' | b',') && digit(k + 1)))
}
/// Whether `a` is written bare as an operand: a single simple atom.
fn simple_operand(a: &[MNode]) -> bool {
match a {
[MNode::Run(r)] => {
let mut cs = r.text.chars();
match (cs.next(), cs.next()) {
@@ -532,8 +546,14 @@ fn lin_operand(a: &[MNode], s: &mut String, depth: usize) {
}
[MNode::Delim { .. }] => true,
_ => false,
};
if simple && !inner.is_empty() {
}
}
/// An argument as an operand: bare when it's a single simple atom, parenthesised otherwise.
fn lin_operand(a: &[MNode], s: &mut String, depth: usize) {
let mut inner = String::new();
lin_arg(a, &mut inner, depth);
if simple_operand(a) && !inner.is_empty() {
s.push_str(&inner);
} else {
s.push('(');
@@ -542,6 +562,37 @@ fn lin_operand(a: &[MNode], s: &mut String, depth: usize) {
}
}
/// A script base: bare when simple, else in invisible brackets `〖…〗`, as Word's Linear format
/// writes it. The parser reads them back as grouping only, so `〖a^b〗^c` keeps its tree, where
/// `(a^b)^c` would gain a visible delimiter (#6075). A base that is itself one invisible delimiter
/// (LaTeX `\left.a\right.`) gets an outer pair too, so the inner one reads back as that delimiter.
/// So does an operator (`⊗`, `×`, `<`…): a script after one reads as a pre-script, so `⊗_i` would
/// come back as `⊗` and a pre-script, where `〖⊗〗_i` keeps it the base. And so does a run of several
/// letters: the parser attaches a script to the last character before it (`mc^2` is `m`, `c²`), so
/// `mc` is written `〖mc〗^2`, as Word linearizes it (#6228). A number (`10^3`, as Word writes it) and
/// an upright function name (`sin^2`, read whole as a name) stay bare.
fn lin_base(a: &[MNode], s: &mut String, depth: usize) {
let mut inner = String::new();
lin_arg(a, &mut inner, depth);
let invisible = matches!(a, [MNode::Delim { beg: None, end: None, elems, .. }] if elems.len() == 1);
let operator = matches!(a, [MNode::Run(r)] if r.text.chars().all(crate::math_linear::is_boundary));
let name = |r: &MRun| r.sty == Some(MSty::Plain) && crate::math_linear::FUNCTION_NAMES.contains(&r.text.as_str());
// A number by the parser's rule (`1,000`, `2.5`, `.5`) is one item, so it stays bare too.
let number = matches!(a, [MNode::Run(r)] if is_number(&r.text));
let letters = matches!(a, [MNode::Run(r)] if r.text.chars().nth(1).is_some() && !number && !name(r));
// A base starting with a digit or `.` right after a digit, `.` or `,` would continue the number
// before it (`1` then `23^4` is `123^4`), so it keeps its brackets: `1〖23〗^4`.
let joins = s.chars().next_back().is_some_and(|c| c.is_ascii_digit() || matches!(c, '.' | ','))
&& inner.chars().next().is_some_and(|c| c.is_ascii_digit() || c == '.');
if (simple_operand(a) || number) && !inner.is_empty() && !invisible && !operator && !letters && !joins {
s.push_str(&inner);
} else {
s.push('〖');
s.push_str(&inner);
s.push('〗');
}
}
/// A script or limit operand. The parser reads a run of letters and digits up to the next space or
/// operator, so `V_dd` is written bare as Word's Linear format shows it (`V_(dd)` reads back the same).
fn lin_script(a: &[MNode], s: &mut String, depth: usize) {
@@ -586,7 +637,7 @@ fn lin_node(n: &MNode, s: &mut String, depth: usize) {
lin_operand(base, s, depth);
return;
}
lin_operand(base, s, depth);
lin_base(base, s, depth);
if matches!(kind, ScriptKind::Sub | ScriptKind::SubSup) {
s.push('_');
lin_script(sub, s, depth);
@@ -610,11 +661,12 @@ fn lin_node(n: &MNode, s: &mut String, depth: usize) {
}
MNode::Nary { chr, sub_hide, sup_hide, sub, sup, e, .. } => {
s.push(*chr);
if !sub_hide && !sub.is_empty() {
// A shown limit is written even when empty (`_()`): left out, it reads back hidden (#6076).
if !sub_hide {
s.push('_');
lin_script(sub, s, depth);
}
if !sup_hide && !sup.is_empty() {
if !sup_hide {
s.push('^');
lin_script(sup, s, depth);
}
+104 -16
View File
@@ -9,7 +9,9 @@
//! an operator or space; a parenthesised operand loses its parentheses). `^`/`_` with nothing
//! before them are pre-scripts. A top-level `#` numbers the equation (`E=mc^2#(1)`).
use crate::math::{Arg, FracKind, MAX_DEPTH, MClass, MNode, MRun, ScriptKind, any_too_deep, is_nary_char, math_class, merge_runs, too_deep};
use crate::math::{
Arg, FracKind, MAX_DEPTH, MClass, MNode, MRun, ScriptKind, WRAP_DEPTH, any_too_deep, is_nary_char, math_class, merge_runs, too_deep,
};
/// Function names set upright and applied to the following operand.
pub const FUNCTION_NAMES: &[&str] = &[
@@ -91,7 +93,7 @@ pub fn is_combining(c: char) -> bool {
}
/// Characters that end an operand.
fn is_boundary(c: char) -> bool {
pub(crate) fn is_boundary(c: char) -> bool {
matches!(c, ' ' | '&' | '@' | '#' | '▒' | '│' | '/' | '⁄' | '∕' | '¦' | '\u{2061}')
|| is_closer(c)
|| matches!(math_class(c), MClass::Bin | MClass::Rel | MClass::Punct)
@@ -116,6 +118,23 @@ impl P {
fn peek_at(&self, k: usize) -> Option<char> {
self.c.get(self.i + k).copied()
}
/// Length of the number at the cursor (0 if none), as Word reads one: digits, where a `.` or `,`
/// continues it only when a digit follows (`2.5`, `3.14`, `1,000`), and a leading `.` before a
/// digit starts one (`.5`). A trailing point (`2.`) isn't part of it.
fn number_len(&self) -> usize {
let digit = |k: usize| self.peek_at(k).is_some_and(|c| c.is_ascii_digit());
if !digit(0) && !(self.peek() == Some('.') && digit(1)) {
return 0;
}
let mut k = 0;
loop {
match self.peek_at(k) {
Some(c) if c.is_ascii_digit() => k += 1,
Some('.' | ',') if digit(k + 1) => k += 1,
_ => return k,
}
}
}
fn tired(&mut self) -> bool {
self.steps += 1;
self.steps > MAX_STEPS || self.depth > MAX_DEPTH
@@ -171,14 +190,15 @@ impl P {
if pre {
out.push(self.prescript(stops));
} else {
let group = self.after_group();
self.i += 1;
let s = self.script_operand(stops);
let s = self.script_chain(c, stops, 0);
if out.last().is_some_and(too_deep) {
out.push(text(c));
out.extend(s);
} else {
let base = out.pop();
out.push(attach_script(base, c == '^', s));
out.push(attach_script(base, c == '^', s, group));
}
}
}
@@ -242,10 +262,23 @@ impl P {
if c.is_ascii_alphabetic() {
return self.word(stops);
}
// A number is one item, so a script or a fraction takes all of it (`10^3`, `2.5/3`), as Word
// reads it (#6229).
let n = self.number_len();
if n > 0 {
let t: String = self.c.get(self.i..self.i + n).unwrap_or(&[]).iter().collect();
self.i += n;
return vec![MNode::Run(MRun::new(t))];
}
self.i += 1;
vec![text(c)]
}
/// The character just before the cursor closed a `〖…〗` group.
fn after_group(&self) -> bool {
self.i.checked_sub(1).and_then(|k| self.c.get(k)) == Some(&'〗')
}
/// A bracket group after its opening character; `closers` end it.
fn group(&mut self, open: Option<char>, closers: &[char]) -> MNode {
let mut stops: Vec<char> = closers.to_vec();
@@ -449,12 +482,15 @@ impl P {
}
Some(c @ ('^' | '_')) => {
self.i += 1;
let s = self.script_operand(stops);
let mut n = attach_script(Some(MNode::Run(MRun::plain(word.clone()))), c == '^', s);
if let Some(c2 @ ('^' | '_')) = self.peek() {
// `sin^2^3` nests to the right like any other script (#6074).
let s = self.script_chain(c, stops, 0);
let mut n = attach_script(Some(MNode::Run(MRun::plain(word.clone()))), c == '^', s, false);
// Only the other script joins it, and it nests the same way (`log_2^3`, `sin^2_a_b`);
// the same one again is what the chain left at its depth cap.
if let Some(c2 @ ('^' | '_')) = self.peek().filter(|&c2| c2 != c) {
self.i += 1;
let s2 = self.script_operand(stops);
n = attach_script(Some(n), c2 == '^', s2);
let s2 = self.script_chain(c2, stops, 0);
n = attach_script(Some(n), c2 == '^', s2, false);
}
vec![n]
}
@@ -465,7 +501,10 @@ impl P {
self.i += 1;
}
let next = self.peek();
let applies = next.is_some_and(|c| !stops.contains(&c) && !is_closer(c) && (!is_boundary(c) || c == '(' || matches!(c, '−' | '-' | '+')));
// A `^`/`_` here is what the script chain left at its depth cap: text for `expr`, not an operand.
let applies = next.is_some_and(|c| {
!stops.contains(&c) && !is_closer(c) && !matches!(c, '^' | '_') && (!is_boundary(c) || c == '(' || matches!(c, '−' | '-' | '+'))
});
if !applies {
return name;
}
@@ -575,6 +614,7 @@ impl P {
}
// The base is already deep: the operator is text (see `too_deep`).
let deep = if whole { any_too_deep(out) } else { out.last().is_some_and(too_deep) };
let group = self.after_group();
self.i += 1;
if deep {
let s = if matches!(c, '^' | '_' | '┬' | '┴') { self.script_operand(stops) } else { Vec::new() };
@@ -584,9 +624,9 @@ impl P {
}
match c {
'^' | '_' => {
let s = self.script_operand(stops);
let s = self.script_chain(c, stops, 0);
let b = base(out);
out.push(attach_script(b, c == '^', s));
out.push(attach_script(b, c == '^', s, group));
}
'┬' | '┴' => {
let lim = self.script_operand(stops);
@@ -601,6 +641,32 @@ impl P {
}
}
/// A script operand, with the same script operator after it nested inside: `a^b^c` is
/// `a^(b^c)`, as Word builds it (#6074). The chain stops at `WRAP_DEPTH` like every other
/// wrap, so `x^1^1^1…` stays shallow (#1456) and the rest is left to the caller as text. The
/// cap holds for the whole tree too: when the operands are deep themselves, a level that would
/// make it too deep keeps its operator as text, as `expr` does.
fn script_chain(&mut self, op: char, stops: &[char], level: usize) -> Arg {
let s = self.script_operand(stops);
if self.peek() != Some(op) || s.is_empty() || level + 1 >= WRAP_DEPTH || self.tired() || any_too_deep(&s) {
return s;
}
self.i += 1;
self.depth += 1;
let inner = self.script_chain(op, stops, level + 1);
self.depth -= 1;
let (kind, sub, sup) = if op == '^' { (ScriptKind::Sup, Vec::new(), inner) } else { (ScriptKind::Sub, inner, Vec::new()) };
let node = MNode::Script { kind, base: s, sub, sup };
if !too_deep(&node) {
return vec![node];
}
let MNode::Script { base: mut out, sub, sup, .. } = node else { return Vec::new() };
out.push(text(op));
out.extend(sub);
out.extend(sup);
out
}
/// A script or limit: a parenthesised group, a structure, a number, a signed operand, a run of
/// letters (and digits) or one other character.
fn script_operand(&mut self, stops: &[char]) -> Arg {
@@ -624,10 +690,18 @@ impl P {
}
}
Some(c) if is_prefix(c) || closer(c).is_some() => self.atom(stops),
Some(c) if c.is_ascii_digit() => {
Some(c) if c.is_ascii_digit() || self.number_len() > 0 => {
// A number by `number_len`'s rule (`2.5`, `1,000`, `.5`; `x^2.` keeps the point out),
// and letters after it stay in the script (`V_10a`, #1609).
let start = self.i;
while self.peek().is_some_and(|k| k.is_alphanumeric() || k == '.') {
self.i += 1;
while let Some(k) = self.peek() {
if k.is_alphanumeric() {
self.i += 1;
} else if matches!(k, '.' | ',') && self.peek_at(1).is_some_and(|n| n.is_ascii_digit()) {
self.i += 2;
} else {
break;
}
}
let t: String = self.c.get(start..self.i).unwrap_or(&[]).iter().collect();
vec![MNode::Run(MRun::new(t))]
@@ -683,10 +757,21 @@ pub fn strip_parens(mut a: Arg) -> Arg {
a
}
fn attach_script(base: Option<MNode>, sup: bool, s: Arg) -> MNode {
/// `group`: the base was just closed by `〗`, so a characterless delimiter around it is that grouping
/// (and dropped), not an explicit `├…┤` one (kept).
fn attach_script(base: Option<MNode>, sup: bool, s: Arg, group: bool) -> MNode {
match base {
Some(MNode::Script { kind: ScriptKind::Sub, base, sub, .. }) if sup => MNode::Script { kind: ScriptKind::SubSup, base, sub, sup: s },
Some(MNode::Script { kind: ScriptKind::Sup, base, sup: sp, .. }) if !sup => MNode::Script { kind: ScriptKind::SubSup, base, sub: s, sup: sp },
// `〖…〗` only groups: as a script base it leaves no delimiter, as Word builds it (#6075).
Some(MNode::Delim { beg: None, end: None, mut elems, .. }) if group && elems.len() == 1 => {
let base = elems.pop().unwrap_or_default();
if sup {
MNode::Script { kind: ScriptKind::Sup, base, sub: Vec::new(), sup: s }
} else {
MNode::Script { kind: ScriptKind::Sub, base, sub: s, sup: Vec::new() }
}
}
b => {
let base = b.map(|b| vec![b]).unwrap_or_default();
if sup {
@@ -760,3 +845,6 @@ pub fn map_args(n: MNode, f: &dyn Fn(Arg) -> Arg) -> MNode {
MNode::Phant { show, zero_wid, zero_asc, zero_desc, e } => MNode::Phant { show, zero_wid, zero_asc, zero_desc, e: f(e) },
}
}
#[cfg(test)]
mod tests;
+253
View File
@@ -0,0 +1,253 @@
//! The linear format (UnicodeMath) parser: one case per construct in the module doc. Where Word
//! builds the same text (observed with Word's build-up), the expected tree is the one Word builds;
//! where it differs, the case says so.
use super::*;
use crate::math::{ColJc, to_linear};
fn r(t: &str) -> MNode {
MNode::Run(MRun::new(t))
}
fn a(t: &str) -> Arg {
vec![r(t)]
}
fn up(t: &str) -> Arg {
vec![MNode::Run(MRun::plain(t))]
}
fn sup(base: Arg, s: Arg) -> MNode {
MNode::Script { kind: ScriptKind::Sup, base, sub: Vec::new(), sup: s }
}
fn sub(base: Arg, s: Arg) -> MNode {
MNode::Script { kind: ScriptKind::Sub, base, sub: s, sup: Vec::new() }
}
fn frac(kind: FracKind, num: Arg, den: Arg) -> MNode {
MNode::Frac { kind, num, den }
}
/// A delimiter as the parser makes it: one element has no separator.
fn delim(beg: Option<char>, end: Option<char>, elems: Vec<Arg>) -> MNode {
let sep = (elems.len() > 1).then_some('|');
MNode::Delim { beg, end, sep, grow: true, shp_match: false, elems }
}
#[track_caller]
fn parses(s: &str, want: Arg) {
assert_eq!(parse(s), want, "{s}");
}
/// Linear text printed back from the tree parses to the same tree.
#[track_caller]
fn stable(s: &str) {
let n = parse(s);
let back = to_linear(&n);
assert_eq!(parse(&back), n, "{s} → {back}");
}
// --- Fractions. ---------------------------------------------------------------------------------
#[test]
fn fraction_operators() {
parses("a/b+c", vec![frac(FracKind::Bar, a("a"), a("b")), r("+c")]);
parses("a⁄b", vec![frac(FracKind::Skewed, a("a"), a("b"))]);
parses("a∕b", vec![frac(FracKind::Linear, a("a"), a("b"))]);
parses("a¦b", vec![frac(FracKind::NoBar, a("a"), a("b"))]);
// A parenthesised operand loses its parentheses; `/` groups to the left (as in Word).
parses("(a+b)/(c+d)", vec![frac(FracKind::Bar, a("a+b"), a("c+d"))]);
parses("a/b/c", vec![frac(FracKind::Bar, vec![frac(FracKind::Bar, a("a"), a("b"))], a("c"))]);
// Placeholders are empty arguments; a missing denominator is empty.
parses("⬚/⬚", vec![frac(FracKind::Bar, vec![], vec![])]);
parses("a/", vec![frac(FracKind::Bar, a("a"), vec![])]);
}
// --- Scripts. -----------------------------------------------------------------------------------
#[test]
fn scripts() {
parses("x^(-1)", vec![sup(a("x"), a("-1"))]);
parses("x_i^2", vec![MNode::Script { kind: ScriptKind::SubSup, base: a("x"), sub: a("i"), sup: a("2") }]);
// Either order makes one sub-superscript.
parses("a^b_c", vec![MNode::Script { kind: ScriptKind::SubSup, base: a("a"), sub: a("c"), sup: a("b") }]);
parses("x_(i_j)", vec![sub(a("x"), vec![sub(a("i"), a("j"))])]);
}
/// `^`/`_` with nothing before them are pre-scripts (module doc). Word's build-up doesn't make an
/// `m:sPre` from this text.
#[test]
fn pre_scripts() {
parses("_1^n▒Y", vec![MNode::Script { kind: ScriptKind::Pre, base: a("Y"), sub: a("1"), sup: a("n") }]);
}
// --- Radicals, n-ary operators, functions, limits. ----------------------------------------------
#[test]
fn radicals() {
parses("√x", vec![MNode::Rad { deg: vec![], deg_hide: true, e: a("x") }]);
parses("√(3&x)", vec![MNode::Rad { deg: a("3"), deg_hide: false, e: a("x") }]);
parses("√", vec![MNode::Rad { deg: vec![], deg_hide: true, e: vec![] }]);
}
#[test]
fn nary_operators() {
let nary = |chr, sub, sup, e| MNode::Nary { chr, lim_loc: None, grow: false, sub_hide: false, sup_hide: false, sub, sup, e };
parses("∑_(i=1)^n▒i^2", vec![nary('∑', a("i=1"), a("n"), vec![sup(a("i"), a("2"))])]);
parses("∫_0^1▒f(x)dx", vec![nary('∫', a("0"), a("1"), vec![r("f"), delim(Some('('), Some(')'), vec![a("x")]), r("dx")])]);
}
#[test]
fn function_names() {
parses("sin x", vec![MNode::Func { name: up("sin"), e: a("x") }]);
parses("log_2 x", vec![MNode::Func { name: vec![sub(up("log"), a("2"))], e: a("x") }]);
parses("lim┬(n→∞) a_n", vec![MNode::Func { name: vec![MNode::Lim { upper: false, e: up("lim"), lim: a("n→∞") }], e: vec![sub(a("a"), a("n"))] }]);
}
#[test]
fn limits_on_any_base() {
parses("x┬k", vec![MNode::Lim { upper: false, e: a("x"), lim: a("k") }]);
parses("x┴k", vec![MNode::Lim { upper: true, e: a("x"), lim: a("k") }]);
parses("a/b┬c", vec![frac(FracKind::Bar, a("a"), vec![MNode::Lim { upper: false, e: a("b"), lim: a("c") }])]);
}
// --- Brackets. ----------------------------------------------------------------------------------
#[test]
fn brackets() {
parses("(a│b)", vec![delim(Some('('), Some(')'), vec![a("a"), a("b")])]);
parses("|x|+‖v‖", vec![delim(Some('|'), Some('|'), vec![a("x")]), r("+"), delim(Some('‖'), Some('‖'), vec![a("v")])]);
parses("f'(x)", vec![r("f'"), delim(Some('('), Some(')'), vec![a("x")])]);
// `├`…`┤` make one-sided or reversed brackets (module doc; Word's build-up leaves `├]a[┤` as
// text, but builds `{█(x@y)┤`).
parses("├]a[┤", vec![delim(Some(']'), Some('['), vec![a("a")])]);
parses("{█(x@y)┤", vec![delim(Some('{'), None, vec![vec![MNode::EqArr { rows: vec![a("x"), a("y")] }]])]);
// An unclosed bracket closes at the end; stray closers are text.
parses("(a", vec![delim(Some('('), None, vec![a("a")])]);
parses("a)", a("a)"));
parses("]x", a("]x"));
parses(")a(", vec![r(")a"), delim(Some('('), None, vec![vec![]])]);
}
// --- Prefix structures and accents. -------------------------------------------------------------
#[test]
fn prefix_structures() {
parses("▭(a)", vec![MNode::BorderBox { hide: [false; 4], strike: [false; 4], e: a("a") }]);
parses("□(a)", vec![MNode::Boxed { e: a("a") }]);
parses("¯(ab)", vec![MNode::Bar { top: true, e: a("ab") }]);
parses("▁(ab)", vec![MNode::Bar { top: false, e: a("ab") }]);
parses("⏞(a+b)", vec![MNode::GroupChr { chr: '⏞', top: true, e: a("a+b") }]);
parses("⏟(a+b)", vec![MNode::GroupChr { chr: '⏟', top: false, e: a("a+b") }]);
}
#[test]
fn combining_accents() {
parses("A\u{20D7}", vec![MNode::Acc { chr: '\u{20D7}', e: a("A") }]);
parses("x\u{302}", vec![MNode::Acc { chr: '\u{302}', e: a("x") }]);
assert!(is_combining('\u{302}') && is_combining('\u{20D7}'));
assert!(!is_combining('x') && !is_combining('^'));
}
// --- Arrays and numbering. ----------------------------------------------------------------------
#[test]
fn arrays() {
parses("█(a=b@c=d)", vec![MNode::EqArr { rows: vec![a("a=b"), a("c=d")] }]);
parses("█(a@b", vec![MNode::EqArr { rows: vec![a("a"), a("b")] }]);
// Column alignments are left to the writer (it writes centred columns).
parses("■(a&b@c&d)", vec![MNode::Matrix { rows: vec![vec![a("a"), a("b")], vec![a("c"), a("d")]], col_jc: Vec::<ColJc>::new() }]);
}
#[test]
fn a_top_level_hash_numbers_the_equation() {
let number = delim(Some('('), Some(')'), vec![a("1")]);
parses("E=mc^2#(1)", vec![MNode::EqArr { rows: vec![vec![r("E=m"), sup(a("c"), a("2")), r("#"), number]] }]);
assert!(matches!(&parse("a=b#")[..], [MNode::EqArr { rows }] if rows.len() == 1));
assert!(!matches!(&parse("a=b")[..], [MNode::EqArr { .. }]));
}
// --- Helpers. -----------------------------------------------------------------------------------
#[test]
fn closers_pair_with_openers() {
for (o, c) in [('(', ')'), ('[', ']'), ('{', '}'), ('⟨', '⟩'), ('〈', '〉'), ('⌈', '⌉'), ('⌊', '⌋'), ('⟦', '⟧'), ('〖', '〗')]
{
assert_eq!(closer(o), Some(c));
assert!(is_closer(c));
}
assert_eq!(closer('a'), None);
assert_eq!(closer('|'), None, "| closes itself, by matching");
}
#[test]
fn strip_parens_unwraps_one_plain_group() {
let inner = a("a+b");
assert_eq!(strip_parens(vec![delim(Some('('), Some(')'), vec![inner.clone()])]), inner);
assert_eq!(strip_parens(vec![delim(None, None, vec![inner.clone()])]), inner, "invisible brackets");
let square = vec![delim(Some('['), Some(']'), vec![inner.clone()])];
assert_eq!(strip_parens(square.clone()), square, "only round or invisible brackets");
let two = vec![delim(Some('('), Some(')'), vec![a("a"), a("b")])];
assert_eq!(strip_parens(two.clone()), two, "only one element");
let more = vec![delim(Some('('), Some(')'), vec![inner]), r("c")];
assert_eq!(strip_parens(more.clone()), more, "only a lone group");
}
// --- Round trip through `to_linear`. ------------------------------------------------------------
#[test]
fn every_construct_prints_back_to_the_same_tree() {
for s in [
"a/b+c",
"(a+b)/(c+d)",
"a/b/c",
"a⁄b",
"a∕b",
"a¦b",
"⬚/⬚",
"x_i^2",
"a^b_c",
"x^(-1)",
"x_(i_j)",
"_1^n▒Y",
"√x",
"√(3&x)",
"∑_(i=1)^n▒i^2",
"∫_0^1▒f(x)dx",
"sin x",
"log_2 x",
"lim┬(n→∞) a_n",
"x┬k",
"x┴k",
"a/b┬c",
"(a│b)",
"|x|+‖v‖",
"f'(x)",
"├]a[┤",
"{█(x@y)┤",
"(a",
")a(",
"▭(a)",
"□(a)",
"¯(ab)",
"▁(ab)",
"⏞(a+b)",
"⏟(a+b)",
"A\u{20D7}",
"x\u{302}",
"█(a=b@c=d)",
"■(a&b@c&d)",
"E=mc^2#(1)",
] {
stable(s);
}
}
#[test]
fn truncated_input_parses() {
for s in ["√", "(a", "a/", "█(a@b", "x_", "■(", "├", "┤", "〖", "#", "▒", "/", "^", "_"] {
let n = parse(s);
assert_eq!(parse(&to_linear(&n)), n, "{s:?} → {:?}", to_linear(&n));
}
}
+29 -2
View File
@@ -58,9 +58,36 @@ fn parse_kept(xml: &str) -> Option<El> {
Options { ns_decls: false, ..Options::default() }.with_limits(limits).parse(xml.as_bytes()).ok()
}
/// Is `xml` (kept OMML) well-formed enough to write back as it is?
/// Whether `xml` (kept OMML) can be written back as it is: exactly one well-formed `m:oMath` (not
/// `m:oMathPara`), with nothing around it. The writer copies it verbatim into the host document,
/// and [`Math::omml`] also comes from documents saved as JSON, so anything else (an unclosed or
/// mismatched tag, an unknown entity, markup or text after the element, an `m:oMathPara` that
/// would be nested in a second one) is written from the nodes instead (wordcraft#6072).
///
/// The strict [`craft_xml`] read bounds the nesting and rejects bad tags, entities and trailing
/// content, but it is lenient about the rest of XML: names that aren't XML names, undeclared
/// prefixes, two attributes with one expanded name, a `<` in an attribute value, `]]>` in text,
/// characters XML 1.0 doesn't allow. A conforming parser rejects all of those, so it runs last,
/// with only the canonical prefixes of kept OMML declared (`m:`, `w:`, `mc:`, as the host
/// document's root declares them): any other prefix is undeclared there. The element must be
/// `m:oMath` by namespace, so an `m:` bound to another URI isn't one.
fn is_well_formed(xml: &str) -> bool {
xml.starts_with("<m:oMath") && Options::default().strict().parse(xml.as_bytes()).is_ok()
// The name ends at `>` or XML whitespace (XML 1.0 §2.3 S), not at `/>` (an empty equation) or
// a longer name (`m:oMathPara`).
let named = xml.strip_prefix("<m:oMath").and_then(|r| r.chars().next()).is_some_and(|c| matches!(c, '>' | ' ' | '\t' | '\r' | '\n'));
// Both parses are capped as the reader caps what it keeps ([`parse`]): kept OMML can come from
// a hostile JSON document, and a larger one is written from its nodes.
let limits = craft_xml::Limits { max_nodes: MAX_ELEMENTS.saturating_mul(2), ..craft_xml::Limits::DEFAULT };
if !named || Options::default().strict().with_limits(limits).parse(xml.as_bytes()).is_err() {
return false;
}
let wrapped = format!("<x xmlns:m=\"{MATH_NS}\" xmlns:w=\"{W_NS}\" xmlns:mc=\"{MC_NS}\">{xml}</x>");
// The wrapper and the document root are two more nodes.
let nodes_limit = u32::try_from(limits.max_nodes.saturating_add(2)).unwrap_or(u32::MAX);
let options = roxmltree::ParsingOptions { nodes_limit, ..roxmltree::ParsingOptions::default() };
let Ok(doc) = roxmltree::Document::parse_with_options(&wrapped, options) else { return false };
let mut nodes = doc.root_element().children();
matches!((nodes.next(), nodes.next()), (Some(e), None) if e.tag_name().namespace() == Some(MATH_NS) && e.tag_name().name() == "oMath")
}
/// An equation from OMML text ([`parse`]): an `m:oMathPara`'s first `m:oMath` with the
+17 -1
View File
@@ -44,7 +44,7 @@ pub fn write_equation(w: &mut W, linear: &str, display: bool, math: &Math, color
w.close("m:oMathParaPr");
}
}
if !math.omml.is_empty() && math.omml.starts_with("<m:oMath") && is_well_formed(&math.omml) {
if is_well_formed(&math.omml) {
w.raw(&math.omml);
} else {
let parsed;
@@ -434,7 +434,11 @@ fn run(w: &mut W, r: &MRun) {
MSty::Italic => "i",
MSty::BoldItalic => "bi",
});
// `CT_RPR` holds `m:nor` or `m:scr`/`m:sty`, not both, and Word drops the `m:sty` of a normal-text
// run: its bold and italic go in `w:rPr` below, where the reader takes them back (#6073).
let sty = sty.filter(|_| !r.nor);
let scr = match r.scr {
_ if r.nor => None,
MScr::Roman => None,
MScr::Script => Some("script"),
MScr::Fraktur => Some("fraktur"),
@@ -466,6 +470,15 @@ fn run(w: &mut W, r: &MRun) {
w.open("w:rPr", &[]);
let font = r.font.as_deref().filter(|_| r.nor).unwrap_or("Cambria Math");
w.empty("w:rFonts", &[("w:ascii", font), ("w:hAnsi", font)]);
// Normal text's bold and italic (see `sty` above).
if r.nor {
if matches!(r.sty, Some(MSty::Bold | MSty::BoldItalic)) {
w.empty("w:b", &[]);
}
if matches!(r.sty, Some(MSty::Italic | MSty::BoldItalic)) {
w.empty("w:i", &[]);
}
}
if let Some(c) = r.color {
w.val("w:color", &c.hex());
}
@@ -478,3 +491,6 @@ fn run(w: &mut W, r: &MRun) {
w.leaf("m:t", &[("xml:space", "preserve")], &r.text);
w.close("m:r");
}
#[cfg(test)]
mod tests;
+613
View File
@@ -0,0 +1,613 @@
//! The OMML writer: content and values are checked by writing a tree and reading it back with
//! [`crate::omml::read_omath`]; element order, which the reader can't see (it looks children
//! up by name), is checked against exact XML. The golden strings were checked against the
//! ECMA-376 shared-math schema (`CT_*` sequences); they come from this writer, not from Word.
use super::*;
use crate::math::to_linear;
const RED: Rgb = Rgb(0xFF, 0, 0);
const GREEN: Rgb = Rgb(0, 0x80, 0);
const BLUE: Rgb = Rgb(0, 0, 0xFF);
fn r(t: &str) -> MNode {
MNode::Run(MRun::new(t))
}
fn a(t: &str) -> Arg {
vec![r(t)]
}
fn delim(beg: Option<char>, end: Option<char>, elems: Vec<Arg>) -> MNode {
MNode::Delim { beg, end, sep: Some('|'), grow: true, shp_match: false, elems }
}
fn math(nodes: Arg) -> Math {
Math { nodes, ..Default::default() }
}
/// `write_equation` into a fresh writer, without the XML declaration.
fn write(m: &Math, linear: &str, display: bool, color: Option<Rgb>) -> String {
let mut w = W::default();
write_equation(&mut w, linear, display, m, color);
w.s
}
fn xml(nodes: &Arg) -> String {
write(&math(nodes.clone()), "", false, None)
}
/// Read written OMML back (inline or display), as the DOCX reader does.
fn read(xml: &str) -> Math {
let e = crate::omml::parse(xml).unwrap();
match e.name.as_str() {
"m:oMathPara" => read_omath(e.find("m:oMath").unwrap(), crate::omml::para_jc(&e)),
_ => read_omath(&e, MathJc::CenterGroup),
}
}
fn round_trip(nodes: &Arg) -> Arg {
read(&xml(nodes)).nodes
}
#[track_caller]
fn assert_round_trip(label: &str, nodes: Arg) {
assert_eq!(round_trip(&nodes), nodes, "{label}: {}", xml(&nodes));
}
/// The equation's runs.
fn runs(nodes: &Arg) -> Vec<MRun> {
let mut out = Vec::new();
let mut n = nodes.clone();
crate::math_tree::each_run_mut(&mut n, &mut |r| out.push(r.clone()));
out
}
// --- Round trip: every structure and option comes back as written. -----------------------------
#[test]
fn every_structure_round_trips() {
use MNode::*;
for kind in [FracKind::Bar, FracKind::Skewed, FracKind::Linear, FracKind::NoBar] {
assert_round_trip("frac", vec![Frac { kind, num: a("a"), den: a("b") }]);
}
assert_round_trip("empty frac", vec![Frac { kind: FracKind::Bar, num: vec![], den: vec![] }]);
assert_round_trip("sup", vec![Script { kind: ScriptKind::Sup, base: a("x"), sub: vec![], sup: a("2") }]);
assert_round_trip("sub", vec![Script { kind: ScriptKind::Sub, base: a("x"), sub: a("i"), sup: vec![] }]);
assert_round_trip("subsup", vec![Script { kind: ScriptKind::SubSup, base: a("x"), sub: a("i"), sup: a("2") }]);
assert_round_trip("pre", vec![Script { kind: ScriptKind::Pre, base: a("x"), sub: a("i"), sup: a("2") }]);
assert_round_trip("sqrt", vec![Rad { deg: vec![], deg_hide: true, e: a("x") }]);
assert_round_trip("root", vec![Rad { deg: a("3"), deg_hide: false, e: a("x") }]);
assert_round_trip("empty degree shown", vec![Rad { deg: vec![], deg_hide: false, e: a("x") }]);
for (chr, lim_loc) in [('∫', None), ('∑', Some(LimLoc::UndOvr)), ('∏', Some(LimLoc::SubSup))] {
assert_round_trip("nary", vec![Nary { chr, lim_loc, grow: false, sub_hide: false, sup_hide: false, sub: a("i"), sup: a("n"), e: a("x") }]);
}
assert_round_trip(
"nary flags",
vec![Nary { chr: '∑', lim_loc: None, grow: true, sub_hide: true, sup_hide: true, sub: vec![], sup: vec![], e: a("x") }],
);
assert_round_trip("parens", vec![delim(Some('('), Some(')'), vec![a("a")])]);
assert_round_trip("one-sided", vec![delim(Some('{'), None, vec![a("a")])]);
assert_round_trip("no opening", vec![delim(None, Some(']'), vec![a("a")])]);
assert_round_trip("empty element", vec![delim(Some('('), Some(')'), vec![vec![]])]);
assert_round_trip(
"brackets, separator, two elements",
vec![Delim { beg: Some('['), end: Some(']'), sep: Some(';'), grow: true, shp_match: false, elems: vec![a("a"), a("b")] }],
);
assert_round_trip(
"no separator",
vec![Delim { beg: Some('('), end: Some(')'), sep: None, grow: true, shp_match: false, elems: vec![a("a"), a("b")] }],
);
assert_round_trip(
"fixed size, matched shape",
vec![Delim { beg: Some('|'), end: Some('|'), sep: Some('|'), grow: false, shp_match: true, elems: vec![a("a")] }],
);
assert_round_trip("func", vec![Func { name: vec![MNode::Run(MRun::plain("sin"))], e: a("x") }]);
assert_round_trip("lim low", vec![Lim { upper: false, e: vec![MNode::Run(MRun::plain("lim"))], lim: a("n→∞") }]);
assert_round_trip("lim upp", vec![Lim { upper: true, e: a("x"), lim: a("k") }]);
assert_round_trip("hat", vec![Acc { chr: '\u{302}', e: a("x") }]);
assert_round_trip("vector", vec![Acc { chr: '\u{20D7}', e: a("v") }]);
assert_round_trip("overbar", vec![Bar { top: true, e: a("x") }]);
assert_round_trip("underbar", vec![Bar { top: false, e: a("x") }]);
assert_round_trip("border box", vec![BorderBox { hide: [false; 4], strike: [false; 4], e: a("x") }]);
assert_round_trip("border box flags", vec![BorderBox { hide: [true, false, true, false], strike: [false, true, false, true], e: a("x") }]);
assert_round_trip("box", vec![Boxed { e: a("x") }]);
assert_round_trip("underbrace", vec![GroupChr { chr: '\u{23DF}', top: false, e: a("x") }]);
assert_round_trip("overbrace", vec![GroupChr { chr: '\u{23DE}', top: true, e: a("x") }]);
assert_round_trip("eqarr", vec![EqArr { rows: vec![a("a=b"), a("c=d")] }]);
assert_round_trip("numbered eqarr", vec![EqArr { rows: vec![a("a=b#(1)")] }]);
assert_round_trip("matrix", vec![Matrix { rows: vec![vec![a("a"), a("b")], vec![a("c"), a("d")]], col_jc: vec![ColJc::Left, ColJc::Right] }]);
assert_round_trip("phantom", vec![Phant { show: true, zero_wid: false, zero_asc: false, zero_desc: false, e: a("x") }]);
assert_round_trip("hidden phantom", vec![Phant { show: false, zero_wid: true, zero_asc: true, zero_desc: true, e: a("x") }]);
}
#[test]
fn nested_structures_round_trip() {
let quadratic = parse_linear("x=(-b±√(b^2-4ac))/2a");
assert_round_trip("quadratic", quadratic);
let sum = parse_linear("∑_(i=1)^n▒(i^2)/(n+1)");
assert_round_trip("sum", sum);
}
#[test]
fn run_properties_round_trip() {
let with = |f: &dyn Fn(&mut MRun)| {
let mut x = MRun::new("ab");
f(&mut x);
vec![MNode::Run(x)]
};
for s in [MSty::Plain, MSty::Bold, MSty::Italic, MSty::BoldItalic] {
assert_round_trip("sty", with(&|x| x.sty = Some(s)));
}
for s in [MScr::Script, MScr::Fraktur, MScr::DoubleStruck, MScr::SansSerif, MScr::Monospace] {
assert_round_trip("scr", with(&|x| x.scr = s));
}
assert_round_trip("lit", with(&|x| x.lit = true));
assert_round_trip(
"normal text in a font",
with(&|x| {
x.nor = true;
x.font = Some("Arial".into());
}),
);
assert_round_trip("size", with(&|x| x.size = Some(11.0)));
assert_round_trip("half-point size", with(&|x| x.size = Some(10.5)));
assert_round_trip("colour", with(&|x| x.color = Some(RED)));
assert_round_trip("break", with(&|x| x.brk = Some(0)));
assert_round_trip("aligned break", with(&|x| x.brk = Some(3)));
for t in ["a<b&c\"d'e>f", " a b ", " ", "a\tb\nc", "𝑥𝟙", "\u{F061}"] {
assert_round_trip(t, a(t));
}
}
// --- Normalisation: what the reader gives back differently, on purpose. ------------------------
#[test]
fn reading_back_normalises_runs() {
// Equal neighbours merge (`merge_runs`); an empty run is no run.
assert_eq!(round_trip(&vec![r("a"), r("b")]), a("ab"));
assert_eq!(round_trip(&vec![r("a"), r(""), r("b")]), a("ab"));
assert_eq!(round_trip(&a("")), vec![]);
// Characters XML can't carry are dropped.
assert_eq!(round_trip(&a("a\u{1}b")), a("ab"));
// Sizes are half points, within 1–1638 pt.
let sized = |s: f32| vec![MNode::Run(MRun { size: Some(s), ..MRun::new("x") })];
assert_eq!(round_trip(&sized(10.3)), sized(10.5));
assert_eq!(round_trip(&sized(0.5)), sized(1.0));
assert_eq!(round_trip(&sized(2000.0)), sized(1638.0));
// A font belongs to normal text only; normal text without one is written in Cambria Math,
// as Word writes it (layout treats that as the text font).
let font = vec![MNode::Run(MRun { font: Some("Arial".into()), ..MRun::new("x") })];
assert_eq!(round_trip(&font), a("x"));
let nor = vec![MNode::Run(MRun { nor: true, ..MRun::new("x") })];
assert_eq!(round_trip(&nor), vec![MNode::Run(MRun { nor: true, font: Some("Cambria Math".into()), ..MRun::new("x") })]);
}
#[test]
fn reading_back_normalises_structures() {
use MNode::*;
// A script keeps only the slots its kind has.
let stray = vec![Script { kind: ScriptKind::Sup, base: a("x"), sub: a("i"), sup: a("2") }];
assert_eq!(round_trip(&stray), vec![Script { kind: ScriptKind::Sup, base: a("x"), sub: vec![], sup: a("2") }]);
// A delimiter has at least one element.
assert_eq!(round_trip(&vec![delim(Some('('), Some(')'), vec![])]), vec![delim(Some('('), Some(')'), vec![vec![]])]);
// A matrix gets one column alignment per column and rectangular rows (#3643).
let cells = vec![vec![a("a"), a("b")], vec![a("c")]];
let padded = vec![vec![a("a"), a("b")], vec![a("c"), vec![]]];
assert_eq!(round_trip(&vec![Matrix { rows: cells, col_jc: vec![] }]), vec![Matrix { rows: padded, col_jc: vec![ColJc::Center; 2] }]);
assert_eq!(round_trip(&vec![Matrix { rows: vec![], col_jc: vec![] }]), vec![Matrix { rows: vec![], col_jc: vec![ColJc::Center] }]);
}
/// Every linear-format equation saves and reopens as the same tree, once matrices have their
/// column alignments filled in.
#[test]
fn linear_equations_survive_a_save() {
fn fill_col_jc(a: Arg) -> Arg {
a.into_iter()
.map(|n| match n {
MNode::Matrix { rows, col_jc } if col_jc.is_empty() => {
let cols = rows.iter().map(Vec::len).max().unwrap_or(0).max(1);
let rows = rows.into_iter().map(|row| row.into_iter().map(fill_col_jc).collect()).collect();
MNode::Matrix { rows, col_jc: vec![ColJc::Center; cols] }
}
other => crate::math_linear::map_args(other, &fill_col_jc),
})
.collect()
}
for s in [
"x=(-b±√(b^2-4ac))/2a",
"〖a+b〗^2",
"├]a[┤",
"{█(x@y)┤",
"(a│b)",
"▭(a)+□(b)+¯(c)+▁(d)",
"⏞(a+b)+⏟(c+d)",
"⬚/⬚",
"a⁄b+a∕b+a¦b",
"_1^n▒Y",
"x┬k+x┴k",
"A⃗+x̂",
"log_2⁡x",
"lim┬(n→∞)⁡a_n",
")a(",
"E=mc^2#(1)",
"■(a&b@c&d)",
"√(3&x)",
"∫_0^1▒f(x)dx",
"|x|+‖v‖",
] {
let n = parse_linear(s);
assert_eq!(round_trip(&n), fill_col_jc(n.clone()), "{s} → {}", to_linear(&n));
}
}
// --- Where `write_equation` takes the equation from. --------------------------------------------
#[test]
fn kept_omml_is_written_back_unchanged() {
let kept = "<m:oMath><m:r><m:t>KEPT</m:t></m:r></m:oMath>";
let m = Math { nodes: a("NODES"), omml: kept.into(), ..Default::default() };
assert_eq!(write(&m, "linear", false, None), kept);
}
#[test]
fn kept_xml_that_is_not_an_omath_is_rewritten_from_the_nodes() {
let m = Math { nodes: a("NODES"), omml: "<m:r><m:t>X</m:t></m:r>".into(), ..Default::default() };
let out = write(&m, "linear", false, None);
assert_eq!(read(&out).nodes, a("NODES"));
}
#[test]
fn kept_omml_larger_than_the_reader_keeps_is_rewritten_from_the_nodes() {
// The same cap as the reader's: one more element than it reads is written from the nodes,
// one fewer is kept.
let cap = crate::omml::MAX_ELEMENTS * 2;
let kept = |runs: usize| format!("<m:oMath>{}</m:oMath>", "<m:r/>".repeat(runs));
let over = Math { nodes: a("NODES"), omml: kept(cap + 1), ..Default::default() };
assert_eq!(read(&write(&over, "linear", false, None)).nodes, a("NODES"));
let under = Math { nodes: a("NODES"), omml: kept(cap - 10), ..Default::default() };
assert!(write(&under, "linear", false, None).contains(&under.omml));
}
#[test]
fn without_nodes_the_linear_text_is_written() {
let out = write(&Math::default(), "a/b", false, None);
assert_eq!(read(&out).nodes, parse_linear("a/b"));
assert_eq!(write(&Math::default(), "", false, None), "<m:oMath></m:oMath>");
}
#[test]
fn an_equation_colour_rewrites_the_kept_omml() {
let kept_red = r#"<m:oMath><m:r><w:rPr><w:color w:val="FF0000"/></w:rPr><m:t>a</m:t></m:r></m:oMath>"#;
let nodes = vec![r("a"), MNode::Run(MRun { color: Some(GREEN), ..MRun::new("g") })];
let m = Math { nodes, omml: kept_red.into(), ..Default::default() };
let colours = |c: Option<Rgb>| runs(&read(&write(&m, "", false, c)).nodes).into_iter().map(|r| (r.text, r.color)).collect::<Vec<_>>();
// The same colour keeps the source XML.
assert_eq!(write(&m, "", false, Some(RED)), kept_red);
// Another colour goes on every run without its own (#1467).
assert_eq!(colours(Some(BLUE)), vec![("a".to_string(), Some(BLUE)), ("g".to_string(), Some(GREEN))]);
// No colour takes the old one off.
assert_eq!(colours(None), vec![("a".to_string(), None), ("g".to_string(), Some(GREEN))]);
}
#[test]
fn kept_omml_without_one_colour_is_kept_without_an_equation_colour() {
for kept in [
"<m:oMath><m:r><m:t>a</m:t></m:r></m:oMath>",
r#"<m:oMath><m:r><w:rPr><w:color w:val="FF0000"/></w:rPr><m:t>a</m:t></m:r><m:r><m:t>b</m:t></m:r></m:oMath>"#,
] {
let m = Math { nodes: a("ab"), omml: kept.into(), ..Default::default() };
assert_eq!(write(&m, "", false, None), kept);
}
}
#[test]
fn display_justification_round_trips() {
for jc in [MathJc::CenterGroup, MathJc::Center, MathJc::Left, MathJc::Right] {
let out = write(&Math { nodes: a("x"), jc, ..Default::default() }, "", true, None);
assert_eq!(read(&out).jc, jc, "{out}");
assert_eq!(out.contains("m:oMathParaPr"), jc != MathJc::CenterGroup, "{out}");
}
assert!(!write(&math(a("x")), "", false, None).contains("oMathPara"));
}
// --- Equation numbers. --------------------------------------------------------------------------
fn rows(rs: &[&str]) -> Math {
math(vec![MNode::EqArr { rows: rs.iter().map(|s| a(s)).collect() }])
}
#[test]
fn automatic_numbers_are_written_out() {
// A `#` with nothing after it gets the next number; a written number counts too, as in
// layout's `auto_numbers`.
let mut n = 0;
let out = resolve_numbers(&rows(&["a=b#", "c=d", "e=f#(9)", "g#"]), true, &mut n).unwrap();
assert_eq!(n, 3);
assert_eq!(to_linear(&out.nodes), "█(a=b#(1)@c=d@e=f#(9)@g#(3))");
assert!(out.omml.is_empty(), "the numbered copy is written from its nodes");
// The counter carries on into the next equation.
let out = resolve_numbers(&rows(&["h#"]), true, &mut n).unwrap();
assert_eq!((n, to_linear(&out.nodes)), (4, "h#(4)".to_string()), "a one-row array prints without █");
}
#[test]
fn equations_without_automatic_numbers_are_left_alone() {
let mut n = 5;
assert!(resolve_numbers(&rows(&["a=b#(7)"]), true, &mut n).is_none());
assert_eq!(n, 6, "a written number still counts");
let mut n = 0;
assert!(resolve_numbers(&rows(&["a#"]), false, &mut n).is_none(), "inline");
assert!(resolve_numbers(&math(a("a=b#")), true, &mut n).is_none(), "not an equation array");
let nested = math(vec![MNode::EqArr { rows: vec![vec![MNode::Frac { kind: FracKind::Bar, num: a("a#"), den: a("b") }]] }]);
assert!(resolve_numbers(&nested, true, &mut n).is_none(), "a # inside a structure isn't a number mark");
assert_eq!(n, 0);
}
// --- Settings: m:mathPr. ------------------------------------------------------------------------
fn math_pr_round_trip(m: &MathProps) -> MathProps {
let mut w = W::default();
math_pr(&mut w, m);
let root = parse_kept(&w.s).unwrap();
assert_eq!(root.name, "m:mathPr");
crate::omml::read_math_pr(&root)
}
#[test]
fn math_properties_round_trip() {
for m in [
MathProps::default(),
MathProps { brk_bin: BrkBin::After, brk_bin_sub: BrkBinSub::PlusMinus, ..Default::default() },
MathProps { brk_bin: BrkBin::Repeat, brk_bin_sub: BrkBinSub::MinusPlus, ..Default::default() },
MathProps { wrap_indent: 0.0, ..Default::default() },
MathProps { wrap_indent: 12.35, ..Default::default() },
MathProps { wrap_right: true, ..Default::default() },
] {
assert_eq!(math_pr_round_trip(&m), m);
}
}
#[test]
fn math_properties_are_clamped() {
let indent = |v: f32| math_pr_round_trip(&MathProps { wrap_indent: v, ..Default::default() }).wrap_indent;
assert_eq!(indent(5000.0), 1584.0);
assert_eq!(indent(-3.0), 0.0);
assert_eq!(indent(f32::NAN), crate::math::DEFAULT_WRAP_INDENT);
// `wrapIndent` and `wrapRight` are a choice: aligning right drops the indent.
let right = math_pr_round_trip(&MathProps { wrap_right: true, wrap_indent: 10.0, ..Default::default() });
assert_eq!(right, MathProps { wrap_right: true, ..Default::default() });
}
// --- Limits. ------------------------------------------------------------------------------------
#[test]
fn matrix_caps_hold_on_save() {
let wide = vec![MNode::Matrix { rows: vec![vec![a("x"); MAX_MATRIX_COLS + 6]; 3], col_jc: vec![] }];
let back = round_trip(&wide);
let [MNode::Matrix { rows, col_jc }] = &back[..] else { panic!("{back:?}") };
assert_eq!((rows.len(), rows[0].len(), col_jc.len()), (3, MAX_MATRIX_COLS, MAX_MATRIX_COLS));
let tall = vec![MNode::Matrix { rows: vec![vec![a("x")]; MAX_MATRIX_ROWS + 5], col_jc: vec![] }];
let back = round_trip(&tall);
let [MNode::Matrix { rows, .. }] = &back[..] else { panic!("{back:?}") };
assert_eq!(rows.len(), MAX_MATRIX_ROWS);
}
fn fraction_chain(depth: usize) -> Arg {
let mut cur = a("LEAF");
for _ in 0..depth {
cur = vec![MNode::Frac { kind: FracKind::Bar, num: cur, den: a("d") }];
}
cur
}
#[test]
fn a_tree_past_the_depth_cap_writes_well_formed_xml() {
for depth in [MAX_DEPTH, MAX_DEPTH + 1, 4 * MAX_DEPTH] {
let out = xml(&fraction_chain(depth));
assert!(craft_xml::Options::default().strict().parse(out.as_bytes()).is_ok(), "depth {depth}");
}
assert!(!xml(&fraction_chain(MAX_DEPTH + 1)).contains("LEAF"), "the writer stops at MAX_DEPTH");
}
// --- Golden XML: element order and what is left out. --------------------------------------------
const CTRL: &str = r#"<m:ctrlPr><w:rPr><w:rFonts w:ascii="Cambria Math" w:hAnsi="Cambria Math"/><w:i/></w:rPr></m:ctrlPr>"#;
/// `m:r` for `x` with no properties of its own.
fn rx(t: &str) -> String {
format!(r#"<m:r><w:rPr><w:rFonts w:ascii="Cambria Math" w:hAnsi="Cambria Math"/></w:rPr><m:t xml:space="preserve">{t}</m:t></m:r>"#)
}
/// The golden string with `{C}` standing for [`CTRL`] and `{a}`… for [`rx`] runs.
fn expand(s: &str) -> String {
let mut out = s.replace("{C}", CTRL);
for t in ["a", "b", "c", "d", "x", "i", "n", "2", "3", "k"] {
out = out.replace(&format!("{{{t}}}"), &rx(t));
}
format!("<m:oMath>{out}</m:oMath>")
}
#[track_caller]
fn assert_golden(label: &str, nodes: Arg, expected: &str) {
assert_eq!(xml(&nodes), expand(expected), "{label}");
}
#[test]
fn golden_runs() {
assert_golden("plain run", a("x"), "{x}");
let all = MRun { sty: Some(MSty::Bold), scr: MScr::Script, lit: true, brk: Some(2), color: Some(RED), size: Some(11.0), ..MRun::new("x") };
assert_golden(
"every math run property",
vec![MNode::Run(all)],
r#"<m:r><m:rPr><m:lit/><m:scr m:val="script"/><m:sty m:val="b"/><m:brk m:alnAt="2"/></m:rPr><w:rPr><w:rFonts w:ascii="Cambria Math" w:hAnsi="Cambria Math"/><w:color w:val="FF0000"/><w:sz w:val="22"/><w:szCs w:val="22"/></w:rPr><m:t xml:space="preserve">x</m:t></m:r>"#,
);
let nor = MRun { nor: true, font: Some("Arial".into()), brk: Some(0), ..MRun::new("x y") };
assert_golden(
"normal text",
vec![MNode::Run(nor)],
r#"<m:r><m:rPr><m:nor/><m:brk/></m:rPr><w:rPr><w:rFonts w:ascii="Arial" w:hAnsi="Arial"/></w:rPr><m:t xml:space="preserve">x y</m:t></m:r>"#,
);
}
#[test]
fn golden_fractions_scripts_and_radicals() {
use MNode::*;
assert_golden(
"bar fraction",
vec![Frac { kind: FracKind::Bar, num: a("a"), den: a("b") }],
"<m:f><m:fPr>{C}</m:fPr><m:num>{a}</m:num><m:den>{b}</m:den></m:f>",
);
assert_golden(
"skewed fraction, empty denominator",
vec![Frac { kind: FracKind::Skewed, num: a("a"), den: vec![] }],
r#"<m:f><m:fPr><m:type m:val="skw"/>{C}</m:fPr><m:num>{a}</m:num><m:den/></m:f>"#,
);
assert_golden(
"sup",
vec![Script { kind: ScriptKind::Sup, base: a("x"), sub: vec![], sup: a("2") }],
"<m:sSup><m:sSupPr>{C}</m:sSupPr><m:e>{x}</m:e><m:sup>{2}</m:sup></m:sSup>",
);
assert_golden(
"sub",
vec![Script { kind: ScriptKind::Sub, base: a("x"), sub: a("i"), sup: vec![] }],
"<m:sSub><m:sSubPr>{C}</m:sSubPr><m:e>{x}</m:e><m:sub>{i}</m:sub></m:sSub>",
);
assert_golden(
"subsup",
vec![Script { kind: ScriptKind::SubSup, base: a("x"), sub: a("i"), sup: a("2") }],
"<m:sSubSup><m:sSubSupPr>{C}</m:sSubSupPr><m:e>{x}</m:e><m:sub>{i}</m:sub><m:sup>{2}</m:sup></m:sSubSup>",
);
// CT_SPre: sub, sup, then the base.
assert_golden(
"pre",
vec![Script { kind: ScriptKind::Pre, base: a("x"), sub: a("i"), sup: a("2") }],
"<m:sPre><m:sPrePr>{C}</m:sPrePr><m:sub>{i}</m:sub><m:sup>{2}</m:sup><m:e>{x}</m:e></m:sPre>",
);
assert_golden(
"square root",
vec![Rad { deg: vec![], deg_hide: true, e: a("x") }],
r#"<m:rad><m:radPr><m:degHide m:val="1"/>{C}</m:radPr><m:deg/><m:e>{x}</m:e></m:rad>"#,
);
assert_golden(
"cube root",
vec![Rad { deg: a("3"), deg_hide: false, e: a("x") }],
"<m:rad><m:radPr>{C}</m:radPr><m:deg>{3}</m:deg><m:e>{x}</m:e></m:rad>",
);
}
#[test]
fn golden_operators_and_delimiters() {
use MNode::*;
let nary = |chr, lim_loc, on| Nary { chr, lim_loc, grow: on, sub_hide: on, sup_hide: on, sub: a("i"), sup: a("n"), e: a("x") };
assert_golden(
"integral",
vec![nary('∫', None, false)],
"<m:nary><m:naryPr>{C}</m:naryPr><m:sub>{i}</m:sub><m:sup>{n}</m:sup><m:e>{x}</m:e></m:nary>",
);
assert_golden(
"sum, every property",
vec![nary('∑', Some(LimLoc::UndOvr), true)],
r#"<m:nary><m:naryPr><m:chr m:val="∑"/><m:limLoc m:val="undOvr"/><m:grow m:val="1"/><m:subHide m:val="1"/><m:supHide m:val="1"/>{C}</m:naryPr><m:sub>{i}</m:sub><m:sup>{n}</m:sup><m:e>{x}</m:e></m:nary>"#,
);
assert_golden("parentheses", vec![delim(Some('('), Some(')'), vec![a("x")])], "<m:d><m:dPr>{C}</m:dPr><m:e>{x}</m:e></m:d>");
assert_golden(
"delimiter, every property",
vec![Delim { beg: Some('['), end: None, sep: Some(';'), grow: false, shp_match: true, elems: vec![a("a"), a("b")] }],
r#"<m:d><m:dPr><m:begChr m:val="["/><m:sepChr m:val=";"/><m:endChr m:val=""/><m:grow m:val="0"/><m:shp m:val="match"/>{C}</m:dPr><m:e>{a}</m:e><m:e>{b}</m:e></m:d>"#,
);
assert_golden(
"function",
vec![Func { name: a("a"), e: a("x") }],
"<m:func><m:funcPr>{C}</m:funcPr><m:fName>{a}</m:fName><m:e>{x}</m:e></m:func>",
);
assert_golden(
"lower limit",
vec![Lim { upper: false, e: a("a"), lim: a("n") }],
"<m:limLow><m:limLowPr>{C}</m:limLowPr><m:e>{a}</m:e><m:lim>{n}</m:lim></m:limLow>",
);
assert_golden(
"upper limit",
vec![Lim { upper: true, e: a("a"), lim: a("k") }],
"<m:limUpp><m:limUppPr>{C}</m:limUppPr><m:e>{a}</m:e><m:lim>{k}</m:lim></m:limUpp>",
);
}
#[test]
fn golden_accents_bars_and_boxes() {
use MNode::*;
assert_golden("accent", vec![Acc { chr: '\u{302}', e: a("x") }], "<m:acc><m:accPr><m:chr m:val=\"\u{302}\"/>{C}</m:accPr><m:e>{x}</m:e></m:acc>");
assert_golden("overbar", vec![Bar { top: true, e: a("x") }], r#"<m:bar><m:barPr><m:pos m:val="top"/>{C}</m:barPr><m:e>{x}</m:e></m:bar>"#);
assert_golden("underbar", vec![Bar { top: false, e: a("x") }], r#"<m:bar><m:barPr><m:pos m:val="bot"/>{C}</m:barPr><m:e>{x}</m:e></m:bar>"#);
assert_golden(
"border box",
vec![BorderBox { hide: [false; 4], strike: [false; 4], e: a("x") }],
"<m:borderBox><m:borderBoxPr>{C}</m:borderBoxPr><m:e>{x}</m:e></m:borderBox>",
);
assert_golden(
"border box, every property",
vec![BorderBox { hide: [true; 4], strike: [true; 4], e: a("x") }],
r#"<m:borderBox><m:borderBoxPr><m:hideTop m:val="1"/><m:hideBot m:val="1"/><m:hideLeft m:val="1"/><m:hideRight m:val="1"/><m:strikeH m:val="1"/><m:strikeV m:val="1"/><m:strikeBLTR m:val="1"/><m:strikeTLBR m:val="1"/>{C}</m:borderBoxPr><m:e>{x}</m:e></m:borderBox>"#,
);
assert_golden("box", vec![Boxed { e: a("x") }], "<m:box><m:boxPr>{C}</m:boxPr><m:e>{x}</m:e></m:box>");
assert_golden(
"underbrace",
vec![GroupChr { chr: '\u{23DF}', top: false, e: a("x") }],
"<m:groupChr><m:groupChrPr><m:chr m:val=\"\u{23DF}\"/><m:pos m:val=\"bot\"/><m:vertJc m:val=\"top\"/>{C}</m:groupChrPr><m:e>{x}</m:e></m:groupChr>",
);
assert_golden(
"overbrace",
vec![GroupChr { chr: '\u{23DE}', top: true, e: a("x") }],
"<m:groupChr><m:groupChrPr><m:chr m:val=\"\u{23DE}\"/><m:pos m:val=\"top\"/><m:vertJc m:val=\"bot\"/>{C}</m:groupChrPr><m:e>{x}</m:e></m:groupChr>",
);
assert_golden(
"phantom",
vec![Phant { show: true, zero_wid: false, zero_asc: false, zero_desc: false, e: a("x") }],
r#"<m:phant><m:phantPr><m:show m:val="1"/>{C}</m:phantPr><m:e>{x}</m:e></m:phant>"#,
);
assert_golden(
"phantom, every property",
vec![Phant { show: false, zero_wid: true, zero_asc: true, zero_desc: true, e: a("x") }],
r#"<m:phant><m:phantPr><m:show m:val="0"/><m:zeroWid m:val="1"/><m:zeroAsc m:val="1"/><m:zeroDesc m:val="1"/>{C}</m:phantPr><m:e>{x}</m:e></m:phant>"#,
);
}
#[test]
fn golden_arrays() {
use MNode::*;
assert_golden("eqarr", vec![EqArr { rows: vec![a("a"), a("b")] }], "<m:eqArr><m:eqArrPr>{C}</m:eqArrPr><m:e>{a}</m:e><m:e>{b}</m:e></m:eqArr>");
assert_golden(
"numbered eqarr",
vec![EqArr { rows: vec![vec![r("a"), r("#")]] }],
r#"<m:eqArr><m:eqArrPr><m:maxDist m:val="1"/>{C}</m:eqArrPr><m:e>{a}<m:r><w:rPr><w:rFonts w:ascii="Cambria Math" w:hAnsi="Cambria Math"/></w:rPr><m:t xml:space="preserve">#</m:t></m:r></m:e></m:eqArr>"#,
);
assert_golden(
"matrix",
vec![Matrix { rows: vec![vec![a("a"), a("b")], vec![a("c")]], col_jc: vec![ColJc::Left] }],
r#"<m:m><m:mPr><m:mcs><m:mc><m:mcPr><m:count m:val="1"/><m:mcJc m:val="left"/></m:mcPr></m:mc><m:mc><m:mcPr><m:count m:val="1"/><m:mcJc m:val="center"/></m:mcPr></m:mc></m:mcs>{C}</m:mPr><m:mr><m:e>{a}</m:e><m:e>{b}</m:e></m:mr><m:mr><m:e>{c}</m:e><m:e/></m:mr></m:m>"#,
);
}
#[test]
fn golden_display_and_settings() {
let out = write(&Math { nodes: a("x"), jc: MathJc::Left, ..Default::default() }, "", true, None);
assert_eq!(out, format!(r#"<m:oMathPara><m:oMathParaPr><m:jc m:val="left"/></m:oMathParaPr>{}</m:oMathPara>"#, expand("{x}")));
assert_eq!(write(&math(a("x")), "", true, None), format!("<m:oMathPara>{}</m:oMathPara>", expand("{x}")));
let pr = |m: &MathProps| {
let mut w = W::default();
math_pr(&mut w, m);
w.s
};
assert_eq!(pr(&MathProps::default()), r#"<m:mathPr><m:brkBin m:val="before"/><m:brkBinSub m:val="--"/><m:wrapIndent m:val="1440"/></m:mathPr>"#);
assert_eq!(
pr(&MathProps { brk_bin: BrkBin::After, brk_bin_sub: BrkBinSub::PlusMinus, wrap_right: true, ..Default::default() }),
r#"<m:mathPr><m:brkBin m:val="after"/><m:brkBinSub m:val="+-"/><m:wrapRight/></m:mathPr>"#
);
}
/// The run helper is used by every golden: a run with no properties is exactly `rx`.
#[test]
fn golden_helpers_match_the_writer() {
assert_eq!(xml(&a("x")), format!("<m:oMath>{}</m:oMath>", rx("x")));
assert!(expand("{C}").contains("m:ctrlPr"));
}
+24
View File
@@ -0,0 +1,24 @@
//! An n-ary operator's empty but shown limit survives linear text (#6076): half-typed `∑_` has an
//! empty lower limit that is shown, and `to_linear` writes it as `_()`. Left out, it reads back as a
//! hidden limit.
use craft_math::math::{MNode, MRun, parse_linear, to_linear};
#[test]
fn an_empty_shown_limit_prints_back_the_same() {
for s in ["∑_", "∑^", "∫_0^▒x", "∑_()^n▒i"] {
let n = parse_linear(s);
assert_eq!(parse_linear(&to_linear(&n)), n, "{s} → {}", to_linear(&n));
}
}
#[test]
fn hidden_and_filled_limits_print_as_before() {
let nary = |sub_hide, sup_hide, sub: &str, sup: &str| {
let arg = |t: &str| if t.is_empty() { Vec::new() } else { vec![MNode::Run(MRun::new(t))] };
vec![MNode::Nary { chr: '∑', lim_loc: None, grow: false, sub_hide, sup_hide, sub: arg(sub), sup: arg(sup), e: arg("x") }]
};
assert_eq!(to_linear(&nary(true, true, "", "")), "∑▒x");
assert_eq!(to_linear(&nary(false, false, "i", "n")), "∑_i^n▒x");
assert_eq!(to_linear(&nary(false, true, "", "")), "∑_()▒x");
}
@@ -0,0 +1,39 @@
//! A script base of several letters survives linear text (#6228). The parser attaches a script to the
//! last character before it (`ab^2` is `a`, `b²`), so `to_linear` writes such a base in invisible
//! brackets, `〖mc〗^2`, as Word linearizes it. Single characters, numbers and upright function
//! names stay bare.
use craft_math::math::{MNode, MRun, ScriptKind, parse_linear, to_linear};
fn a(t: &str) -> Vec<MNode> {
vec![MNode::Run(MRun::new(t))]
}
fn sup(base: Vec<MNode>, s: Vec<MNode>) -> MNode {
MNode::Script { kind: ScriptKind::Sup, base, sub: Vec::new(), sup: s }
}
#[test]
fn a_base_of_several_letters_prints_back_whole() {
for base in ["ab", "mc", "x1", "αβ"] {
let n = vec![sup(a(base), a("2"))];
assert_eq!(to_linear(&n), format!("〖{base}〗^2"));
assert_eq!(parse_linear(&to_linear(&n)), n, "{base}");
}
// After other text, and as the base of a base.
let e = vec![MNode::Run(MRun::new("E=")), sup(a("mc"), a("2"))];
assert_eq!(to_linear(&e), "E=〖mc〗^2");
assert_eq!(parse_linear(&to_linear(&e)), e);
let nested = vec![sup(vec![sup(a("ab"), a("2"))], a("3"))];
assert_eq!(parse_linear(&to_linear(&nested)), nested, "{}", to_linear(&nested));
}
#[test]
fn single_characters_numbers_and_function_names_stay_bare() {
assert_eq!(to_linear(&[sup(a("x"), a("2"))]), "x^2");
// Word writes a number base bare too (`10^3`).
assert_eq!(to_linear(&[sup(a("10"), a("3"))]), "10^3");
assert_eq!(to_linear(&[sup(a("2.5"), a("2"))]), "2.5^2");
let sin = vec![sup(vec![MNode::Run(MRun::plain("sin"))], a("2"))];
assert_eq!(to_linear(&sin), "sin^2");
}
+81
View File
@@ -0,0 +1,81 @@
//! A script whose base is itself a script survives linear text (#6075). `to_linear` puts a base that
//! isn't simple in invisible brackets, `〖a^b〗^c`, as Word linearizes it, and the parser treats
//! `〖…〗` as a script base as grouping only, as Word builds it: no delimiter is left.
use craft_math::math::{MNode, MRun, ScriptKind, parse_linear, to_linear};
fn a(t: &str) -> Vec<MNode> {
vec![MNode::Run(MRun::new(t))]
}
fn sup(base: Vec<MNode>, s: Vec<MNode>) -> MNode {
MNode::Script { kind: ScriptKind::Sup, base, sub: Vec::new(), sup: s }
}
#[test]
fn a_script_on_a_script_prints_back_the_same() {
// sSup(sSup(a, b), c), as Word files hold it.
let left = vec![sup(vec![sup(a("a"), a("b"))], a("c"))];
assert_eq!(to_linear(&left), "〖a^b〗^c");
assert_eq!(parse_linear(&to_linear(&left)), left);
// Subscripts and a longer base too.
let sub =
vec![MNode::Script { kind: ScriptKind::Sub, base: vec![sup(a("x"), a("2")), MNode::Run(MRun::new("+y"))], sub: a("i"), sup: Vec::new() }];
assert_eq!(parse_linear(&to_linear(&sub)), sub, "{}", to_linear(&sub));
}
#[test]
fn invisible_brackets_only_group_a_script_base() {
assert_eq!(parse_linear("〖a+b〗^2"), vec![sup(a("a+b"), a("2"))]);
// Visible brackets stay.
let [MNode::Script { base, .. }] = &parse_linear("(a+b)^2")[..] else { panic!() };
assert!(matches!(&base[..], [MNode::Delim { beg: Some('('), .. }]), "{base:?}");
}
#[test]
fn half_typed_scripts_print_back_the_same() {
for s in ["x^2^", "x_i_", "(a^b)^c", "a^b"] {
let n = parse_linear(s);
assert_eq!(parse_linear(&to_linear(&n)), n, "{s} → {}", to_linear(&n));
}
}
#[test]
fn an_invisible_delimiter_as_the_base_is_kept() {
// A base that is itself an invisible delimiter (LaTeX `\left.a\right.^2` makes one) is written
// `〖〖a〗〗^2`: the outer pair only groups, the inner one reads back as that delimiter.
let invisible = MNode::Delim { beg: None, end: None, sep: None, grow: true, shp_match: false, elems: vec![a("a")] };
let n = vec![sup(vec![invisible], a("2"))];
assert_eq!(parse_linear(&to_linear(&n)), n, "{}", to_linear(&n));
let latex = craft_math::math_latex::parse_latex(r"\left.a\right.^2");
assert!(matches!(&latex[..], [MNode::Script { base, .. }] if matches!(&base[..], [MNode::Delim { beg: None, end: None, .. }])), "{latex:?}");
assert_eq!(parse_linear(&to_linear(&latex)), latex, "{}", to_linear(&latex));
}
#[test]
fn an_operator_as_the_base_prints_back_the_same() {
// A script after an operator reads as a pre-script, so an operator base is grouped: `〖⊗〗_i`.
for op in ["⊗", "×", "∗", "*", "<", "&", "#"] {
let n = vec![MNode::Script { kind: ScriptKind::Sub, base: a(op), sub: a("i"), sup: Vec::new() }];
assert_eq!(parse_linear(&to_linear(&n)), n, "{op}: {}", to_linear(&n));
let n = vec![sup(a(op), a("2"))];
assert_eq!(parse_linear(&to_linear(&n)), n, "{op}: {}", to_linear(&n));
}
}
#[test]
fn an_explicit_delimiter_as_the_base_is_kept() {
// `├a┤` is an explicit (invisible) delimiter, not a grouping `〖a〗`: it stays the base.
let [MNode::Script { base, sup: two, .. }] = &parse_linear("├a┤^2")[..] else { panic!() };
assert_eq!(two, &a("2"));
assert!(matches!(&base[..], [MNode::Delim { beg: None, end: None, elems, .. }] if elems == &vec![a("a")]), "{base:?}");
// Grouping still leaves none.
assert_eq!(parse_linear("〖a〗^2"), vec![sup(a("a"), a("2"))]);
}
#[test]
fn invisible_brackets_before_a_space_stay_a_delimiter() {
// Only `〗` right before `^`/`_` makes them a script base; after a space they are kept as typed.
let n = parse_linear("〖a+b〗 ^2");
assert!(matches!(&n[..], [MNode::Delim { beg: None, end: None, .. }, ..]), "{n:?}");
}
+136
View File
@@ -0,0 +1,136 @@
//! A number is one item in the linear format, as Word reads it (#6229): the base of a script is the
//! whole number before it (`10^3` is `10³`, not `1`, `0³`), and so is a fraction's operand. A number is
//! a run of digits; a `.` or `,` continues it only when a digit follows (`2.5`, `1,000`), and a leading
//! `.` before a digit starts one (`.5`). Letters and signs are separate items. Every expected tree is the
//! one Word for Windows (build 16.0.20527) builds from the same text.
use craft_math::math::{FracKind, MNode, MRun, ScriptKind, parse_linear};
fn r(t: &str) -> MNode {
MNode::Run(MRun::new(t))
}
fn a(t: &str) -> Vec<MNode> {
vec![r(t)]
}
fn sup(base: &str, s: &str) -> MNode {
MNode::Script { kind: ScriptKind::Sup, base: a(base), sub: Vec::new(), sup: a(s) }
}
fn sub(base: &str, s: &str) -> MNode {
MNode::Script { kind: ScriptKind::Sub, base: a(base), sub: a(s), sup: Vec::new() }
}
fn frac(num: &str, den: &str) -> MNode {
MNode::Frac { kind: FracKind::Bar, num: a(num), den: a(den) }
}
#[track_caller]
fn parses(s: &str, want: Vec<MNode>) {
assert_eq!(parse_linear(s), want, "{s}");
}
#[test]
fn a_whole_number_is_the_base() {
parses("10^3", vec![sup("10", "3")]);
parses("123^4", vec![sup("123", "4")]);
for n in ["2.5", "3.14", "0.5", ".5", "1,000", "1.2.3", "1,2,3"] {
parses(&format!("{n}^2"), vec![sup(n, "2")]);
}
parses("10_i", vec![sub("10", "i")]);
parses("10_i^2", vec![MNode::Script { kind: ScriptKind::SubSup, base: a("10"), sub: a("i"), sup: a("2") }]);
parses("10^3_i", vec![MNode::Script { kind: ScriptKind::SubSup, base: a("10"), sub: a("i"), sup: a("3") }]);
parses("10^-3", vec![sup("10", "-3")]);
parses("10^(3)", vec![sup("10", "3")]);
}
#[test]
fn what_comes_before_the_number_stays_outside() {
parses("a10^2", vec![r("a"), sup("10", "2")]);
parses("x+10^3", vec![r("x+"), sup("10", "3")]);
parses("-10^2", vec![r("-"), sup("10", "2")]);
parses("1e10^2", vec![r("1e"), sup("10", "2")]);
// A point with no digit after it isn't part of the number.
parses("2.^2", vec![r("2"), sup(".", "2")]);
}
#[test]
fn letters_after_a_number_are_their_own_base() {
parses("2x^2", vec![r("2"), sup("x", "2")]);
parses("10x^2", vec![r("10"), sup("x", "2")]);
parses("x2^3", vec![r("x"), sup("2", "3")]);
parses("3.14r^2", vec![r("3.14"), sup("r", "2")]);
parses("2.5x^2", vec![r("2.5"), sup("x", "2")]);
}
#[test]
fn a_number_script_is_read_by_the_same_rule() {
parses("x^.5", vec![sup("x", ".5")]);
parses("x^2.5", vec![sup("x", "2.5")]);
parses("x^0.5", vec![sup("x", "0.5")]);
parses("x_1,000", vec![sub("x", "1,000")]);
parses("x_1.2.3", vec![sub("x", "1.2.3")]);
parses("x^2.", vec![sup("x", "2"), r(".")]);
// Letters after the digits stay in the script (#1609).
parses("x_10a", vec![sub("x", "10a")]);
parses("2^10", vec![sup("2", "10")]);
}
#[test]
fn a_whole_number_is_a_fraction_operand() {
parses("2.5/3", vec![frac("2.5", "3")]);
parses("1,000/2", vec![frac("1,000", "2")]);
parses("x/2.5", vec![frac("x", "2.5")]);
parses("0.5/0.25", vec![frac("0.5", "0.25")]);
parses("10/2^3", vec![MNode::Frac { kind: FracKind::Bar, num: a("10"), den: vec![sup("2", "3")] }]);
}
#[test]
fn a_comma_between_digits_in_brackets_joins_them() {
let [MNode::Run(f), MNode::Delim { beg: Some('('), elems, .. }] = &parse_linear("f(1,2^3)")[..] else { panic!() };
assert_eq!(f.text, "f");
assert_eq!(elems, &vec![vec![sup("1,2", "3")]]);
}
/// Linear text and back: the same tree.
#[track_caller]
fn prints_back(t: Vec<MNode>, want: &str) {
let lin = craft_math::math::to_linear(&t);
assert_eq!(lin, want);
assert_eq!(parse_linear(&lin), t, "{lin}");
}
#[test]
fn a_number_base_prints_bare() {
// A number the parser reads as one item needs no brackets as a base, with a comma too.
for (base, want) in [("10", "10^2"), ("2.5", "2.5^2"), (".5", ".5^2"), ("1,000", "1,000^2")] {
prints_back(vec![sup(base, "2")], want);
}
}
#[test]
fn a_comma_before_a_digit_after_a_script_stays_outside_it() {
// `x^2,3` would read `,3` into the number script, so a space ends the script first.
prints_back(vec![sup("x", "2"), r(",3")], "x^2 ,3");
prints_back(vec![sup("x", "a"), r(",3")], "x^a ,3");
// Also when the comma and the digit are separate runs (read back as one).
let lin = craft_math::math::to_linear(&[sup("x", "2"), r(","), r("3")]);
assert_eq!(lin, "x^2 ,3");
assert_eq!(parse_linear(&lin), vec![sup("x", "2"), r(",3")]);
// A comma before anything else ends the script on its own: no space is added.
assert_eq!(craft_math::math::to_linear(&[sup("x", "2"), r(", y")]), "x^2, y");
}
#[test]
fn a_number_base_after_a_number_keeps_its_brackets() {
// Bare, the base would continue the number before it: `1` then `23^4` would read `123^4`.
for (before, base, want) in
[("1", "23", "1〖23〗^4"), ("1", "2", "1〖2〗^4"), ("x.", "5", "x.〖5〗^4"), ("1,", "5", "1,〖5〗^4"), ("1", ".5", "1〖.5〗^4")]
{
prints_back(vec![r(before), sup(base, "4")], want);
}
// After a letter or an operator it can't, so it stays bare.
prints_back(vec![r("a"), sup("2", "4")], "a2^4");
prints_back(vec![r("1+"), sup("2", "4")], "1+2^4");
}
+85
View File
@@ -0,0 +1,85 @@
//! Stacked scripts in the linear format nest to the right, as Word builds them (#6074): the
//! superscript of `a^b^c` is `b^c`, so `a^b^c` is `a^(b^c)`. Mixed scripts still make one
//! sub-superscript, and brackets still group to the left.
use craft_math::math::{MNode, MRun, ScriptKind, parse_linear};
fn a(t: &str) -> Vec<MNode> {
vec![MNode::Run(MRun::new(t))]
}
fn sup(base: Vec<MNode>, s: Vec<MNode>) -> MNode {
MNode::Script { kind: ScriptKind::Sup, base, sub: Vec::new(), sup: s }
}
fn sub(base: Vec<MNode>, s: Vec<MNode>) -> MNode {
MNode::Script { kind: ScriptKind::Sub, base, sub: s, sup: Vec::new() }
}
#[test]
fn stacked_scripts_nest_to_the_right() {
assert_eq!(parse_linear("a^b^c"), vec![sup(a("a"), vec![sup(a("b"), a("c"))])]);
assert_eq!(parse_linear("a_b_c"), vec![sub(a("a"), vec![sub(a("b"), a("c"))])]);
assert_eq!(parse_linear("x^2^3"), vec![sup(a("x"), vec![sup(a("2"), a("3"))])]);
assert_eq!(parse_linear("a^b^c^d"), vec![sup(a("a"), vec![sup(a("b"), vec![sup(a("c"), a("d"))])])]);
}
#[test]
fn mixed_scripts_and_brackets_are_unchanged() {
// `a_b^c` and `a^b_c` are one sub-superscript, as in Word.
let subsup = vec![MNode::Script { kind: ScriptKind::SubSup, base: a("a"), sub: a("b"), sup: a("c") }];
assert_eq!(parse_linear("a_b^c"), subsup);
let subsup = vec![MNode::Script { kind: ScriptKind::SubSup, base: a("a"), sub: a("c"), sup: a("b") }];
assert_eq!(parse_linear("a^b_c"), subsup);
// Brackets group to the left, with a visible delimiter, as in Word.
let [MNode::Script { kind: ScriptKind::Sup, base, sup: c, .. }] = &parse_linear("(a^b)^c")[..] else { panic!() };
assert_eq!(c, &a("c"));
assert!(matches!(&base[..], [MNode::Delim { beg: Some('('), elems, .. }] if elems[0] == vec![sup(a("a"), a("b"))]), "{base:?}");
}
#[test]
fn stacked_scripts_on_a_function_name_nest_to_the_right() {
let name = |s: &str| vec![MNode::Run(MRun::plain(s))];
let func = |n: Vec<MNode>| vec![MNode::Func { name: n, e: a("x") }];
assert_eq!(parse_linear("sin^2^3 x"), func(vec![sup(name("sin"), vec![sup(a("2"), a("3"))])]));
assert_eq!(parse_linear("log_a_b x"), func(vec![sub(name("log"), vec![sub(a("a"), a("b"))])]));
// Mixed scripts on a name are still one sub-superscript.
let subsup = MNode::Script { kind: ScriptKind::SubSup, base: name("log"), sub: a("2"), sup: a("3") };
assert_eq!(parse_linear("log_2^3 x"), func(vec![subsup]));
// The other script nests too, as `x^2_a_b` does, and `x` is still the operand.
let subsup = MNode::Script { kind: ScriptKind::SubSup, base: name("sin"), sub: vec![sub(a("a"), a("b"))], sup: a("2") };
assert_eq!(parse_linear("sin^2_a_b x"), func(vec![subsup]));
let subsup = MNode::Script { kind: ScriptKind::SubSup, base: name("sin"), sub: a("a"), sup: vec![sup(a("2"), a("3"))] };
assert_eq!(parse_linear("sin_a^2^3 x"), func(vec![subsup]));
}
/// The whole chain stays within the parsers' depth cap (#1456), also when every operand is itself a
/// deep chain: the tree survives `serde_json` (its 128-level limit) and the rest is text.
#[test]
fn a_chain_of_deep_operands_stays_shallow() {
std::thread::Builder::new()
.stack_size(512 * 1024)
.spawn(|| {
let group = format!("({}c)", "b^".repeat(30));
for s in [format!("a{}", format!("^{group}").repeat(40)), format!("sin{} x", format!("^{group}").repeat(40))] {
let n = parse_linear(&s);
let json = serde_json::to_string(&n).unwrap();
let back: Vec<MNode> = serde_json::from_str(&json).unwrap_or_else(|e| panic!("{e}"));
assert_eq!(back, n);
}
})
.unwrap()
.join()
.unwrap();
}
/// A script operator the chain leaves at its cap stays text: it isn't taken as a function's operand.
#[test]
fn an_operator_left_at_the_cap_is_not_a_function_operand() {
let n = parse_linear(&format!("sin{} x", "^1".repeat(40)));
let operand_starts_with_a_script = |n: &MNode| match n {
MNode::Func { e, .. } => matches!(e.first(), Some(MNode::Run(r)) if r.text.starts_with(['^', '_'])),
_ => false,
};
assert!(!n.iter().any(operand_starts_with_a_script), "{n:?}");
}
+2 -1
View File
@@ -167,7 +167,8 @@ fn embedded_formula_object_reads_its_mathml() {
.flat_map(|p| &p.inlines)
.filter_map(|i| if let Inline::Equation { linear, display } = i { Some((linear.clone(), *display)) } else { None })
.collect();
assert_eq!(eqs, vec![("E=mc^2".to_string(), true)]);
// The base is `mc` (`<msup><mi>mc</mi>…`), so its linear form groups it, as Word writes it (#6228).
assert_eq!(eqs, vec![("E=〖mc〗^2".to_string(), true)]);
}
#[test]
+2
View File
@@ -4,6 +4,8 @@
pub mod encodings;
mod std14;
mod std14_metrics;
#[cfg(feature = "cos")]
pub mod wire;
pub use std14::{Match as Std14Match, Std14};
+236
View File
@@ -0,0 +1,236 @@
//! Pure COS wire builders for embedded Type0 / CIDFontType0 / CIDFontType2 fonts,
//! FontDescriptors, ToUnicode CMaps, and CID-to-GID CMap streams.
//!
//! No font-file parser or application asset policy lives here; callers supply
//! pre-validated metrics, glyph mappings, and program bytes.
use std::collections::BTreeMap;
use std::fmt::Write as _;
use crate::cos::{Dict, Document, Object, PdfString, Stream};
/// One mapped character/cluster in an embedded Type0 font.
pub struct CidMapping<'a> {
pub cid: u16,
pub glyph: u16,
pub width: f64,
pub unicode: &'a str,
}
/// Scaled metrics and metadata for a PDF `/FontDescriptor` dictionary.
pub struct FontDescriptorSpec<'a> {
pub font_name: &'a str,
pub family: &'a str,
pub italic_angle: f64,
pub ascent: f64,
pub descent: f64,
pub cap_height: f64,
pub bbox: [f64; 4],
pub cff: bool,
pub program: Object,
}
/// Add an uncompressed raw COS stream to `doc` and return its indirect reference.
pub fn raw_stream(doc: &mut Document, bytes: Vec<u8>) -> Object {
Object::Ref(doc.add(Object::Stream(Stream::from_raw(Dict::new(), bytes))))
}
/// Build a compressed full font program stream (`FontFile2` or `FontFile3` for CFF/OpenType).
pub fn font_program_stream(doc: &mut Document, bytes: &[u8], cff: bool) -> Object {
let mut d = Dict::new();
d.set(b"Length1".to_vec(), Object::Int(bytes.len() as i64));
if cff {
d.set(b"Subtype".to_vec(), Object::name("OpenType"));
}
d.set(b"PCFullFont".to_vec(), Object::Bool(true));
Object::Ref(doc.add(Object::Stream(Stream::flate(d, bytes))))
}
/// Build the `/ToUnicode` CMap stream (`PCUnicode`) mapping 2-byte CIDs to UTF-16BE hex strings.
pub fn build_to_unicode_cmap(mappings: &[CidMapping<'_>]) -> String {
let mut cmap = String::from(
"/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CMapName /PCUnicode def\n/CMapType 2 def\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n",
);
for chunk in mappings.chunks(100) {
let _ = writeln!(cmap, "{} beginbfchar", chunk.len());
for m in chunk {
let hex: String = m.unicode.encode_utf16().map(|u| format!("{u:04X}")).collect();
let _ = writeln!(cmap, "<{:04X}> <{hex}>", m.cid);
}
cmap.push_str("endbfchar\n");
}
cmap.push_str("endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n");
cmap
}
/// Build the `/Encoding` CMap stream (`PCGlyphs`) mapping 2-byte CIDs to CFF glyph IDs.
pub fn build_cid_encoding_cmap(mappings: &[CidMapping<'_>]) -> String {
let mut cid_encoding = String::from(
"/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CMapName /PCGlyphs def\n/CMapType 1 def\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n",
);
for chunk in mappings.chunks(100) {
let _ = writeln!(cid_encoding, "{} begincidchar", chunk.len());
for m in chunk {
let _ = writeln!(cid_encoding, "<{:04X}> {}", m.cid, m.glyph);
}
cid_encoding.push_str("endcidchar\n");
}
cid_encoding.push_str("endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n");
cid_encoding
}
/// Build a PDF `/FontDescriptor` dictionary.
pub fn build_font_descriptor(spec: &FontDescriptorSpec<'_>) -> Dict {
let mut descriptor = Dict::new();
descriptor.set(b"Type".to_vec(), Object::name("FontDescriptor"));
descriptor.set(b"FontName".to_vec(), Object::name(spec.font_name));
descriptor.set(b"FontFamily".to_vec(), Object::String(PdfString::literal(spec.family.as_bytes().to_vec())));
descriptor.set(b"Flags".to_vec(), Object::Int(4));
descriptor.set(b"ItalicAngle".to_vec(), Object::Real(spec.italic_angle));
descriptor.set(b"Ascent".to_vec(), Object::Real(spec.ascent));
descriptor.set(b"Descent".to_vec(), Object::Real(spec.descent));
descriptor.set(b"CapHeight".to_vec(), Object::Real(spec.cap_height));
descriptor.set(b"StemV".to_vec(), Object::Int(80));
descriptor.set(b"FontBBox".to_vec(), Object::Array(spec.bbox.map(Object::Real).to_vec()));
descriptor.set(if spec.cff { b"FontFile3".to_vec() } else { b"FontFile2".to_vec() }, spec.program.clone());
descriptor
}
/// Build a descendant `CIDFontType0` or `CIDFontType2` dictionary.
pub fn build_cid_font_dict(
doc: &mut Document,
name: &str,
descriptor: Object,
cff: bool,
cff_widths: BTreeMap<u16, f64>,
gids: Vec<u8>,
widths: Vec<Object>,
) -> Dict {
let mut system = Dict::new();
system.set(b"Registry".to_vec(), Object::String(PdfString::literal(b"Adobe".to_vec())));
system.set(b"Ordering".to_vec(), Object::String(PdfString::literal(b"Identity".to_vec())));
system.set(b"Supplement".to_vec(), Object::Int(0));
let mut cid = Dict::new();
cid.set(b"Type".to_vec(), Object::name("Font"));
cid.set(b"Subtype".to_vec(), Object::name(if cff { "CIDFontType0" } else { "CIDFontType2" }));
cid.set(b"BaseFont".to_vec(), Object::name(name));
cid.set(b"CIDSystemInfo".to_vec(), Object::Dict(system));
cid.set(b"FontDescriptor".to_vec(), descriptor);
if cff {
cid.set(
b"W".to_vec(),
Object::Array(cff_widths.into_iter().flat_map(|(gid, w)| [Object::Int(i64::from(gid)), Object::Array(vec![Object::Real(w)])]).collect()),
);
} else {
cid.set(b"CIDToGIDMap".to_vec(), raw_stream(doc, gids));
cid.set(b"W".to_vec(), Object::Array(vec![Object::Int(1), Object::Array(widths)]));
}
cid
}
/// Build the top-level `Type0` font dictionary.
pub fn build_type0_font_dict(doc: &mut Document, name: &str, descendant: Object, cid_encoding: Option<Vec<u8>>, to_unicode: Vec<u8>) -> Dict {
let mut top = Dict::new();
top.set(b"Type".to_vec(), Object::name("Font"));
top.set(b"Subtype".to_vec(), Object::name("Type0"));
top.set(b"BaseFont".to_vec(), Object::name(name));
top.set(
b"Encoding".to_vec(),
match cid_encoding {
Some(bytes) => raw_stream(doc, bytes),
None => Object::name("Identity-H"),
},
);
top.set(b"DescendantFonts".to_vec(), Object::Array(vec![descendant]));
top.set(b"ToUnicode".to_vec(), raw_stream(doc, to_unicode));
top
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn to_unicode_and_cid_cmaps_chunk_at_100_and_handle_surrogates() {
let mappings: Vec<CidMapping<'_>> =
(1..=105u16).map(|cid| CidMapping { cid, glyph: cid + 10, width: 500.0, unicode: if cid == 105 { "𠀋" } else { "A" } }).collect();
let tu = build_to_unicode_cmap(&mappings);
assert!(tu.contains("100 beginbfchar\n"));
assert!(tu.contains("5 beginbfchar\n"));
assert!(tu.contains("<0001> <0041>\n"));
assert!(tu.contains("<0069> <D840DC0B>\n"));
let ce = build_cid_encoding_cmap(&mappings);
assert!(ce.contains("100 begincidchar\n"));
assert!(ce.contains("5 begincidchar\n"));
assert!(ce.contains("<0001> 11\n"));
assert!(ce.contains("<0069> 115\n"));
}
#[test]
fn font_descriptor_program_stream_cid_and_type0_dicts_match_wire_layout() {
let mut doc = Document::new_empty();
let program_bytes = b"dummy-sfnt-data-repeated-for-flate-compression-dummy-sfnt-data";
let tt_prog = font_program_stream(&mut doc, program_bytes, false);
let tt_obj = doc.resolve(&tt_prog);
assert!(matches!(tt_obj.as_ref(), Object::Stream(_)));
if let Object::Stream(tt_stream) = tt_obj.as_ref() {
assert_eq!(tt_stream.dict.name(b"Filter"), Some(b"FlateDecode".as_slice()));
assert_eq!(tt_stream.dict.get(b"Subtype"), None);
assert_eq!(tt_stream.decoded().ok().as_deref(), Some(program_bytes.as_slice()));
}
let cff_prog = font_program_stream(&mut doc, program_bytes, true);
let cff_obj = doc.resolve(&cff_prog);
assert!(matches!(cff_obj.as_ref(), Object::Stream(_)));
if let Object::Stream(cff_stream) = cff_obj.as_ref() {
assert_eq!(cff_stream.dict.name(b"Subtype"), Some(b"OpenType".as_slice()));
}
let tt_desc = build_font_descriptor(&FontDescriptorSpec {
font_name: "Inter",
family: "Inter",
italic_angle: 0.0,
ascent: 900.0,
descent: -200.0,
cap_height: 700.0,
bbox: [-100.0, -200.0, 1000.0, 900.0],
cff: false,
program: tt_prog,
});
assert!(tt_desc.get(b"FontFile2").is_some());
assert!(tt_desc.get(b"FontFile3").is_none());
let cff_desc = build_font_descriptor(&FontDescriptorSpec {
font_name: "InterOTF",
family: "Inter",
italic_angle: 0.0,
ascent: 900.0,
descent: -200.0,
cap_height: 700.0,
bbox: [-100.0, -200.0, 1000.0, 900.0],
cff: true,
program: cff_prog,
});
assert!(cff_desc.get(b"FontFile3").is_some());
assert!(cff_desc.get(b"FontFile2").is_none());
let tt_desc_ref = Object::Ref(doc.add(Object::Dict(tt_desc)));
let tt_cid = build_cid_font_dict(&mut doc, "Inter", tt_desc_ref, false, BTreeMap::new(), vec![0, 0, 0, 3], vec![Object::Real(600.0)]);
assert_eq!(tt_cid.name(b"Subtype"), Some(b"CIDFontType2".as_slice()));
assert!(tt_cid.get(b"CIDToGIDMap").is_some());
let cff_desc_ref = Object::Ref(doc.add(Object::Dict(cff_desc)));
let cff_cid = build_cid_font_dict(&mut doc, "InterOTF", cff_desc_ref, true, BTreeMap::from([(3, 600.0)]), Vec::new(), Vec::new());
assert_eq!(cff_cid.name(b"Subtype"), Some(b"CIDFontType0".as_slice()));
assert!(cff_cid.get(b"CIDToGIDMap").is_none());
let tt_cid_ref = Object::Ref(doc.add(Object::Dict(tt_cid)));
let tt_top = build_type0_font_dict(&mut doc, "Inter", tt_cid_ref, None, b"tu".to_vec());
assert_eq!(tt_top.name(b"Encoding"), Some(b"Identity-H".as_slice()));
let cff_cid_ref = Object::Ref(doc.add(Object::Dict(cff_cid)));
let cff_top = build_type0_font_dict(&mut doc, "InterOTF", cff_cid_ref, Some(b"enc".to_vec()), b"tu".to_vec());
assert!(matches!(cff_top.get(b"Encoding"), Some(Object::Ref(_))));
}
}