use super::{Block, Body, Content, Section, read_story};
use crate::enumerations::assert_names;
use crate::ns::{A, PIC, R, V, W, WP};
use crate::quirks::{
BodyFieldResults, ContinuousSectionEnd, HeaderFieldResults, NumberForms, PageWithoutSection,
RepeatedNoteId, SavedDateWithoutPicture,
};
use crate::reader::PartReader;
use crate::warnings::ReadAs;
use f_office_paint::Orientation;
use f_office_units::Length;
use f_office_xml::{Document, Limits};
fn body(xml: &str) -> Body {
body_with(xml, BodyFieldResults::ComputesFields)
}
/// The page settings of the last section of the body `xml`.
fn last_section(xml: &str) -> Section {
body(xml).sections.last().section
}
fn body_with(xml: &str, results: BodyFieldResults) -> Body {
body_in(xml, results, NumberForms::Digits)
}
fn body_in(xml: &str, results: BodyFieldResults, forms: NumberForms) -> Body {
let doc = Document::parse(
format!(r#"<w:body xmlns:w="{W}">{xml}</w:body>"#).as_bytes(),
&Limits::default(),
)
.unwrap();
Body::read(
&mut PartReader::new(&doc)
.with_number_formats(crate::reader::settings::NumberFormats::with_forms(forms)),
doc.root().unwrap(),
(
crate::reader::settings::ReaderSettings::base()
.with_body_results(results)
.with_section_ends(ContinuousSectionEnd::OnlyBlockKeepsLine),
crate::mode::ModeRules::default(),
),
)
}
/// Run content without the field marks, which the tests of what a field shows leave out;
/// `leaves_field_marks_where_results_start_and_fields_end` tests them.
fn shown(content: &[Content]) -> Vec<Content> {
content
.iter()
.filter(|content| **content != Content::FieldMark)
.cloned()
.collect()
}
#[test]
fn leaves_field_marks_where_results_start_and_fields_end() {
let content = |xml: &str| -> Vec<Content> {
let body = body(&format!("<w:p>{xml}</w:p>"));
let Block::Paragraph(paragraph) = &body.blocks[0] else {
panic!("not a paragraph");
};
paragraph
.runs
.iter()
.flat_map(|run| run.content.clone())
.collect()
};
let text = |text: &str| Content::Text(text.to_owned());
let field = |code: &str, result: &str| {
format!(
r#"<w:r><w:t xml:space="preserve">a </w:t></w:r><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> {code} </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>{result}</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r><w:r><w:t xml:space="preserve"> b</w:t></w:r>"#
)
};
// A stored result that the story shows starts after a mark, and the field's end leaves
// one.
assert_eq!(
content(&field("TITLE", "x")),
[
text("a "),
Content::FieldMark,
text("x"),
Content::FieldMark,
text(" b")
]
);
// A computed value is a result too, and the stored result that it replaces leaves no
// mark.
assert_eq!(
content(&field("PAGE", "9")),
[
text("a "),
Content::FieldMark,
Content::PageNumber,
Content::FieldMark,
text(" b")
]
);
// A field in the code of another field leaves no mark: it is part of that code.
let nested = r#"<w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> IF </w:instrText></w:r><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> TITLE </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>x</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r><w:r><w:instrText xml:space="preserve"> = "x" "y" "z" </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>y</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r>"#;
let marks = content(nested)
.iter()
.filter(|item| **item == Content::FieldMark)
.count();
assert_eq!(marks, 2, "{:?}", content(nested));
}
#[test]
fn number_refs_obey_target_results_and_locks_in_both_field_forms() {
for results in [
BodyFieldResults::ComputesFields,
BodyFieldResults::ShowsStoredResults,
BodyFieldResults::ComputesFieldsAndReferences,
] {
for locked in [false, true] {
for simple in [false, true] {
for switch in [
"\\n",
"\\r",
"\\w",
"\\r \\h",
"\\n \\* MERGEFORMAT",
"\\p",
"",
"\\h",
] {
for marked in [false, true] {
check_number_ref(results, (locked, marked), simple, switch);
}
}
}
}
}
}
/// Checks a REF field with `switch` in a field of each form, locked or not and with its
/// bookmark in the body or not (`marked`). A field of text shows its stored result where its
/// bookmark exists.
fn check_number_ref(
results: BodyFieldResults,
(locked, marked): (bool, bool),
simple: bool,
switch: &str,
) {
let flags = if locked { r#" w:fldLock="true""# } else { "" };
let bookmark = if marked {
r#"<w:bookmarkStart w:id="0" w:name="probe"/><w:bookmarkEnd w:id="0"/>"#
} else {
""
};
let code = format!(" REF probe {switch} ");
let field = if simple {
format!(
r#"<w:fldSimple w:instr="{code}"{flags}><w:r><w:t>stored</w:t></w:r></w:fldSimple>"#
)
} else {
format!(
r#"<w:r><w:fldChar w:fldCharType="begin"{flags}/><w:instrText>{code}</w:instrText><w:fldChar w:fldCharType="separate"/><w:t>stored</w:t><w:fldChar w:fldCharType="end"/></w:r>"#
)
};
let parsed = body_with(&format!("<w:p>{bookmark}{field}</w:p>"), results);
let content: Vec<_> = first_paragraph(&parsed.blocks)
.runs
.iter()
.flat_map(|run| &run.content)
.collect();
let text = matches!(switch, "" | "\\h");
let computes = results == BodyFieldResults::ComputesFieldsAndReferences
&& !locked
&& switch != "\\p"
&& !(text && marked);
assert_eq!(
content
.iter()
.any(|item| matches!(item, Content::NumberRef(_))),
computes,
"{results:?} {locked} {marked} {simple} {switch}"
);
if !computes {
assert!(
content
.iter()
.any(|item| matches!(item, Content::Text(text) if text == "stored"))
);
}
}
#[test]
fn reads_the_shown_branch_of_alternate_content_around_runs_blocks_and_cells() {
fn text(blocks: &[Block]) -> Vec<String> {
let mut out = Vec::new();
for block in blocks {
match block {
Block::Paragraph(p) => out.push(
p.runs
.iter()
.flat_map(|r| &r.content)
.filter_map(|c| match c {
Content::Text(t) => Some(t.as_str()),
_ => None,
})
.collect(),
),
Block::Table(t) => {
for row in &t.rows {
for cell in &row.cells {
out.extend(text(&cell.blocks));
}
}
}
}
}
out
}
let (mc, w14) = (crate::ns::MC, crate::ns::W14);
let alternate = |choice: &str, fallback: &str| {
format!(
r#"<mc:AlternateContent xmlns:mc="{mc}" xmlns:w14="{w14}"><mc:Choice Requires="w14">{choice}</mc:Choice><mc:Fallback>{fallback}</mc:Fallback></mc:AlternateContent>"#
)
};
let run = |text: &str| format!("<w:r><w:t>{text}</w:t></w:r>");
let para = |text: &str| format!("<w:p>{}</w:p>", run(text));
let cell = |text: &str| format!("<w:tc>{}</w:tc>", para(text));
let xml = format!(
"<w:p>{}{}</w:p>{}<w:tbl><w:tr>{}</w:tr></w:tbl>",
run("A "),
alternate(&run("choice"), &run("fallback")),
alternate(¶("block"), ¶("old block")),
alternate(&cell("cell"), &cell("old cell")),
);
assert_eq!(text(&body(&xml).blocks), ["A choice", "block", "cell"]);
}
#[test]
fn reads_runs_and_content() {
let body = body(
r#"<w:p><w:pPr><w:jc w:val="center"/></w:pPr><w:r><w:rPr><w:rStyle w:val="Strong"/><w:b/></w:rPr><w:t>a</w:t><w:t xml:space="preserve"> b c</w:t><w:tab/><w:br/><w:br w:type="page"/><w:cr/><w:noBreakHyphen/></w:r><w:hyperlink><w:r><w:t>link</w:t></w:r></w:hyperlink><w:bookmarkStart/></w:p>"#,
);
let Block::Paragraph(paragraph) = &body.blocks[0] else {
panic!("not a paragraph");
};
// The hyperlink's run lies between the marks of its content's start and end, and the
// start's code in Word's text stands in an empty run after the start's mark.
assert_eq!(paragraph.runs.len(), 5);
let run = ¶graph.runs[0];
assert_eq!(run.style.as_deref(), Some("Strong"));
assert_eq!(run.props.bold, Some(true));
assert_eq!(
run.content,
vec![
Content::Text("a b c".into()),
Content::Tab,
Content::LineBreak,
Content::PageBreak,
Content::LineBreak,
Content::Text(crate::text::NON_BREAKING_HYPHEN.to_string()),
]
);
let rest: Vec<&Content> = paragraph.runs[1..]
.iter()
.flat_map(|run| &run.content)
.collect();
assert_eq!(
rest,
[
&Content::HyperlinkEdge,
&Content::Text("link".into()),
&Content::HyperlinkEdge
]
);
assert_eq!(body.sections.last().section, Section::default());
}
#[test]
fn reads_the_leader_of_a_page_tab_and_heavy_as_no_leader() {
let leader = |value: &str| {
let body = body(&format!(
r#"<w:p><w:r><w:ptab w:alignment="right" w:leader="{value}"/></w:r></w:p>"#
));
let Some(Block::Paragraph(paragraph)) = body.blocks.first() else {
return None;
};
match paragraph.runs.first()?.content.first()? {
Content::PositionTab { leader, .. } => *leader,
_ => None,
}
};
let read = ["dot", "middleDot", "none", "heavy", "Dot"].map(leader);
assert_eq!(read, [Some('.'), Some('\u{b7}'), None, None, None]);
}
/// Two paragraphs of text.
const TWO_PARAGRAPHS: &str = "<w:p><w:r><w:t>a</w:t></w:r></w:p><w:p><w:r><w:t>b</w:t></w:r></w:p>";
/// The page that each target's profile gives a body without section properties.
fn pages_of_targets() -> Vec<PageWithoutSection> {
crate::Target::all()
.map(|target| {
crate::profile::Profile::of(target)
.unwrap()
.quirks()
.page_without_section
})
.collect()
}
/// The width and height of a page, in twips.
fn page_twips(section: &Section) -> (i64, i64) {
let twips = |length: Length| length.units() / Length::UNITS_PER_TWIP;
(twips(section.width), twips(section.height))
}
/// The width and height of the page of `page`, in twips.
const fn expected_twips(page: PageWithoutSection) -> (i64, i64) {
match page {
PageWithoutSection::Letter => (12_240, 15_840),
PageWithoutSection::A4 => (11_906, 16_838),
}
}
/// Two paragraphs without section properties, with the page of `page`.
fn placed_without_section(page: PageWithoutSection) -> Body {
let mut without = body(TWO_PARAGRAPHS);
assert!(without.without_section);
without.place_pages(
&crate::reader::settings::ReaderSettings::base()
.with_page(page)
.template_section(),
false,
);
without
}
#[test]
fn gives_a_body_without_section_properties_the_page_of_each_target() {
let pages = pages_of_targets();
assert!(pages.contains(&PageWithoutSection::Letter));
assert!(pages.contains(&PageWithoutSection::A4));
let default = Section::default();
for page in pages {
let placed = placed_without_section(page);
let section = placed.sections.last().section;
assert_eq!(page_twips(§ion), expected_twips(page));
assert_eq!(
(section.left, section.bottom),
(default.left, default.bottom)
);
assert_eq!(placed.sections.count(), 1);
}
}
#[test]
fn gives_a_section_without_a_page_size_the_default_page_on_every_target() {
// An empty `w:sectPr`, or one in a paragraph, gives the page of a section that says
// nothing, whatever page the target gives a body without section properties.
for xml in [
format!("{TWO_PARAGRAPHS}<w:sectPr/>"),
format!("<w:p><w:pPr><w:sectPr/></w:pPr></w:p>{TWO_PARAGRAPHS}"),
] {
for page in [PageWithoutSection::Letter, PageWithoutSection::A4] {
let mut with = body(&xml);
assert!(!with.without_section);
with.place_pages(
&crate::reader::settings::ReaderSettings::base()
.with_page(page)
.template_section(),
false,
);
assert_eq!(with.sections.last().section, Section::default());
}
}
}
#[test]
fn reads_text_in_its_composed_form() {
// An `i` with a combining acute accent becomes `í`, and two marks on an `a` become one
// character when the table has it. A mark without a composed form, the Greek question mark
// and the ohm sign stay as they are.
let body = body(
"<w:p><w:r><w:t>Di\u{301}az a\u{302}\u{301} q\u{301} ;\u{37E} \u{2126}</w:t></w:r></w:p>",
);
let Block::Paragraph(paragraph) = &body.blocks[0] else {
panic!("not a paragraph");
};
assert_eq!(
paragraph.runs[0].content,
vec![Content::Text(
"D\u{ED}az \u{1EA5} q\u{301} ;\u{37E} \u{2126}".into()
)]
);
}
#[test]
fn reads_a_symbol_as_a_run_of_its_own_in_its_font() {
let body = body(
r#"<w:p><w:r><w:rPr><w:b/></w:rPr><w:t>a</w:t><w:sym w:font="Wingdings" w:char="F0E0"/><w:t>b</w:t></w:r><w:r><w:sym w:font="Symbol" w:char="F0B7"/><w:sym w:char="zz"/></w:r></w:p>"#,
);
let Block::Paragraph(paragraph) = &body.blocks[0] else {
panic!("not a paragraph");
};
let texts: Vec<_> = paragraph.runs.iter().map(|r| r.content.clone()).collect();
let text = |s: &str| vec![Content::Text(s.into())];
assert_eq!(
texts,
[text("a"), text("\u{F0E0}"), text("b"), text("\u{F0B7}")]
);
let symbol = ¶graph.runs[1].props;
let wingdings = Some(crate::props::FontRef::Name("Wingdings".into()));
assert_eq!(symbol.font_ascii, wingdings);
assert_eq!(symbol.font_hansi, wingdings);
assert_eq!(symbol.bold, Some(true));
assert_eq!(paragraph.runs[2].props.font_ascii, None);
assert_eq!(paragraph.runs[2].props.bold, Some(true));
}
#[test]
fn reads_date_fields_with_their_picture_and_stored_result() {
let body = body(
r#"<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> DATE \@ "d\ MMMM\ yyyy" </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>1 May</w:t></w:r><w:r><w:t xml:space="preserve"> 2020</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r><w:fldSimple w:instr="TIME"><w:r><w:t>9:00 AM</w:t></w:r></w:fldSimple></w:p>"#,
);
let Block::Paragraph(paragraph) = &body.blocks[0] else {
panic!("not a paragraph");
};
let content: Vec<_> = paragraph
.runs
.iter()
.flat_map(|r| shown(&r.content))
.collect();
let date = |picture: &str, stored: &str| {
Content::Date(Box::new(super::DateField {
picture: picture.to_owned(),
stored: stored.to_owned(),
}))
};
assert_eq!(
content,
[
date("d MMMM yyyy", "1 May 2020"),
date(crate::dates::TIME_PICTURE, "9:00 AM")
]
);
// A document property field in a footer names its property, quoted or not.
let fields = r#"<w:p><w:fldSimple w:instr=" DOCPROPERTY "AsAtDate" \* MERGEFORMAT "><w:r><w:t>AsAtDate</w:t></w:r></w:fldSimple><w:fldSimple w:instr="DOCPROPERTY Suffix"><w:r><w:t>x</w:t></w:r></w:fldSimple><w:fldSimple w:instr=" DOCPROPERTY StartDate \@ "d/M/yy" "><w:r><w:t>29/12/18</w:t></w:r></w:fldSimple></w:p>"#;
let footer = Document::parse(
format!(r#"<w:ftr xmlns:w="{W}">{fields}</w:ftr>"#).as_bytes(),
&Limits::default(),
)
.unwrap();
let blocks = super::read_header_story(
&mut PartReader::new(&footer),
footer.root().unwrap(),
crate::reader::settings::ReaderSettings::base()
.with_header_results(HeaderFieldResults::ComputesFields),
);
let Block::Paragraph(paragraph) = &blocks[0] else {
panic!("not a paragraph");
};
let named: Vec<_> = paragraph
.runs
.iter()
.flat_map(|r| &r.content)
.filter_map(|c| match c {
Content::DocProperty(p) => {
Some((p.name.as_str(), p.stored.as_str(), p.picture.as_deref()))
}
_ => None,
})
.collect();
assert_eq!(
named,
[
("AsAtDate", "AsAtDate", None),
("Suffix", "x", None),
("StartDate", "29/12/18", Some("d/M/yy"))
]
);
// In the body, the fields keep their stored results.
let property = super::tests::body(fields);
let Block::Paragraph(paragraph) = &property.blocks[0] else {
panic!("not a paragraph");
};
let texts: Vec<_> = paragraph
.runs
.iter()
.flat_map(|r| shown(&r.content))
.collect();
let stored = ["AsAtDate", "x", "29/12/18"].map(|t| Content::Text(t.into()));
assert_eq!(texts, stored);
// A save or print date with a picture is a date as well; without one it keeps its
// stored result.
let saved = super::tests::body(
r#"<w:p><w:fldSimple w:instr=" SAVEDATE \@ "MMMM d, yyyy" "><w:r><w:t>May 6, 2019</w:t></w:r></w:fldSimple><w:fldSimple w:instr="PRINTDATE"><w:r><w:t>2014</w:t></w:r></w:fldSimple></w:p>"#,
);
let Block::Paragraph(paragraph) = &saved.blocks[0] else {
panic!("not a paragraph");
};
let content: Vec<_> = paragraph
.runs
.iter()
.flat_map(|r| shown(&r.content))
.collect();
assert_eq!(
content,
[
date("MMMM d, yyyy", "May 6, 2019"),
Content::Text("2014".to_owned())
]
);
}
#[test]
fn shows_a_save_or_print_date_without_a_picture_as_the_target_says() {
let xml = format!(
r#"<w:body xmlns:w="{W}"><w:p><w:fldSimple w:instr="PRINTDATE"><w:r><w:t>2014</w:t></w:r></w:fldSimple><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> SAVEDATE \* MERGEFORMAT </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>x</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p></w:body>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let date = |stored: &str| {
Content::Date(Box::new(super::DateField {
picture: crate::dates::SAVED_DATE_PICTURE.to_owned(),
stored: stored.to_owned(),
}))
};
let text = |text: &str| Content::Text(text.to_owned());
for (variant, expected) in [
(
SavedDateWithoutPicture::KeepsStoredResult,
[text("2014"), text("x")],
),
(
SavedDateWithoutPicture::DateAndTime,
[date("2014"), date("x")],
),
] {
let settings = crate::reader::settings::ReaderSettings::base()
.with_body_results(BodyFieldResults::ComputesFields)
.with_saved_dates(variant);
let body = Body::read(
&mut PartReader::new(&doc).with_saved_date_picture(settings.saved_date_picture()),
doc.root().unwrap(),
(settings, crate::mode::ModeRules::default()),
);
let Block::Paragraph(paragraph) = &body.blocks[0] else {
panic!("not a paragraph");
};
let content: Vec<_> = paragraph
.runs
.iter()
.flat_map(|r| shown(&r.content))
.collect();
assert_eq!(content, expected, "{variant:?}");
}
}
#[test]
fn reads_styleref_fields_and_keeps_those_with_other_switches() {
let body = body(
r#"<w:p><w:fldSimple w:instr=" STYLEREF "Heading 1" \l "><w:r><w:t>Old</w:t></w:r></w:fldSimple><w:fldSimple w:instr="styleref CharNo"><w:r><w:t>r. 1</w:t></w:r></w:fldSimple><w:fldSimple w:instr="STYLEREF Heading1 \n"><w:r><w:t>2.</w:t></w:r></w:fldSimple><w:fldSimple w:instr=" STYLEREF CharNo \* CHARFORMAT "><w:r><w:t>17</w:t></w:r></w:fldSimple><w:fldSimple w:instr="STYLEREF CharNo \* Upper"><w:r><w:t>X</w:t></w:r></w:fldSimple></w:p>"#,
);
let Block::Paragraph(paragraph) = &body.blocks[0] else {
panic!("not a paragraph");
};
let content: Vec<_> = paragraph
.runs
.iter()
.flat_map(|r| shown(&r.content))
.collect();
let style_ref = |style: &str, last, stored: &str| {
Content::StyleRef(Box::new(super::StyleRef {
style: style.to_owned(),
last,
number: false,
stored: stored.to_owned(),
}))
};
assert_eq!(
content,
[
style_ref("Heading 1", true, "Old"),
style_ref("CharNo", false, "r. 1"),
Content::Text("2.".into()),
// A format switch that only formats the result keeps the field live.
style_ref("CharNo", false, "17"),
Content::Text("X".into())
]
);
}
#[test]
fn gives_an_empty_paragraph_that_ends_a_section_no_page_break_before() {
let body = body(
"<w:p><w:pPr><w:pageBreakBefore/><w:sectPr/></w:pPr></w:p><w:p><w:pPr><w:pageBreakBefore/></w:pPr><w:r><w:t>Next</w:t></w:r></w:p><w:sectPr/>",
);
let breaks: Vec<_> = body
.blocks
.iter()
.map(|block| match block {
Block::Paragraph(p) => p.props.page_break_before,
Block::Table(_) => None,
})
.collect();
assert_eq!(breaks, [Some(false), Some(true)]);
}
/// The paragraph that ends the first section of a body, with its own page break before and
/// before a section that starts on a new page, when it holds `runs`.
fn section_end_paragraph(runs: &str) -> super::Paragraph {
let body = body(&format!(
"<w:p><w:pPr><w:pageBreakBefore/><w:sectPr/></w:pPr>{runs}</w:p><w:p><w:r><w:t>Next</w:t></w:r></w:p><w:sectPr/>"
));
match body.blocks.into_iter().next() {
Some(Block::Paragraph(paragraph)) => paragraph,
other => panic!("not a paragraph: {other:?}"),
}
}
#[test]
fn gives_a_section_end_that_holds_a_shape_a_check_box_or_a_note_reference_its_page_break_before() {
let shape = format!(
r#"<w:r><w:pict xmlns:v="{V}" xmlns:w10="{W10}"><v:rect style="width:20pt;height:1pt"><w10:anchorlock/></v:rect></w:pict></w:r>"#,
W10 = crate::ns::W10
);
let check_box = r#"<w:r><w:fldChar w:fldCharType="begin"><w:ffData><w:checkBox><w:sizeAuto/></w:checkBox></w:ffData></w:fldChar></w:r><w:r><w:instrText xml:space="preserve"> FORMCHECKBOX </w:instrText></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r>"#;
let note = r#"<w:r><w:footnoteReference w:id="1"/></w:r>"#;
assert_section_end_not_empty(&shape, |c| matches!(c, Content::Drawing(_)));
assert_section_end_not_empty(check_box, |c| matches!(c, Content::CheckBox(_)));
assert_section_end_not_empty(note, |c| matches!(c, Content::FootnoteReference(..)));
}
/// Checks that the paragraph of [`section_end_paragraph`] with `runs` holds content of `kind`,
/// keeps its own page break before and is no section end.
fn assert_section_end_not_empty(runs: &str, kind: fn(&Content) -> bool) {
let paragraph = section_end_paragraph(runs);
let mut content = paragraph.runs.iter().flat_map(|r| &r.content);
assert!(content.any(kind), "{runs}");
assert_eq!(paragraph.props.page_break_before, Some(true), "{runs}");
assert_eq!(paragraph.props.section_end, None, "{runs}");
}
#[test]
fn keeps_a_section_end_of_spaces_marks_and_breaks_empty() {
for empty in [
r#"<w:r><w:t xml:space="preserve"> </w:t></w:r>"#,
r#"<w:bookmarkStart w:id="0" w:name="a"/><w:bookmarkEnd w:id="0"/>"#,
r#"<w:r><w:commentReference w:id="0"/></w:r>"#,
r#"<w:r><w:br w:type="page"/></w:r>"#,
"<w:r><w:br/></w:r>",
] {
let paragraph = section_end_paragraph(empty);
assert_eq!(paragraph.props.page_break_before, Some(false), "{empty}");
assert_eq!(paragraph.props.section_end, Some(true), "{empty}");
}
}
#[test]
fn reads_a_body_whose_own_section_stands_before_a_paragraphs() {
// The body's own `w:sectPr` before a paragraph's (not valid in ECMA-376) gives a section
// that ends where the blocks end, as the flow reads it, and the paragraph's section and a
// last section of defaults follow it.
let body = body(
r#"<w:p/><w:sectPr><w:pgSz w:w="11906" w:h="16838"/></w:sectPr><w:p><w:pPr><w:sectPr/></w:pPr></w:p><w:p/>"#,
);
let ends: Vec<usize> = body.sections.iter().map(|part| part.end).collect();
assert_eq!(ends, [3, 2, 3]);
assert_eq!(page_twips(&body.sections.first().section), (11_906, 16_838));
}
#[test]
fn reads_the_picture_switch_of_a_field() {
let cases = [
(
r#"DATE \@ "dddd, MMMM d, yyyy""#,
Some("dddd, MMMM d, yyyy"),
),
(r#"DATE \@"yyyy""#, Some("yyyy")),
(r"DATE \@ dd/MM \* MERGEFORMAT", Some("dd/MM")),
(r#"DATE \@ "'Week' \"d\"""#, Some("'Week' \"d\"")),
(r"DATE \* MERGEFORMAT", None),
];
for (code, picture) in cases {
assert_eq!(
super::fields::picture_switch(code).as_deref(),
picture,
"{code}"
);
}
}
#[test]
fn keeps_deleted_and_moved_text_in_line() {
let body = body(
r#"<w:p><w:r><w:t xml:space="preserve">Test </w:t></w:r><w:del w:author="A"><w:r><w:delText xml:space="preserve">test </w:delText></w:r><w:r><w:fldChar w:fldCharType="begin"/><w:delInstrText> PAGE </w:delInstrText><w:fldChar w:fldCharType="end"/></w:r></w:del><w:ins w:author="A"><w:r><w:t>abc</w:t></w:r></w:ins><w:moveFrom><w:r><w:delText>x</w:delText></w:r></w:moveFrom><w:moveTo><w:r><w:t>y</w:t></w:r></w:moveTo></w:p>"#,
);
let content: Vec<Content> = first_paragraph(&body.blocks)
.runs
.iter()
.flat_map(|run| shown(&run.content))
.collect();
assert_eq!(
content,
vec![
Content::Text("Test ".into()),
Content::Text("test ".into()),
Content::PageNumber,
Content::Text("abc".into()),
Content::Text("x".into()),
Content::Text("y".into()),
]
);
}
#[test]
fn marks_tracked_changes_in_the_color_of_their_author() {
let body = body(
r#"<w:p><w:r><w:t>a</w:t></w:r><w:del w:author="Ann"><w:r><w:rPr><w:color w:val="00FF00"/></w:rPr><w:delText>b</w:delText></w:r></w:del><w:ins w:author="Ann"><w:r><w:t>c</w:t></w:r></w:ins><w:moveFrom w:author="Bob"><w:r><w:delText>d</w:delText></w:r></w:moveFrom><w:moveTo w:author="Bob"><w:r><w:t>e</w:t></w:r></w:moveTo></w:p>"#,
);
let runs = &first_paragraph(&body.blocks).runs;
let marks: Vec<_> = runs
.iter()
.map(|r| (r.props.strike, r.props.underline, r.props.color))
.collect();
assert_eq!(marks[0], (None, None, None));
// The author's color wins over the run's own color.
let ann = marks[1].2;
assert!(ann.is_some() && ann != Some(crate::props::Color::Rgb([0, 255, 0])));
let (struck, underlined) = (
Some(crate::props::Strike::Single),
Some(crate::props::Underline::Single),
);
assert_eq!(marks[1], (struck, None, ann));
assert_eq!(marks[2], (None, underlined, ann));
let bob = marks[3].2;
assert_eq!(marks[3], (struck, None, bob));
assert_eq!(marks[4], (None, underlined, bob));
}
#[test]
fn marks_the_mark_of_a_paragraph_whose_properties_changed() {
let body = body(
r#"<w:p><w:pPr><w:jc w:val="center"/><w:pPrChange w:author="Ann"><w:pPr/></w:pPrChange></w:pPr></w:p><w:p><w:pPr><w:jc w:val="center"/></w:pPr></w:p>"#,
);
let changed: Vec<_> = body
.blocks
.iter()
.map(|block| match block {
Block::Paragraph(paragraph) => paragraph.props.mark.changed,
Block::Table(_) => panic!("not a paragraph"),
})
.collect();
assert_eq!(changed, [Some(true), None]);
}
fn first_paragraph(blocks: &[Block]) -> &super::Paragraph {
match blocks.first() {
Some(Block::Paragraph(paragraph)) => paragraph,
_ => panic!("not a paragraph"),
}
}
#[test]
fn gives_a_field_result_the_direction_of_the_run_of_its_code() {
let rtl = r"<w:rPr><w:rtl/></w:rPr>";
let field = |code: &str, result: &str| {
format!(
r#"<w:p><w:r><w:t>a</w:t></w:r><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r>{code}<w:instrText> PAGE </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r>{result}<w:t>9</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r><w:r><w:t>b</w:t></w:r></w:p>"#
)
};
let of = |blocks: &[Block]| -> Vec<Option<bool>> {
first_paragraph(blocks)
.runs
.iter()
.filter(|run| !shown(&run.content).is_empty())
.map(|run| run.props.field_rtl)
.collect()
};
let marks = |xml: &str| of(&body(xml).blocks);
// Only the run that shows the computed number has the mark, with the direction of the
// code's run.
assert_eq!(marks(&field(rtl, "")), [None, Some(true), None]);
assert_eq!(marks(&field("", rtl)), [None, Some(false), None]);
// A stored result that Word shows keeps the direction of its own run.
let stored = body_with(&field(rtl, ""), BodyFieldResults::ShowsStoredResults);
assert_eq!(of(&stored.blocks), [None, None, None]);
// In a header or footer the computed number reads from right to left, whatever the runs
// of the field say.
let header = Document::parse(
format!(
r#"<w:hdr xmlns:w="{W}">{}</w:hdr>"#,
field("", "").replace(r#" xmlns:w=""#, "")
)
.as_bytes(),
&Limits::default(),
)
.unwrap();
for results in [
HeaderFieldResults::ComputesFields,
HeaderFieldResults::ComputesPageFields,
] {
let blocks = super::read_header_story(
&mut PartReader::new(&header),
header.root().unwrap(),
crate::reader::settings::ReaderSettings::base().with_header_results(results),
);
assert_eq!(of(&blocks), [None, Some(true), None]);
}
// A field without a separator shows its value in the run of its end.
let short = format!(
r#"<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r>{rtl}<w:instrText>PAGE</w:instrText></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>"#
);
assert_eq!(marks(&short), [Some(true)]);
// A simple field has no run of its code.
let simple = r#"<w:p><w:fldSimple w:instr="PAGE"><w:r><w:t>3</w:t></w:r></w:fldSimple></w:p>"#;
assert_eq!(marks(simple), [None]);
}
#[test]
fn marks_the_runs_of_the_result_of_a_text_form_field() {
let field = |code: &str| {
format!(
r#"<w:p><w:r><w:t>a</w:t></w:r><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText> {code} </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>b</w:t></w:r><w:r><w:t>c</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r><w:r><w:t>d</w:t></w:r></w:p>"#
)
};
let marks = |xml: &str| -> Vec<Option<bool>> {
first_paragraph(&body(xml).blocks)
.runs
.iter()
.filter(|run| !shown(&run.content).is_empty())
.map(|run| run.props.form_text)
.collect()
};
assert_eq!(
marks(&field("FORMTEXT")),
[None, Some(true), Some(true), None]
);
assert_eq!(marks(&field("MERGEFIELD Name")), [None; 4]);
}
#[test]
fn computes_page_fields_in_table_cells() {
let body = body(
r#"<w:tbl><w:tr><w:tc><w:sdt><w:sdtContent><w:p><w:fldSimple w:instr="PAGE"><w:r><w:t>3</w:t></w:r></w:fldSimple></w:p></w:sdtContent></w:sdt></w:tc></w:tr></w:tbl>"#,
);
let Some(Block::Table(table)) = body.blocks.first() else {
panic!("not a table");
};
let cell = &table.rows[0].cells[0];
let content: Vec<Content> = first_paragraph(&cell.blocks)
.runs
.iter()
.flat_map(|r| shown(&r.content))
.collect();
assert_eq!(content, vec![Content::PageNumber]);
}
#[test]
fn keeps_bookmarks_between_paragraphs_and_in_field_results() {
// A bookmark between paragraphs starts the next one, also through a table, and a
// bookmark in the result of a page field stays where the computed number replaces
// that result.
let body = body(
r#"<w:p/><w:bookmarkStart w:id="0" w:name="next"/><w:tbl><w:tr><w:tc><w:p><w:r><w:t>Cell</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText>PAGE</w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:bookmarkStart w:id="1" w:name="inside"/><w:r><w:t>3</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>"#,
);
let content = |paragraph: &super::Paragraph| -> Vec<Content> {
paragraph
.runs
.iter()
.flat_map(|r| shown(&r.content))
.collect()
};
let Some(Block::Table(table)) = body.blocks.get(1) else {
panic!("not a table");
};
let cell = content(first_paragraph(&table.rows[0].cells[0].blocks));
assert_eq!(cell.first(), Some(&Content::Bookmark("next".to_owned())));
let Some(Block::Paragraph(last)) = body.blocks.get(2) else {
panic!("not a paragraph");
};
assert_eq!(
content(last),
vec![Content::Bookmark("inside".to_owned()), Content::PageNumber]
);
}
#[test]
fn reads_tables_between_paragraphs() {
let body = body("<w:p/><w:tbl><w:tr><w:tc><w:p/></w:tc></w:tr></w:tbl><w:bookmarkEnd/><w:p/>");
assert!(matches!(
body.blocks.as_slice(),
[Block::Paragraph(_), Block::Table(t), Block::Paragraph(_)] if t.rows.len() == 1
));
}
#[test]
fn reads_the_section() {
let body = body(
r#"<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="-1417" w:right="1000" w:bottom="1134" w:left="1200" w:gutter="100"/></w:sectPr>"#,
);
let s = body.sections.last().section;
let twips = |l: Length| l.units() / Length::UNITS_PER_TWIP;
let sides = [s.width, s.height, s.top, s.right, s.bottom, s.left].map(twips);
assert_eq!(sides, [11_906, 16_838, 1_417, 1_000, 1_134, 1_300]);
let defaults = Section::default();
assert_eq!((s.header, s.footer), (defaults.header, defaults.footer));
assert_eq!((s.title_page, s.first_page_number), (false, 1));
assert_eq!(s.vertical, super::PageAlign::Top);
}
#[test]
fn reads_the_line_pitch_of_a_document_grid() {
let pitch = |grid: &str| last_section(&format!("<w:sectPr>{grid}</w:sectPr>")).line_pitch;
let lines = r#"<w:docGrid w:type="lines" w:linePitch="312"/>"#;
assert_eq!(pitch(lines), Length::from_twips(312));
let both = r#"<w:docGrid w:type="linesAndChars" w:linePitch="360" w:charSpace="0"/>"#;
assert_eq!(pitch(both), Length::from_twips(360));
// Without a type, the grid does not apply.
assert_eq!(pitch(r#"<w:docGrid w:linePitch="360"/>"#), None);
assert_eq!(pitch(""), None);
// `snapToChars` does not snap lines to a line grid, but keeps `spacing_line_pitch` for
// `w:beforeLines` / `w:afterLines`.
let snap =
last_section(r#"<w:sectPr><w:docGrid w:type="snapToChars" w:linePitch="360"/></w:sectPr>"#);
assert_eq!(
(snap.line_pitch, snap.spacing_line_pitch),
(None, Length::from_twips(360))
);
}
#[test]
fn reads_the_character_pitch_of_a_character_grid() {
let added = |grid: &str| last_section(&format!("<w:sectPr>{grid}</w:sectPr>")).char_pitch;
// ECMA-376 Part 1, 17.6.5: 40960 in 4096ths of a point is 10 pt.
let both = r#"<w:docGrid w:type="linesAndChars" w:linePitch="360" w:charSpace="40960"/>"#;
assert_eq!(added(both), Length::from_points(10));
// -1541 is -0.376 pt, 9,556 units rounded.
let less = r#"<w:docGrid w:type="linesAndChars" w:linePitch="398" w:charSpace="-1541"/>"#;
assert_eq!(added(less), Some(Length::from_units(-9_556)));
// A line grid has no character grid; a character grid of the pitch 0, or of none, adds 0.
let lines = r#"<w:docGrid w:type="lines" w:linePitch="360" w:charSpace="40960"/>"#;
assert_eq!(added(lines), None);
let zero = r#"<w:docGrid w:type="linesAndChars" w:linePitch="360" w:charSpace="0"/>"#;
assert_eq!(added(zero), Some(Length::ZERO));
let none = r#"<w:docGrid w:type="linesAndChars" w:linePitch="360"/>"#;
assert_eq!(added(none), Some(Length::ZERO));
}
#[test]
fn reads_a_character_pitch_beyond_32_bits_as_0_with_a_warning() {
let read = |space: &str| {
let xml = format!(
r#"<w:body xmlns:w="{W}"><w:sectPr><w:docGrid w:type="linesAndChars" w:linePitch="360" w:charSpace="{space}"/></w:sectPr></w:body>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let mut reader = PartReader::new(&doc);
let root = doc.root().unwrap();
let body = Body::read(
&mut reader,
root,
(
crate::reader::settings::ReaderSettings::base()
.with_body_results(BodyFieldResults::ComputesFields)
.with_section_ends(ContinuousSectionEnd::OnlyBlockKeepsLine),
crate::mode::ModeRules::default(),
),
);
let pitch = body.sections.last().section.char_pitch;
(pitch, reader.invalid_values())
};
// The ends of 32 bits keep their pitch: 2^31 - 1 and -2^31 4096ths of a point, rounded.
let largest = Some(Length::from_units(13_316_915_194));
assert_eq!(read("2147483647"), (largest, vec![]));
let lowest = Some(Length::from_units(-13_316_915_200));
assert_eq!(read("-2147483648"), (lowest, vec![]));
let warning = vec![(
"docGrid".to_string(),
Some("charSpace".to_string()),
ReadAs::Missing,
1,
)];
for space in ["2147483648", "-2147483649", "9223372036854775807"] {
assert_eq!(
read(space),
(Some(Length::ZERO), warning.clone()),
"{space}"
);
}
}
#[test]
fn reads_the_orientation_of_a_section_and_an_unknown_one_as_portrait_with_a_warning() {
let read = |size: &str| {
let xml = format!(r#"<w:body xmlns:w="{W}"><w:sectPr>{size}</w:sectPr></w:body>"#);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let mut reader = PartReader::new(&doc);
let root = doc.root().unwrap();
let body = Body::read(
&mut reader,
root,
(
crate::reader::settings::ReaderSettings::base()
.with_body_results(BodyFieldResults::ComputesFields)
.with_section_ends(ContinuousSectionEnd::OnlyBlockKeepsLine),
crate::mode::ModeRules::default(),
),
);
let orientation = body.sections.last().section.orientation;
(orientation, reader.invalid_values())
};
let (portrait, landscape) = (Orientation::Portrait, Orientation::Landscape);
let across = r#"<w:pgSz w:w="16838" w:h="11906" w:orient="landscape"/>"#;
assert_eq!(read(across), (landscape, vec![]));
// The attribute alone decides: a page wider than high in a section that sets no
// orientation, or sets portrait, lies in a portrait section.
assert_eq!(
read(r#"<w:pgSz w:w="16838" w:h="11906"/>"#),
(portrait, vec![])
);
let upright = r#"<w:pgSz w:w="16838" w:h="11906" w:orient="portrait"/>"#;
assert_eq!(read(upright), (portrait, vec![]));
assert_eq!(read(""), (portrait, vec![]));
let warning = vec![(
"pgSz".to_string(),
Some("orient".to_string()),
ReadAs::Missing,
1,
)];
let unknown = r#"<w:pgSz w:w="16838" w:h="11906" w:orient="sideways"/>"#;
assert_eq!(read(unknown), (portrait, warning));
}
#[test]
fn reads_the_vertical_alignment_of_a_section() {
let align = |value: &str| {
last_section(&format!(
r#"<w:sectPr><w:vAlign w:val="{value}"/></w:sectPr>"#
))
.vertical
};
assert_eq!(align("center"), super::PageAlign::Center);
assert_eq!(align("bottom"), super::PageAlign::Bottom);
// Vertical justification is not done yet.
assert_eq!(align("both"), super::PageAlign::Top);
}
#[test]
fn reads_the_chapter_level_and_separator_of_page_numbers() {
let chapter = |numbers: &str| {
last_section(&format!(r"<w:sectPr><w:pgNumType {numbers}/></w:sectPr>"))
.chapter
.map(|c| (c.level, c.separator.char()))
};
assert_eq!(chapter(r#"w:chapStyle="1""#), Some((1, '-')));
assert_eq!(
chapter(r#"w:chapStyle="2" w:chapSep="period""#),
Some((2, '.'))
);
assert_eq!(
chapter(r#"w:chapStyle="3" w:chapSep="emDash""#),
Some((3, '\u{2014}'))
);
// Level 0 names no heading style.
assert_eq!(chapter(r#"w:chapStyle="0""#), None);
assert_eq!(chapter(r#"w:start="1""#), None);
}
#[test]
fn reads_page_borders_without_art_borders() {
let read = body(
r#"<w:sectPr><w:pgBorders w:offsetFrom="page" w:display="notFirstPage"><w:top w:val="single" w:sz="18" w:space="24" w:color="C00000"/><w:left w:val="twistedLines1" w:sz="20" w:space="24"/><w:bottom w:val="none"/></w:pgBorders></w:sectPr>"#,
);
let borders = read.sections.first().borders.unwrap();
assert!(borders.from_page);
assert_eq!(borders.pages, super::BorderPages::NotFirst);
let top = borders.sides.top.and_then(super::PageSide::line).unwrap();
assert_eq!(top.width, Length::from_eighth_points(18).unwrap());
assert_eq!(top.space, Length::from_points(24).unwrap());
let others = [
borders.sides.left,
borders.sides.bottom,
borders.sides.right,
];
assert_eq!(others, [None, None, None]);
let art = body(
r#"<w:sectPr><w:pgBorders><w:top w:val="twistedLines1" w:sz="20"/></w:pgBorders></w:sectPr>"#,
);
assert_eq!(art.sections.first().borders, None);
}
#[test]
fn draws_a_page_border_of_other_lines_as_one_line_and_text_as_no_line() {
let page = |style: &str| {
body(&format!(
r#"<w:sectPr><w:pgBorders><w:top w:val="{style}" w:sz="8"/></w:pgBorders></w:sectPr>"#
))
.sections
.first()
.borders
.and_then(|borders| borders.sides.top)
.and_then(super::PageSide::line)
.map(|top| top.lines().len())
};
let read = [
"dotted",
"double",
"outset",
"threeDEngrave",
"Single",
"solid",
]
.map(page);
assert_eq!(read, [Some(1), Some(2), Some(1), Some(3), None, None]);
let names = super::section::PAGE_BORDER_LINE.names();
let distinct: std::collections::HashSet<&str> = names.iter().map(|(name, _)| *name).collect();
assert_eq!((names.len(), distinct.len()), (191, 191));
}
#[test]
fn reads_header_and_footer_references() {
let body = body(&format!(
r#"<w:sectPr xmlns:r="{R}"><w:headerReference w:type="default" r:id="h1"/><w:headerReference w:type="first" r:id="h2"/><w:footerReference w:type="even" r:id="f1"/><w:footerReference r:id="f2"/></w:sectPr>"#
));
let id = |s: &Option<String>| s.clone().unwrap_or_default();
let last = body.sections.last();
let headers = [
&last.headers.default,
&last.headers.first,
&last.headers.even,
]
.map(id);
assert_eq!(headers, ["h1", "h2", ""]);
let footers = [
&last.footers.default,
&last.footers.first,
&last.footers.even,
]
.map(id);
assert_eq!(footers, ["f2", "", "f1"]);
}
#[test]
fn reads_equal_columns_and_their_areas() {
let twips = |t: i64| t * Length::UNITS_PER_TWIP;
let columns = |cols: &str| last_section(&format!("<w:sectPr>{cols}</w:sectPr>")).columns;
// Without `w:col` elements, unequal columns are equal; without `w:cols`, there is one.
assert_eq!(columns(r#"<w:cols w:num="2" w:equalWidth="0"/>"#).count, 2);
assert_eq!(columns("").count, 1);
let (left, width) = (Length::from_units(5), Length::from_units(100));
assert_eq!(
columns("").areas(left, width, |exact| exact),
[(left, width)]
);
assert_eq!(
columns(r#"<w:cols w:num="2"/>"#).space,
Length::from_units(twips(720))
);
}
#[test]
fn reads_columns_and_their_areas() {
let twips = |t: i64| Length::from_units(t * Length::UNITS_PER_TWIP);
let columns = |cols: &str| last_section(&format!("<w:sectPr>{cols}</w:sectPr>")).columns;
// Equal columns share the width after the spaces between them.
let equal = columns(r#"<w:cols w:num="3" w:space="360" w:sep="1"/>"#);
assert_eq!((equal.count, equal.separator), (3, true));
let exact: fn(Length) -> Length = |exact| exact;
for rule in [exact, whole_twips] {
assert_eq!(
equal.areas(twips(1_000), twips(9_720), rule),
[(1_000, 3_000), (4_360, 3_000), (7_720, 3_000)].map(|(l, w)| (twips(l), twips(w)))
);
}
// Columns of their own widths take each width and the space after it.
let own = columns(
r#"<w:cols w:num="2" w:equalWidth="0"><w:col w:w="2000" w:space="500"/><w:col w:w="6000"/></w:cols>"#,
);
assert_eq!(own.count, 2);
assert_eq!(
own.areas(twips(1_000), twips(8_500), whole_twips),
[(twips(1_000), twips(2_000)), (twips(3_500), twips(6_000))]
);
}
/// The whole twips of an equal column's exact width `exact`, as a target that rounds equal
/// columns down to whole twips gives them.
fn whole_twips(exact: Length) -> Length {
exact.toward_zero_whole(Length::UNITS_PER_TWIP)
}
#[test]
fn rounds_equal_columns_down_to_whole_twips_by_the_rule() {
let twips = |t: i64| Length::from_units(t * Length::UNITS_PER_TWIP);
let half = Length::from_units(Length::UNITS_PER_TWIP / 2);
let columns = |cols: &str| last_section(&format!("<w:sectPr>{cols}</w:sectPr>")).columns;
// A free width of 7,785 twips over two columns is 3,892.5 twips: the exact rule keeps the
// half, and the whole-twip rule drops it, which moves the second column's edge.
let two = columns(r#"<w:cols w:num="2" w:space="720"/>"#);
assert_eq!(
two.areas(twips(1_701), twips(8_505), |exact| exact),
[
(twips(1_701), twips(3_892) + half),
(twips(6_313) + half, twips(3_892) + half)
]
);
assert_eq!(
two.areas(twips(1_701), twips(8_505), whole_twips),
[(twips(1_701), twips(3_892)), (twips(6_313), twips(3_892))]
);
// Five columns of 1,582.4 twips take 1,582 each, so the fourth starts 1.2 twips left.
let five = columns(r#"<w:cols w:num="5" w:space="360"/>"#);
let whole = five.areas(twips(1_440), twips(9_352), whole_twips);
assert_eq!(whole[3], (twips(7_266), twips(1_582)));
}
#[test]
fn reads_column_breaks() {
let body = body(r#"<w:p><w:r><w:t>a</w:t><w:br w:type="column"/><w:t>b</w:t></w:r></w:p>"#);
let Block::Paragraph(paragraph) = &body.blocks[0] else {
panic!("not a paragraph");
};
assert_eq!(paragraph.runs[0].content[1], Content::ColumnBreak);
}
#[test]
fn reads_line_breaks_that_clear_floating_objects() {
let content = |br: &str| {
let body = body(&format!(r"<w:p><w:r>{br}</w:r></w:p>"));
let Block::Paragraph(paragraph) = &body.blocks[0] else {
panic!("not a paragraph");
};
paragraph.runs[0].content[0].clone()
};
let all = r#"<w:br w:type="textWrapping" w:clear="all"/>"#;
assert_eq!(content(all), Content::ClearingBreak);
// Clearing one side is not done yet.
assert_eq!(content(r#"<w:br w:clear="left"/>"#), Content::LineBreak);
assert_eq!(content(r#"<w:br w:clear="none"/>"#), Content::LineBreak);
}
#[test]
fn reads_line_numbers() {
let numbers = |attributes: &str| {
let xml = format!("<w:sectPr><w:lnNumType {attributes}/></w:sectPr>");
last_section(&xml).line_numbers.unwrap()
};
let twips = |l: Length| l.units() / Length::UNITS_PER_TWIP;
let n = numbers(r#"w:countBy="5" w:start="2" w:distance="283" w:restart="continuous""#);
assert_eq!((n.count_by, n.start, twips(n.distance)), (5, 2, 283));
assert_eq!(n.restart, super::LineNumberRestart::Continuous);
// With only `w:countBy`, every line counts from 1 on each page, a quarter inch away.
let n = numbers(r#"w:countBy="1""#);
assert_eq!((n.count_by, n.start, twips(n.distance)), (1, 0, 360));
assert_eq!(n.restart, super::LineNumberRestart::NewPage);
let n = numbers(r#"w:countBy="2" w:restart="newSection""#);
assert_eq!(
(n.count_by, n.restart),
(2, super::LineNumberRestart::NewSection)
);
}
#[test]
fn reads_no_line_numbers_without_a_count() {
assert_eq!(last_section("<w:sectPr/>").line_numbers, None);
// Without `w:countBy`, or with 0, the section has no line numbers.
for attributes in ["", r#"w:distance="0""#, r#"w:countBy="0" w:start="5""#] {
let xml = format!("<w:sectPr><w:lnNumType {attributes}/></w:sectPr>");
assert_eq!(last_section(&xml).line_numbers, None, "{attributes}");
}
}
#[test]
fn reads_header_and_footer_distances() {
let s = last_section(
r#"<w:sectPr><w:pgMar w:header="708" w:footer="-500"/><w:pgNumType w:start="0"/><w:titlePg/></w:sectPr>"#,
);
let twips = |l: Length| l.units() / Length::UNITS_PER_TWIP;
assert_eq!((twips(s.header), twips(s.footer)), (708, 500));
assert_eq!((s.title_page, s.first_page_number), (true, 0));
let roman = last_section(r#"<w:sectPr><w:pgNumType w:fmt="upperRoman"/></w:sectPr>"#);
assert_eq!(roman.page_number(4), "IV");
let formats = [
"lowerRoman",
"lowerLetter",
"upperLetter",
"numberInDash",
"decimal",
"arabicAbjad",
"thaiLetters",
];
let written = |forms: NumberForms| -> Vec<String> {
formats
.iter()
.map(|f| {
let xml = format!(r#"<w:sectPr><w:pgNumType w:fmt="{f}"/></w:sectPr>"#);
let body = body_in(&xml, BodyFieldResults::ComputesFields, forms);
body.sections.last().section.page_number(3)
})
.collect()
};
// Page numbers take the forms of list labels, and decimal digits where F-Office has none.
let signs = ["iii", "c", "C", "- 3 -", "3", "ج", "3"];
assert_eq!(written(NumberForms::Signs), signs);
let digits = ["iii", "c", "C", "- 3 -", "3", "3", "3"];
assert_eq!(written(NumberForms::Digits), digits);
let off = last_section(r#"<w:sectPr><w:titlePg w:val="0"/></w:sectPr>"#);
assert!(!off.title_page);
}
#[test]
fn reads_negative_top_and_bottom_margins_as_fixed() {
let section = |margins: &str| last_section(&format!("<w:sectPr>{margins}</w:sectPr>"));
let top = section(r#"<w:pgMar w:top="-1080" w:bottom="1440"/>"#);
let twips = |l: Length| l.units() / Length::UNITS_PER_TWIP;
assert_eq!((twips(top.top), top.fixed), (1080, (true, false)));
let bottom = section(r#"<w:pgMar w:top="1440" w:bottom="-720"/>"#);
assert_eq!((twips(bottom.bottom), bottom.fixed), (720, (false, true)));
assert_eq!(section("").fixed, (false, false));
}
#[test]
fn computes_page_fields_and_keeps_other_results() {
let xml = r#"<w:p><w:r><w:t>Page </w:t></w:r><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText> PAGE </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>9</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r><w:fldSimple w:instr="NUMPAGES"><w:r><w:t>7</w:t></w:r></w:fldSimple><w:fldSimple w:instr="AUTHOR"><w:r><w:t>Ann</w:t></w:r></w:fldSimple><w:r><w:fldChar w:fldCharType="begin"/><w:instrText>page</w:instrText><w:fldChar w:fldCharType="end"/></w:r></w:p>"#;
let content = |results| -> Vec<Content> {
let body = body_with(xml, results);
first_paragraph(&body.blocks)
.runs
.iter()
.flat_map(|r| shown(&r.content))
.collect()
};
assert_eq!(
content(BodyFieldResults::ComputesFields),
vec![
Content::Text("Page ".into()),
Content::PageNumber,
Content::PageCount,
Content::Text("Ann".into()),
Content::PageNumber,
]
);
// Where Word updates no field of the body, a field with a stored result shows it, and a
// field without one still shows its value.
assert_eq!(
content(BodyFieldResults::ShowsStoredResults),
vec![
Content::Text("Page ".into()),
Content::Text("9".into()),
Content::Text("7".into()),
Content::Text("Ann".into()),
Content::PageNumber,
]
);
}
#[test]
fn computes_only_the_fields_that_come_from_the_pages_in_a_header_where_the_target_says_so() {
let field = |code: &str, stored: &str| {
format!(r#"<w:fldSimple w:instr="{code}"><w:r><w:t>{stored}</w:t></w:r></w:fldSimple>"#)
};
let fields = [
field("PAGE", "5"),
field("NUMPAGES", "4"),
field("STYLEREF Heading1", "old"),
field(r"DATE \@ "yyyy-MM-dd"", "2001-02-03"),
field("DOCPROPERTY Title", "kept"),
field(r"IF 1 = 1 "yes" "no"", "no"),
field("PAGEREF mark", "7"),
r#"<w:fldSimple w:instr="TIME"/>"#.to_owned(),
]
.concat();
let header = Document::parse(
format!(r#"<w:hdr xmlns:w="{W}"><w:p>{fields}</w:p></w:hdr>"#).as_bytes(),
&Limits::default(),
)
.unwrap();
let content = |results| -> Vec<Content> {
let blocks = super::read_header_story(
&mut PartReader::new(&header),
header.root().unwrap(),
crate::reader::settings::ReaderSettings::base().with_header_results(results),
);
first_paragraph(&blocks)
.runs
.iter()
.flat_map(|r| shown(&r.content))
.collect()
};
// The fields whose value comes from the pages and the `IF` field show their values, and
// the others with a stored result show that result. A field without one shows its value.
let pages = content(HeaderFieldResults::ComputesPageFields);
let [
Content::PageNumber,
Content::PageCount,
Content::StyleRef(_),
Content::Text(date),
Content::Text(property),
Content::If(_),
Content::PageRef(_),
Content::Date(_),
] = pages.as_slice()
else {
panic!("{pages:?}");
};
assert_eq!([date, property], ["2001-02-03", "kept"]);
// Where Word computes every field, none shows its stored result.
let all = content(HeaderFieldResults::ComputesFields);
assert!(
all.iter().all(|c| !matches!(c, Content::Text(_))),
"{all:?}"
);
}
#[test]
fn computes_the_paragraph_number_of_a_header_style_field_where_the_target_says_so() {
let header = Document::parse(
format!(
r#"<w:hdr xmlns:w="{W}"><w:p><w:fldSimple w:instr="STYLEREF Number \n"><w:r><w:t>4</w:t></w:r></w:fldSimple></w:p></w:hdr>"#
)
.as_bytes(),
&Limits::default(),
)
.unwrap();
let content = |results| -> Vec<Content> {
let blocks = super::read_header_story(
&mut PartReader::new(&header),
header.root().unwrap(),
crate::reader::settings::ReaderSettings::base().with_header_results(results),
);
first_paragraph(&blocks)
.runs
.iter()
.flat_map(|r| shown(&r.content))
.collect()
};
let numbers = content(HeaderFieldResults::ComputesFieldsAndNumbers);
let [Content::StyleRef(field)] = numbers.as_slice() else {
panic!("not a computed field");
};
assert!(field.number);
assert_eq!(field.stored, "4");
// The other variants keep the stored result.
for results in [
HeaderFieldResults::ComputesFields,
HeaderFieldResults::ComputesPageFields,
] {
assert_eq!(content(results), [Content::Text("4".into())]);
}
}
#[test]
fn shows_nothing_of_the_code_of_a_field() {
// A non-breaking hyphen in a switch, and a `PAGE` field in the code of an `IF` field
// without a stored result.
let begin = r#"<w:r><w:fldChar w:fldCharType="begin"/></w:r>"#;
let separate = r#"<w:r><w:fldChar w:fldCharType="separate"/></w:r>"#;
let end = r#"<w:r><w:fldChar w:fldCharType="end"/></w:r>"#;
let body = body(&format!(
r#"<w:p>{begin}<w:r><w:instrText> TOC \n "2</w:instrText><w:noBreakHyphen/><w:instrText>7" </w:instrText></w:r>{separate}<w:r><w:t>Part 1</w:t></w:r>{end}{begin}<w:r><w:instrText> IF </w:instrText></w:r>{begin}<w:r><w:instrText> PAGE </w:instrText></w:r>{end}<w:r><w:instrText> = 1 "One" "More" </w:instrText></w:r>{end}</w:p>"#
));
let content: Vec<Content> = first_paragraph(&body.blocks)
.runs
.iter()
.flat_map(|r| shown(&r.content))
.collect();
// The `IF` field shows what layout evaluates, and its `PAGE` field is part of its code.
let [Content::Text(text), Content::If(field_if)] = content.as_slice() else {
panic!("{content:?}");
};
assert_eq!(text, "Part 1");
assert!(
field_if
.parts
.contains(&super::CodePart::Field(Content::PageNumber)),
"{field_if:?}"
);
}
#[test]
fn keeps_the_values_of_fields_nested_in_the_code_of_an_if_field() {
// A simple field in the code whose stored result is written as instruction text, as
// some files do, and an `IF` field with a stored result, which keeps it.
let body = body(
r#"<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText> IF </w:instrText></w:r><w:fldSimple w:instr=" STYLEREF Part \n "><w:r><w:instrText>0</w:instrText></w:r></w:fldSimple><w:r><w:instrText> = 0 "yes" "no"</w:instrText></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r><w:fldSimple w:instr=' IF 1 = 1 "a" "b" '><w:r><w:t>kept</w:t></w:r></w:fldSimple></w:p>"#,
);
let content: Vec<Content> = first_paragraph(&body.blocks)
.runs
.iter()
.flat_map(|r| shown(&r.content))
.collect();
let [Content::If(field_if), Content::Text(kept)] = content.as_slice() else {
panic!("{content:?}");
};
assert!(field_if.parts.contains(&super::CodePart::Text("0".into())));
assert_eq!(kept, "kept");
// In a header or footer, an `IF` field with a stored result is evaluated as well.
let header = Document::parse(
format!(
r#"<w:hdr xmlns:w="{W}"><w:p><w:fldSimple w:instr=' IF 1 = 1 "a" "b" '><w:r><w:t>kept</w:t></w:r></w:fldSimple></w:p></w:hdr>"#
)
.as_bytes(),
&Limits::default(),
)
.unwrap();
let blocks = super::read_header_story(
&mut PartReader::new(&header),
header.root().unwrap(),
crate::reader::settings::ReaderSettings::base()
.with_header_results(HeaderFieldResults::ComputesFields),
);
let content: Vec<Content> = first_paragraph(&blocks)
.runs
.iter()
.flat_map(|r| shown(&r.content))
.collect();
assert!(
matches!(content.as_slice(), [Content::If(field)] if field.stored == "kept"),
"{content:?}"
);
}
#[test]
fn finds_page_counts_in_tables_and_text_boxes() {
let counts = |xml: &str| super::refers_to_pages(&body(xml).blocks);
let field = r#"<w:fldSimple w:instr="NUMPAGES"><w:r><w:t>7</w:t></w:r></w:fldSimple>"#;
assert!(!counts(r#"<w:p><w:fldSimple w:instr="PAGE"/></w:p>"#));
assert!(counts(&format!(
"<w:tbl><w:tr><w:tc><w:p>{field}</w:p></w:tc></w:tr></w:tbl>"
)));
assert!(!counts(
"<w:tbl><w:tr><w:tc><w:p><w:r><w:t>x</w:t></w:r></w:p></w:tc></w:tr></w:tbl>"
));
let floating = super::Content::Floating(Box::default());
let paragraph = |content| {
super::Block::Paragraph(super::Paragraph {
runs: vec![super::Run {
content: vec![content],
..super::Run::default()
}],
..super::Paragraph::empty()
})
};
assert!(!super::refers_to_pages(&[paragraph(floating)]));
let mut text_box = crate::floating::Floating::default();
text_box.blocks.push(paragraph(super::Content::PageCount));
let floating = super::Content::Floating(Box::new(text_box));
assert!(super::refers_to_pages(&[paragraph(floating)]));
}
#[test]
fn reads_inline_drawings_with_their_effect_extent() {
let body = body(&format!(
r#"<w:p><w:r><w:drawing xmlns:wp="{WP}"><wp:inline><wp:extent cx="914400" cy="457200"/><wp:effectExtent l="12700" t="0" r="25400" b="6350"/></wp:inline></w:drawing><w:drawing xmlns:wp="{WP}"><wp:anchor><wp:extent cx="1" cy="1"/></wp:anchor></w:drawing></w:r></w:p>"#
));
let points = |p: i64| Length::from_points(p).unwrap();
assert_eq!(
first_paragraph(&body.blocks).runs[0].content,
vec![Content::Object {
width: points(75),
height: Length::from_units(points(36).units() + 1_270 * 10),
picture: None,
extent: Some(points(36)),
}]
);
}
#[test]
fn reads_the_picture_inside_the_effect_extent() {
let body = body(&format!(
r#"<w:p><w:r><w:drawing xmlns:wp="{WP}" xmlns:a="{A}" xmlns:pic="{PIC}" xmlns:r="{R}"><wp:inline><wp:extent cx="914400" cy="457200"/><wp:effectExtent l="12700" t="25400" r="0" b="0"/><a:graphic><a:graphicData><pic:pic><pic:blipFill><a:blip r:embed="rId4"/></pic:blipFill></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>"#
));
let Block::Paragraph(paragraph) = &body.blocks[0] else {
panic!("no paragraph");
};
let Content::Object {
picture: Some(picture),
..
} = ¶graph.runs[0].content[0]
else {
panic!("no picture");
};
let points = |p: i64| Length::from_points(p).unwrap();
assert_eq!(picture.embed, "rId4");
assert_eq!(
[picture.left, picture.top, picture.width, picture.height],
[points(1), points(2), points(72), points(36)]
);
}
#[test]
fn reads_stories_and_breaks_outside_runs() {
let doc = Document::parse(
format!(r#"<w:hdr xmlns:w="{W}"><w:p><w:r><w:t>a</w:t></w:r><w:br/></w:p><w:tbl/><w:p/></w:hdr>"#)
.as_bytes(),
&Limits::default(),
)
.unwrap();
let story = read_story(&mut PartReader::new(&doc), doc.root().unwrap());
assert!(matches!(
story.as_slice(),
[Block::Paragraph(_), Block::Table(_), Block::Paragraph(_)]
));
assert_eq!(
first_paragraph(&story).runs[1].content,
vec![Content::LineBreak]
);
let wrapped = Document::parse(
format!(r#"<w:ftr xmlns:w="{W}"><w:sdt><w:sdtPr/><w:sdtContent><w:p/><w:customXml><w:p/></w:customXml></w:sdtContent></w:sdt><w:sdt/></w:ftr>"#)
.as_bytes(),
&Limits::default(),
)
.unwrap();
assert_eq!(
read_story(&mut PartReader::new(&wrapped), wrapped.root().unwrap()).len(),
2
);
}
#[test]
fn reads_check_box_fields_into_the_run_that_starts_them() {
let field = |check_box: &str, result: &str| {
let body = body(&format!(
r#"<w:p><w:r><w:rPr><w:sz w:val="20"/></w:rPr><w:fldChar w:fldCharType="begin"><w:ffData><w:name w:val="Check1"/>{check_box}</w:ffData></w:fldChar></w:r><w:r><w:instrText xml:space="preserve"> FORMCHECKBOX </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r>{result}<w:r><w:rPr><w:sz w:val="28"/></w:rPr><w:fldChar w:fldCharType="end"/></w:r><w:r><w:t xml:space="preserve"> Yes</w:t></w:r></w:p>"#
));
let Block::Paragraph(paragraph) = &body.blocks[0] else {
panic!("not a paragraph");
};
paragraph
.runs
.iter()
.map(|run| (run.props.size, shown(&run.content)))
.filter(|(_, content)| !content.is_empty())
.collect::<Vec<_>>()
};
let check_box = |size, checked| Content::CheckBox(super::CheckBox { size, checked });
// The box stays in the run that starts the field, and the field shows nothing else.
assert_eq!(
field(
r#"<w:checkBox><w:sizeAuto/><w:default w:val="0"/></w:checkBox>"#,
""
),
[
(Some(20), vec![check_box(None, false)]),
(None, vec![Content::Text(" Yes".into())])
]
);
// `w:checked` wins over `w:default`, and an on/off value without `w:val` is on.
let first = |settings: &str| field(settings, "")[0].1.clone();
assert_eq!(
first(r#"<w:checkBox><w:size w:val="18"/><w:default w:val="1"/></w:checkBox>"#),
[check_box(Some(18), true)]
);
assert_eq!(
first(
r#"<w:checkBox><w:sizeAuto/><w:default w:val="1"/><w:checked w:val="0"/></w:checkBox>"#
),
[check_box(None, false)]
);
assert_eq!(
first(r"<w:checkBox><w:sizeAuto/><w:checked/></w:checkBox>"),
[check_box(None, true)]
);
// A stored result does not show.
let with_result = field(
r"<w:checkBox><w:sizeAuto/></w:checkBox>",
r"<w:r><w:t>X</w:t></w:r>",
);
assert_eq!(with_result.len(), 2);
// A field start without a check box adds nothing.
let text_field = field(r"<w:textInput/>", r"<w:r><w:t>X</w:t></w:r>");
assert!(
text_field
.iter()
.all(|(_, c)| !matches!(c.first(), Some(Content::CheckBox(_))))
);
}
#[test]
fn shows_the_entry_that_a_drop_down_field_selects() {
let field = |list: &str, separate: &str| {
let body = body(&format!(
r#"<w:p><w:r><w:t xml:space="preserve">Side: </w:t></w:r><w:r><w:fldChar w:fldCharType="begin"><w:ffData><w:name w:val="Dropdown1"/><w:ddList>{list}<w:listEntry w:val="DC"/><w:listEntry w:val="MC"/><w:listEntry w:val="CS"/></w:ddList></w:ffData></w:fldChar></w:r><w:r><w:instrText xml:space="preserve"> FORMDROPDOWN </w:instrText></w:r>{separate}<w:r><w:fldChar w:fldCharType="end"/></w:r><w:r><w:t xml:space="preserve"> 116</w:t></w:r></w:p>"#
));
let Block::Paragraph(paragraph) = &body.blocks[0] else {
panic!("not a paragraph");
};
paragraph
.runs
.iter()
.flat_map(|run| shown(&run.content))
.filter_map(|content| match content {
Content::Text(text) => Some(text),
_ => None,
})
.collect::<String>()
};
// Without a stored result, the first entry shows.
assert_eq!(field("", ""), "Side: DC 116");
// `w:result` selects an entry from 0, before `w:default`.
assert_eq!(
field(r#"<w:result w:val="2"/><w:default w:val="1"/>"#, ""),
"Side: CS 116"
);
assert_eq!(field(r#"<w:default w:val="1"/>"#, ""), "Side: MC 116");
// An index past the list counts as missing.
assert_eq!(field(r#"<w:result w:val="7"/>"#, ""), "Side: DC 116");
// The selected entry replaces a stored result.
let stored = r#"<w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>XX</w:t></w:r>"#;
assert_eq!(field(r#"<w:result w:val="1"/>"#, stored), "Side: MC 116");
}
#[test]
fn makes_a_paragraph_of_equations_alone_a_centered_display() {
let fraction = "<m:oMath><m:f><m:num><m:r><m:t>a</m:t></m:r></m:num><m:den><m:r><m:t>b</m:t></m:r></m:den></m:f></m:oMath>";
let read = |props: &str, after: &str| {
let xml = format!(
r#"<w:body xmlns:w="{W}" xmlns:m="{}"><w:p><w:pPr>{props}<w:jc w:val="right"/></w:pPr>{fraction}{after}</w:p></w:body>"#,
crate::ns::M
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let body = Body::read(
&mut PartReader::new(&doc),
doc.root().unwrap(),
(
crate::reader::settings::ReaderSettings::base()
.with_body_results(BodyFieldResults::ComputesFields)
.with_section_ends(ContinuousSectionEnd::OnlyBlockKeepsLine),
crate::mode::ModeRules::default(),
),
);
let Some(Block::Paragraph(paragraph)) = body.blocks.into_iter().next() else {
panic!("not a paragraph");
};
let display = paragraph
.runs
.iter()
.filter_map(|run| run.props.math_script)
.map(crate::props::MathScript::is_display)
.collect::<Vec<_>>();
(paragraph.props.alignment, display)
};
let (alignment, display) = read("", "");
assert_eq!(alignment, Some(crate::props::Alignment::Center));
assert_eq!(display, vec![true, true]);
let unnumbered = r#"<w:numPr><w:numId w:val="0"/></w:numPr>"#;
let numbered = r#"<w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr>"#;
assert_eq!(
read(unnumbered, "").0,
Some(crate::props::Alignment::Center)
);
let inline = [("", "<w:r><w:t>x</w:t></w:r>"), (numbered, "")];
for (props, after) in inline {
let (alignment, display) = read(props, after);
assert_eq!(alignment, Some(crate::props::Alignment::End));
assert_eq!(display, vec![false, false]);
}
}
/// The alignment of the first paragraph of a body of `content`, read with a style `Listed` in
/// the list 1, and whether each of its math runs starts a display.
fn listed_math(content: &str) -> (Option<crate::props::Alignment>, Vec<bool>) {
let styles = format!(
r#"<w:styles xmlns:w="{W}"><w:style w:type="paragraph" w:styleId="Listed"><w:pPr><w:numPr><w:numId w:val="1"/></w:numPr></w:pPr></w:style></w:styles>"#
);
let styles = Document::parse(styles.as_bytes(), &Limits::default()).unwrap();
let styles = crate::styles::Styles::read(&mut PartReader::new(&styles), styles.root().unwrap());
let xml = format!(
r#"<w:body xmlns:w="{W}" xmlns:m="{}"><w:p>{content}</w:p></w:body>"#,
crate::ns::M
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let body = Body::read(
&mut PartReader::new(&doc).with_styles(Some(&styles)),
doc.root().unwrap(),
(
crate::reader::settings::ReaderSettings::base(),
crate::mode::ModeRules::default(),
),
);
let Some(Block::Paragraph(paragraph)) = body.blocks.into_iter().next() else {
panic!("not a paragraph");
};
let display = paragraph
.runs
.iter()
.filter_map(|run| run.props.math_script)
.map(crate::props::MathScript::is_display)
.collect();
(paragraph.props.alignment, display)
}
/// The text of the runs of the first paragraph of the body `xml`, whose paragraphs may hold
/// equations.
fn math_text(paragraph: &str) -> String {
let xml = format!(r#"<w:p xmlns:m="{}">{paragraph}</w:p>"#, crate::ns::M);
let Some(Block::Paragraph(paragraph)) = body(&xml).blocks.into_iter().next() else {
panic!("not a paragraph");
};
let texts = paragraph.runs.iter().flat_map(|run| &run.content);
texts
.filter_map(|content| match content {
Content::Text(text) => Some(text.as_str()),
_ => None,
})
.collect()
}
#[test]
fn goes_on_from_an_equation_right_before_another() {
// In a line of text, an equation right after another one reads the operand at that one's
// end, so its relation stands between two operands; with text between them, the relation
// leads its equation.
let first = "<m:oMath><m:r><m:t>a</m:t></m:r></m:oMath>";
let second = "<m:oMath><m:r><m:t>\u{2265}b</m:t></m:r></m:oMath>";
let space = "<w:r><w:t xml:space=\"preserve\"> </w:t></w:r>";
assert_eq!(
math_text(&format!("{space}{first}{second}")),
" \u{1D44E}\u{a0}\u{200A}\u{2265}\u{200A}\u{E0A0}\u{1D44F}"
);
assert_eq!(
math_text(&format!("{space}{first}{space}{second}")),
" \u{1D44E} \u{2265}\u{200A}\u{E0A0}\u{1D44F}"
);
}
#[test]
fn sets_equations_inline_after_a_list_label_of_the_paragraph_or_its_style() {
let math = "<m:oMath><m:f><m:num><m:r><m:t>a</m:t></m:r></m:num><m:den><m:r><m:t>b</m:t></m:r></m:den></m:f></m:oMath>";
let para = format!("<m:oMathPara>{math}</m:oMathPara>");
let listed = r#"<w:pPr><w:pStyle w:val="Listed"/></w:pPr>"#;
let own = r#"<w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr>"#;
let removed =
r#"<w:pPr><w:pStyle w:val="Listed"/><w:numPr><w:numId w:val="0"/></w:numPr></w:pPr>"#;
let inline = (None, vec![false, false]);
let centered = (Some(crate::props::Alignment::Center), vec![true, true]);
let cases = [
format!("{listed}{math}"),
format!("{listed}{para}"),
format!("{own}{para}"),
format!("{removed}{math}"),
format!("{removed}{para}"),
];
let read: Vec<_> = cases.iter().map(|content| listed_math(content)).collect();
assert_eq!(
read,
[
inline.clone(),
inline.clone(),
inline,
centered.clone(),
centered
]
);
}
#[test]
fn each_enumeration_table_holds_each_name_of_its_type() {
// The names of each simple type in ISO/IEC 29500-4:2016 (Transitional), wml.xsd.
// ST_LineNumberRestart
assert_names(
super::section::LINE_NUMBER_RESTART,
"newPage newSection continuous",
);
// ST_PageOrientation
assert_names(super::section::PAGE_ORIENTATION, "portrait landscape");
// ST_ChapterSep
assert_names(
super::section::CHAPTER_SEPARATOR,
"hyphen period colon emDash enDash",
);
// ST_SectionMark
assert_names(
super::section::SECTION_MARK,
"nextPage nextColumn continuous evenPage oddPage",
);
// ST_PageBorderDisplay
assert_names(
super::section::BORDER_DISPLAY,
"allPages firstPage notFirstPage",
);
// ST_PageBorderOffset
assert_names(super::section::BORDER_OFFSET, "page text");
// ST_DocGrid
assert_names(
super::section::DOC_GRID,
"default lines linesAndChars snapToChars",
);
// ST_HdrFtr
assert_names(super::section::HEADER_KIND, "even default first");
// ST_VerticalJc
assert_names(super::section::SECTION_V_ALIGN, "top center both bottom");
// ST_BrType
assert_names(super::runs::BREAK_KIND, "page column textWrapping");
// ST_BrClear
assert_names(super::runs::BREAK_CLEAR, "none left right all");
// ST_FldCharType
assert_names(super::FIELD_CHAR, "begin separate end");
// ST_PTabAlignment
assert_names(super::runs::PTAB_ALIGNMENT, "left center right");
// ST_PTabLeader
assert_names(
super::runs::PTAB_LEADER,
"none dot hyphen underscore middleDot",
);
// ST_FtnEdn
assert_names(
super::NOTE_TYPE,
"normal separator continuationSeparator continuationNotice",
);
}
/// The values that F-Office draws as another value, with their warnings, in a body of `blocks`
/// whose last section has `columns` columns.
fn unsupported_in_columns(
blocks: &str,
columns: u32,
) -> Vec<(String, Option<String>, &'static str, u32)> {
let xml = format!(
r#"<w:body xmlns:w="{W}" xmlns:v="{V}">{blocks}<w:sectPr><w:cols w:num="{columns}"/></w:sectPr></w:body>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let mut reader = PartReader::new(&doc);
let root = doc.root().unwrap();
Body::read(
&mut reader,
root,
(
crate::reader::settings::ReaderSettings::base()
.with_body_results(BodyFieldResults::ComputesFields)
.with_section_ends(ContinuousSectionEnd::OnlyBlockKeepsLine),
crate::mode::ModeRules::default(),
),
);
reader.unsupported_values()
}
/// A paragraph with a floating `v:rect` whose CSS declarations end with `style`.
fn floating_rect(style: &str) -> String {
format!(
r#"<w:p><w:r><w:pict><v:rect style="position:absolute;width:10pt;height:10pt;{style}"/></w:pict></w:r></w:p>"#
)
}
/// The warning that F-Office draws the text column across of `count` VML shapes as the margins.
fn text_column_warning(count: u32) -> Vec<(String, Option<String>, &'static str, u32)> {
let property = "style mso-position-horizontal-relative".to_string();
vec![("rect".to_string(), Some(property), "text", count)]
}
#[test]
fn warns_of_a_vml_shape_from_the_text_column_in_a_section_of_columns() {
// No keyword and `text` mean the text column, which F-Office draws as the margins: in a
// section of two columns it warns, and in one column the two are the same place.
for style in ["", "mso-position-horizontal-relative:text"] {
let shape = floating_rect(style);
assert_eq!(
unsupported_in_columns(&shape, 2),
text_column_warning(1),
"{style}"
);
assert_eq!(unsupported_in_columns(&shape, 1), vec![], "{style}");
}
let margin = floating_rect("mso-position-horizontal-relative:margin");
assert_eq!(unsupported_in_columns(&margin, 2), vec![]);
}
#[test]
fn warns_of_a_vml_shape_from_the_text_column_only_in_a_body_paragraph_of_its_section() {
// In a table cell the margins count from the cell's column, and a text box is no
// paragraph of the body.
let cell = format!(
"<w:tbl><w:tr><w:tc>{}</w:tc></w:tr></w:tbl>",
floating_rect("")
);
assert_eq!(unsupported_in_columns(&cell, 2), vec![]);
let text_box = format!(
r#"<w:p><w:r><w:pict><v:rect style="position:absolute;width:20pt;height:20pt;mso-position-horizontal-relative:margin"><v:textbox><w:txbxContent>{}</w:txbxContent></v:textbox></v:rect></w:pict></w:r></w:p>"#,
floating_rect("")
);
assert_eq!(unsupported_in_columns(&text_box, 2), vec![]);
// A shape counts in the section that holds its paragraph: one shape before a paragraph that
// ends a section, and two shapes in the last section.
let shape = floating_rect("");
let first = |columns: u32| {
format!(
r#"{shape}<w:p><w:pPr><w:sectPr><w:cols w:num="{columns}"/></w:sectPr></w:pPr></w:p>{shape}{shape}"#
)
};
assert_eq!(unsupported_in_columns(&first(2), 1), text_column_warning(1));
assert_eq!(unsupported_in_columns(&first(1), 2), text_column_warning(2));
}
/// The steps of the warnings of text columns that the read of [`unsupported_in_columns`] takes
/// for `blocks` and `columns`, after it checks that the read warns of `count` shapes.
fn text_column_steps(blocks: &str, columns: u32, count: usize) -> usize {
super::TEXT_COLUMN_STEPS.with(|steps| steps.set(0));
let count = u32::try_from(count).unwrap();
assert_eq!(
unsupported_in_columns(blocks, columns),
text_column_warning(count)
);
super::TEXT_COLUMN_STEPS.with(std::cell::Cell::get)
}
#[test]
fn warns_of_many_vml_shapes_of_one_paragraph_with_one_walk_of_the_paragraph() {
// 20,000 shapes in one paragraph of a section of two columns, and one more in a text box
// of the paragraph, which is not warned of. A walk of the paragraph for each shape would
// visit about 3 · 20,000² / 2 elements.
const SHAPES: usize = 20_000;
let rect =
r#"<w:r><w:pict><v:rect style="position:absolute;width:10pt;height:10pt"/></w:pict></w:r>"#;
let text_box = format!(
r#"<w:r><w:pict><v:rect style="position:absolute;width:20pt;height:20pt;mso-position-horizontal-relative:margin"><v:textbox><w:txbxContent><w:p>{rect}</w:p></w:txbxContent></v:textbox></v:rect></w:pict></w:r>"#
);
let paragraph = format!("<w:p>{}{text_box}</w:p>", rect.repeat(SHAPES));
let steps = text_column_steps(¶graph, 2, SHAPES);
// A look at the section for each shape, and each element of the paragraph once.
assert!(steps <= 4 * SHAPES + 10, "{steps} steps");
}
#[test]
fn warns_of_vml_shapes_in_many_sections_with_one_walk_of_the_sections() {
// 5,000 sections of two columns, each with a shape in the paragraph before the paragraph
// that ends it. A search of the sections from the first for each shape would look at about
// 5,000² / 2 of them.
const SECTIONS: usize = 5_000;
let section = format!(
r#"{}<w:p><w:pPr><w:sectPr><w:cols w:num="2"/></w:sectPr></w:pPr></w:p>"#,
floating_rect("")
);
let steps = text_column_steps(§ion.repeat(SECTIONS), 1, SECTIONS);
// Two looks at the sections and a walk of four elements for each shape.
assert!(steps <= 6 * SECTIONS + 10, "{steps} steps");
}
/// Made-up alternate content in a run of the part's root, with the namespaces of the tests: the
/// branch that F-Office shows by its index among the content's children, and the kinds of the
/// warnings of the choices that it passes over, each with its count.
fn shown_choice(alternate: &str) -> (Option<usize>, Vec<(String, u32)>) {
use crate::ns::{MC, W14, W16SE, WPC, WPS};
let xml = format!(
r#"<w:r xmlns:w="{W}" xmlns:mc="{MC}" xmlns:wps="{WPS}" xmlns:wpc="{WPC}" xmlns:w14="{W14}" xmlns:w16se="{W16SE}" xmlns:a="{A}" xmlns:pic="{PIC}" xmlns:wpi="urn:ink" xmlns:x="urn:other">{alternate}</w:r>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let content = doc.children(doc.root().unwrap())[0];
let children: Vec<_> = doc.child_elements(content).collect();
assert_eq!(
super::alternate_branch(&doc, content),
{
let mut reader = PartReader::new(&doc);
super::shown_branch(&mut reader, content)
},
"both give one branch"
);
let mut reader = PartReader::new(&doc);
let branch = super::shown_branch(&mut reader, content);
let mut warnings = crate::Warnings::default();
reader.finish(&mut warnings);
let kinds = warnings
.iter()
.map(|(warning, count)| (warning.kind().to_string(), count))
.collect();
(
branch.map(|b| children.iter().position(|c| *c == b).unwrap()),
kinds,
)
}
/// Made-up alternate content with the choices `choices`, each with its `Requires` and its
/// content, and the fallback `fallback`, if any.
fn alternate(choices: &[(&str, &str)], fallback: Option<&str>) -> String {
use std::fmt::Write as _;
let mut out = String::from("<mc:AlternateContent>");
for (requires, content) in choices {
write!(
out,
r#"<mc:Choice Requires="{requires}">{content}</mc:Choice>"#
)
.unwrap();
}
if let Some(fallback) = fallback {
write!(out, "<mc:Fallback>{fallback}</mc:Fallback>").unwrap();
}
out + "</mc:AlternateContent>"
}
#[test]
fn takes_the_first_choice_whose_namespaces_f_office_takes_else_the_fallback() {
let graphic = |inner: &str| {
format!(
"<w:drawing><a:graphic><a:graphicData>{inner}</a:graphicData></a:graphic></w:drawing>"
)
};
let (shape, picture) = (graphic("<wps:wsp/>"), graphic("<pic:pic/>"));
let (ink, canvas) = (graphic("<w14:contentPart/>"), graphic("<wpc:wpc/>"));
let skipped = || vec![("shape-skipped".to_string(), 1)];
let bare = format!(
"<mc:AlternateContent><mc:Choice>{shape}</mc:Choice><mc:Fallback/></mc:AlternateContent>"
);
let cases = [
// A choice of shapes, which F-Office reads, is shown, with no warning.
(
alternate(&[("wps", &shape)], Some(&picture)),
Some(0),
vec![],
),
// Ink, whose namespace F-Office does not take, gives way to the fallback's picture and
// keeps the warning of the ink that is left out.
(
alternate(&[("wpi", &ink)], Some(&picture)),
Some(1),
skipped(),
),
// A later choice that F-Office takes comes before the fallback.
(
alternate(&[("wpi", &ink), ("wps", &shape)], Some(&picture)),
Some(1),
skipped(),
),
// Every prefix must be taken, and a prefix that no declaration binds is not.
(
alternate(&[("wps x", &shape)], Some(&picture)),
Some(1),
skipped(),
),
(
alternate(&[("unbound", &shape)], Some(&picture)),
Some(1),
skipped(),
),
// With no branch to show, nothing is shown, and the choice still warns.
(alternate(&[("wpi", &ink)], None), None, skipped()),
// A choice without `Requires` requires nothing.
(bare, Some(0), vec![]),
// The canvas's choice is taken, so that an inline canvas keeps its room.
(
alternate(&[("wpc", &canvas)], Some(&picture)),
Some(0),
vec![],
),
];
for (content, branch, warnings) in cases {
assert_eq!(shown_choice(&content), (branch, warnings), "{content}");
}
}
#[test]
fn takes_the_choice_of_the_symbol_extension_and_warns_of_its_character() {
use crate::ns::{MC, W16SE};
let doc = Document::parse(
format!(
r#"<w:body xmlns:w="{W}" xmlns:mc="{MC}" xmlns:w16se="{W16SE}"><w:p><w:r><w:t>a</w:t><mc:AlternateContent><mc:Choice Requires="w16se"><w16se:symEx w16se:font="F" w16se:char="263A"/></mc:Choice><mc:Fallback><w:t>x</w:t></mc:Fallback></mc:AlternateContent></w:r></w:p></w:body>"#
)
.as_bytes(),
&Limits::default(),
)
.unwrap();
let mut reader = PartReader::new(&doc);
let body = Body::read(
&mut reader,
doc.root().unwrap(),
(
crate::reader::settings::ReaderSettings::base()
.with_body_results(BodyFieldResults::ComputesFields)
.with_section_ends(ContinuousSectionEnd::OnlyBlockKeepsLine),
crate::mode::ModeRules::default(),
),
);
let Block::Paragraph(paragraph) = &body.blocks[0] else {
panic!("not a paragraph");
};
let content: Vec<_> = paragraph.runs.iter().flat_map(|r| &r.content).collect();
assert_eq!(content, [&Content::Text("a".into())], "no fallback text");
let mut warnings = crate::Warnings::default();
reader.finish(&mut warnings);
let kinds: Vec<_> = warnings
.iter()
.map(|(warning, count)| (warning.kind().to_string(), count))
.collect();
assert_eq!(kinds, [("symbol-extension-not-supported".to_string(), 1)]);
}
#[test]
fn warns_of_a_passed_choice_of_another_content() {
let other = r#"<mc:AlternateContent><mc:Choice Requires="x"><w:t>y</w:t></mc:Choice><mc:Fallback><w:t>x</w:t></mc:Fallback></mc:AlternateContent>"#;
assert_eq!(
shown_choice(other),
(
Some(1),
vec![("alternate-choice-not-supported".to_string(), 1)]
)
);
// Ink that stands in its drawing in place of a graphic is a shape that is left out.
let ink = r#"<mc:AlternateContent><mc:Choice Requires="wpi"><w:drawing><w14:contentPart/></w:drawing></mc:Choice><mc:Fallback/></mc:AlternateContent>"#;
assert_eq!(
shown_choice(ink),
(Some(1), vec![("shape-skipped".to_string(), 1)])
);
}
#[test]
fn passes_over_every_choice_before_the_first_taken_one_wherever_the_fallback_stands() {
// A fallback before a choice, which the schema does not allow: with no choice taken, the
// fallback is shown and both choices are passed over; a taken choice after the fallback is
// shown, and only the choice before it is passed over.
let choice =
|requires: &str| format!(r#"<mc:Choice Requires="{requires}"><w:t>y</w:t></mc:Choice>"#);
let content = |last: &str| {
format!(
r"<mc:AlternateContent>{}<mc:Fallback><w:t>x</w:t></mc:Fallback>{last}</mc:AlternateContent>",
choice("x")
)
};
let passed = |count| vec![("alternate-choice-not-supported".to_string(), count)];
assert_eq!(shown_choice(&content(&choice("x"))), (Some(1), passed(2)));
assert_eq!(shown_choice(&content(&choice("wps"))), (Some(2), passed(1)));
}
#[test]
fn takes_the_choices_of_namespaces_that_f_office_does_not_read() {
// The symbol extension's entry goes when F-Office draws the symbol extension.
use super::TakenBecause::{FallbackRejected, Read};
let not_read: Vec<_> = super::TAKEN_CHOICES
.iter()
.filter(|(_, because)| *because != Read)
.copied()
.collect();
assert_eq!(not_read, vec![(crate::ns::W16SE, FallbackRejected)]);
}
#[test]
fn takes_a_choice_whose_prefix_binds_a_strict_namespace() {
let xml = format!(
r#"<w:r xmlns:w="{W}" xmlns:mc="{}" xmlns:s="http://purl.oclc.org/ooxml/wordprocessingml/main"><mc:AlternateContent><mc:Choice Requires="s"><w:t>s</w:t></mc:Choice><mc:Fallback/></mc:AlternateContent></w:r>"#,
crate::ns::MC
);
let doc = Document::parse_with_aliases(
xml.as_bytes(),
&Limits::default(),
crate::ns::STRICT_ALIASES,
)
.unwrap();
let content = doc.children(doc.root().unwrap())[0];
let choice = doc.child_elements(content).next();
assert_eq!(super::alternate_branch(&doc, content), choice);
}
#[test]
fn reads_an_equation_of_a_strict_document_as_the_same_equation_of_a_transitional_one() {
// A Strict document writes its equations in the Strict namespace of Office Math.
let read = |(w, m): (&str, &str)| {
let xml = format!(
r#"<w:body xmlns:w="{w}" xmlns:m="{m}"><w:p><w:r><w:t>x</w:t></w:r><m:oMath><m:f><m:num><m:r><m:t>a</m:t></m:r></m:num><m:den><m:r><m:t>b</m:t></m:r></m:den></m:f></m:oMath></w:p></w:body>"#
);
let doc = Document::parse_with_aliases(
xml.as_bytes(),
&Limits::default(),
crate::ns::STRICT_ALIASES,
)
.unwrap();
let body = Body::read(
&mut PartReader::new(&doc),
doc.root().unwrap(),
(
crate::reader::settings::ReaderSettings::base()
.with_body_results(BodyFieldResults::ComputesFields)
.with_section_ends(ContinuousSectionEnd::OnlyBlockKeepsLine),
crate::mode::ModeRules::default(),
),
);
first_paragraph(&body.blocks)
.runs
.iter()
.map(|run| (run.props.math_script, run.content.clone()))
.collect::<Vec<_>>()
};
let transitional = read((W, crate::ns::M));
assert!(
transitional.iter().any(|(math, _)| math.is_some()),
"{transitional:?}"
);
let strict = read((
"http://purl.oclc.org/ooxml/wordprocessingml/main",
"http://purl.oclc.org/ooxml/officeDocument/math",
));
assert_eq!(strict, transitional);
}
/// Whether the two runs of a paragraph whose `w:rPr` hold `first` and `second` have the same run
/// record.
fn same_record(first: &str, second: &str) -> bool {
let body = body(&format!(
"<w:p><w:r><w:rPr>{first}</w:rPr><w:t>a</w:t></w:r><w:r><w:rPr>{second}</w:rPr><w:t>a</w:t></w:r></w:p>"
));
let runs = &first_paragraph(&body.blocks).runs;
assert_eq!(runs.len(), 2);
runs.first().map(|run| &run.record) == runs.last().map(|run| &run.record)
}
#[test]
fn a_run_record_holds_the_children_in_no_order() {
// Another order of the children, or of a child's attributes, is the same record.
let snap_off = r#"<w:snapToGrid w:val="0"/>"#;
assert!(same_record(
&format!("<w:noProof/>{snap_off}"),
&format!("{snap_off}<w:noProof/>")
));
assert!(same_record(
r#"<w:rFonts w:ascii="A" w:hAnsi="B"/>"#,
r#"<w:rFonts w:hAnsi="B" w:ascii="A"/>"#
));
// A tracked change of the properties is no part of the record.
assert!(same_record(
"<w:b/>",
r#"<w:b/><w:rPrChange w:id="1" w:author="x"><w:rPr/></w:rPrChange>"#
));
}
#[test]
fn a_run_record_reads_an_on_off_value_as_on_or_off() {
assert!(same_record("<w:b/>", r#"<w:b w:val="1"/>"#));
assert!(same_record(r#"<w:b w:val="off"/>"#, r#"<w:b w:val="0"/>"#));
assert!(!same_record("<w:b/>", r#"<w:b w:val="0"/>"#));
}
#[test]
fn a_run_record_differs_in_a_child_that_one_run_holds() {
// Also a child with the value that the run would have without it.
assert!(!same_record("", "<w:noProof/>"));
assert!(!same_record("", r#"<w:snapToGrid w:val="1"/>"#));
assert!(!same_record("", r#"<w:rStyle w:val="Strong"/>"#));
assert!(!same_record(
r#"<w:lang w:val="en-US"/>"#,
r#"<w:lang w:val="en-GB"/>"#
));
}
#[test]
fn keeps_the_format_of_the_code_run_on_a_page_number_without_merge_format() {
let small = r#"<w:rPr><w:b/><w:sz w:val="16"/></w:rPr>"#;
let field = |code: &str| {
format!(
r#"<w:p><w:r><w:t>a</w:t></w:r><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r>{small}<w:instrText>{code}</w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>9</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r><w:r><w:t>b</w:t></w:r></w:p>"#
)
};
let formats = |code: &str| -> Vec<Option<(Option<i64>, Option<bool>)>> {
let read = body(&field(code));
first_paragraph(&read.blocks)
.runs
.iter()
.filter(|run| !shown(&run.content).is_empty())
.map(|run| {
run.code_format.as_ref().map(|format| {
let props = format.over(&crate::props::RunProps::default());
(props.size, props.bold)
})
})
.collect()
};
// Only the run that shows the computed number has the code run's format.
assert_eq!(
formats(" PAGE "),
[None, Some((Some(16), Some(true))), None]
);
assert_eq!(
formats(" NUMPAGES "),
[None, Some((Some(16), Some(true))), None]
);
// With `\* MERGEFORMAT`, the number keeps the format of its own run.
assert_eq!(formats(r" PAGE \* MERGEFORMAT "), [None, None, None]);
// A page reference keeps the format of its own run.
assert_eq!(formats(r" PAGEREF _Toc1 \h "), [None, None, None]);
}
#[test]
fn keeps_the_style_and_direct_properties_of_the_code_run_in_a_page_reference() {
let code = r#"<w:rPr><w:rStyle w:val="Strong"/><w:u w:val="single"/></w:rPr>"#;
let read = body(&format!(
r#"<w:p><w:r>{code}<w:fldChar w:fldCharType="begin"/></w:r><w:r>{code}<w:instrText> PAGEREF missing \h </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>9</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>"#
));
let code_run = first_paragraph(&read.blocks)
.runs
.iter()
.flat_map(|run| &run.content)
.find_map(|content| match content {
Content::PageRef(field) => field.code.clone(),
_ => None,
})
.unwrap();
assert_eq!(code_run.style.as_deref(), Some("Strong"));
assert!(code_run.props.underline.is_some());
}
#[test]
fn gives_a_page_number_the_color_of_its_size_and_no_decorations_where_the_target_says_so() {
use crate::props::Color;
use crate::quirks::{ComputedFieldDecorations as Decorations, ComputedFieldFormat as Format};
let (red, gray) = (Color::Rgb([255, 0, 0]), Color::Rgb([128, 128, 128]));
let code = r#"<w:rPr><w:color w:val="FF0000"/></w:rPr>"#;
let result = r#"<w:rPr><w:color w:val="808080"/><w:u w:val="single"/><w:strike/><w:highlight w:val="yellow"/></w:rPr>"#;
let shown = |instruction: &str, format: Format, decorations: Decorations| {
let parsed = body(&format!(
r#"<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r>{code}<w:instrText>{instruction}</w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r>{result}<w:t>9</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>"#
));
let run = first_paragraph(&parsed.blocks)
.runs
.iter()
.find(|run| {
run.content
.iter()
.any(|c| matches!(c, Content::PageNumber | Content::PageCount))
})
.unwrap();
let props = run.direct_props(format == Format::CodeRun, decorations == Decorations::Drawn);
let decorated =
props.underline.is_some() || props.strike.is_some() || props.highlight.is_some();
(props.color, decorated)
};
let win = (Format::CodeRun, Decorations::Dropped);
assert_eq!(shown(" PAGE ", win.0, win.1), (Some(red), false));
assert_eq!(
shown(r" NUMPAGES \* CHARFORMAT ", win.0, win.1),
(Some(red), false)
);
assert_eq!(
shown(r" PAGE \* MERGEFORMAT ", win.0, win.1),
(Some(gray), false)
);
let kept = (Format::ResultRun, Decorations::Drawn);
assert_eq!(shown(" PAGE ", kept.0, kept.1), (Some(gray), true));
}
#[test]
fn gives_a_styleref_field_the_code_run_format_without_merge_format() {
let props_of = |code: &str, code_rpr: &str, res_rpr: &str| {
let xml = format!(
concat!(
r#"<w:p><w:r>{code_rpr}<w:fldChar w:fldCharType="begin"/></w:r>"#,
r#"<w:r>{code_rpr}<w:instrText xml:space="preserve">{code}</w:instrText></w:r>"#,
r#"<w:r>{code_rpr}<w:fldChar w:fldCharType="separate"/></w:r>"#,
r#"<w:r>{res_rpr}<w:t>old</w:t></w:r>"#,
r#"<w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>"#,
),
code_rpr = code_rpr,
res_rpr = res_rpr,
code = code,
);
let body = body(&xml);
let Block::Paragraph(p) = &body.blocks[0] else {
panic!("not a paragraph");
};
let run = p
.runs
.iter()
.find(|r| r.content.iter().any(|c| matches!(c, Content::StyleRef(_))))
.unwrap();
let props = run.direct_props(true, false);
(props.bold, props.size)
};
let bold12 = r#"<w:rPr><w:b/><w:sz w:val="24"/></w:rPr>"#;
let bold = "<w:rPr><w:b/></w:rPr>";
assert_eq!(
(
props_of(r" STYLEREF RefOne \* CHARFORMAT ", "", bold),
props_of(" STYLEREF RefOne ", "", bold),
props_of(r" STYLEREF RefOne \* MERGEFORMAT ", "", bold),
props_of(r" STYLEREF RefOne \* CHARFORMAT ", bold12, ""),
props_of(" STYLEREF RefOne ", bold12, ""),
props_of(r" STYLEREF RefOne \* MERGEFORMAT ", bold12, ""),
),
(
(None, None),
(None, None),
(Some(true), None),
(Some(true), Some(24)),
(Some(true), Some(24)),
(None, None),
)
);
}
#[test]
fn style_ref_edge_cases_split_code_lock_and_character_style() {
let read_run = |xml: &str| {
let story = body(&format!("<w:p>{xml}</w:p>"));
let Block::Paragraph(para) = &story.blocks[0] else {
panic!("expected paragraph");
};
para.runs
.iter()
.find(|r| {
r.content
.iter()
.any(|c| matches!(c, Content::StyleRef(_) | Content::Text(_)))
})
.cloned()
.expect("result run")
};
// Split instruction runs: leading whitespace run is plain, keyword run is bold 12 pt.
let split = read_run(concat!(
r#"<w:r><w:fldChar w:fldCharType="begin"/></w:r>"#,
r#"<w:r><w:instrText xml:space="preserve"> </w:instrText></w:r>"#,
r#"<w:r><w:rPr><w:b/><w:sz w:val="24"/></w:rPr><w:instrText>STYLEREF RefOne</w:instrText></w:r>"#,
r#"<w:r><w:fldChar w:fldCharType="separate"/></w:r>"#,
r#"<w:r><w:t>X</w:t></w:r>"#,
r#"<w:r><w:fldChar w:fldCharType="end"/></w:r>"#,
));
let split_props = split.direct_props(true, false);
assert_eq!((split_props.bold, split_props.size), (Some(true), Some(24)));
// Locked STYLEREF keeps its stored text and stored result formatting.
let locked = read_run(concat!(
r#"<w:r><w:fldChar w:fldCharType="begin" w:fldLock="1"/></w:r>"#,
r#"<w:r><w:instrText> STYLEREF RefOne </w:instrText></w:r>"#,
r#"<w:r><w:fldChar w:fldCharType="separate"/></w:r>"#,
r#"<w:r><w:rPr><w:b/><w:sz w:val="24"/></w:rPr><w:t>X</w:t></w:r>"#,
r#"<w:r><w:fldChar w:fldCharType="end"/></w:r>"#,
));
assert!(
locked
.content
.iter()
.any(|c| matches!(c, Content::Text(t) if t == "X"))
);
let locked_props = locked.direct_props(true, false);
assert_eq!(
(locked_props.bold, locked_props.size),
(Some(true), Some(24))
);
// Code run character style replaces the showing run's character style (including clearing it).
let code_style = read_run(concat!(
r#"<w:r><w:fldChar w:fldCharType="begin"/></w:r>"#,
r#"<w:r><w:rPr><w:rStyle w:val="Bold12"/></w:rPr><w:instrText> STYLEREF RefOne </w:instrText></w:r>"#,
r#"<w:r><w:fldChar w:fldCharType="separate"/></w:r>"#,
r#"<w:r><w:t>X</w:t></w:r>"#,
r#"<w:r><w:fldChar w:fldCharType="end"/></w:r>"#,
));
assert_eq!(code_style.character_style(true), Some("Bold12"));
assert_eq!(code_style.character_style(false), None);
let res_style = read_run(concat!(
r#"<w:r><w:fldChar w:fldCharType="begin"/></w:r>"#,
r#"<w:r><w:instrText> STYLEREF RefOne </w:instrText></w:r>"#,
r#"<w:r><w:fldChar w:fldCharType="separate"/></w:r>"#,
r#"<w:r><w:rPr><w:rStyle w:val="Bold12"/></w:rPr><w:t>X</w:t></w:r>"#,
r#"<w:r><w:fldChar w:fldCharType="end"/></w:r>"#,
));
assert_eq!(res_style.character_style(true), None);
assert_eq!(res_style.character_style(false), Some("Bold12"));
}
/// Of two normal notes of one number, the reader keeps the later one or the first one, as the
/// target's quirk says, with one warning that names the number.
#[test]
fn keeps_the_later_or_the_first_note_of_one_number_with_a_warning() {
let note = |id: &str, text: &str| {
format!(r#"<w:footnote w:id="{id}"><w:p><w:r><w:t>{text}</w:t></w:r></w:p></w:footnote>"#)
};
let doc = Document::parse(
format!(
r#"<w:footnotes xmlns:w="{W}">{}{}{}</w:footnotes>"#,
note("2", "First"),
note("02", "Later"),
note("3", "Other")
)
.as_bytes(),
&Limits::default(),
)
.unwrap();
for (repeated, kept) in [
(RepeatedNoteId::LaterReplaces, "Later"),
(RepeatedNoteId::FirstStays, "First"),
] {
let mut reader = PartReader::new(&doc);
let notes = super::Notes::read(
&mut reader,
doc.root().unwrap(),
crate::reader::settings::ReaderSettings::base().with_repeated_notes(repeated),
);
let mut texts: Vec<String> = notes
.by_id
.values()
.flatten()
.filter_map(|block| match block {
Block::Paragraph(p) => Some(
p.runs
.iter()
.flat_map(|r| &r.content)
.filter_map(|c| match c {
Content::Text(t) => Some(t.as_str()),
_ => None,
})
.collect(),
),
Block::Table(_) => None,
})
.collect();
texts.sort();
assert_eq!(texts, [kept, "Other"], "{repeated:?}");
let mut warnings = crate::Warnings::new();
reader.finish(&mut warnings);
let repeats: Vec<_> = warnings
.iter()
.filter_map(|(warning, count)| match warning {
crate::Warning::NoteIdRepeated { id, .. } => Some((*id, count)),
_ => None,
})
.collect();
assert_eq!(repeats, [(2, 1)], "{repeated:?}");
}
}
/// The body `xml` and the kinds and counts of the warnings that its reader keeps.
fn body_warned(xml: &str) -> (Body, Vec<(String, u32)>) {
let doc = Document::parse(
format!(r#"<w:body xmlns:w="{W}">{xml}</w:body>"#).as_bytes(),
&Limits::default(),
)
.unwrap();
let mut reader = PartReader::new(&doc);
let body = Body::read(
&mut reader,
doc.root().unwrap(),
(
crate::reader::settings::ReaderSettings::base()
.with_body_results(BodyFieldResults::ComputesFields)
.with_section_ends(ContinuousSectionEnd::OnlyBlockKeepsLine),
crate::mode::ModeRules::default(),
),
);
let mut warnings = crate::Warnings::default();
reader.finish(&mut warnings);
let mut kinds: Vec<(String, u32)> = warnings
.iter()
.map(|(warning, count)| (warning.kind().to_string(), count))
.collect();
kinds.sort();
(body, kinds)
}
/// The content of the runs of the first paragraph of `body`.
fn first_content(body: &Body) -> Vec<&Content> {
first_paragraph(&body.blocks)
.runs
.iter()
.flat_map(|run| &run.content)
.collect()
}
#[test]
fn leaves_out_the_text_of_a_bidirectional_embedding_or_override_with_a_warning() {
let (body, kinds) = body_warned(
r#"<w:p><w:r><w:t>a</w:t></w:r><w:dir w:val="rtl"><w:r><w:t>b</w:t></w:r></w:dir><w:hyperlink><w:bdo w:val="ltr"><w:r><w:t>c</w:t></w:r></w:bdo></w:hyperlink></w:p>"#,
);
// The hyperlink leaves only the marks of its content's edges.
assert_eq!(
first_content(&body),
[
&Content::Text("a".into()),
&Content::HyperlinkEdge,
&Content::HyperlinkEdge
]
);
assert_eq!(
kinds,
[("bidirectional-embedding-not-supported".to_string(), 2)]
);
}
#[test]
fn leaves_out_a_phonetic_guide_a_page_number_element_and_date_elements_with_a_warning_each() {
let (body, kinds) = body_warned(
r"<w:p><w:r><w:t>a</w:t><w:ruby><w:rubyPr/><w:rt><w:r><w:t>g</w:t></w:r></w:rt><w:rubyBase><w:r><w:t>b</w:t></w:r></w:rubyBase></w:ruby><w:pgNum/><w:dayShort/><w:dayLong/><w:monthShort/><w:monthLong/><w:yearShort/><w:yearLong/></w:r></w:p>",
);
assert_eq!(first_content(&body), [&Content::Text("a".into())]);
assert_eq!(
kinds,
[
("date-block-not-supported".to_string(), 6),
("page-number-element-not-supported".to_string(), 1),
("ruby-not-supported".to_string(), 1),
]
);
}
#[test]
fn leaves_out_the_marks_ranges_and_properties_that_draw_nothing_without_a_warning() {
let (_, kinds) = body_warned(
r#"<w:p><w:pPr/><w:proofErr w:type="spellStart"/><w:permStart w:id="1"/><w:commentRangeStart w:id="2"/><w:r><w:lastRenderedPageBreak/><w:t>a</w:t></w:r><w:commentRangeEnd w:id="2"/><w:moveFromRangeStart w:id="4" w:author="x"/><w:moveFromRangeEnd w:id="4"/><w:sdt><w:sdtPr/><w:sdtEndPr/><w:sdtContent><w:r><w:t>b</w:t></w:r></w:sdtContent></w:sdt><w:permEnd w:id="1"/><w:proofErr w:type="spellEnd"/></w:p>"#,
);
assert_eq!(kinds, []);
}
/// The start of a field with the code `code`, without its separator.
fn field_begin(code: &str) -> String {
format!(
r#"<w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> {code} </w:instrText></w:r>"#
)
}
const FIELD_SEPARATE: &str = r#"<w:r><w:fldChar w:fldCharType="separate"/></w:r>"#;
const FIELD_END: &str = r#"<w:r><w:fldChar w:fldCharType="end"/></w:r>"#;
/// The run content of the one paragraph `paragraph` of a story, with the limits that its
/// fields reached and their counts.
fn read_fields(paragraph: &str) -> (Vec<Content>, Vec<(crate::warnings::Limit, u32)>) {
let doc = Document::parse(
format!(r#"<w:hdr xmlns:w="{W}"><w:p>{paragraph}</w:p></w:hdr>"#).as_bytes(),
&Limits::default(),
)
.unwrap();
let mut reader = PartReader::new(&doc);
let story = read_story(&mut reader, doc.root().unwrap());
let content = first_paragraph(&story)
.runs
.iter()
.flat_map(|run| run.content.clone())
.collect();
(content, reader.limits_reached())
}
#[test]
fn computes_a_field_inside_the_most_open_fields_and_reads_one_past_them_as_its_content() {
use crate::params::MAX_FIELD_DEPTH;
use crate::warnings::Limit;
let kept = field_begin("TITLE") + FIELD_SEPARATE;
let page = field_begin("PAGE") + FIELD_SEPARATE + "<w:r><w:t>9</w:t></w:r>" + FIELD_END;
let inside = |around: usize| {
let paragraph = kept.repeat(around) + &page + &FIELD_END.repeat(around);
let (content, limits) = read_fields(¶graph);
(shown(&content), limits)
};
// With the `PAGE` field, MAX_FIELD_DEPTH fields are open: it is computed.
assert_eq!(
inside(MAX_FIELD_DEPTH - 1),
(vec![Content::PageNumber], vec![])
);
// One field more: the `PAGE` field is read as the content of the field around it, which
// shows its stored result.
assert_eq!(
inside(MAX_FIELD_DEPTH),
(
vec![Content::Text("9".to_owned())],
vec![(Limit::FieldDepth, 1)]
)
);
}
#[test]
fn reads_twenty_thousand_nested_if_fields_with_the_nesting_of_the_most_open_fields() {
use crate::params::MAX_FIELD_DEPTH;
use crate::warnings::Limit;
// Each `IF` field lies in the code of the one around it. Without a limit, the value of
// the outermost field nests 20,000 deep, and its copy, its text and its drop recurse once
// for each level, which overflows the stack.
let depth = 20_000;
let paragraph =
field_begin("IF").repeat(depth) + "<w:r><w:t>x</w:t></w:r>" + &FIELD_END.repeat(depth);
let (content, limits) = read_fields(¶graph);
let content = shown(&content);
let [Content::If(outermost)] = content.as_slice() else {
panic!("not one IF field: {}", content.len());
};
let mut nesting = 1;
let mut field: &super::IfField = outermost;
while let Some(inner) = field.parts.iter().find_map(|part| match part {
super::CodePart::Field(Content::If(inner)) => Some(inner.as_ref()),
_ => None,
}) {
nesting += 1;
field = inner;
}
assert_eq!(nesting, MAX_FIELD_DEPTH);
let past = u32::try_from(depth.saturating_sub(MAX_FIELD_DEPTH)).unwrap();
assert_eq!(limits, [(Limit::FieldDepth, past)]);
}
#[test]
fn keeps_the_most_open_fields_open_when_fields_do_not_end() {
use crate::params::MAX_FIELD_DEPTH;
use crate::warnings::Limit;
// Each field shows its stored result and never ends. Without a limit, every item after
// them searches the list of all of them.
let count = 10_000;
let field = field_begin("TITLE") + FIELD_SEPARATE + "<w:r><w:t>x</w:t></w:r>";
let (content, limits) = read_fields(&field.repeat(count));
let texts = shown(&content)
.iter()
.filter(|item| **item == Content::Text("x".to_owned()))
.count();
assert_eq!(texts, count);
let past = u32::try_from(count.saturating_sub(MAX_FIELD_DEPTH)).unwrap();
assert_eq!(limits, [(Limit::FieldDepth, past)]);
}
#[test]
fn streamed_body_matches_full_dom_blocks_sections_and_spans() {
use crate::mode::ModeRules;
use crate::reader::settings::ReaderSettings;
let xml = concat!(
r#"<?xml version="1.0" encoding="UTF-8"?>"#,
r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">"#,
r#"<w:background w:color="FFEEAA"/>"#,
r#"<w:body>"#,
r#"<w:bookmarkStart w:id="0" w:name="intro"/>"#,
r#"<w:p><w:r><w:t>First paragraph</w:t></w:r></w:p>"#,
r#"<w:tbl><w:tr><w:tc><w:p><w:r><w:t>Cell A</w:t></w:r></w:p></w:tc></w:tr></w:tbl>"#,
r#"<w:p><w:pPr><w:sectPr><w:pgSz w:w="12240" w:h="15840"/></w:sectPr></w:pPr><w:r><w:t>End section 1</w:t></w:r></w:p>"#,
r#"<w:p><w:r><w:t>Second section</w:t></w:r></w:p>"#,
r#"<w:sectPr><w:pgSz w:w="15840" w:h="12240"/></w:sectPr>"#,
r#"</w:body></w:document>"#,
);
let limits = f_office_xml::Limits::default();
let streamed_scan = f_office_xml::scan_body_children(
xml.as_bytes(),
&[crate::ns::W, crate::ns::W_STRICT],
&limits,
)
.unwrap()
.expect("should scan UTF-8 body");
assert!(!streamed_scan.has_revisions);
assert!(!streamed_scan.has_cross_block_features);
assert!(streamed_scan.background.is_some());
let doc =
Document::parse_with_aliases(xml.as_bytes(), &limits, crate::ns::STRICT_ALIASES).unwrap();
let root = doc.root().unwrap();
let body_node = doc.child(root, crate::ns::W, "body").unwrap();
let mut dom_warnings = crate::Warnings::new();
let dom_ids = crate::body::ParagraphIds::default();
let mut dom_reading = crate::parts::Reading {
warnings: &mut dom_warnings,
ids: &dom_ids,
settings: ReaderSettings::base(),
notes: None,
colors: f_office_drawingml::color::SchemeColors::default(),
styles: None,
small_frac: crate::props::SmallFractions::Off,
};
let dom_body = crate::parts::read_with(
&doc,
("word/document.xml", body_node),
&mut dom_reading,
|part, node| Body::read(part, node, (ReaderSettings::base(), ModeRules::default())),
);
let mut stream_warnings = crate::Warnings::new();
let stream_ids = crate::body::ParagraphIds::default();
let mut stream_reading = crate::parts::Reading {
warnings: &mut stream_warnings,
ids: &stream_ids,
settings: ReaderSettings::base(),
notes: None,
colors: f_office_drawingml::color::SchemeColors::default(),
styles: None,
small_frac: crate::props::SmallFractions::Off,
};
let streamed_body = Body::read_streamed(
xml.as_bytes(),
&streamed_scan,
("word/document.xml", &limits),
&mut stream_reading,
(ReaderSettings::base(), ModeRules::default()),
)
.unwrap();
assert_eq!(streamed_body.blocks, dom_body.blocks);
assert_eq!(streamed_body.sections, dom_body.sections);
assert_eq!(streamed_body.without_section, dom_body.without_section);
assert_eq!(stream_warnings, dom_warnings);
}