mod forms;
mod references;
pub use forms::Form;
pub use references::{NumberContext, ReferenceKind};
use std::collections::HashMap;
use std::num::NonZeroU32;
use std::rc::Rc;
use f_office_paint::Image;
use f_office_units::Length;
use f_office_xml::enumeration::{Values, another, own};
use f_office_xml::{Document, NodeId};
use crate::ns::{A, MC, O, R, V, W, WP};
use crate::numbers;
use crate::on_off;
use crate::params::{
ALPHABET_LETTERS, CARDINAL_TEXT_LIMIT, DECIMAL_PLACES, LETTER_LIMIT, LIST_LEVELS as LEVELS,
ROMAN_LIMIT, ROMAN_NUMERALS, SIGN_REPEATS,
};
use crate::props::{ParaProps, RunProps};
use crate::reader::settings::{BuiltIn, ReaderSettings};
use crate::reader::{PartReader, child_val};
const BUILT_IN: &str = "built-in ";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Format {
Decimal,
DecimalZero,
LowerLetter,
UpperLetter,
LowerRoman,
UpperRoman,
CardinalText,
OrdinalText,
Signs(Form),
Bullet,
Nothing,
}
pub(crate) const NUMBER_FORMATS: &[&str] = &[
"decimal",
"upperRoman",
"lowerRoman",
"upperLetter",
"lowerLetter",
"ordinal",
"cardinalText",
"ordinalText",
"hex",
"chicago",
"ideographDigital",
"japaneseCounting",
"aiueo",
"iroha",
"decimalFullWidth",
"decimalHalfWidth",
"japaneseLegal",
"japaneseDigitalTenThousand",
"decimalEnclosedCircle",
"decimalFullWidth2",
"aiueoFullWidth",
"irohaFullWidth",
"decimalZero",
"bullet",
"ganada",
"chosung",
"decimalEnclosedFullstop",
"decimalEnclosedParen",
"decimalEnclosedCircleChinese",
"ideographEnclosedCircle",
"ideographTraditional",
"ideographZodiac",
"ideographZodiacTraditional",
"taiwaneseCounting",
"ideographLegalTraditional",
"taiwaneseCountingThousand",
"taiwaneseDigital",
"chineseCounting",
"chineseLegalSimplified",
"chineseCountingThousand",
"koreanDigital",
"koreanCounting",
"koreanLegal",
"koreanDigital2",
"vietnameseCounting",
"russianLower",
"russianUpper",
"none",
"numberInDash",
"hebrew1",
"hebrew2",
"arabicAlpha",
"arabicAbjad",
"hindiVowels",
"hindiConsonants",
"hindiNumbers",
"hindiCounting",
"thaiLetters",
"thaiNumbers",
"thaiCounting",
"bahtText",
"dollarText",
"custom",
];
pub(crate) const FORMAT: &Values<Format> = &Values::with_others(
&[
own("decimal", Format::Decimal),
own("decimalZero", Format::DecimalZero),
own("lowerLetter", Format::LowerLetter),
own("upperLetter", Format::UpperLetter),
own("lowerRoman", Format::LowerRoman),
own("upperRoman", Format::UpperRoman),
own("cardinalText", Format::CardinalText),
own("ordinalText", Format::OrdinalText),
own("bullet", Format::Bullet),
own("none", Format::Nothing),
own("ordinal", signs(Form::Ordinal)),
own(
"chicago",
signs(Form::Repeated(&forms::CHICAGO, SIGN_REPEATS)),
),
own(
"ideographDigital",
signs(Form::Digits(&forms::IDEOGRAPH_DIGITS)),
),
own(
"japaneseCounting",
signs(Form::Counting(&forms::JAPANESE_COUNTING)),
),
own("aiueo", signs(Form::Cycled(&forms::AIUEO))),
own("iroha", signs(Form::Cycled(&forms::IROHA))),
own(
"decimalFullWidth",
signs(Form::Digits(&forms::FULL_WIDTH_DIGITS)),
),
own("decimalHalfWidth", Format::Decimal),
own(
"japaneseLegal",
signs(Form::Counting(&forms::JAPANESE_LEGAL)),
),
own(
"japaneseDigitalTenThousand",
signs(Form::DigitsBelowTenThousand(&forms::IDEOGRAPH_DIGITS)),
),
own(
"decimalEnclosedCircle",
signs(Form::Listed(&forms::ENCLOSED_CIRCLE)),
),
own(
"decimalFullWidth2",
signs(Form::Digits(&forms::FULL_WIDTH_DIGITS)),
),
own(
"aiueoFullWidth",
signs(Form::Cycled(&forms::AIUEO_FULL_WIDTH)),
),
own(
"irohaFullWidth",
signs(Form::Cycled(&forms::IROHA_FULL_WIDTH)),
),
own("ganada", signs(Form::Cycled(&forms::GANADA))),
own("chosung", signs(Form::Cycled(&forms::CHOSUNG))),
own(
"decimalEnclosedFullstop",
signs(Form::Listed(&forms::ENCLOSED_FULL_STOP)),
),
own(
"decimalEnclosedParen",
signs(Form::Listed(&forms::ENCLOSED_PARENTHESES)),
),
own(
"decimalEnclosedCircleChinese",
signs(Form::Listed(ENCLOSED_CIRCLE_TO_TEN)),
),
own(
"ideographEnclosedCircle",
signs(Form::Listed(&forms::IDEOGRAPH_ENCLOSED_CIRCLE)),
),
own("ideographTraditional", signs(Form::Listed(&forms::STEMS))),
own("ideographZodiac", signs(Form::Listed(&forms::BRANCHES))),
own("ideographZodiacTraditional", signs(Form::StemsAndBranches)),
own(
"taiwaneseCounting",
signs(Form::ShortCounting(
&forms::CHINESE_COUNTING,
&forms::CIRCLE_ZERO_DIGITS,
)),
),
own(
"ideographLegalTraditional",
signs(Form::Counting(&forms::TRADITIONAL_LEGAL)),
),
own(
"taiwaneseCountingThousand",
signs(Form::Counting(&forms::TAIWANESE_COUNTING)),
),
own(
"taiwaneseDigital",
signs(Form::Digits(&forms::CIRCLE_ZERO_DIGITS)),
),
own(
"chineseCounting",
signs(Form::ShortCounting(
&forms::CHINESE_COUNTING,
&forms::CIRCLE_ZERO_DIGITS,
)),
),
own(
"chineseLegalSimplified",
signs(Form::Counting(&forms::SIMPLIFIED_LEGAL)),
),
own(
"chineseCountingThousand",
signs(Form::Counting(&forms::CHINESE_COUNTING)),
),
own("koreanDigital", signs(Form::Digits(&forms::KOREAN_DIGITS))),
own(
"koreanCounting",
signs(Form::Counting(&forms::KOREAN_COUNTING)),
),
own("koreanLegal", signs(Form::KoreanWords)),
own("koreanDigital2", signs(Form::Digits(&forms::HANJA_DIGITS))),
own(
"russianLower",
signs(Form::Repeated(&forms::RUSSIAN_LOWER, SIGN_REPEATS)),
),
own(
"russianUpper",
signs(Form::Repeated(&forms::RUSSIAN_UPPER, SIGN_REPEATS)),
),
own("numberInDash", signs(Form::InDashes)),
own("hebrew1", signs(Form::Hebrew)),
own(
"arabicAlpha",
signs(Form::Repeated(&forms::ARABIC_ALPHA, forms::ARABIC_REPEATS)),
),
own(
"arabicAbjad",
signs(Form::Repeated(&forms::ARABIC_ABJAD, forms::ARABIC_REPEATS)),
),
own(
"hindiNumbers",
signs(Form::WrappedDigits(&forms::DEVANAGARI_DIGITS)),
),
own(
"thaiNumbers",
signs(Form::WrappedDigits(&forms::THAI_DIGITS)),
),
own("bahtText", Format::Decimal),
own("dollarText", Format::Decimal),
],
NUMBER_FORMATS,
Format::Decimal,
);
pub(crate) fn read_format(reader: &mut PartReader, node: NodeId, name: &str) -> Option<Format> {
let format = reader.enumeration(node, name, FORMAT)?;
Some(reader.number_formats().format(format))
}
const fn signs(form: Form) -> Format {
Format::Signs(form)
}
const ENCLOSED_CIRCLE_TO_TEN: &[&str] = forms::ENCLOSED_CIRCLE
.split_at(forms::IDEOGRAPH_ENCLOSED_CIRCLE.len())
.0;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Suffix {
Tab,
Space,
Nothing,
Legacy {
space: Length,
indent: Length,
},
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LabelAlign {
#[default]
Left,
Center,
Right,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Level {
pub start: i64,
pub format: Format,
pub text: String,
pub legal: bool,
pub suffix: Suffix,
pub align: LabelAlign,
pub para: ParaProps,
pub run: RunProps,
pub picture: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Label {
pub text: String,
pub value: i64,
pub reference: NumberContext,
pub run: RunProps,
pub suffix: Suffix,
pub align: LabelAlign,
pub picture: bool,
pub(crate) bullet_image: Option<Image>,
pub(crate) bullet_size: Option<(Length, Length)>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct PictureBullet {
embed: Option<String>,
size: Option<(Length, Length)>,
image: Option<Image>,
}
#[derive(Clone, Debug, Default)]
struct Instance {
abstract_id: String,
starts: HashMap<usize, i64>,
levels: HashMap<usize, Level>,
}
#[derive(Debug, Default)]
struct ListDefinitions {
abstracts: HashMap<String, HashMap<usize, Level>>,
instances: HashMap<NonZeroU32, Instance>,
pictures: HashMap<String, PictureBullet>,
part: Rc<f_office_warnings::Name>,
built_in_for_undefined: bool,
}
#[derive(Clone, Debug, Default)]
pub struct Numbering {
definitions: Rc<ListDefinitions>,
counters: ListCounters,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ListCounters {
levels: [HashMap<String, [Option<i64>; LEVELS]>; 2],
used: [std::collections::HashSet<NonZeroU32>; 2],
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Text {
New = 0,
Original = 1,
}
impl ListDefinitions {
fn read_abstract(&mut self, reader: &mut PartReader, node: NodeId) {
let doc = reader.doc;
let Some(id) = doc.attribute(node, Some(W), "abstractNumId") else {
return;
};
let levels = doc
.child_elements(node)
.filter(|n| doc.is(*n, W, "lvl"))
.filter_map(|n| read_level(reader, n))
.collect();
self.abstracts.insert(id.to_owned(), levels);
}
fn read_instance(&mut self, reader: &mut PartReader, node: NodeId) {
let doc = reader.doc;
let Some(id) = reader
.number::<u32>(node, "numId", numbers::NOT_NEGATIVE)
.and_then(NonZeroU32::new)
else {
return;
};
let Some(abstract_id) = child_val(doc, node, "abstractNumId") else {
return;
};
let mut instance = Instance {
abstract_id: abstract_id.to_owned(),
..Instance::default()
};
for item in doc
.child_elements(node)
.filter(|n| doc.is(*n, W, "lvlOverride"))
{
read_override(reader, item, &mut instance);
}
self.instances.insert(id, instance);
}
}
impl ListDefinitions {
fn for_undefined(built_in: BuiltIn) -> Self {
let mut definitions = Self::default();
if built_in.for_undefined {
definitions.built_in_for_undefined = true;
definitions
.abstracts
.insert(BUILT_IN.to_owned(), built_in_levels(built_in));
}
definitions
}
}
fn built_in_levels(built_in: BuiltIn) -> HashMap<usize, Level> {
(0..LEVELS)
.map(|index| {
let para = match built_in.indent_step {
None => ParaProps::default(),
Some(step) => ParaProps {
indent_left: i64::try_from(index + 1)
.ok()
.and_then(|steps| step.checked_mul(steps)),
indent_first: Length::ZERO.checked_sub(step),
..ParaProps::default()
},
};
let level = Level {
start: 1,
format: Format::Decimal,
text: format!("%{}.", index + 1),
legal: false,
suffix: Suffix::Tab,
align: LabelAlign::Left,
para,
run: RunProps::default(),
picture: None,
};
(index, level)
})
.collect()
}
impl Numbering {
pub(crate) fn part(&self) -> &Rc<f_office_warnings::Name> {
&self.definitions.part
}
pub(crate) fn read(reader: &mut PartReader, root: NodeId, settings: ReaderSettings) -> Self {
let doc = reader.doc;
let pictures = doc
.child_elements(root)
.filter(|node| doc.is(*node, W, "numPicBullet"))
.filter_map(|node| {
let id = doc.attribute(node, Some(W), "numPicBulletId")?;
let (embed, size) = bullet_image_spec(doc, node);
let bullet = PictureBullet {
embed,
size,
image: None,
};
Some((id.to_owned(), bullet))
})
.collect();
let mut definitions = ListDefinitions {
pictures,
part: Rc::new(f_office_warnings::Name::new(reader.part())),
..ListDefinitions::for_undefined(settings.built_in_list())
};
let mut uses_style = HashMap::new();
let mut defines_style = HashMap::new();
for node in doc.child_elements(root) {
if doc.is(node, W, "abstractNum") {
let id = doc.attribute(node, Some(W), "abstractNumId").unwrap_or("");
if let Some(style) = child_val(doc, node, "numStyleLink") {
uses_style.insert(id.to_owned(), style.to_owned());
}
if let Some(style) = child_val(doc, node, "styleLink") {
defines_style.insert(style.to_owned(), id.to_owned());
}
definitions.read_abstract(reader, node);
} else if doc.is(node, W, "num") {
definitions.read_instance(reader, node);
}
}
for instance in definitions.instances.values_mut() {
let defining = uses_style
.get(&instance.abstract_id)
.and_then(|style| defines_style.get(style));
if let Some(defining) = defining {
instance.abstract_id.clone_from(defining);
}
}
Self {
definitions: Rc::new(definitions),
counters: ListCounters::default(),
}
}
pub(crate) fn has_picture_embeds(&self) -> bool {
self.definitions
.pictures
.values()
.any(|bullet| bullet.embed.is_some())
}
pub(crate) fn attach_images(&mut self, find: &mut impl FnMut(&str) -> Option<Image>) {
let Some(definitions) = Rc::get_mut(&mut self.definitions) else {
return;
};
let mut keys: Vec<String> = definitions.pictures.keys().cloned().collect();
keys.sort();
for key in keys {
if let Some(bullet) = definitions.pictures.get_mut(&key)
&& let Some(embed) = bullet.embed.as_deref()
{
bullet.image = find(embed);
}
}
}
#[must_use]
pub(crate) fn without_part(settings: ReaderSettings) -> Self {
let built_in = settings.built_in_list();
let mut definitions = ListDefinitions::for_undefined(built_in);
definitions
.abstracts
.insert(BUILT_IN.to_owned(), built_in_levels(built_in));
Self {
definitions: Rc::new(definitions),
counters: ListCounters::default(),
}
}
fn list(&self, num_id: NonZeroU32) -> Option<(&str, Option<&Instance>)> {
let definitions = &self.definitions;
if let Some(instance) = definitions.instances.get(&num_id)
&& (!definitions.built_in_for_undefined
|| definitions.abstracts.contains_key(&instance.abstract_id))
{
return Some((&instance.abstract_id, Some(instance)));
}
self.definitions
.abstracts
.contains_key(BUILT_IN)
.then_some((BUILT_IN, None))
}
#[must_use]
pub fn level(&self, num_id: NonZeroU32, ilvl: usize) -> Option<&Level> {
self.own_level(num_id, self.used_level(num_id, ilvl)?)
}
fn used_level(&self, num_id: NonZeroU32, ilvl: usize) -> Option<usize> {
(0..=ilvl)
.rev()
.find(|index| self.own_level(num_id, *index).is_some())
}
fn own_level(&self, num_id: NonZeroU32, ilvl: usize) -> Option<&Level> {
let (abstract_id, instance) = self.list(num_id)?;
instance
.and_then(|i| i.levels.get(&ilvl))
.or_else(|| self.definitions.abstracts.get(abstract_id)?.get(&ilvl))
}
fn start(&self, num_id: NonZeroU32, ilvl: usize) -> Option<i64> {
let (_, instance) = self.list(num_id)?;
instance
.and_then(|i| i.starts.get(&ilvl))
.copied()
.or_else(|| self.level(num_id, ilvl).map(|l| l.start))
}
fn counters_of(
&mut self,
text: Text,
num_id: NonZeroU32,
) -> Option<&mut [Option<i64>; LEVELS]> {
let index = text as usize;
let first = self.counters.used.get_mut(index)?.insert(num_id);
let (key, restarts) = self.counter_key(num_id, first)?;
let counters = self
.counters
.levels
.get_mut(index)?
.entry(key)
.or_insert([None; LEVELS]);
for (index, slot) in counters.iter_mut().enumerate() {
if restarts.contains(&index) {
*slot = None;
}
}
Some(counters)
}
fn counter_key(&self, num_id: NonZeroU32, first: bool) -> Option<(String, Vec<usize>)> {
let (abstract_id, instance) = self.list(num_id)?;
let shared = self.definitions.built_in_for_undefined;
let key = match instance {
Some(_) => abstract_id.to_owned(),
None if shared => BUILT_IN.to_owned(),
None => format!("{BUILT_IN}{num_id}"),
};
let restarts = match instance {
Some(instance) if first => instance.starts.keys().copied().collect(),
None if first && shared => (0..LEVELS).collect(),
_ => Vec::new(),
};
Some((key, restarts))
}
#[must_use]
pub const fn counters(&self) -> &ListCounters {
&self.counters
}
#[must_use]
pub fn with_counters(&self, counters: ListCounters) -> Self {
Self {
definitions: Rc::clone(&self.definitions),
counters,
}
}
pub fn next_label(
&mut self,
new: Option<(NonZeroU32, usize)>,
original: Option<(NonZeroU32, usize)>,
) -> Option<Label> {
let new = new.and_then(|(num_id, ilvl)| self.count(Text::New, num_id, ilvl));
let original = original.and_then(|(num_id, ilvl)| self.count(Text::Original, num_id, ilvl));
match (original, new) {
(Some(original), Some(mut new)) if original.text != new.text => {
new.text = original.text + &new.text;
Some(new)
}
(original, new) => new.or(original),
}
}
fn count(&mut self, text: Text, num_id: NonZeroU32, ilvl: usize) -> Option<Label> {
let ilvl = self.used_level(num_id, ilvl)?;
let level = self.level(num_id, ilvl)?.clone();
let start = self.start(num_id, ilvl).unwrap_or(level.start);
let shallower: Vec<i64> = (0..ilvl)
.map(|index| self.start(num_id, index).unwrap_or(0))
.collect();
let counters = self.counters_of(text, num_id)?;
for (slot, first) in counters.iter_mut().zip(shallower) {
slot.get_or_insert(first);
}
let value = counters
.get(ilvl)
.copied()
.flatten()
.map_or(start, |v| v.saturating_add(1));
if let Some(slot) = counters.get_mut(ilvl) {
*slot = Some(value);
}
for deeper in counters.iter_mut().skip(ilvl + 1) {
*deeper = None;
}
let snapshot = *counters;
let text = self.label_text(num_id, &level, &snapshot);
let reference = NumberContext {
list: num_id,
values: snapshot
.iter()
.take(ilvl + 1)
.map(|value| value.unwrap_or(0))
.collect(),
patterns: (0..=ilvl)
.map(|index| {
let Some(level) = self.level(num_id, index) else {
return (index, String::new());
};
let first = (0..=index)
.find(|ancestor| level.text.contains(&format!("%{}", ancestor + 1)))
.unwrap_or(index);
(first, self.label_text(num_id, level, &snapshot))
})
.collect(),
};
let bullet = level
.picture
.as_ref()
.and_then(|id| self.definitions.pictures.get(id));
let picture = bullet.is_some();
let bullet_image = bullet.and_then(|bullet| bullet.image.clone());
let bullet_size = bullet.and_then(|bullet| bullet.size);
Some(Label {
text,
value,
reference,
run: level.run,
suffix: level.suffix,
align: level.align,
picture,
bullet_image,
bullet_size,
})
}
fn label_text(
&self,
num_id: NonZeroU32,
level: &Level,
counters: &[Option<i64>; LEVELS],
) -> String {
let mut text = level.text.clone();
for (index, value) in counters.iter().enumerate() {
let placeholder = format!("%{}", index + 1);
if !text.contains(&placeholder) {
continue;
}
let format = self
.level(num_id, index)
.map_or(Format::Decimal, |l| l.format);
let format = if level.legal && !matches!(format, Format::DecimalZero | Format::Nothing)
{
Format::Decimal
} else {
format
};
if format == Format::Nothing {
text = text.replace(&placeholder, "");
continue;
}
let value = value.or_else(|| self.start(num_id, index)).unwrap_or(0);
let number = format_number(value, format);
text = text.replace(&placeholder, &number);
}
text
}
}
const SUFFIX: &Values<Suffix> = &Values::new(&[
own("tab", Suffix::Tab),
own("space", Suffix::Space),
own("nothing", Suffix::Nothing),
]);
const LEVEL_JC: &Values<LabelAlign> = &Values::new(&[
own("left", LabelAlign::Left),
own("start", LabelAlign::Left),
own("center", LabelAlign::Center),
own("right", LabelAlign::Right),
own("end", LabelAlign::Right),
another("both", LabelAlign::Left),
another("distribute", LabelAlign::Left),
another("mediumKashida", LabelAlign::Left),
another("highKashida", LabelAlign::Left),
another("lowKashida", LabelAlign::Left),
another("thaiDistribute", LabelAlign::Left),
another("numTab", LabelAlign::Left),
]);
fn read_level(reader: &mut PartReader, node: NodeId) -> Option<(usize, Level)> {
let doc = reader.doc;
let ilvl = reader.number(node, "ilvl", numbers::indices(LEVELS))?;
let level = Level {
start: doc
.child(node, W, "start")
.and_then(|n| reader.number(n, "val", numbers::ANY))
.unwrap_or(0),
format: doc
.child(node, W, "numFmt")
.and_then(|n| read_format(reader, n, "val"))
.unwrap_or(Format::Decimal),
text: child_val(doc, node, "lvlText").unwrap_or("").to_owned(),
legal: doc
.child(node, W, "isLgl")
.is_some_and(|n| on_off::element(doc, n, W)),
suffix: legacy(reader, node).unwrap_or_else(|| {
doc.child(node, W, "suff")
.and_then(|n| reader.enumeration(n, "val", SUFFIX))
.unwrap_or(Suffix::Tab)
}),
align: doc
.child(node, W, "lvlJc")
.and_then(|n| reader.enumeration(n, "val", LEVEL_JC))
.unwrap_or_default(),
para: doc
.child(node, W, "pPr")
.map_or_default(|p| ParaProps::read(reader, p)),
run: doc
.child(node, W, "rPr")
.map_or_default(|r| RunProps::read(reader, r)),
picture: child_val(doc, node, "lvlPicBulletId").map(str::to_owned),
};
Some((ilvl, level))
}
fn read_override(reader: &mut PartReader, node: NodeId, instance: &mut Instance) {
let doc = reader.doc;
let Some(ilvl) = reader.number::<usize>(node, "ilvl", numbers::NOT_NEGATIVE) else {
return;
};
let start = doc
.child(node, W, "startOverride")
.and_then(|n| reader.number(n, "val", numbers::ANY));
if let Some(start) = start {
instance.starts.insert(ilvl, start);
}
if let Some((_, level)) = doc
.child(node, W, "lvl")
.and_then(|n| read_level(reader, n))
{
instance.levels.insert(ilvl, level);
}
}
fn legacy(reader: &mut PartReader, node: NodeId) -> Option<Suffix> {
let doc = reader.doc;
let legacy = doc.child(node, W, "legacy")?;
if doc
.attribute(legacy, Some(W), "legacy")
.and_then(on_off::read)
!= Some(true)
{
return None;
}
let mut twips = |name| reader.twips(legacy, name).unwrap_or(Length::ZERO);
Some(Suffix::Legacy {
space: twips("legacySpace"),
indent: twips("legacyIndent"),
})
}
pub(crate) fn format_number(value: i64, format: Format) -> String {
match format {
Format::Decimal | Format::Bullet | Format::Nothing => value.to_string(),
Format::DecimalZero => format!("{value:02}"),
Format::LowerLetter => letters(value),
Format::UpperLetter => letters(value).to_uppercase(),
Format::LowerRoman => roman(value),
Format::UpperRoman => roman(value).to_uppercase(),
Format::CardinalText => cardinal_text(value),
Format::OrdinalText => ordinal_text(value),
Format::Signs(form) => form.write(value).unwrap_or_else(|| value.to_string()),
}
}
fn ordinal_text(value: i64) -> String {
if !(1..CARDINAL_TEXT_LIMIT).contains(&value) {
return value.to_string();
}
let words = forms::ordinal_words(&english(value));
let mut chars = words.chars();
chars
.next()
.map_or_default(|first| first.to_uppercase().chain(chars).collect())
}
fn cardinal_text(value: i64) -> String {
if !(1..CARDINAL_TEXT_LIMIT).contains(&value) {
return value.to_string();
}
let words = english(value);
let mut chars = words.chars();
chars
.next()
.map_or_default(|first| first.to_uppercase().chain(chars).collect())
}
fn english(value: i64) -> String {
const ONES: [&str; 20] = [
"zero",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
"eighteen",
"nineteen",
];
const TENS: [&str; 10] = [
"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety",
];
let word = |words: &[&'static str], n: i64| {
usize::try_from(n)
.ok()
.and_then(|n| words.get(n).copied())
.unwrap_or_default()
};
let joined = |head: String, rest: i64| {
if rest == 0 {
head
} else {
format!("{head} {}", english(rest))
}
};
let (decade, hundred, thousand) = DECIMAL_PLACES;
let own_words = i64::try_from(ONES.len()).unwrap_or(0);
match value {
v if (0..own_words).contains(&v) => word(&ONES, value).to_owned(),
v if (own_words..hundred).contains(&v) => {
let tens = word(&TENS, value / decade);
if value % decade == 0 {
tens.to_owned()
} else {
format!("{tens}-{}", word(&ONES, value % decade))
}
}
v if (hundred..thousand).contains(&v) => joined(
format!("{} hundred", word(&ONES, value / hundred)),
value % hundred,
),
_ => joined(
format!("{} thousand", english(value / thousand)),
value % thousand,
),
}
}
fn letters(value: i64) -> String {
if !(1..LETTER_LIMIT).contains(&value) {
return value.to_string();
}
let index = u8::try_from((value - 1) % ALPHABET_LETTERS).unwrap_or(0);
let count = usize::try_from((value - 1) / ALPHABET_LETTERS + 1).unwrap_or(1);
char::from(b'a' + index).to_string().repeat(count)
}
fn roman(value: i64) -> String {
if !(1..ROMAN_LIMIT).contains(&value) {
return value.to_string();
}
let mut rest = value;
let mut out = String::new();
for (amount, numeral) in ROMAN_NUMERALS {
while rest >= amount {
out.push_str(numeral);
rest -= amount;
}
}
out
}
fn bullet_image_spec(doc: &Document, node: NodeId) -> (Option<String>, Option<(Length, Length)>) {
if doc.is(node, MC, "AlternateContent") {
for choice in doc
.child_elements(node)
.filter(|child| doc.is(*child, MC, "Choice"))
{
let spec = bullet_image_spec(doc, choice);
if spec.0.is_some() {
return spec;
}
}
return doc
.child(node, MC, "Fallback")
.map_or((None, None), |fallback| bullet_image_spec(doc, fallback));
}
let embed = bullet_image_rel(doc, node);
let size = bullet_declared_size(doc, node);
(embed, size)
}
fn bullet_declared_size(doc: &Document, node: NodeId) -> Option<(Length, Length)> {
if doc.is(node, WP, "extent") {
let cx = doc
.attribute(node, None, "cx")
.and_then(f_office_drawingml::emu_length)?;
let cy = doc
.attribute(node, None, "cy")
.and_then(f_office_drawingml::emu_length)?;
return (cx > Length::ZERO && cy > Length::ZERO).then_some((cx, cy));
}
if (doc.is(node, V, "shape") || doc.is(node, V, "rect") || doc.is(node, V, "oval"))
&& let Some(style_text) = doc.attribute(node, None, "style")
{
let style = f_office_vml::css::Style::new(style_text);
if let (Some(w), Some(h)) = (
style.get("width").and_then(f_office_vml::css::length),
style.get("height").and_then(f_office_vml::css::length),
) && w > Length::ZERO
&& h > Length::ZERO
{
return Some((w, h));
}
}
doc.child_elements(node)
.find_map(|child| bullet_declared_size(doc, child))
}
fn bullet_image_rel(doc: &Document, node: NodeId) -> Option<String> {
if doc.is(node, A, "blip") {
return doc.attribute(node, Some(R), "embed").map(str::to_owned);
}
if doc.is(node, V, "imagedata") {
return doc
.attribute(node, Some(R), "id")
.or_else(|| doc.attribute(node, Some(O), "relid"))
.map(str::to_owned);
}
doc.child_elements(node)
.find_map(|child| bullet_image_rel(doc, child))
}
#[cfg(test)]
mod tests {
use std::num::NonZeroU32;
use super::{Format, Label, Numbering, Suffix, format_number, letters, roman};
use crate::reader::PartReader;
use crate::reader::settings::ReaderSettings;
use f_office_units::Length;
use f_office_xml::{Document, Limits};
fn id(num_id: u32) -> NonZeroU32 {
NonZeroU32::new(num_id).unwrap()
}
fn label(n: &mut Numbering, num_id: u32, ilvl: usize) -> Option<Label> {
let num_id = id(num_id);
n.next_label(Some((num_id, ilvl)), Some((num_id, ilvl)))
}
#[test]
fn numbers_lists_with_decimals_without_a_numbering_part() {
let mut numbering = Numbering::without_part(ReaderSettings::with_built_in_list(
crate::quirks::BuiltInList::WithoutPart,
));
let text = |n: &mut Numbering, list: u32| label(n, list, 0).map(|l| l.text);
assert_eq!(text(&mut numbering, 2), Some("1.".to_owned()));
assert_eq!(text(&mut numbering, 2), Some("2.".to_owned()));
assert_eq!(text(&mut numbering, 5), Some("1.".to_owned()));
let level = numbering.level(id(2), 1).unwrap();
assert_eq!((level.suffix, level.text.as_str()), (Suffix::Tab, "%2."));
assert_eq!(level.para.indent_left, None);
assert!(Numbering::default().level(id(2), 0).is_none());
}
#[test]
fn numbers_undefined_lists_as_instances_of_the_built_in_list_that_share_its_counters() {
use crate::quirks::BuiltInList;
let parse = |xml: &str| Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let empty = parse(
r#"<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"/>"#,
);
let other = parse(
r#"<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:num w:numId="1"><w:abstractNumId w:val="7"/></w:num></w:numbering>"#,
);
let read = |doc: &Document| {
Numbering::read(
&mut PartReader::new(doc),
doc.root().unwrap(),
ReaderSettings::with_built_in_list(BuiltInList::ForUndefined),
)
};
let numberings = [
Numbering::without_part(ReaderSettings::with_built_in_list(
BuiltInList::ForUndefined,
)),
read(&empty),
read(&other),
];
for mut numbering in numberings {
let texts: Vec<String> = [(1, 0), (1, 0), (2, 0), (1, 0), (2, 0), (3, 0), (1, 1)]
.into_iter()
.chain([(2, 0), (1, 0)])
.map(|(list, ilvl)| label(&mut numbering, list, ilvl).unwrap().text)
.collect();
assert_eq!(
texts,
["1.", "2.", "1.", "2.", "3.", "1.", "1.", "2.", "3."]
);
let step = crate::params::BUILT_IN_LIST_INDENT;
let level = numbering.level(id(1), 1).unwrap();
assert_eq!(level.para.indent_left, Some(step * 2));
assert_eq!(level.para.indent_first, Length::ZERO.checked_sub(step));
}
let mut kept = read_part(&empty);
assert!(label(&mut kept, 1, 0).is_none());
}
const NUMBERING: &str = r#"<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:abstractNum w:abstractNumId="0">
<w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl>
<w:lvl w:ilvl="1"><w:start w:val="1"/><w:numFmt w:val="lowerLetter"/><w:lvlText w:val="%1.%2)"/><w:suff w:val="space"/></w:lvl>
<w:lvl w:ilvl="2"><w:numFmt w:val="bullet"/><w:lvlText w:val="-"/><w:suff w:val="nothing"/><w:rPr><w:b/></w:rPr></w:lvl>
</w:abstractNum>
<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>
<w:num w:numId="2"><w:abstractNumId w:val="0"/><w:lvlOverride w:ilvl="0"><w:startOverride w:val="5"/></w:lvlOverride></w:num>
<w:num w:numId="3"><w:abstractNumId w:val="9"/></w:num>
</w:numbering>"#;
fn read_part(doc: &Document) -> Numbering {
let settings = ReaderSettings::with_built_in_list(crate::quirks::BuiltInList::WithoutPart);
Numbering::read(&mut PartReader::new(doc), doc.root().unwrap(), settings)
}
fn numbering() -> Numbering {
let doc = Document::parse(NUMBERING.as_bytes(), &Limits::default()).unwrap();
read_part(&doc)
}
#[test]
fn marks_the_labels_of_picture_bullets() {
let xml = r#"<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:numPicBullet w:numPicBulletId="0"><w:pict/></w:numPicBullet>
<w:abstractNum w:abstractNumId="0">
<w:lvl w:ilvl="0"><w:numFmt w:val="bullet"/><w:lvlText w:val="o"/><w:lvlPicBulletId w:val="0"/></w:lvl>
<w:lvl w:ilvl="1"><w:numFmt w:val="bullet"/><w:lvlText w:val="o"/><w:lvlPicBulletId w:val="5"/></w:lvl>
</w:abstractNum>
<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>
</w:numbering>"#;
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let mut numbering = read_part(&doc);
let mut picture = |level: usize| label(&mut numbering, 1, level).map(|l| l.picture);
assert_eq!(picture(0), Some(true));
assert_eq!(picture(1), Some(false));
}
#[test]
fn resolves_picture_bullet_relationships_for_vml_drawing_and_alternate_content() {
use super::{A, Image, MC, R, V, W};
let xml = format!(
r#"<w:numbering xmlns:w="{W}" xmlns:v="{V}" xmlns:r="{R}" xmlns:a="{A}" xmlns:mc="{MC}">
<w:numPicBullet w:numPicBulletId="0"><w:pict><v:shape><v:imagedata r:id="rId1"/></v:shape></w:pict></w:numPicBullet>
<w:numPicBullet w:numPicBulletId="1"><w:drawing><a:blip r:embed="rId2"/></w:drawing></w:numPicBullet>
<w:numPicBullet w:numPicBulletId="2"><mc:AlternateContent><mc:Choice Requires="w14"><w:drawing><a:blip r:embed="rId3"/></w:drawing></mc:Choice><mc:Fallback><w:pict><v:shape><v:imagedata r:id="rId4"/></v:shape></w:pict></mc:Fallback></mc:AlternateContent></w:numPicBullet>
<w:abstractNum w:abstractNumId="0">
<w:lvl w:ilvl="0"><w:numFmt w:val="bullet"/><w:lvlText w:val="o"/><w:lvlPicBulletId w:val="0"/></w:lvl>
<w:lvl w:ilvl="1"><w:numFmt w:val="bullet"/><w:lvlText w:val="o"/><w:lvlPicBulletId w:val="1"/></w:lvl>
<w:lvl w:ilvl="2"><w:numFmt w:val="bullet"/><w:lvlText w:val="o"/><w:lvlPicBulletId w:val="2"/></w:lvl>
</w:abstractNum>
<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>
</w:numbering>"#
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let mut numbering = read_part(&doc);
assert!(numbering.has_picture_embeds());
let mut seen = Vec::new();
numbering.attach_images(&mut |rid| {
seen.push(rid.to_owned());
Some(Image::new(rid.as_bytes().to_vec()))
});
assert_eq!(seen, ["rId1", "rId2", "rId3"]);
for (ilvl, expected) in [(0, b"rId1" as &[u8]), (1, b"rId2"), (2, b"rId3")] {
let lbl = label(&mut numbering, 1, ilvl).unwrap();
assert!(lbl.picture);
assert_eq!(lbl.bullet_image.as_ref().unwrap().data.as_ref(), expected);
}
}
#[test]
fn keeps_the_level_text_of_a_level_without_a_number_format() {
let xml = r#"<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:abstractNum w:abstractNumId="0">
<w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="none"/><w:lvlText w:val="(a)"/></w:lvl>
<w:lvl w:ilvl="1"><w:start w:val="1"/><w:numFmt w:val="none"/><w:lvlText w:val="Part %1-%2."/></w:lvl>
</w:abstractNum>
<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>
</w:numbering>"#;
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let mut numbering = read_part(&doc);
let mut text = |level: usize| label(&mut numbering, 1, level).map(|l| l.text);
assert_eq!(text(0), Some("(a)".to_owned()));
assert_eq!(text(1), Some("Part -.".to_owned()));
}
#[test]
fn writes_legal_labels_in_digits() {
let xml = r#"<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:abstractNum w:abstractNumId="0">
<w:lvl w:ilvl="0"><w:start w:val="3"/><w:numFmt w:val="cardinalText"/><w:lvlText w:val="Article %1"/></w:lvl>
<w:lvl w:ilvl="1"><w:start w:val="8"/><w:numFmt w:val="decimalZero"/><w:isLgl/><w:lvlText w:val="Section %1.%2"/></w:lvl>
<w:lvl w:ilvl="2"><w:start w:val="2"/><w:numFmt w:val="lowerRoman"/><w:isLgl w:val="0"/><w:lvlText w:val="%1.%3"/></w:lvl>
</w:abstractNum>
<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>
</w:numbering>"#;
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let mut numbering = read_part(&doc);
let mut text = |level: usize| label(&mut numbering, 1, level).map(|l| l.text);
assert_eq!(text(0).as_deref(), Some("Article Three"));
assert_eq!(text(1).as_deref(), Some("Section 3.08"));
assert_eq!(text(2).as_deref(), Some("Three.ii"));
}
#[test]
fn takes_the_levels_of_a_linked_numbering_style() {
let xml = r#"<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:abstractNum w:abstractNumId="1"><w:styleLink w:val="Outline"/><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1)"/></w:lvl></w:abstractNum>
<w:abstractNum w:abstractNumId="2"><w:numStyleLink w:val="Outline"/></w:abstractNum>
<w:abstractNum w:abstractNumId="3"><w:numStyleLink w:val="Missing"/></w:abstractNum>
<w:num w:numId="5"><w:abstractNumId w:val="1"/></w:num>
<w:num w:numId="6"><w:abstractNumId w:val="2"/></w:num>
<w:num w:numId="7"><w:abstractNumId w:val="3"/></w:num>
</w:numbering>"#;
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let mut n = read_part(&doc);
let text = |n: &mut Numbering, list: u32| label(n, list, 0).map(|l| l.text);
assert_eq!(text(&mut n, 6), Some("1)".to_owned()));
assert_eq!(text(&mut n, 5), Some("2)".to_owned()));
assert_eq!(text(&mut n, 7), None);
}
#[test]
fn reads_the_gap_of_legacy_levels() {
let suffix = |legacy: &str| {
let xml = NUMBERING.replace(
r#"<w:suff w:val="space"/>"#,
&format!(r#"<w:suff w:val="space"/>{legacy}"#),
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
read_part(&doc).level(id(1), 1).unwrap().suffix
};
let legacy = r#"<w:legacy w:legacy="1" w:legacySpace="20" w:legacyIndent="274"/>"#;
let gap = Suffix::Legacy {
space: Length::from_twips(20).unwrap(),
indent: Length::from_twips(274).unwrap(),
};
assert_eq!(suffix(legacy), gap);
assert_eq!(suffix(r#"<w:legacy w:legacy="0"/>"#), Suffix::Space);
assert_eq!(suffix(""), Suffix::Space);
}
#[test]
fn counts_levels_and_resets_deeper_ones() {
let mut n = numbering();
let text = |n: &mut Numbering, ilvl| label(n, 1, ilvl).unwrap().text;
assert_eq!(text(&mut n, 0), "1.");
assert_eq!(text(&mut n, 1), "1.a)");
assert_eq!(text(&mut n, 1), "1.b)");
assert_eq!(text(&mut n, 0), "2.");
assert_eq!(text(&mut n, 1), "2.a)");
let bullet = label(&mut n, 1, 2).unwrap();
assert_eq!(
(bullet.text.as_str(), bullet.suffix),
("-", Suffix::Nothing)
);
assert_eq!(bullet.run.bold, Some(true));
}
#[test]
fn shows_the_first_number_of_a_level_that_has_not_been_counted() {
let text = |num_id| label(&mut numbering(), num_id, 1).unwrap().text;
assert_eq!(text(1), "1.a)");
assert_eq!(text(2), "5.a)");
}
#[test]
fn counts_the_first_number_of_a_level_that_a_deeper_paragraph_shows() {
let mut n = numbering();
let text = |n: &mut Numbering, ilvl| label(n, 2, ilvl).unwrap().text;
assert_eq!(text(&mut n, 1), "5.a)");
assert_eq!(text(&mut n, 1), "5.b)");
assert_eq!(text(&mut n, 0), "6.");
}
#[test]
fn keeps_no_instance_of_the_id_0() {
let xml = r#"<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:abstractNum w:abstractNumId="0"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/></w:lvl></w:abstractNum><w:num w:numId="0"><w:abstractNumId w:val="0"/></w:num><w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num></w:numbering>"#;
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let mut n = read_part(&doc);
assert_eq!(
n.definitions.instances.keys().copied().collect::<Vec<_>>(),
[id(1)]
);
assert_eq!(label(&mut n, 1, 0).unwrap().text, "1.");
}
#[test]
fn reads_levels_and_overrides() {
let mut n = numbering();
let level = n.level(id(1), 0).unwrap();
assert_eq!(level.para.indent_left, Length::from_twips(720));
assert_eq!(n.level(id(1), 1).unwrap().suffix, Suffix::Space);
assert_eq!(label(&mut n, 2, 0).unwrap().text, "5.");
assert!(label(&mut n, 3, 0).is_none());
assert!(label(&mut n, 7, 0).is_none());
assert_eq!(n.level(id(1), 5).unwrap().format, Format::Bullet);
}
#[test]
fn restarts_a_shared_list_at_the_first_paragraph_of_an_overriding_instance() {
let mut n = numbering();
let labels: Vec<String> = [1, 1, 2, 2, 1]
.into_iter()
.map(|list| label(&mut n, list, 0).unwrap().text)
.collect();
assert_eq!(labels, ["1.", "2.", "5.", "6.", "7."]);
}
#[test]
fn counts_the_original_and_the_new_text_of_tracked_changes() {
let item = Some((id(1), 0));
let (both, deleted, inserted) = ((item, item), (None, item), (item, None));
let mut n = numbering();
let labels: Vec<String> = [both, deleted, both, inserted, both]
.into_iter()
.map(|(new, original)| n.next_label(new, original).unwrap().text)
.collect();
assert_eq!(labels, ["1.", "2.", "3.2.", "3.", "4."]);
let mut n = numbering();
let labels: Vec<String> = [inserted, deleted]
.into_iter()
.map(|(new, original)| n.next_label(new, original).unwrap().text)
.collect();
assert_eq!(labels, ["1.", "1."]);
let mut n = numbering();
assert_eq!(n.next_label(None, item).unwrap().text, "1.");
assert!(n.next_label(None, None).is_none());
}
#[test]
fn counts_a_paragraph_at_an_undefined_level_at_the_nearest_shallower_one() {
let doc = Document::parse(
r#"<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:abstractNum w:abstractNumId="0"><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/></w:lvl></w:abstractNum><w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num></w:numbering>"#.as_bytes(),
&Limits::default(),
)
.unwrap();
let mut n = read_part(&doc);
let labels: Vec<String> = [0, 0, 1, 1, 0]
.into_iter()
.map(|ilvl| label(&mut n, 1, ilvl).unwrap().text)
.collect();
assert_eq!(labels, ["1.", "2.", "3.", "4.", "5."]);
}
#[test]
fn formats_numbers() {
let cases = [
(3, Format::Decimal, "3"),
(3, Format::DecimalZero, "03"),
(28, Format::LowerLetter, "bb"),
(2, Format::UpperLetter, "B"),
(14, Format::LowerRoman, "xiv"),
(1994, Format::UpperRoman, "MCMXCIV"),
(8, Format::CardinalText, "Eight"),
(12, Format::CardinalText, "Twelve"),
(21, Format::CardinalText, "Twenty-one"),
(40, Format::CardinalText, "Forty"),
(305, Format::CardinalText, "Three hundred five"),
(2_017, Format::CardinalText, "Two thousand seventeen"),
(0, Format::CardinalText, "0"),
];
for (value, format, text) in cases {
assert_eq!(format_number(value, format), text);
}
assert_eq!((letters(0), roman(0)), ("0".to_owned(), "0".to_owned()));
assert_eq!(letters(99_999), "c".repeat(3_847));
assert_eq!(letters(100_000), "100000");
}
fn assert_signs(cases: &[(&str, &[(i64, &str)])]) {
for &(name, values) in cases {
let (format, _, _) = super::FORMAT.find(name).unwrap();
for &(value, text) in values {
assert_eq!(format_number(value, *format), text, "{name} {value}");
}
}
}
#[test]
fn writes_ordinals_and_the_numbers_of_other_scripts_in_their_signs() {
assert_signs(&[
(
"ordinal",
&[(1, "1st"), (12, "12th"), (21, "21st"), (113, "113th")],
),
(
"ordinalText",
&[
(12, "Twelfth"),
(21, "Twenty-first"),
(101, "One hundred first"),
(1_000, "One thousandth"),
],
),
(
"chicago",
&[
(1, "*"),
(6, "††"),
(120, "§".repeat(30).leak()),
(121, "*"),
],
),
(
"russianLower",
&[(30, "аа"), (120, "ггггг"), (99_999, "ж".repeat(29).leak())],
),
(
"hebrew1",
&[(15, "טו"), (116, "קטז"), (999, "רטו"), (2_000, "מ")],
),
(
"arabicAlpha",
&[(29, "أأ"), (200, "ث".repeat(8).leak()), (11_000, "م")],
),
("thaiNumbers", &[(32_767, "๓๒๗๖๗"), (32_768, "๑")]),
("numberInDash", &[(7, "- 7 -")]),
]);
}
#[test]
fn writes_east_asian_numbers_in_their_signs() {
assert_signs(&[
("ideographDigital", &[(10, "一〇"), (2_024, "二〇二四")]),
(
"japaneseCounting",
&[
(10, "十"),
(110, "百十"),
(1_100, "千百"),
(11_000, "一万一千"),
(32_767, "三万二千七百六十七"),
],
),
(
"japaneseLegal",
&[
(10, "壱拾"),
(1_001, "壱阡壱"),
(32_768, "参萬弐阡七百六拾八"),
],
),
(
"japaneseDigitalTenThousand",
&[(9_999, "九九九九"), (10_000, "")],
),
("decimalFullWidth", &[(101, "101")]),
("decimalEnclosedCircle", &[(20, "⑳"), (21, "21")]),
("decimalEnclosedCircleChinese", &[(10, "⑩"), (11, "11")]),
("ideographZodiac", &[(11, "戍"), (13, "13")]),
(
"ideographZodiacTraditional",
&[(11, "甲戍"), (61, "甲子"), (32_767, "庚午")],
),
("aiueo", &[(45, "ヲ"), (47, "ア"), (2_024, "ン")]),
("irohaFullWidth", &[(43, "ヱ"), (48, "ン"), (49, "イ")]),
("ganada", &[(14, "하"), (15, "가")]),
(
"chineseCounting",
&[(10, "十"), (99, "九十九"), (101, "一○一")],
),
(
"chineseCountingThousand",
&[
(110, "一百一十"),
(1_010, "一千〇一十"),
(10_001, "一万〇一"),
],
),
(
"taiwaneseCountingThousand",
&[(10, "十"), (2_024, "二千零二十四"), (10_010, "一萬零一十")],
),
(
"ideographLegalTraditional",
&[
(10, "壹拾"),
(1_010, "壹仟零壹拾"),
(99_999, "玖萬玖仟玖佰玖拾玖"),
],
),
(
"koreanCounting",
&[(10_000, "만"), (11_000, "만일천"), (101, "백일")],
),
(
"koreanLegal",
&[(1, "하나"), (99, "아흔아홉"), (130, "백삼십")],
),
]);
}
#[test]
fn writes_the_largest_start_in_digits_and_keeps_it() {
let xml = format!(
r#"<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:abstractNum w:abstractNumId="0"><w:lvl w:ilvl="0"><w:start w:val="{}"/><w:numFmt w:val="lowerLetter"/><w:lvlText w:val="%1."/></w:lvl></w:abstractNum><w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num></w:numbering>"#,
i64::MAX
);
let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
let mut n = read_part(&doc);
let labels: Vec<String> = (0..2).map(|_| label(&mut n, 1, 0).unwrap().text).collect();
let last = format!("{}.", i64::MAX);
assert_eq!(labels, [last.clone(), last]);
}
#[test]
fn each_enumeration_table_holds_each_name_of_its_type() {
let formats: std::collections::HashSet<&str> =
super::NUMBER_FORMATS.iter().copied().collect();
assert_eq!((super::NUMBER_FORMATS.len(), formats.len()), (63, 63));
crate::enumerations::assert_names(super::FORMAT, &super::NUMBER_FORMATS.join(" "));
crate::enumerations::assert_names(super::SUFFIX, "tab space nothing");
crate::enumerations::assert_names(
super::LEVEL_JC,
concat!(
"start center end both mediumKashida distribute numTab highKashida lowKashida ",
"thaiDistribute left right",
),
);
}
}