f-office-docx 0.2.1

DOCX model and Word's layout rules.
Documentation
//! The automatic hyphenation points of a paragraph's words: the places where the line breaker
//! may end a line with a hyphen under the document's automatic hyphenation.
//!
//! A word is a row of letters of one language with no letter, digit, apostrophe or hyphen
//! that does not break right before or after it. Its points come from the hyphenation data of
//! its language, less those that leave too few letters before or after them and those inside a
//! ligature. Each point becomes a piece of its own, a glyph of [`AUTOMATIC_HYPHEN`] with the
//! hyphen of its run, which takes no room unless a line ends there.

use f_office_hyphenate::Language;

use crate::lines::Piece;
use crate::styles::Capitals;
use crate::text::{AUTOMATIC_HYPHEN, Glyph, NON_BREAKING_HYPHEN, SOFT_HYPHEN};

/// The pieces of one measured text whose words may take automatic hyphenation points.
#[derive(Clone, Copy, Debug)]
pub(in crate::layout) struct HyphenRun {
    /// The index of its first piece.
    pub(in crate::layout) start: usize,
    /// The index after its last piece.
    pub(in crate::layout) end: usize,
    /// The language of its words.
    pub(in crate::layout) language: Language,
    /// The hyphen that a line shows where it ends at a point, measured with the text's
    /// properties.
    pub(in crate::layout) hyphen: Glyph,
}

/// Which points of a word the layout keeps.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) struct WordRules {
    /// The fewest letters before a point and after it.
    pub(in crate::layout) least: (usize, usize),
    /// Whether words in capitals take points.
    pub(in crate::layout) capitals: Capitals,
}

/// `pieces` with a piece of [`AUTOMATIC_HYPHEN`] at each point of each word in `runs`, whose
/// indices count from `offset` in `pieces`.
pub(in crate::layout) fn with_points(
    pieces: Vec<Piece>,
    offset: usize,
    runs: &[HyphenRun],
    rules: WordRules,
) -> Vec<Piece> {
    if runs.is_empty() {
        return pieces;
    }
    let run_at = |index: usize| {
        let index = index.checked_sub(offset)?;
        let found = runs.partition_point(|run| run.end <= index);
        runs.get(found).filter(|run| run.start <= index)
    };
    let mut out = Vec::with_capacity(pieces.len());
    let mut i = 0;
    while let Some(piece) = pieces.get(i) {
        let before = i.checked_sub(1).and_then(|k| pieces.get(k));
        let Some(run) = run_at(i).filter(|_| letter(Some(piece)) && !letter(before)) else {
            out.push(*piece);
            i += 1;
            continue;
        };
        let mut end = i;
        while letter(pieces.get(end)) && run_at(end).is_some_and(|r| r.language == run.language) {
            end += 1;
        }
        let word = pieces.get(i..end).unwrap_or_default();
        let points = if stands_alone(before) && stands_alone(pieces.get(end)) {
            word_points(word, run.language, rules)
        } else {
            Vec::new()
        };
        for (k, piece) in word.iter().enumerate() {
            if points.contains(&k)
                && let Some(Piece::Glyph(letter)) = k.checked_sub(1).and_then(|j| word.get(j))
                && let Some(hyphen) = run_at(i + k - 1).map(|r| r.hyphen)
            {
                out.push(Piece::Glyph(Glyph {
                    ch: AUTOMATIC_HYPHEN,
                    place: letter.place,
                    ..hyphen
                }));
            }
            out.push(*piece);
        }
        i = end;
    }
    out
}

/// The points of a word of letter glyphs in `language` that `rules` keep, as the numbers of
/// letters before them.
fn word_points(word: &[Piece], language: Language, rules: WordRules) -> Vec<usize> {
    let letters: Vec<&Glyph> = word
        .iter()
        .filter_map(|piece| match piece {
            Piece::Glyph(glyph) => Some(glyph),
            _ => None,
        })
        .collect();
    let text: String = letters.iter().map(|glyph| glyph.ch).collect();
    if rules.capitals == Capitals::Kept && text.chars().all(char::is_uppercase) {
        return Vec::new();
    }
    let (before, after) = rules.least;
    let count = letters.len();
    f_office_hyphenate::points(language, &text)
        .into_iter()
        .filter(|&point| point >= before && point + after <= count)
        .filter(|&point| letters.get(point).is_some_and(|glyph| !glyph.part))
        .collect()
}

/// Whether a piece is a letter of the text, and not of a list label.
fn letter(piece: Option<&Piece>) -> bool {
    matches!(piece, Some(Piece::Glyph(glyph)) if glyph.ch.is_alphabetic() && !glyph.label)
}

/// Whether the piece next to a word leaves it a word of its own: no letter, digit, apostrophe,
/// soft hyphen or non-breaking hyphen.
fn stands_alone(piece: Option<&Piece>) -> bool {
    !matches!(piece, Some(Piece::Glyph(glyph)) if glyph.ch.is_alphanumeric()
        || matches!(glyph.ch, '\'' | '\u{2019}' | SOFT_HYPHEN | NON_BREAKING_HYPHEN))
}

#[cfg(test)]
mod tests {
    use super::{HyphenRun, WordRules, with_points};
    use crate::lines::Piece;
    use crate::styles::Capitals;
    use crate::text::{AUTOMATIC_HYPHEN, FaceIndex, Glyph};
    use f_office_hyphenate::Language;

    fn glyph(ch: char) -> Glyph {
        Glyph::plain(FaceIndex::nth(0), ch)
    }

    fn pieces(text: &str) -> Vec<Piece> {
        text.chars().map(|ch| Piece::Glyph(glyph(ch))).collect()
    }

    fn shown(pieces: &[Piece]) -> String {
        pieces
            .iter()
            .map(|piece| match piece {
                Piece::Glyph(g) if g.ch == AUTOMATIC_HYPHEN => '=',
                Piece::Glyph(g) => g.ch,
                _ => '?',
            })
            .collect()
    }

    fn run(start: usize, end: usize) -> HyphenRun {
        HyphenRun {
            start,
            end,
            language: Language::English,
            hyphen: glyph('-'),
        }
    }

    const MODE_15: WordRules = WordRules {
        least: (2, 3),
        capitals: Capitals::Hyphenated,
    };

    #[test]
    fn puts_a_point_where_the_data_and_the_least_letters_allow() {
        let text = "the representatives";
        let points: Vec<usize> = f_office_hyphenate::points(Language::English, "representatives")
            .into_iter()
            .filter(|&p| p >= 2 && p + 3 <= 15)
            .collect();
        let out = with_points(pieces(text), 0, &[run(0, 19)], MODE_15);
        assert!(out.len() > 19);
        assert_eq!(out.len(), 19 + points.len());
        assert_eq!(shown(&out).replace('=', ""), text);
        // A short word and a word of capitals under `doNotHyphenateCaps` take none.
        let caps = WordRules {
            capitals: Capitals::Kept,
            ..MODE_15
        };
        let out = with_points(pieces("REPRESENTATIVES"), 0, &[run(0, 15)], caps);
        assert_eq!(out.len(), 15);
    }

    #[test]
    fn leaves_words_outside_the_runs_and_words_joined_to_other_text_whole() {
        let text = "representatives representatives";
        // Only the second word lies in a run, which starts after the offset of a label.
        let mut all = pieces("1.");
        all.extend(pieces(text));
        let out = with_points(all, 2, &[run(16, 31)], MODE_15);
        let shown = shown(&out);
        assert!(!shown.get(..18).unwrap().contains('='), "{shown}");
        assert!(shown.get(18..).unwrap().contains('='), "{shown}");
        // A digit or an apostrophe next to a word keeps it whole.
        for text in ["representatives1", "representatives'"] {
            let out = with_points(pieces(text), 0, &[run(0, 16)], MODE_15);
            assert_eq!(out.len(), 16, "{text}");
        }
    }
}