f-office 0.2.4

Renders Office Open XML documents the way Microsoft Office does.
Documentation
//! The numbers of footnotes and endnotes: the format, the start and the restart of the settings
//! and of each section, section over settings.

use std::fmt::Write as _;

use super::{SECTION, docx, lines, render};
use crate::test_fonts::{CARLITO_RUN, carlito};

/// A run of Carlito text.
fn text(text: &str) -> String {
    format!(r#"<w:r>{CARLITO_RUN}<w:t xml:space="preserve">{text}</w:t></w:r>"#)
}

/// A run with the reference of the note `id` of the kind `kind`, `footnote` or `endnote`.
fn reference(kind: &str, id: u32) -> String {
    format!(r#"<w:r>{CARLITO_RUN}<w:{kind}Reference w:id="{id}"/></w:r>"#)
}

/// The notes part of the kind `kind` with a separator and the notes 1 to `count`, each its mark
/// and " Note" with its ID.
fn notes(kind: &str, count: u32) -> String {
    let mut part = format!(
        r#"<w:{kind} w:type="separator" w:id="-1"><w:p><w:r><w:separator/></w:r></w:p></w:{kind}>"#
    );
    for id in 1..=count {
        write!(
            part,
            r#"<w:{kind} w:id="{id}"><w:p><w:r>{CARLITO_RUN}<w:{kind}Ref/></w:r>{}</w:p></w:{kind}>"#,
            text(&format!(" Note{id}"))
        )
        .unwrap();
    }
    part
}

/// The texts of the lines of each page of the body `body` with the settings `settings`, the
/// footnotes 1 to `footnotes` and the endnotes 1 to `endnotes`.
fn pages(body: &str, settings: &str, (footnotes, endnotes): (u32, u32)) -> Vec<Vec<String>> {
    let parts = [
        ("n1", notes("footnote", footnotes)),
        ("e1", notes("endnote", endnotes)),
    ];
    let parts: Vec<(&str, &str)> = parts.iter().map(|(id, xml)| (*id, xml.as_str())).collect();
    lines(&render(&docx(body, &parts, settings)))
        .iter()
        .map(|page| page.iter().map(|(_, text)| text.clone()).collect())
        .collect()
}

/// A body of one paragraph of the runs `runs` in each section, which starts on a new page and
/// whose properties hold `notes` before the page size.
fn sections(runs: &[String], notes: &[&str]) -> String {
    assert_eq!(runs.len(), notes.len());
    let mut body = String::new();
    for (index, (paragraph, notes)) in runs.iter().zip(notes).enumerate() {
        if index + 1 < runs.len() {
            write!(
                body,
                "<w:p><w:pPr><w:sectPr>{notes}{SECTION}</w:sectPr></w:pPr>{paragraph}</w:p>"
            )
        } else {
            write!(
                body,
                "<w:p>{paragraph}</w:p><w:sectPr>{notes}{SECTION}</w:sectPr>"
            )
        }
        .unwrap();
    }
    body
}

#[test]
fn numbers_footnotes_in_the_format_and_from_the_start_of_their_section() {
    let body = |notes: &str| {
        format!(
            "<w:p>{}{}{}{}</w:p><w:sectPr>{SECTION}{notes}</w:sectPr>",
            text("A"),
            reference("footnote", 1),
            text("B"),
            reference("footnote", 2)
        )
    };
    let settings =
        r#"<w:footnotePr><w:numFmt w:val="decimal"/><w:numStart w:val="5"/></w:footnotePr>"#;
    // The section's format stands over the settings' one, and the settings' start, which the
    // section does not set, holds. The references and the marks show the same labels.
    let own = r#"<w:footnotePr><w:numFmt w:val="lowerRoman"/></w:footnotePr>"#;
    assert_eq!(
        pages(&body(own), settings, (2, 0)),
        [["AvBvi", "v Note1", "vi Note2"]]
    );
    assert_eq!(
        pages(&body(""), settings, (2, 0)),
        [["A5B6", "5 Note1", "6 Note2"]]
    );
    // A document that sets nothing numbers its footnotes from 1 in decimal.
    assert_eq!(
        pages(&body(""), "", (2, 0)),
        [["A1B2", "1 Note1", "2 Note2"]]
    );
}

#[test]
fn starts_footnote_numbers_again_in_a_section_that_restarts_them() {
    let paragraphs = [
        text("A") + &reference("footnote", 1),
        text("B") + &reference("footnote", 2),
    ];
    let restart = r#"<w:footnotePr><w:numRestart w:val="eachSect"/></w:footnotePr>"#;
    assert_eq!(
        pages(&sections(&paragraphs, &["", restart]), "", (2, 0)),
        [["A1", "1 Note1"], ["B1", "1 Note2"]]
    );
    // Numbers that go on in the section go on from the section before.
    assert_eq!(
        pages(&sections(&paragraphs, &["", ""]), "", (2, 0)),
        [["A1", "1 Note1"], ["B2", "2 Note2"]]
    );
}

#[test]
fn starts_footnote_numbers_again_on_each_page_by_the_pages_of_the_pass_before() {
    // One paragraph of fourteen lines on pages with room for about ten: the references of its
    // first and its last line are measured together on the first page, and stand on two
    // pages. A first pass counts both on the first page; the next pass numbers them by the
    // pages where the first pass placed them.
    let mut lines = vec![format!("{}{}", text("L1"), reference("footnote", 1))];
    for number in 2..=13 {
        lines.push(text(&format!("L{number}")));
    }
    lines.push(format!("{}{}", text("Z"), reference("footnote", 2)));
    let body = format!(
        "<w:p>{}</w:p><w:sectPr>{SECTION}</w:sectPr>",
        lines.join("<w:r><w:br/></w:r>")
    );
    let restart = r#"<w:footnotePr><w:numRestart w:val="eachPage"/></w:footnotePr>"#;
    let last_page = |settings: &str| {
        let pages = pages(&body, settings, (2, 0));
        assert_eq!(pages.len(), 2, "{pages:?}");
        pages[1].clone()
    };
    let restarted = last_page(restart);
    assert!(restarted.contains(&"Z1".to_owned()), "{restarted:?}");
    assert!(restarted.contains(&"1 Note2".to_owned()), "{restarted:?}");
    let continued = last_page("");
    assert!(continued.contains(&"Z2".to_owned()), "{continued:?}");
    assert!(continued.contains(&"2 Note2".to_owned()), "{continued:?}");
}

#[test]
fn numbers_footnotes_on_after_pages_that_restart_them_by_every_footnote_before() {
    // Two sections that start their footnote numbers again on each page, one footnote on each
    // of their pages, and a section whose numbers go on: its footnote counts both footnotes
    // before it, not the last number shown.
    let paragraphs = [
        text("A") + &reference("footnote", 1),
        text("B") + &reference("footnote", 2),
        text("C") + &reference("footnote", 3),
    ];
    let restart = r#"<w:footnotePr><w:numRestart w:val="eachPage"/></w:footnotePr>"#;
    assert_eq!(
        pages(&sections(&paragraphs, &[restart, restart, ""]), "", (3, 0)),
        [["A1", "1 Note1"], ["B1", "1 Note2"], ["C3", "3 Note3"]]
    );
}

#[test]
fn numbers_endnotes_as_the_section_of_their_reference_asks() {
    let paragraphs = [
        text("A") + &reference("endnote", 1),
        text("B") + &reference("endnote", 2),
    ];
    // The second section numbers its endnotes in decimal from 1 again; the first keeps lower
    // Roman numbers.
    let own =
        r#"<w:endnotePr><w:numFmt w:val="decimal"/><w:numRestart w:val="eachSect"/></w:endnotePr>"#;
    assert_eq!(
        pages(&sections(&paragraphs, &["", own]), "", (0, 2)),
        [vec!["Ai"], vec!["B1", "i Note1", "1 Note2"]]
    );
    // Without a restart, the decimal numbers go on from the first section's endnote.
    let own = r#"<w:endnotePr><w:numFmt w:val="decimal"/></w:endnotePr>"#;
    assert_eq!(
        pages(&sections(&paragraphs, &["", own]), "", (0, 2)),
        [vec!["Ai"], vec!["B2", "i Note1", "2 Note2"]]
    );
}

/// A body that shows "A" with a reference of the ID `reference` to a note of the kind `kind`,
/// `footnote` or `endnote`, opened with Carlito. The notes part holds a separator of the ID -1
/// and then, in order, a normal note of each ID of `notes`, which shows its mark and the
/// note's text.
fn opened_with_notes(
    kind: &str,
    reference: &str,
    notes: &[(&str, &str)],
) -> crate::Warned<crate::Document> {
    let body = format!(
        r#"<w:p>{}<w:r>{CARLITO_RUN}<w:{kind}Reference w:id="{reference}"/></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"#,
        text("A")
    );
    let mut part = format!(
        r#"<w:{kind} w:type="separator" w:id="-1"><w:p><w:r><w:separator/></w:r></w:p></w:{kind}>"#
    );
    for (id, shown) in notes {
        write!(
            part,
            r#"<w:{kind} w:id="{id}"><w:p><w:r>{CARLITO_RUN}<w:{kind}Ref/></w:r>{}</w:p></w:{kind}>"#,
            text(shown)
        )
        .unwrap();
    }
    let name = if kind == "footnote" { "n1" } else { "e1" };
    crate::Document::open(
        &docx(&body, &[(name, &part)], ""),
        &carlito(),
        &crate::Options::base(),
    )
    .unwrap()
}

/// The texts of the lines of each page of `document`.
fn page_texts(document: &crate::Document) -> Vec<Vec<String>> {
    lines(document.display_list())
        .iter()
        .map(|page| page.iter().map(|(_, text)| text.clone()).collect())
        .collect()
}

/// The texts of the lines of each page, and the places of the values that do not read, of
/// [`opened_with_notes`] with one note of the ID `id` that shows " Note". A place is the part,
/// the element and the attribute of the warning `InvalidValue`, or its value place when the
/// value lies elsewhere.
fn with_ids(kind: &str, reference: &str, id: &str) -> (Vec<Vec<String>>, Vec<String>) {
    use crate::docx::{ValuePlace, Warning as DocxWarning};
    let opened = opened_with_notes(kind, reference, &[(id, " Note")]);
    let pages = page_texts(&opened.value);
    let invalid = opened
        .warnings
        .iter()
        .filter_map(|(warning, _)| match warning {
            crate::Warning::Docx(DocxWarning::InvalidValue {
                part,
                element,
                place,
                ..
            }) => Some(format!(
                "{} {} {}",
                part.as_str(),
                element.as_str(),
                match place {
                    ValuePlace::Attribute(attribute) => attribute.as_str().to_owned(),
                    other => other.to_string(),
                }
            )),
            _ => None,
        })
        .collect();
    (pages, invalid)
}

#[test]
fn finds_a_note_by_the_number_of_its_id() {
    let found = |kind| with_ids(kind, "01", "1");
    assert_eq!(
        found("footnote"),
        (vec![vec!["A1".to_owned(), "1 Note".to_owned()]], vec![])
    );
    let endnote = with_ids("endnote", "+1", "1.0");
    assert_eq!(
        endnote,
        (vec![vec!["Ai".to_owned(), "i Note".to_owned()]], vec![])
    );
}

#[test]
fn shows_no_number_for_a_reference_whose_id_does_not_read() {
    let (pages, invalid) = with_ids("footnote", "x", "1");
    assert_eq!(pages, [vec!["A"]]);
    assert_eq!(invalid, ["word/document.xml footnoteReference id"]);
    let (pages, invalid) = with_ids("endnote", "x", "1");
    assert_eq!(pages, [vec!["A"]]);
    assert_eq!(invalid, ["word/document.xml endnoteReference id"]);
}

#[test]
fn keeps_no_note_whose_id_does_not_read() {
    let (pages, invalid) = with_ids("footnote", "1", "1x");
    assert_eq!(pages, [vec!["A1"]]);
    assert_eq!(invalid, ["word/n1.xml footnote id"]);
    let (pages, invalid) = with_ids("endnote", "1", "1x");
    assert_eq!(pages, [vec!["Ai"]]);
    assert_eq!(invalid, ["word/e1.xml endnote id"]);
}

#[test]
fn keeps_and_finds_a_normal_note_whose_id_is_negative() {
    let (pages, invalid) = with_ids("footnote", "-03", "-3");
    assert_eq!(pages, [vec!["A1", "1 Note"]]);
    assert_eq!(invalid, Vec::<String>::new());
}

/// Of the normal notes of one number in a part, the layout of the default target keeps the last one, with one
/// warning for each note that replaces another, which names the part and the number. A normal
/// note that shares its number with the separator, which the layout finds by its kind, gives no
/// warning.
#[test]
fn keeps_the_last_note_of_one_number_and_warns_of_each_one_that_replaces_another() {
    use crate::docx::Warning as DocxWarning;
    let notes = [
        ("1", " Early"),
        ("01", " Late"),
        ("2", " Other"),
        ("1.0", " Last"),
        ("-1", " Minus"),
    ];
    for (kind, name, label) in [
        ("footnote", "word/n1.xml", "1"),
        ("endnote", "word/e1.xml", "i"),
    ] {
        let opened = opened_with_notes(kind, "1", &notes);
        assert_eq!(
            page_texts(&opened.value),
            [vec![format!("A{label}"), format!("{label} Last")]]
        );
        let repeated: Vec<_> = opened
            .warnings
            .iter()
            .filter_map(|(warning, count)| match warning {
                crate::Warning::Docx(DocxWarning::NoteIdRepeated { part, id }) => {
                    Some((part.as_str().to_owned(), *id, count))
                }
                _ => None,
            })
            .collect();
        assert_eq!(repeated, [(name.to_owned(), 1, 2)]);
    }
}

/// The note references of `opened` that no note has, each with the part of the reference, the
/// kind of note, the number and the count.
fn missing_notes(
    opened: &crate::Warned<crate::Document>,
) -> Vec<(String, crate::docx::NoteKind, i64, u32)> {
    opened
        .warnings
        .iter()
        .filter_map(|(warning, count)| match warning {
            crate::Warning::Docx(crate::docx::Warning::NoteMissing { part, note, id }) => {
                Some((part.as_str().to_owned(), *note, *id, count))
            }
            _ => None,
        })
        .collect()
}

/// A reference to a note that the notes part does not have draws its number, with one warning
/// that names the reference's part, the kind of note and the number; a reference to a note of
/// the part gives none.
#[test]
fn warns_of_a_reference_to_a_note_that_the_notes_part_does_not_have() {
    use crate::docx::NoteKind;
    for (kind, note, label) in [
        ("footnote", NoteKind::Footnote, "1"),
        ("endnote", NoteKind::Endnote, "i"),
    ] {
        let opened = opened_with_notes(kind, "2", &[("1", " Note")]);
        assert_eq!(page_texts(&opened.value)[0][0], format!("A{label}"));
        assert_eq!(
            missing_notes(&opened),
            [("word/document.xml".to_owned(), note, 2, 1)]
        );
        let opened = opened_with_notes(kind, "1", &[("1", " Note")]);
        assert_eq!(missing_notes(&opened), []);
    }
}