f-office-docx 0.2.1

DOCX model and Word's layout rules.
Documentation
//! How footnotes and endnotes are numbered and where they stand: `w:footnotePr` and
//! `w:endnotePr` of the settings and of each section (ECMA-376 Part 1, 17.11). A section's
//! element stands over the settings' one, element by element, and the settings' one over the
//! defaults: footnotes numbered 1, 2, 3 at the bottom of the page, endnotes numbered i, ii, iii
//! at the end of the document, each numbered on from the notes before.

use std::fmt;

use f_office_xml::NodeId;
use f_office_xml::enumeration::{Values, own};

use crate::ns::W;
use crate::numbering::{Format, format_number, read_format};
use crate::numbers;
use crate::reader::PartReader;

/// Where the numbers of the notes of one kind start again (`ST_RestartNumber`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NoteRestart {
    /// Never: each note takes the number after the note before it (`continuous`).
    #[default]
    Continuous,
    /// At the start of each section (`eachSect`).
    EachSection,
    /// At the top of each page (`eachPage`).
    EachPage,
}

/// Where the notes of one kind stand (`ST_FtnPos`, `ST_EdnPos`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NotePosition {
    /// At the bottom of the page of the reference (`pageBottom`).
    PageBottom,
    /// Right below the last line of text of the page of the reference (`beneathText`).
    BeneathText,
    /// At the end of the section of the reference (`sectEnd`).
    SectionEnd,
    /// At the end of the document (`docEnd`).
    DocumentEnd,
}

/// `ST_RestartNumber` of `w:numRestart`.
const RESTART: &Values<NoteRestart> = &Values::new(&[
    own("continuous", NoteRestart::Continuous),
    own("eachSect", NoteRestart::EachSection),
    own("eachPage", NoteRestart::EachPage),
]);

/// `ST_FtnPos` of `w:pos` in `w:footnotePr`.
const FOOTNOTE_POSITION: &Values<NotePosition> = &Values::new(&[
    own("pageBottom", NotePosition::PageBottom),
    own("beneathText", NotePosition::BeneathText),
    own("sectEnd", NotePosition::SectionEnd),
    own("docEnd", NotePosition::DocumentEnd),
]);

/// `ST_EdnPos` of `w:pos` in `w:endnotePr`.
const ENDNOTE_POSITION: &Values<NotePosition> = &Values::new(&[
    own("sectEnd", NotePosition::SectionEnd),
    own("docEnd", NotePosition::DocumentEnd),
]);

/// How the notes of one kind of a section are numbered and where they stand.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct NoteSetup {
    /// The number format (`w:numFmt`).
    pub format: Format,
    /// The number of the first note after a restart (`w:numStart`).
    pub start: i64,
    /// Where the numbers start again (`w:numRestart`).
    pub restart: NoteRestart,
    /// Where the notes stand (`w:pos`).
    pub position: NotePosition,
}

impl NoteSetup {
    /// The footnotes of a document that sets nothing: 1, 2, 3 at the bottom of the page.
    pub const FOOTNOTES: Self = Self {
        format: Format::Decimal,
        start: 1,
        restart: NoteRestart::Continuous,
        position: NotePosition::PageBottom,
    };

    /// The endnotes of a document that sets nothing: i, ii, iii at the end of the document.
    pub const ENDNOTES: Self = Self {
        format: Format::LowerRoman,
        start: 1,
        restart: NoteRestart::Continuous,
        position: NotePosition::DocumentEnd,
    };
}

/// What one `w:footnotePr` or `w:endnotePr` element sets: each of its elements that it holds.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct NoteProps {
    /// The number format (`w:numFmt`).
    pub format: Option<Format>,
    /// The number of the first note after a restart (`w:numStart`).
    pub start: Option<i64>,
    /// Where the numbers start again (`w:numRestart`).
    pub restart: Option<NoteRestart>,
    /// Where the notes stand (`w:pos`).
    pub position: Option<NotePosition>,
}

impl NoteProps {
    /// Reads the element `node`, whose `w:pos` reads through `positions`.
    fn read(
        reader: &mut PartReader,
        node: NodeId,
        positions: &'static Values<NotePosition>,
    ) -> Self {
        let doc = reader.doc;
        Self {
            format: doc
                .child(node, W, "numFmt")
                .and_then(|n| read_format(reader, n, "val")),
            start: doc
                .child(node, W, "numStart")
                .and_then(|n| reader.number(n, "val", numbers::ANY)),
            restart: doc
                .child(node, W, "numRestart")
                .and_then(|n| reader.enumeration(n, "val", RESTART)),
            position: doc
                .child(node, W, "pos")
                .and_then(|n| reader.enumeration(n, "val", positions)),
        }
    }

    /// The setup that these properties give over `base`: each that they hold stands over the
    /// one of `base`.
    #[must_use]
    pub fn over(self, base: NoteSetup) -> NoteSetup {
        NoteSetup {
            format: self.format.unwrap_or(base.format),
            start: self.start.unwrap_or(base.start),
            restart: self.restart.unwrap_or(base.restart),
            position: self.position.unwrap_or(base.position),
        }
    }
}

/// One value for footnotes and one for endnotes, such as what the settings or a section set.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ByNoteKind<T> {
    /// The value for footnotes.
    pub footnotes: T,
    /// The value for endnotes.
    pub endnotes: T,
}

impl<T> ByNoteKind<T> {
    /// The value for the notes of `kind`.
    pub const fn get(&self, kind: crate::NoteKind) -> &T {
        match kind {
            crate::NoteKind::Footnote => &self.footnotes,
            crate::NoteKind::Endnote => &self.endnotes,
        }
    }
}

impl ByNoteKind<NoteSetup> {
    /// The setups of a document that sets nothing.
    pub const DEFAULT: Self = Self {
        footnotes: NoteSetup::FOOTNOTES,
        endnotes: NoteSetup::ENDNOTES,
    };
}

impl Default for ByNoteKind<NoteSetup> {
    fn default() -> Self {
        Self::DEFAULT
    }
}

impl ByNoteKind<NoteProps> {
    /// Reads `w:footnotePr` and `w:endnotePr` of the settings or of a section `parent`.
    pub(crate) fn read(reader: &mut PartReader, parent: NodeId) -> Self {
        let doc = reader.doc;
        let mut read = |name: &str, positions| {
            doc.child(parent, W, name)
                .map_or_default(|node| NoteProps::read(reader, node, positions))
        };
        Self {
            footnotes: read("footnotePr", FOOTNOTE_POSITION),
            endnotes: read("endnotePr", ENDNOTE_POSITION),
        }
    }

    /// The setups that these properties give over `base`, each kind over its own.
    #[must_use]
    pub fn over(self, base: ByNoteKind<NoteSetup>) -> ByNoteKind<NoteSetup> {
        ByNoteKind {
            footnotes: self.footnotes.over(base.footnotes),
            endnotes: self.endnotes.over(base.endnotes),
        }
    }
}

/// What a note's reference and its mark show: its number in its format.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct NoteLabel {
    /// The number.
    pub value: i64,
    /// The format.
    pub format: Format,
}

impl NoteLabel {
    /// The label 1, which a footnote mark outside a footnote shows.
    pub const FIRST: Self = Self {
        value: 1,
        format: Format::Decimal,
    };
}

impl fmt::Display for NoteLabel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&format_number(self.value, self.format))
    }
}

#[cfg(test)]
mod tests {
    use f_office_xml::{Document, Limits};

    use super::{ByNoteKind, NoteLabel, NotePosition, NoteRestart, NoteSetup};
    use crate::ns::W;
    use crate::numbering::Format;
    use crate::reader::PartReader;

    fn read(xml: &str) -> ByNoteKind<super::NoteProps> {
        let xml = format!(r#"<w:sectPr xmlns:w="{W}">{xml}</w:sectPr>"#);
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        ByNoteKind::read(&mut PartReader::new(&doc), doc.root().unwrap())
    }

    #[test]
    fn value_tables_hold_the_names_of_their_types() {
        crate::enumerations::assert_names(super::RESTART, "continuous eachSect eachPage");
        crate::enumerations::assert_names(
            super::FOOTNOTE_POSITION,
            "pageBottom beneathText sectEnd docEnd",
        );
        crate::enumerations::assert_names(super::ENDNOTE_POSITION, "sectEnd docEnd");
    }

    #[test]
    fn each_element_of_a_section_stands_over_the_settings() {
        let settings = read(
            r#"<w:footnotePr><w:numFmt w:val="lowerRoman"/><w:numStart w:val="3"/></w:footnotePr><w:endnotePr><w:numFmt w:val="decimal"/></w:endnotePr>"#,
        )
        .over(ByNoteKind::DEFAULT);
        let section = read(
            r#"<w:footnotePr><w:numRestart w:val="eachPage"/><w:numStart w:val="2"/><w:pos w:val="beneathText"/></w:footnotePr><w:endnotePr><w:numRestart w:val="eachSect"/><w:pos w:val="sectEnd"/></w:endnotePr>"#,
        )
        .over(settings);
        assert_eq!(
            section.footnotes,
            NoteSetup {
                format: Format::LowerRoman,
                start: 2,
                restart: NoteRestart::EachPage,
                position: NotePosition::BeneathText,
            }
        );
        assert_eq!(
            section.endnotes,
            NoteSetup {
                format: Format::Decimal,
                start: 1,
                restart: NoteRestart::EachSection,
                position: NotePosition::SectionEnd,
            }
        );
        assert_eq!(read("").over(settings), settings);
        assert_eq!(read("").over(ByNoteKind::DEFAULT), ByNoteKind::default());
    }

    #[test]
    fn a_label_shows_its_number_in_its_format() {
        assert_eq!(NoteLabel::FIRST.to_string(), "1");
        let label = NoteLabel {
            value: 4,
            format: Format::LowerRoman,
        };
        assert_eq!(label.to_string(), "iv");
    }
}