f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
//! Character classes: the sets of characters that the layout asks about a character, each a
//! list of named ranges of Unicode blocks.
//!
//! Three classes say "East Asian character", each for its own use, and they hold different
//! ranges: the full-width cell of the character grid and of kinsoku breaks, the East Asian font,
//! and Word's automatic space between East Asian text and Latin text or digits. This table keeps
//! the distinct ranges for each use in one place.

/// A range of code points that a character class lists, named after the Unicode blocks that it
/// covers.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum UnicodeBlock {
    /// Latin Extended-A, U+0100 to U+017F.
    LatinExtendedA,
    /// Greek and Coptic, U+0370 to U+03FF.
    GreekAndCoptic,
    /// Cyrillic, U+0400 to U+04FF.
    Cyrillic,
    /// Thai, U+0E00 to U+0E7F.
    Thai,
    /// Hangul Jamo, U+1100 to U+11FF.
    HangulJamo,
    /// General Punctuation, U+2000 to U+206F.
    GeneralPunctuation,
    /// Letterlike Symbols, U+2100 to U+214F.
    LetterlikeSymbols,
    /// CJK Radicals Supplement and Kangxi Radicals, U+2E80 to U+2FDF.
    CjkAndKangxiRadicals,
    /// Ideographic Description Characters with the unassigned code points before them,
    /// U+2FE0 to U+2FFF.
    IdeographicDescriptionCharacters,
    /// CJK Symbols and Punctuation, U+3000 to U+303F.
    CjkSymbolsAndPunctuation,
    /// Hiragana and Katakana, U+3040 to U+30FF.
    HiraganaAndKatakana,
    /// Bopomofo to CJK Compatibility, U+3100 to U+33FF: Bopomofo, Hangul Compatibility Jamo,
    /// Kanbun, CJK Strokes, Katakana Phonetic Extensions, Enclosed CJK Letters and Months, and
    /// CJK Compatibility.
    BopomofoToCjkCompatibility,
    /// CJK Unified Ideographs Extension A, U+3400 to U+4DBF.
    CjkUnifiedIdeographsExtensionA,
    /// Yijing Hexagram Symbols, U+4DC0 to U+4DFF.
    YijingHexagramSymbols,
    /// CJK Unified Ideographs, U+4E00 to U+9FFF.
    CjkUnifiedIdeographs,
    /// Hangul Jamo Extended-A, U+A960 to U+A97F.
    HangulJamoExtendedA,
    /// Hangul Syllables, U+AC00 to U+D7AF.
    HangulSyllables,
    /// CJK Compatibility Ideographs, U+F900 to U+FAFF.
    CjkCompatibilityIdeographs,
    /// CJK Compatibility Forms, U+FE30 to U+FE4F.
    CjkCompatibilityForms,
    /// The full-width forms of Halfwidth and Fullwidth Forms, U+FF00 to U+FF60.
    FullwidthForms,
    /// The half-width forms of Halfwidth and Fullwidth Forms, U+FF61 to U+FFDF.
    HalfwidthForms,
    /// The full-width signs of Halfwidth and Fullwidth Forms, U+FFE0 to U+FFE6.
    FullwidthSigns,
    /// The half-width signs of Halfwidth and Fullwidth Forms, U+FFE7 to U+FFEF.
    HalfwidthSigns,
    /// The Supplementary Ideographic Plane, U+20000 to U+2FFFF: CJK Unified Ideographs
    /// Extension B and later.
    SupplementaryIdeographicPlane,
}

impl UnicodeBlock {
    /// The first and the last code point of the range.
    const fn ends(self) -> (char, char) {
        match self {
            Self::LatinExtendedA => ('\u{0100}', '\u{017F}'),
            Self::GreekAndCoptic => ('\u{0370}', '\u{03FF}'),
            Self::Cyrillic => ('\u{0400}', '\u{04FF}'),
            Self::Thai => ('\u{0E00}', '\u{0E7F}'),
            Self::HangulJamo => ('\u{1100}', '\u{11FF}'),
            Self::GeneralPunctuation => ('\u{2000}', '\u{206F}'),
            Self::LetterlikeSymbols => ('\u{2100}', '\u{214F}'),
            Self::CjkAndKangxiRadicals => ('\u{2E80}', '\u{2FDF}'),
            Self::IdeographicDescriptionCharacters => ('\u{2FE0}', '\u{2FFF}'),
            Self::CjkSymbolsAndPunctuation => ('\u{3000}', '\u{303F}'),
            Self::HiraganaAndKatakana => ('\u{3040}', '\u{30FF}'),
            Self::BopomofoToCjkCompatibility => ('\u{3100}', '\u{33FF}'),
            Self::CjkUnifiedIdeographsExtensionA => ('\u{3400}', '\u{4DBF}'),
            Self::YijingHexagramSymbols => ('\u{4DC0}', '\u{4DFF}'),
            Self::CjkUnifiedIdeographs => ('\u{4E00}', '\u{9FFF}'),
            Self::HangulJamoExtendedA => ('\u{A960}', '\u{A97F}'),
            Self::HangulSyllables => ('\u{AC00}', '\u{D7AF}'),
            Self::CjkCompatibilityIdeographs => ('\u{F900}', '\u{FAFF}'),
            Self::CjkCompatibilityForms => ('\u{FE30}', '\u{FE4F}'),
            Self::FullwidthForms => ('\u{FF00}', '\u{FF60}'),
            Self::HalfwidthForms => ('\u{FF61}', '\u{FFDF}'),
            Self::FullwidthSigns => ('\u{FFE0}', '\u{FFE6}'),
            Self::HalfwidthSigns => ('\u{FFE7}', '\u{FFEF}'),
            Self::SupplementaryIdeographicPlane => ('\u{20000}', '\u{2FFFF}'),
        }
    }
}

/// A set of characters that the layout asks about a character.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum CharacterClass {
    /// A character that fills a whole cell of East Asian text: an East Asian letter, East Asian
    /// punctuation, or a full-width form. Half-width forms and other characters fill half a
    /// cell of a character grid. A character of this class takes the character spacing twice
    /// where single-byte and double-byte widths balance, and a line may break by kinsoku only
    /// beside one.
    FullWidthCell,
    /// A character of an East Asian script or its punctuation, which takes the East Asian font:
    /// Hangul, the CJK punctuation, kana and ideographs, and the full-width and half-width
    /// forms.
    EastAsianFont,
    /// A Chinese, Japanese or Korean letter for Word's automatic space between East Asian text
    /// and Latin text or digits: an ideograph, kana or a Hangul syllable.
    EastAsianSpacing,
    /// A letter of the Latin Extended-A, Greek and Cyrillic blocks, which takes Calibri in a
    /// run that splits by the character set of its suffixed font name, where code page 1252
    /// lacks it ([`in_code_page_1252`]).
    SplitLetter,
    /// A character of General Punctuation, which takes Arial in such a run where code page
    /// 1252 lacks it.
    SplitPunctuation,
    /// A character of Letterlike Symbols, such as the numero sign, which takes Cambria Math
    /// in such a run where code page 1252 lacks it.
    SplitSymbol,
    /// A character of the Thai block, whose line in a paragraph aligned `thaiDistribute` keeps
    /// its spaces from shrinking.
    Thai,
}

impl CharacterClass {
    /// The ranges of the class, in the order of their code points.
    const fn blocks(self) -> &'static [UnicodeBlock] {
        match self {
            Self::FullWidthCell => &[
                UnicodeBlock::HangulJamo,
                UnicodeBlock::CjkAndKangxiRadicals,
                UnicodeBlock::IdeographicDescriptionCharacters,
                UnicodeBlock::CjkSymbolsAndPunctuation,
                UnicodeBlock::HiraganaAndKatakana,
                UnicodeBlock::BopomofoToCjkCompatibility,
                UnicodeBlock::CjkUnifiedIdeographsExtensionA,
                UnicodeBlock::YijingHexagramSymbols,
                UnicodeBlock::CjkUnifiedIdeographs,
                UnicodeBlock::HangulSyllables,
                UnicodeBlock::CjkCompatibilityIdeographs,
                UnicodeBlock::CjkCompatibilityForms,
                UnicodeBlock::FullwidthForms,
                UnicodeBlock::FullwidthSigns,
            ],
            Self::EastAsianFont => &[
                UnicodeBlock::HangulJamo,
                UnicodeBlock::CjkAndKangxiRadicals,
                UnicodeBlock::CjkSymbolsAndPunctuation,
                UnicodeBlock::HiraganaAndKatakana,
                UnicodeBlock::BopomofoToCjkCompatibility,
                UnicodeBlock::CjkUnifiedIdeographsExtensionA,
                UnicodeBlock::YijingHexagramSymbols,
                UnicodeBlock::CjkUnifiedIdeographs,
                UnicodeBlock::HangulJamoExtendedA,
                UnicodeBlock::HangulSyllables,
                UnicodeBlock::CjkCompatibilityIdeographs,
                UnicodeBlock::CjkCompatibilityForms,
                UnicodeBlock::FullwidthForms,
                UnicodeBlock::HalfwidthForms,
                UnicodeBlock::FullwidthSigns,
                UnicodeBlock::HalfwidthSigns,
                UnicodeBlock::SupplementaryIdeographicPlane,
            ],
            Self::EastAsianSpacing => &[
                UnicodeBlock::HiraganaAndKatakana,
                UnicodeBlock::CjkUnifiedIdeographsExtensionA,
                UnicodeBlock::CjkUnifiedIdeographs,
                UnicodeBlock::HangulSyllables,
                UnicodeBlock::CjkCompatibilityIdeographs,
            ],
            Self::SplitLetter => &[
                UnicodeBlock::LatinExtendedA,
                UnicodeBlock::GreekAndCoptic,
                UnicodeBlock::Cyrillic,
            ],
            Self::SplitPunctuation => &[UnicodeBlock::GeneralPunctuation],
            Self::SplitSymbol => &[UnicodeBlock::LetterlikeSymbols],
            Self::Thai => &[UnicodeBlock::Thai],
        }
    }

    /// Whether the class holds the character `ch`. The ranges are in order, so a character
    /// before the next range ends the search, and a Latin character needs one comparison.
    pub(crate) fn contains(self, ch: char) -> bool {
        self.blocks()
            .iter()
            .map(|block| block.ends())
            .take_while(|&(first, _)| first <= ch)
            .any(|(_, last)| ch <= last)
    }
}

/// Whether `ch` is a Hangul syllable or jamo (Jamo, Compatibility Jamo, Jamo Extended-A,
/// Syllables, or Jamo Extended-B), which wraps at word boundaries when `w:wordWrap` is on.
pub(crate) const fn is_hangul(ch: char) -> bool {
    matches!(
        ch,
        '\u{1100}'..='\u{11FF}'
            | '\u{3130}'..='\u{318F}'
            | '\u{A960}'..='\u{A97F}'
            | '\u{AC00}'..='\u{D7AF}'
            | '\u{D7B0}'..='\u{D7FF}'
    )
}

/// The characters above U+00FF that Windows code page 1252 has, in its bytes 0x80 to 0x9F, as
/// the Unicode Consortium's mapping of the code page (`CP1252.TXT`) gives them.
const CODE_PAGE_1252_ABOVE_LATIN_1: [char; 27] = [
    '\u{0152}', '\u{0153}', '\u{0160}', '\u{0161}', '\u{0178}', '\u{017D}', '\u{017E}', '\u{0192}',
    '\u{02C6}', '\u{02DC}', '\u{2013}', '\u{2014}', '\u{2018}', '\u{2019}', '\u{201A}', '\u{201C}',
    '\u{201D}', '\u{201E}', '\u{2020}', '\u{2021}', '\u{2022}', '\u{2026}', '\u{2030}', '\u{2039}',
    '\u{203A}', '\u{20AC}', '\u{2122}',
];

/// Whether Windows code page 1252 has the character: ASCII, the Latin-1 characters from U+00A0
/// and the 27 characters that its bytes 0x80 to 0x9F give.
pub(crate) fn in_code_page_1252(ch: char) -> bool {
    matches!(ch, '\0'..='\u{7F}' | '\u{A0}'..='\u{FF}')
        || CODE_PAGE_1252_ABOVE_LATIN_1.contains(&ch)
}

#[cfg(test)]
mod tests {
    use super::{CharacterClass, in_code_page_1252};

    const CLASSES: [CharacterClass; 6] = [
        CharacterClass::FullWidthCell,
        CharacterClass::EastAsianFont,
        CharacterClass::EastAsianSpacing,
        CharacterClass::SplitLetter,
        CharacterClass::SplitPunctuation,
        CharacterClass::SplitSymbol,
    ];

    #[test]
    fn tells_the_characters_of_code_page_1252() {
        for ch in [
            'A', '\u{00E9}', '\u{00FF}', '\u{0160}', '\u{2014}', '\u{20AC}', '\u{2122}',
        ] {
            assert!(in_code_page_1252(ch), "{ch}");
        }
        for ch in [
            '\u{0085}', '\u{010D}', '\u{0410}', '\u{03B1}', '\u{2015}', '\u{2116}',
        ] {
            assert!(!in_code_page_1252(ch), "{ch}");
        }
    }

    #[test]
    fn lists_each_class_s_ranges_in_order_without_overlap() {
        for class in CLASSES {
            let ends: Vec<(char, char)> = class.blocks().iter().map(|b| b.ends()).collect();
            for (first, last) in &ends {
                assert!(first <= last, "{class:?}");
            }
            for pair in ends.windows(2) {
                assert!(pair[0].1 < pair[1].0, "{class:?} {pair:?}");
            }
        }
    }

    #[test]
    fn tells_full_width_characters_of_a_character_grid() {
        let full_width = |ch| CharacterClass::FullWidthCell.contains(ch);
        // Ideographs, kana, Hangul, East Asian punctuation and full-width forms fill a cell.
        for ch in ['原', 'の', 'カ', '한', '、', '(', '1', 'A'] {
            assert!(full_width(ch), "{ch}");
        }
        // Latin letters, digits, spaces and half-width katakana fill half of one.
        for ch in ['a', '4', ' ', 'カ', '-'] {
            assert!(!full_width(ch), "{ch}");
        }
    }

    #[test]
    fn holds_the_first_and_last_character_of_each_range_and_the_gaps_between_as_before() {
        // (character, full-width cell, East Asian font, East Asian spacing): the edges of each
        // range and the characters just outside them, where the classes differ.
        let cases = [
            ('A', false, false, false),
            ('0', false, false, false),
            ('\u{10FF}', false, false, false),
            ('\u{1100}', true, true, false),
            ('\u{11FF}', true, true, false),
            ('\u{1200}', false, false, false),
            ('\u{2E7F}', false, false, false),
            ('\u{2E80}', true, true, false),
            ('\u{2FDF}', true, true, false),
            ('\u{2FE0}', true, false, false),
            ('\u{2FFF}', true, false, false),
            ('\u{3000}', true, true, false),
            ('\u{303F}', true, true, false),
            ('\u{3040}', true, true, true),
            ('\u{30FF}', true, true, true),
            ('\u{3100}', true, true, false),
            ('\u{33FF}', true, true, false),
            ('\u{3400}', true, true, true),
            ('\u{4DBF}', true, true, true),
            ('\u{4DC0}', true, true, false),
            ('\u{4DFF}', true, true, false),
            ('\u{4E00}', true, true, true),
            ('\u{9FFF}', true, true, true),
            ('\u{A000}', false, false, false),
            ('\u{A95F}', false, false, false),
            ('\u{A960}', false, true, false),
            ('\u{A97F}', false, true, false),
            ('\u{A980}', false, false, false),
            ('\u{ABFF}', false, false, false),
            ('\u{AC00}', true, true, true),
            ('\u{D7AF}', true, true, true),
            ('\u{D7B0}', false, false, false),
            ('\u{F8FF}', false, false, false),
            ('\u{F900}', true, true, true),
            ('\u{FAFF}', true, true, true),
            ('\u{FB00}', false, false, false),
            ('\u{FE2F}', false, false, false),
            ('\u{FE30}', true, true, false),
            ('\u{FE4F}', true, true, false),
            ('\u{FE50}', false, false, false),
            ('\u{FEFF}', false, false, false),
            ('\u{FF00}', true, true, false),
            ('\u{FF60}', true, true, false),
            ('\u{FF61}', false, true, false),
            ('\u{FFDF}', false, true, false),
            ('\u{FFE0}', true, true, false),
            ('\u{FFE6}', true, true, false),
            ('\u{FFE7}', false, true, false),
            ('\u{FFEF}', false, true, false),
            ('\u{FFF0}', false, false, false),
            ('\u{1FFFF}', false, false, false),
            ('\u{20000}', false, true, false),
            ('\u{2FFFF}', false, true, false),
            ('\u{30000}', false, false, false),
        ];
        let east_asian = [
            CharacterClass::FullWidthCell,
            CharacterClass::EastAsianFont,
            CharacterClass::EastAsianSpacing,
        ];
        for (ch, cell, font, spacing) in cases {
            let held = east_asian.map(|class| class.contains(ch));
            assert_eq!(held, [cell, font, spacing], "U+{:04X}", u32::from(ch));
        }
    }
}