//! Styles, theme fonts and document settings.
use std::collections::{HashMap, HashSet};
use f_office_drawingml::theme::ShapeTheme;
use f_office_fonts::FamilyName;
use f_office_units::Length;
use f_office_xml::enumeration::{Values, another, own};
use f_office_xml::{Document, NodeId};
use crate::mode::{CompatibilityMode, ModeRules};
use crate::note_setup::{ByNoteKind, NoteSetup};
use crate::ns::{A, M, W};
use crate::numbers;
use crate::on_off;
use crate::params;
use crate::props::{
Alignment, Color, EastAsianScript, FontRef, HtmlAutoSpacing, LineSpacing, ListRef, ParaProps,
RunProps, UNDERLINE, Underline, read_shading,
};
use crate::reader::PartReader;
use crate::table::{CELL_V_ALIGN, REGION, Region, TableBorders, TableProps, VerticalAlign};
const MAX_CHAIN: usize = params::MAX_STYLE_CHAIN;
/// The kind of a style (`w:type` of `w:style`), of which a paragraph and a table style can be
/// the default one. A style without a kind is a paragraph style.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum StyleKind {
#[default]
Paragraph,
Character,
Table,
Numbering,
}
impl StyleKind {
/// The kind's name in `ST_StyleType`, for a message.
pub(crate) const fn word(self) -> &'static str {
match self {
Self::Paragraph => "paragraph",
Self::Character => "character",
Self::Table => "table",
Self::Numbering => "numbering",
}
}
}
/// `ST_StyleType`. A style without a kind is a paragraph style, and text outside the type
/// counts as missing, so a default style with it is the default paragraph style, where
/// F-Office made it the default of no kind before.
const STYLE_KIND: &Values<StyleKind> = &Values::new(&[
own("paragraph", StyleKind::Paragraph),
own("character", StyleKind::Character),
own("table", StyleKind::Table),
own("numbering", StyleKind::Numbering),
]);
/// The kind of the style `node`: a style without a kind, or with text outside `ST_StyleType`,
/// is a paragraph style.
pub(crate) fn style_kind(reader: &mut PartReader, node: NodeId) -> StyleKind {
reader
.enumeration(node, "type", STYLE_KIND)
.unwrap_or(StyleKind::Paragraph)
}
/// Whether the style `node` is the default style of its kind (`w:default`), by the set of
/// values of [`on_off::on_only_for_1_or_true`].
pub(crate) fn is_default(doc: &Document, node: NodeId) -> bool {
doc.attribute(node, Some(W), "default")
.is_some_and(on_off::on_only_for_1_or_true)
}
#[derive(Clone, Debug, Default)]
struct Style {
kind: StyleKind,
based_on: Option<String>,
para: ParaProps,
run: RunProps,
/// The kind of the style's underline, which tells apart the kinds that the run's underline
/// flag shares.
underline_kind: Option<Underline>,
table: TableProps,
/// The fill of a table style's cells.
shading: Option<Color>,
/// The vertical alignment of a table style's cells.
align: Option<VerticalAlign>,
regions: Vec<(Region, RegionStyle)>,
}
/// What a table style sets for one region of a table.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RegionStyle {
/// The paragraph properties.
pub para: ParaProps,
/// The run properties.
pub run: RunProps,
/// The cell borders.
pub borders: TableBorders,
/// The fill of the region's cells.
pub shading: Option<Color>,
/// The vertical alignment of the region's cells.
pub align: Option<VerticalAlign>,
}
/// The fill of the cells of a `w:tcPr` element.
fn cell_shading(reader: &mut PartReader, node: NodeId) -> Option<Color> {
let doc = reader.doc;
doc.child(node, W, "tcPr")
.and_then(|t| doc.child(t, W, "shd"))
.and_then(|s| read_shading(reader, s))
}
/// The vertical alignment of the cells of a `w:tcPr` element, which a cell without its own
/// `w:vAlign` takes (ECMA-376 Part 1, 17.7.6).
fn cell_align(reader: &mut PartReader, node: NodeId) -> Option<VerticalAlign> {
let doc = reader.doc;
let align = doc
.child(node, W, "tcPr")
.and_then(|t| doc.child(t, W, "vAlign"))?;
reader.enumeration(align, "val", CELL_V_ALIGN)
}
impl RegionStyle {
fn apply(&mut self, other: &Self) {
self.para.apply(&other.para);
self.run.apply(&other.run);
self.borders.apply(&other.borders);
if other.shading.is_some() {
self.shading = other.shading;
}
if other.align.is_some() {
self.align = other.align;
}
}
fn read(reader: &mut PartReader, node: NodeId) -> Self {
let doc = reader.doc;
Self {
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)),
borders: doc
.child(node, W, "tcPr")
.and_then(|t| doc.child(t, W, "tcBorders"))
.map_or_default(|b| TableBorders::read(reader, b)),
shading: cell_shading(reader, node),
align: cell_align(reader, node),
}
}
}
/// A table style after the cascade: its table properties, the paragraph and run properties
/// that it gives the paragraphs in the table, and its formatting for regions of the table.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TableStyle {
/// The table properties.
pub table: TableProps,
/// The paragraph properties.
pub para: ParaProps,
/// The run properties.
pub run: RunProps,
/// The fill of the table's cells.
pub shading: Option<Color>,
/// The vertical alignment of the table's cells.
pub align: Option<VerticalAlign>,
/// The formatting of regions, one entry for each region that the style sets.
pub regions: Vec<(Region, RegionStyle)>,
/// The alignment set by a conditional region (`w:tblStylePr`) for a cell.
pub(crate) region_alignment: Option<Alignment>,
/// Whether this style resolved to a defined table style in `styles.xml`.
pub(crate) resolved: bool,
}
impl TableStyle {
/// What the style sets for a region.
#[must_use]
pub fn region(&self, region: Region) -> Option<&RegionStyle> {
self.regions
.iter()
.find(|(r, _)| *r == region)
.map(|(_, style)| style)
}
fn add_regions(&mut self, regions: &[(Region, RegionStyle)]) {
for (region, style) in regions {
if let Some((_, own)) = self.regions.iter_mut().find(|(r, _)| r == region) {
own.apply(style);
} else {
self.regions.push((*region, style.clone()));
}
}
}
}
/// The paragraph defaults of Word's own template, which Word takes without default paragraph
/// properties: 8 pt after and lines of 278/240. With `own`, the document defaults, the
/// template leaves out each value that `own` gives the same ([`Styles::take_template`]).
fn template_paragraph(own: Option<&ParaProps>) -> ParaProps {
ParaProps {
after: unless_own(
Length::from_twips(params::DEFAULT_SPACE_AFTER),
own.map(|p| &p.after),
),
line: unless_own(
Some(LineSpacing::Auto(params::DEFAULT_LINE_SPACING)),
own.map(|p| &p.line),
),
..ParaProps::default()
}
}
/// The run defaults of Word's own template, which Word takes without default run properties:
/// it kerns text from 1 pt and turns on standard ligatures, and draws Latin text in the
/// theme's minor font at 12 pt. With `own`, the document defaults, the template leaves out
/// each value that `own` gives the same ([`Styles::take_template`]).
fn template_run(own: Option<&RunProps>) -> RunProps {
let minor = Some(FontRef::MinorLatin);
let size = Some(params::TEMPLATE_FONT_SIZE);
RunProps {
kern: unless_own(Some(2), own.map(|r| &r.kern)),
ligatures: unless_own(Some(true), own.map(|r| &r.ligatures)),
font_ascii: unless_own(minor.clone(), own.map(|r| &r.font_ascii)),
font_hansi: unless_own(minor, own.map(|r| &r.font_hansi)),
size: unless_own(size, own.map(|r| &r.size)),
size_cs: unless_own(size, own.map(|r| &r.size_cs)),
..RunProps::default()
}
}
/// The template's value `template`, or none where the document's own value `own` is the
/// same.
fn unless_own<T: PartialEq>(template: Option<T>, own: Option<&Option<T>>) -> Option<T> {
if own == Some(&template) {
None
} else {
template
}
}
/// The styles part with its document defaults.
#[derive(Clone, Debug)]
pub struct Styles {
default_para: ParaProps,
default_run: RunProps,
by_id: HashMap<String, Style>,
/// The style IDs by lowercase style name.
names: HashMap<String, String>,
default_paragraph_style: Option<String>,
default_table_style: Option<String>,
/// Whether a paragraph whose `w:pStyle` names no paragraph style takes the default
/// paragraph style, rather than the chain of the style that it names.
paragraph_kind_only: bool,
/// Whether the run defaults are Word's own template's, as the part has no `w:rPrDefault`.
template_run_defaults: bool,
}
impl Default for Styles {
/// No styles and empty defaults, where a paragraph's style ID takes the chain of whatever
/// style it names, until [`Styles::refer_only_paragraph_styles`] says otherwise.
fn default() -> Self {
Self {
default_para: ParaProps::default(),
default_run: RunProps::default(),
by_id: HashMap::new(),
names: HashMap::new(),
default_paragraph_style: None,
default_table_style: None,
paragraph_kind_only: false,
template_run_defaults: false,
}
}
}
impl Styles {
/// Reads `word/styles.xml`.
pub(crate) fn read(reader: &mut PartReader, root: NodeId) -> Self {
let doc = reader.doc;
let mut styles = Self::default();
let defaults = doc.child(root, W, "docDefaults");
if let Some(defaults) = defaults {
styles.read_defaults(reader, defaults);
}
let lacks = |name| defaults.and_then(|d| doc.child(d, W, name)).is_none();
if lacks("pPrDefault") {
styles.default_para = template_paragraph(None);
}
if lacks("rPrDefault") {
styles.default_run = template_run(None);
styles.template_run_defaults = true;
}
for node in doc.child_elements(root).filter(|n| doc.is(*n, W, "style")) {
styles.read_style(reader, node);
}
styles
}
/// The styles of a package without a styles part: the paragraph and run defaults of
/// Word's own template, and no styles.
#[must_use]
pub fn without_part() -> Self {
Self {
default_para: template_paragraph(None),
default_run: template_run(None),
template_run_defaults: true,
..Self::default()
}
}
/// Takes the default paragraph style from Word's own template, as a target does that
/// updates the styles of a document whose settings ask for it: the style loses the
/// document's properties and has the paragraph and run defaults of the template, each
/// only where it differs from the document defaults. The document defaults and every
/// other style stay, so a style that is not based on the default paragraph style keeps the
/// document defaults, and a table style wins over a value that the document defaults
/// already give.
pub fn take_template(&mut self) {
let para = template_paragraph(Some(&self.default_para));
let run = template_run(Some(&self.default_run));
let normal = self.default_paragraph_style.clone();
if let Some(style) = normal.and_then(|id| self.by_id.get_mut(&id)) {
style.para = para;
style.run = run;
}
}
fn read_defaults(&mut self, reader: &mut PartReader, defaults: NodeId) {
let doc = reader.doc;
let inner = |outer, inner| {
doc.child(defaults, W, outer)
.and_then(|node| doc.child(node, W, inner))
};
if let Some(rpr) = inner("rPrDefault", "rPr") {
self.default_run = RunProps::read(reader, rpr);
}
if let Some(ppr) = inner("pPrDefault", "pPr") {
self.default_para = ParaProps::read(reader, ppr);
}
}
fn read_style(&mut self, reader: &mut PartReader, node: NodeId) {
let doc = reader.doc;
let Some(id) = doc.attribute(node, Some(W), "styleId") else {
return;
};
let kind = style_kind(reader, node);
if is_default(doc, node) {
match kind {
StyleKind::Paragraph => self.default_paragraph_style = Some(id.to_owned()),
StyleKind::Table => self.default_table_style = Some(id.to_owned()),
StyleKind::Character | StyleKind::Numbering => {}
}
}
let has_table_props = kind == StyleKind::Table
&& (["tblPr", "trPr", "tcPr"].into_iter().any(|tag| {
doc.child(node, W, tag)
.is_some_and(|child| doc.child_elements(child).next().is_some())
}) || doc.child(node, W, "tblStylePr").is_some());
let based_on = doc
.child(node, W, "basedOn")
.and_then(|b| doc.attribute(b, Some(W), "val"))
// A table style that carries its own table, row, cell, or region properties drops a
// forward `w:basedOn` link whose target has not yet appeared in `styles.xml`.
.filter(|base| !has_table_props || self.by_id.contains_key(*base))
.map(str::to_owned);
let style = Style {
kind,
// `RunProps::read` reads this `w:u` again through the part's reader and keeps the
// warnings of its value.
underline_kind: doc
.child(node, W, "rPr")
.and_then(|r| doc.child(r, W, "u"))
.map(|u| {
reader
.again()
.enumeration(u, "val", UNDERLINE)
.unwrap_or(Underline::Single)
}),
based_on,
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)),
table: doc
.child(node, W, "tblPr")
.map_or_default(|t| TableProps::read(reader, t)),
shading: cell_shading(reader, node),
align: cell_align(reader, node),
regions: doc
.child_elements(node)
.filter(|n| doc.is(*n, W, "tblStylePr"))
.filter_map(|n| {
let region = reader.enumeration(n, "type", REGION)?;
Some((region, RegionStyle::read(reader, n)))
})
.collect(),
};
self.by_id.insert(id.to_owned(), style);
let name = doc
.child(node, W, "name")
.and_then(|n| doc.attribute(n, Some(W), "val"));
if let Some(name) = name {
self.names.insert(name.to_lowercase(), id.to_owned());
let aliases = doc
.child(node, W, "aliases")
.and_then(|n| doc.attribute(n, Some(W), "val"))
.filter(|aliases| !aliases.is_empty());
if let Some(aliases) = aliases {
self.names
.entry(format!("{name},{aliases}").to_lowercase())
.or_insert_with(|| id.to_owned());
}
}
}
/// The ID of the style with this name, as a `STYLEREF` field names it, or of the style with
/// this ID. Names match without regard to case, and a name followed by a comma and the
/// style's aliases names the style too.
#[must_use]
pub fn id_of<'s>(&'s self, name: &'s str) -> &'s str {
self.names
.get(&name.to_lowercase())
.map_or(name, String::as_str)
}
/// Returns a table style after the cascade. A missing or unknown style ID selects the
/// default table style.
#[must_use]
pub fn table(&self, style: Option<&str>) -> TableStyle {
let id = style
.filter(|id| self.by_id.contains_key(*id))
.or(self.default_table_style.as_deref());
let mut out = TableStyle {
resolved: id.is_some(),
..TableStyle::default()
};
for style in self.chain(id) {
out.table.apply(&style.table);
out.para.apply(&style.para);
out.run.apply(&style.run);
if style.shading.is_some() {
out.shading = style.shading;
}
if style.align.is_some() {
out.align = style.align;
}
out.add_regions(&style.regions);
}
out
}
/// The run properties of the document defaults (`w:rPrDefault`), or Word's own template's
/// when the styles part has none.
pub(crate) const fn default_run(&self) -> &RunProps {
&self.default_run
}
/// Whether the run defaults are Word's own template's, as the styles part has no
/// `w:rPrDefault`.
pub(crate) const fn template_run_defaults(&self) -> bool {
self.template_run_defaults
}
/// The ID of the default paragraph style, when the styles part names one.
#[must_use]
pub fn default_paragraph_style(&self) -> Option<&str> {
self.default_paragraph_style.as_deref()
}
/// Makes a paragraph whose `w:pStyle` names no paragraph style of the part take the
/// default paragraph style, as a target does that refers paragraphs to paragraph styles
/// only.
pub fn refer_only_paragraph_styles(&mut self) {
self.paragraph_kind_only = true;
}
/// The style ID whose chain a paragraph of the style ID `style` takes: that ID, or the
/// default paragraph style when the paragraph names none, or names an ID that is no
/// paragraph style of the part where the styles refer to paragraph styles only.
pub(crate) fn paragraph_style_id<'s>(&'s self, style: Option<&'s str>) -> Option<&'s str> {
let style = style.filter(|id| {
!self.paragraph_kind_only
|| self
.by_id
.get(*id)
.is_some_and(|s| s.kind == StyleKind::Paragraph)
});
style.or(self.default_paragraph_style.as_deref())
}
/// Whether the document defaults or any style in the paragraph's own style chain sets
/// `w:jc`.
pub(crate) fn paragraph_style_sets_alignment(&self, style: Option<&str>) -> bool {
self.default_para.alignment.is_some()
|| self
.chain(self.paragraph_style_id(style))
.iter()
.any(|s| s.para.alignment.is_some())
}
/// The list that a paragraph style gives a paragraph (`w:numPr` of the style or of a style
/// that it is based on, or of the document defaults), as [`Self::paragraph`] reads it;
/// `None` selects the default paragraph style.
pub(crate) fn list_of(&self, style: Option<&str>) -> Option<ListRef> {
self.paragraph(style, None).0.numbering
}
/// Returns the paragraph and run properties of a paragraph style after the cascade from the
/// document defaults. `None` selects the default paragraph style, and so does an ID that
/// is no paragraph style of the part where [`Self::refer_only_paragraph_styles`] set that. In
/// a table, the table style comes after the document defaults and before the paragraph
/// style.
#[must_use]
pub fn paragraph(
&self,
style: Option<&str>,
table: Option<&TableStyle>,
) -> (ParaProps, RunProps) {
let mut para = self.default_para.clone();
let mut run = self.default_run.clone();
if let Some(table) = table {
para.apply(&table.para);
run.apply_style_layer(&table.run, &self.default_run);
}
let id = self.paragraph_style_id(style);
let mut para_run = RunProps::default();
for style in self.chain(id) {
para.apply(&style.para);
para_run.apply(&style.run);
}
run.apply_style_layer(¶_run, &self.default_run);
para.style = id.map(str::to_owned);
(para, run)
}
/// Returns the paragraph properties of a paragraph whose own properties are `own`: the
/// cascade of its style, after the table style `table` ([`Self::paragraph`]), and then
/// `own`. It leaves out the paragraph properties of a list level, which the layout's
/// cascade of a paragraph that it lays out puts between the style and `own`. The layout
/// asks it where it needs a few properties of a paragraph: of the first paragraph of the
/// next footnote, of a table or of a table row, of a footnote's paragraph for its widow
/// control, and of a paragraph's properties before a tracked change, for their list.
#[must_use]
pub fn paragraph_properties_without_list_level(
&self,
own: &ParaProps,
table: Option<&TableStyle>,
) -> ParaProps {
let (mut para, _) = self.paragraph(own.style.as_deref(), table);
para.apply(own);
para
}
/// Returns the paragraph properties of a style with a list level's paragraph properties in
/// the cascade: right below the youngest style of the chain that names a list, so that the
/// styles it is based on lose to the level and it and the styles based on it win. The list
/// of such a paragraph comes from its style.
#[must_use]
pub fn paragraph_with_level(
&self,
style: Option<&str>,
table: Option<&TableStyle>,
level: &ParaProps,
) -> ParaProps {
let mut para = self.default_para.clone();
if let Some(table) = table {
para.apply(&table.para);
}
let id = self.paragraph_style_id(style);
let chain = self.chain(id);
let names_list = |style: &&Style| style.para.numbering.and_then(ListRef::id).is_some();
let at = chain.iter().rposition(names_list).unwrap_or(chain.len());
for (index, style) in chain.iter().enumerate() {
if index == at {
para.apply(level);
}
para.apply(&style.para);
}
if at == chain.len() {
para.apply(level);
}
para.style = id.map(str::to_owned);
para
}
/// Returns the run properties of a character style chain, without the defaults.
#[must_use]
pub fn character(&self, style: &str) -> RunProps {
let mut run = RunProps::default();
for style in self.chain(Some(style)) {
run.apply(&style.run);
}
run
}
/// Applies a character style chain onto `target` using ECMA-376 Part 1, 17.7.3 toggle
/// combination relative to the document defaults.
pub(crate) fn apply_character(&self, target: &mut RunProps, style: &str) {
target.apply_style_layer(&self.character(style), &self.default_run);
}
/// Whether the directly selected style has one of the built-in link names.
/// Derived custom styles do not take this identity.
pub(crate) fn is_link_style(&self, id: &str) -> bool {
["hyperlink", "followedhyperlink"]
.iter()
.any(|name| self.names.get(*name).is_some_and(|own| own == id))
}
/// The selected character style's full underline value after its style chain.
pub(crate) fn character_underline(&self, id: &str) -> Option<Underline> {
self.chain(Some(id))
.iter()
.rev()
.find_map(|style| style.underline_kind)
}
/// Returns a style and its ancestors, the oldest ancestor first.
/// Whether the styles part defines a style with this ID.
#[must_use]
pub fn has(&self, id: &str) -> bool {
self.by_id.contains_key(id)
}
fn chain(&self, id: Option<&str>) -> Vec<&Style> {
let mut chain = Vec::new();
let mut next = id;
// A style ID that the part does not define stands for no style.
let find = |id: &str| {
self.by_id.get(id).or_else(|| {
params::MISSING_STYLE_FALLBACK.and_then(|fallback| self.by_id.get(fallback))
})
};
while let Some(style) = next.and_then(find) {
if chain.len() == MAX_CHAIN {
break;
}
chain.push(style);
next = style.based_on.as_deref();
}
chain.reverse();
chain
}
}
/// One value for the minor (body) fonts of a theme (`a:minorFont`) and one for its major
/// (heading) fonts (`a:majorFont`).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct MinorMajor<T> {
/// The value of the minor fonts.
pub minor: T,
/// The value of the major fonts.
pub major: T,
}
impl<T> MinorMajor<T> {
/// The value of each of the two font kinds through `f`, which takes the kind's element name.
fn read(mut f: impl FnMut(&str) -> T) -> Self {
Self {
minor: f("minorFont"),
major: f("majorFont"),
}
}
}
/// The theme fonts.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Theme {
/// The minor (body) and major (heading) Latin fonts (`a:latin`).
pub latin: MinorMajor<Option<String>>,
/// The minor (body) and major (heading) complex script fonts.
pub bidi: MinorMajor<Option<String>>,
/// The minor (body) and major (heading) East Asian fonts (`a:ea`), when they are set.
pub east_asian: MinorMajor<Option<String>>,
/// The minor and major fonts by script (`a:font`), such as `Jpan` and `Hans`.
pub scripts: MinorMajor<Vec<(String, String)>>,
/// The colors and line widths that shapes refer to.
pub shapes: ShapeTheme,
/// The Latin fonts of the theme of the target's default template, which the theme font
/// references of a document without a theme part take.
pub template: MinorMajor<Option<&'static str>>,
}
impl Theme {
/// The theme of a document without a theme part, on a target whose default template has
/// the minor (body) Latin font `minor` and the major (heading) Latin font `major`.
#[must_use]
pub fn of_template(minor: &'static str, major: &'static str) -> Self {
Self {
template: MinorMajor {
minor: Some(minor),
major: Some(major),
},
..Self::default()
}
}
/// Reads `word/theme/theme1.xml`.
pub(crate) fn read(reader: &mut PartReader, root: NodeId) -> Self {
let doc = reader.doc;
let scheme = doc
.child(root, A, "themeElements")
.and_then(|node| doc.child(node, A, "fontScheme"));
let latin = |kind: &str| {
scheme
.and_then(|node| doc.child(node, A, kind))
.and_then(|node| doc.child(node, A, "latin"))
.and_then(|node| doc.attribute(node, None, "typeface"))
.map(str::to_owned)
};
// The complex script font, or else the font of the Arabic script.
let bidi = |kind: &str| {
let font = scheme.and_then(|node| doc.child(node, A, kind))?;
let typeface = |node: NodeId| {
doc.attribute(node, None, "typeface")
.filter(|name| !name.is_empty())
.map(str::to_owned)
};
doc.child(font, A, "cs").and_then(typeface).or_else(|| {
doc.child_elements(font)
.filter(|node| doc.is(*node, A, "font"))
.find(|node| doc.attribute(*node, None, "script") == Some("Arab"))
.and_then(typeface)
})
};
let east_asian = |kind: &str| {
let font = scheme.and_then(|node| doc.child(node, A, kind))?;
doc.child(font, A, "ea")
.and_then(|node| doc.attribute(node, None, "typeface"))
.filter(|name| !name.is_empty())
.map(str::to_owned)
};
let scripts = |kind: &str| -> Vec<(String, String)> {
let Some(font) = scheme.and_then(|node| doc.child(node, A, kind)) else {
return Vec::new();
};
doc.child_elements(font)
.filter(|node| doc.is(*node, A, "font"))
.filter_map(|node| {
let script = doc.attribute(node, None, "script")?;
let typeface = doc.attribute(node, None, "typeface")?;
Some((script.to_owned(), typeface.to_owned()))
})
.collect()
};
Self {
latin: MinorMajor::read(latin),
bidi: MinorMajor::read(bidi),
east_asian: MinorMajor::read(east_asian),
scripts: MinorMajor::read(scripts),
shapes: ShapeTheme::read(doc, root, reader.drawing_warnings()),
template: MinorMajor::default(),
}
}
/// The family name that a font reference stands for, for text whose East Asian language
/// is `lang`. The theme's East Asian font is its `a:ea` typeface, or else its font for the
/// script of that language.
#[must_use]
pub fn family_for<'a>(
&'a self,
font: &'a FontRef,
script: Option<EastAsianScript>,
) -> Option<&'a str> {
let (own, scripts) = match font {
FontRef::MinorEastAsia => (&self.east_asian.minor, &self.scripts.minor),
FontRef::MajorEastAsia => (&self.east_asian.major, &self.scripts.major),
_ => return self.family(font),
};
own.as_deref().or_else(|| {
let name = script?.theme_name();
scripts
.iter()
.find(|(script, _)| script == name)
.map(|(_, typeface)| typeface.as_str())
})
}
/// Returns the family name that a font reference stands for.
#[must_use]
pub fn family<'a>(&'a self, font: &'a FontRef) -> Option<&'a str> {
match font {
FontRef::Name(name) => Some(name),
FontRef::MinorLatin => self.latin.minor.as_deref().or(self.template.minor),
FontRef::MajorLatin => self.latin.major.as_deref().or(self.template.major),
FontRef::MinorBidi => self.bidi.minor.as_deref(),
FontRef::MajorBidi => self.bidi.major.as_deref(),
FontRef::MinorEastAsia => self.east_asian.minor.as_deref(),
FontRef::MajorEastAsia => self.east_asian.major.as_deref(),
}
}
}
/// Alternate font names from the font table, and the East Asian character sets and the
/// character sets of suffixed font names that the fonts' entries name.
///
///
/// Word finds an entry whose name differs from the run's font name in the case of ASCII
/// letters, as [`FamilyName`] compares names.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FontTable {
alternates: HashMap<FamilyName, FamilyName>,
charsets: HashMap<FamilyName, EntryCharset>,
/// The font class of each entry, `None` for an entry that names none.
classes: HashMap<FamilyName, Option<FontClass>>,
/// The complex script that each entry names, for the entries that name one.
scripts: HashMap<FamilyName, EntryScript>,
}
/// The **font class** of a font table entry, its `w:family` (in the WordprocessingML schema of
/// ECMA-376, `wml.xsd`: a child of `CT_Font` whose `w:val` has the type `ST_FontFamily`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FontClass {
/// `decorative`: novelty fonts.
Decorative,
/// `modern`: fonts of one width for each character.
Modern,
/// `roman`: proportional fonts with serifs.
Roman,
/// `script`: fonts that look like handwriting.
Script,
/// `swiss`: proportional fonts without serifs.
Swiss,
/// `auto`: no class.
Auto,
}
/// What a font table holds for a font name.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FontEntry {
/// The table has no entry of the name.
Absent,
/// The entry names no font class, or one that `ST_FontFamily` lacks.
NoClass,
/// The entry's font class.
Class(FontClass),
}
impl FontClass {
/// The class of a `w:family` value, or `None` for a value that `ST_FontFamily` lacks.
fn of(value: &str) -> Option<Self> {
match value {
"decorative" => Some(Self::Decorative),
"modern" => Some(Self::Modern),
"roman" => Some(Self::Roman),
"script" => Some(Self::Script),
"swiss" => Some(Self::Swiss),
"auto" => Some(Self::Auto),
_ => None,
}
}
}
/// An East Asian character set that a font table entry names in `w:charset` (ECMA-376
/// Part 1, 17.8.3.2).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EastAsianCharset {
/// Shift JIS, for Japanese (`80`).
ShiftJis,
/// Hangul, for Korean (`81`).
Hangul,
/// GB 2312, for Simplified Chinese (`86`).
Gb2312,
/// Big5, for Traditional Chinese (`88`).
Big5,
}
impl EastAsianCharset {
/// The character set of a `w:charset` value, a byte in hexadecimal.
fn of(value: &str) -> Option<Self> {
match value {
"80" => Some(Self::ShiftJis),
"81" => Some(Self::Hangul),
"86" => Some(Self::Gb2312),
"88" => Some(Self::Big5),
_ => None,
}
}
}
/// A character set of a **suffixed font name**: a font name whose last word names a Windows
/// character set, such as `CYR` in `Times New Roman CYR`. A font table entry names the set in
/// `w:charset` (ECMA-376 Part 1, 17.8.3.2), as the character set values of a Windows `LOGFONT`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SuffixCharset {
/// Central European, the suffix `CE` (`EE`).
CentralEuropean,
/// Cyrillic, the suffix `CYR` (`CC`).
Cyrillic,
/// Greek, the suffix `Greek` (`A1`).
Greek,
/// Baltic, the suffix `Baltic` (`BA`).
Baltic,
/// Turkish, the suffix `TUR` (`A2`).
Turkish,
}
impl SuffixCharset {
/// The suffixes of suffixed font names, each with the `w:charset` value of its character
/// set and the set.
const SUFFIXES: [(&'static str, &'static str, Self); 5] = [
("CE", "EE", Self::CentralEuropean),
("CYR", "CC", Self::Cyrillic),
("Greek", "A1", Self::Greek),
("Baltic", "BA", Self::Baltic),
("TUR", "A2", Self::Turkish),
];
/// The character set of a `w:charset` value, a byte in hexadecimal that compares as
/// [`numbers::hex`] reads it.
fn of(value: &str) -> Option<Self> {
let value = numbers::hex(value)?;
Self::SUFFIXES
.into_iter()
.find(|(_, code, _)| numbers::hex(code) == Some(value))
.map(|(_, _, set)| set)
}
/// The family name before the suffix of a suffixed font name, and the suffix's character
/// set, or `None` for another name. The suffix compares as [`FamilyName`] compares names,
/// without regard to the case of ASCII letters.
#[must_use]
pub fn split(name: &str) -> Option<(&str, Self)> {
let (base, suffix) = name.trim().rsplit_once(' ')?;
let suffix = FamilyName::new(suffix);
let (_, _, set) = Self::SUFFIXES
.into_iter()
.find(|(written, _, _)| suffix.is(written))?;
let base = base.trim_end();
(!base.is_empty()).then_some((base, set))
}
}
/// The complex script that a font table entry names: by its character set (`w:charset`,
/// ECMA-376 Part 1, 17.8.3.2), or else by a code page of its font signature (`w:csb0` of
/// `w:sig`, 17.8.3.16, whose bits are those of `ulCodePageRange1` in the OpenType `OS/2`
/// table).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EntryScript {
/// Arabic: the character set `B2`, or the code page 1256.
Arabic,
/// Hebrew: the character set `B1`, or the code page 1255.
Hebrew,
}
impl EntryScript {
/// The script of an entry's `w:charset` value and its signature's `w:csb0` value: that of
/// the character set, or else that of the lowest code page of a complex script that the
/// signature names, or `None` when neither names one.
fn of(charset: Option<&str>, code_pages: Option<&str>) -> Option<Self> {
use crate::params::{
ARABIC_CHARSET, ARABIC_CODE_PAGE_BIT, HEBREW_CHARSET, HEBREW_CODE_PAGE_BIT,
};
match charset.and_then(numbers::hex) {
Some(ARABIC_CHARSET) => return Some(Self::Arabic),
Some(HEBREW_CHARSET) => return Some(Self::Hebrew),
_ => {}
}
let pages = code_pages.and_then(numbers::hex)?;
if pages >> HEBREW_CODE_PAGE_BIT & 1 == 1 {
Some(Self::Hebrew)
} else if pages >> ARABIC_CODE_PAGE_BIT & 1 == 1 {
Some(Self::Arabic)
} else {
None
}
}
}
/// A character set that a font table entry names and that a rule reads.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum EntryCharset {
/// An East Asian character set.
EastAsian(EastAsianCharset),
/// The character set of a suffixed font name.
Suffix(SuffixCharset),
}
impl EntryCharset {
/// The character set of a `w:charset` value, or `None` for a set that no rule reads.
fn of(value: &str) -> Option<Self> {
EastAsianCharset::of(value)
.map(Self::EastAsian)
.or_else(|| SuffixCharset::of(value).map(Self::Suffix))
}
}
impl FontTable {
/// Reads `word/fontTable.xml`.
///
/// Of entries whose names name one family, the first one counts and the others are left
/// out, as the package reader keeps the first of equivalent entries.
pub fn read(doc: &Document, root: NodeId) -> Self {
let mut table = Self::default();
let mut seen = HashSet::new();
let fonts = doc
.child_elements(root)
.filter(|node| doc.is(*node, W, "font"));
for node in fonts {
let Some(name) = doc.attribute(node, Some(W), "name") else {
continue;
};
let name = FamilyName::new(name);
if !seen.insert(name.clone()) {
continue;
}
let charset = doc
.child(node, W, "charset")
.and_then(|set| doc.attribute(set, Some(W), "val"));
if let Some(set) = charset.and_then(EntryCharset::of) {
table.charsets.insert(name.clone(), set);
}
let code_pages = doc
.child(node, W, "sig")
.and_then(|sig| doc.attribute(sig, Some(W), "csb0"));
if let Some(script) = EntryScript::of(charset, code_pages) {
table.scripts.insert(name.clone(), script);
}
let class = doc
.child(node, W, "family")
.and_then(|family| doc.attribute(family, Some(W), "val"))
.and_then(FontClass::of);
table.classes.insert(name.clone(), class);
let alternate = doc
.child(node, W, "altName")
.and_then(|alt| doc.attribute(alt, Some(W), "val"))
.and_then(|alt| alt.split(',').next())
.map(str::trim)
.filter(|alt| !alt.is_empty());
if let Some(alt) = alternate {
table.alternates.insert(name, FamilyName::new(alt));
}
}
table
}
/// Returns the alternate name that the font table gives for a font.
#[must_use]
pub fn alternate(&self, name: &FamilyName) -> Option<&FamilyName> {
self.alternates.get(name)
}
/// The East Asian character set that the font table's entry for a font names.
#[must_use]
pub fn east_asian_charset(&self, name: &FamilyName) -> Option<EastAsianCharset> {
match self.charsets.get(name) {
Some(EntryCharset::EastAsian(set)) => Some(*set),
Some(EntryCharset::Suffix(_)) | None => None,
}
}
/// The character set of a suffixed font name that the font table's entry for a font names.
#[must_use]
pub fn suffix_charset(&self, name: &FamilyName) -> Option<SuffixCharset> {
match self.charsets.get(name) {
Some(EntryCharset::Suffix(set)) => Some(*set),
Some(EntryCharset::EastAsian(_)) | None => None,
}
}
/// The complex script that the font table's entry for a font names.
#[must_use]
pub fn complex_script(&self, name: &FamilyName) -> Option<EntryScript> {
self.scripts.get(name).copied()
}
/// What the font table's entry for a font says of its font class.
#[must_use]
pub fn entry(&self, name: &FamilyName) -> FontEntry {
match self.classes.get(name) {
None => FontEntry::Absent,
Some(None) => FontEntry::NoClass,
Some(Some(class)) => FontEntry::Class(*class),
}
}
}
/// Document settings that layout needs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Settings {
/// The distance between default tab stops.
pub default_tab_stop: Length,
/// What the rules that depend on the compatibility mode do in this document, from the
/// `compatibilityMode` compatibility setting.
pub mode_rules: ModeRules,
/// Whether even pages have their own headers and footers (`w:evenAndOddHeaders`).
pub even_and_odd_headers: bool,
/// How footnotes and endnotes are numbered and where they stand (`w:footnotePr`,
/// `w:endnotePr`), which each section's own elements stand over.
pub notes: ByNoteKind<NoteSetup>,
/// Whether the left indent of a hanging indent is a tab stop for the tab after a list
/// label. `w:doNotUseIndentAsNumberingTabStop` turns it off.
pub indent_is_numbering_tab_stop: bool,
/// Whether the gutter lies in the top margin (`w:gutterAtTop`) instead of the left one.
pub gutter_at_top: bool,
/// Which side margins the pages take (`w:mirrorMargins`).
pub side_margins: SideMargins,
/// Which separator stands above the footnotes of a page.
pub footnote_separators: NoteSeparators,
/// The script of the document's East Asian language (`w:themeFontLang w:eastAsia`), for
/// text whose run properties name none.
pub east_asian_script: Option<EastAsianScript>,
/// Whether kerned runs close up pairs of punctuation marks.
pub punctuation_kerning: PunctuationKerning,
/// What justified lines do with the blank halves of punctuation marks.
pub punctuation: Punctuation,
/// Whether justified lines without spaces spread their room over the gaps between glyphs.
pub gap_spread: GapSpread,
/// How much of its run's character spacing a full-width character takes.
pub full_width_spacing: FullWidthSpacing,
/// How wide a space next to East Asian text is.
pub space_balance: SpaceBalance,
/// Whether the lines of table cells follow the section's line grid.
pub cell_grid: CellGrid,
/// Whether a justified paragraph justifies its lines that end in a soft line break.
pub soft_break_lines: SoftBreakLines,
/// Whose justification the settings ask for (`w:wpJustification`).
pub justification: Justification,
/// How the document reads automatic paragraph spacing.
pub html_auto_spacing: HtmlAutoSpacing,
/// Whether the settings ask for the styles of the template.
pub template_styles: TemplateStyles,
/// The document's automatic hyphenation (`w:autoHyphenation`), or `None` when it is off.
pub hyphenation: Option<AutoHyphenation>,
/// The page color of the main document (`w:background w:color`), or `None` when it has
/// none. It fills every page under all else, also when the settings do not ask to show it
/// (`w:displayBackgroundShape`), and it is the shading behind automatic text where no fill
/// lies.
pub page_color: Option<[u8; 3]>,
/// Whether display fractions step down in size like inline fractions (`m:mathPr/m:smallFrac`).
pub(crate) small_frac: crate::props::SmallFractions,
/// Whether `w:compat/w:spaceForUL` is set, which shifts the alignment box of exact lines
/// under `w:textAlignment`.
pub(crate) space_for_ul: SpaceForUl,
}
/// Whether `w:compat/w:spaceForUL` is set in `word/settings.xml`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum SpaceForUl {
/// Option absent or off.
#[default]
Off,
/// Option set.
On,
}
impl SpaceForUl {
const fn of(set: bool) -> Self {
if set { Self::On } else { Self::Off }
}
}
/// The settings of a document's automatic hyphenation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AutoHyphenation {
/// The hyphenation zone (`w:hyphenationZone`): in the compatibility modes where it holds, a
/// word that does not fit is hyphenated only when the room that the line leaves for it is
/// wider than the zone.
pub zone: Length,
/// The most lines in a row that may end with a hyphen (`w:consecutiveHyphenLimit`), or
/// `None` for no limit, which 0 and a missing element give.
pub limit: Option<std::num::NonZeroUsize>,
/// Whether words in capitals are hyphenated (`w:doNotHyphenateCaps`).
pub capitals: Capitals,
}
/// Whether automatic hyphenation hyphenates a word whose letters are all capitals.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Capitals {
/// Words in capitals are hyphenated as other words.
Hyphenated,
/// Words in capitals stay whole (`w:doNotHyphenateCaps`).
Kept,
}
/// Which separator stands above the footnotes of a page.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NoteSeparators {
/// The settings list no special footnotes, so the separator is the application's own
/// and not the one that the footnotes part has.
#[default]
Own,
/// The settings list special footnotes (`w:footnotePr` with `w:footnote`), which are the
/// separators of the footnotes part.
Listed,
}
impl NoteSeparators {
/// Reads which separator the settings under `root` ask for.
fn read(doc: &Document, root: NodeId) -> Self {
let listed = doc
.child(root, W, "footnotePr")
.is_some_and(|list| doc.child(list, W, "footnote").is_some());
if listed { Self::Listed } else { Self::Own }
}
}
/// Whether a document's settings ask the application to update its styles from the template.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TemplateStyles {
/// No `w:linkStyles`, or the settings name an attached template.
#[default]
Kept,
/// `w:linkStyles` is on and the settings name no attached template, so the template is
/// the application's own.
Linked,
}
/// Whether the lines of table cells follow the section's line grid.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CellGrid {
/// A cell's lines keep their own heights, as without a grid.
#[default]
Own,
/// A cell's lines follow the grid as the body's do: the compatibility option
/// `w:adjustLineHeightInTable` is set.
Follows,
}
/// Which side margins the pages of a document take.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SideMargins {
/// Every page takes the left and right margins of its section.
#[default]
Section,
/// A mirrored page, one with an even number, swaps the left and right margins of its
/// section (`w:mirrorMargins`).
Mirrored,
/// Book-fold printing (`w:bookFoldPrinting`): on landscape sections, `w:right + w:gutter`
/// sits on the inside edge (left on odd pages, right on even pages) and `w:left` sits on the
/// outside edge; on portrait sections, `w:gutter` is omitted from `w:left`.
BookFold,
/// Reverse book-fold printing (`w:bookFoldRevPrinting`): on landscape sections,
/// `w:right + w:gutter` sits on the inside edge (right on odd pages, left on even pages) and
/// `w:left` sits on the outside edge; on portrait sections, `w:gutter` is omitted from
/// `w:left`.
BookFoldReverse,
}
impl SideMargins {
/// Reads side-margin settings (`w:mirrorMargins`, `w:bookFoldPrinting`, `w:bookFoldRevPrinting`).
fn read(doc: &Document, root: NodeId) -> Self {
let on = |name: &str| {
doc.child(root, W, name)
.is_some_and(|n| on_off::off_only_for_0_or_false(doc, n))
};
if on("mirrorMargins") {
Self::Mirrored
} else if on("bookFoldPrinting") {
Self::BookFold
} else if on("bookFoldRevPrinting") {
Self::BookFoldReverse
} else {
Self::Section
}
}
}
/// How wide a space (U+0020) next to East Asian text is.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SpaceBalance {
/// Every space keeps its font's own width.
#[default]
Own,
/// A space next to an East Asian character, and the spaces that it stands among, advance
/// half an em of their font: the compatibility options
/// `w:balanceSingleByteDoubleByteWidth` and `w:useFELayout` are both set.
HalfEm,
}
/// How much of its run's character spacing a full-width character takes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FullWidthSpacing {
/// The spacing once, as every other character.
#[default]
Once,
/// The spacing twice, once for each half cell: the compatibility option
/// `w:balanceSingleByteDoubleByteWidth` is set.
Twice,
}
/// Whether kerned runs close up pairs of East Asian punctuation marks by half an em.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PunctuationKerning {
/// Every mark keeps its width.
#[default]
Off,
/// Kerned runs close up the pairs: the compatibility option `w:useFELayout` is set and
/// `w:noPunctuationKerning` is not.
On,
}
/// `ST_CharacterSpacing` (`w:characterSpacingControl`), as whether punctuation is compressed:
/// the compression of Japanese kana too is drawn as that of punctuation only.
const CHARACTER_SPACING: &Values<bool> = &Values::new(&[
own("doNotCompress", false),
own("compressPunctuation", true),
another("compressPunctuationAndJapaneseKana", true),
]);
/// What justified lines do with the blank halves of punctuation marks.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Punctuation {
/// They keep their width.
#[default]
Kept,
/// They shrink so that more text fits: `w:characterSpacingControl` is
/// `compressPunctuation` and the compatibility option `w:useFELayout` is set.
Compressed,
}
/// What a justified line without spaces does with the room that it has left.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum GapSpread {
/// It keeps the room at its end.
#[default]
Kept,
/// It spreads the room over the gaps between its glyphs in equal shares: the compatibility
/// option `w:useFELayout` is set, whatever the punctuation does.
Spread,
}
impl GapSpread {
/// The gap spread of a document that sets `w:useFELayout` (`east_asian_layout`) or not.
const fn of(east_asian_layout: bool) -> Self {
if east_asian_layout {
Self::Spread
} else {
Self::Kept
}
}
}
/// Whose justification the settings ask for: Word's own, or that of `WordPerfect`, which the
/// compatibility option `w:wpJustification` asks for.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Justification {
/// Word's own.
#[default]
Word,
/// That of `WordPerfect`: the option is set.
WordPerfect,
}
impl Justification {
/// The justification where the option is set (`set`) or not.
const fn of(set: bool) -> Self {
if set { Self::WordPerfect } else { Self::Word }
}
}
/// Whether a justified paragraph justifies its lines that end in a soft line break (a `w:br`
/// without a page or column type, or a `w:cr`), as the compatibility option
/// `w:doNotExpandShiftReturn` says (ECMA-376 Part 1, 17.15.3.5).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SoftBreakLines {
/// Justified, as every line of the paragraph but its last.
#[default]
Justified,
/// Aligned as the paragraph's last line: the option is set.
AsLastLine,
}
impl SoftBreakLines {
/// The alignment of the lines where the option is set (`set`) or not.
fn of(set: bool) -> Self {
if set {
Self::AsLastLine
} else {
Self::Justified
}
}
}
impl Default for Settings {
fn default() -> Self {
Self {
default_tab_stop: Length::from_units(
params::DEFAULT_TAB_DISTANCE * Length::UNITS_PER_TWIP,
),
mode_rules: ModeRules::default(),
even_and_odd_headers: false,
notes: ByNoteKind::DEFAULT,
indent_is_numbering_tab_stop: true,
gutter_at_top: false,
side_margins: SideMargins::Section,
footnote_separators: NoteSeparators::Own,
east_asian_script: None,
punctuation_kerning: PunctuationKerning::Off,
punctuation: Punctuation::Kept,
gap_spread: GapSpread::Kept,
full_width_spacing: FullWidthSpacing::Once,
space_balance: SpaceBalance::Own,
cell_grid: CellGrid::Own,
soft_break_lines: SoftBreakLines::Justified,
justification: Justification::Word,
html_auto_spacing: HtmlAutoSpacing::Html,
template_styles: TemplateStyles::Kept,
hyphenation: None,
page_color: None,
small_frac: crate::props::SmallFractions::Off,
space_for_ul: SpaceForUl::Off,
}
}
}
/// The automatic hyphenation that the settings `root` turn on (`w:autoHyphenation`, read as
/// `ST_OnOff`), with its zone, its limit and its rule for capitals, or `None` when it is off.
fn auto_hyphenation(reader: &mut PartReader, root: NodeId) -> Option<AutoHyphenation> {
let doc = reader.doc;
if !doc
.child(root, W, "autoHyphenation")
.is_some_and(|node| on_off::element(doc, node, W))
{
return None;
}
let zone = doc
.child(root, W, "hyphenationZone")
.and_then(|node| reader.twips(node, "val"))
.filter(|zone| zone.units() >= 0)
.unwrap_or(Length::from_units(
params::DEFAULT_HYPHENATION_ZONE * Length::UNITS_PER_TWIP,
));
let limit = doc
.child(root, W, "consecutiveHyphenLimit")
.and_then(|node| reader.number::<usize>(node, "val", numbers::NOT_NEGATIVE))
.and_then(std::num::NonZeroUsize::new);
let capitals = if doc
.child(root, W, "doNotHyphenateCaps")
.is_some_and(|node| on_off::element(doc, node, W))
{
Capitals::Kept
} else {
Capitals::Hyphenated
};
Some(AutoHyphenation {
zone,
limit,
capitals,
})
}
impl Settings {
/// Reads `word/settings.xml`.
pub(crate) fn read(reader: &mut PartReader, root: NodeId) -> Self {
let doc = reader.doc;
let defaults = Self::default();
// A distance of 0 leaves no default stops, so that a tab without a custom stop after
// it takes no room.
let default_tab_stop = doc
.child(root, W, "defaultTabStop")
.and_then(|node| reader.twips(node, "val"))
.filter(|stop| stop.units() >= 0)
.unwrap_or(defaults.default_tab_stop);
let compat = doc.child(root, W, "compat");
let compat_on = |name: &str| {
compat
.and_then(|c| doc.child(c, W, name))
.is_some_and(|n| on_off::off_only_for_0_or_false(doc, n))
};
let use_fe_layout = compat_on("useFELayout");
let indent_is_numbering_tab_stop = !compat
.and_then(|c| doc.child(c, W, "doNotUseIndentAsNumberingTabStop"))
.is_some_and(|n| on_off::off_only_for_0_or_false(doc, n));
// Word also reads the mode outside `w:compat`.
let compat_setting = |name: &str| {
compat
.into_iter()
.flat_map(|compat| doc.child_elements(compat))
.chain(doc.child_elements(root))
.filter(|node| doc.is(*node, W, "compatSetting"))
.find(|node| doc.attribute(*node, Some(W), "name") == Some(name))
};
let compatibility_mode = CompatibilityMode::read(
compat_setting("compatibilityMode")
.and_then(|node| reader.number(node, "val", numbers::ANY)),
);
let open_type_features = compat_setting("enableOpenTypeFeatures")
.and_then(|node| doc.attribute(node, Some(W), "val"))
.is_some_and(|value| on_off::read(value) == Some(true));
let on = |name: &str| {
doc.child(root, W, name)
.is_some_and(|n| on_off::off_only_for_0_or_false(doc, n))
};
let even_and_odd_headers = on("evenAndOddHeaders");
let hyphenation = auto_hyphenation(reader, root);
let notes = ByNoteKind::read(reader, root).over(defaults.notes);
let compressed = doc
.child(root, W, "characterSpacingControl")
.and_then(|node| reader.enumeration(node, "val", CHARACTER_SPACING))
.unwrap_or(false);
Self {
default_tab_stop,
mode_rules: ModeRules::of(compatibility_mode)
.with_open_type_features(open_type_features),
even_and_odd_headers,
notes,
indent_is_numbering_tab_stop,
gutter_at_top: on("gutterAtTop"),
side_margins: SideMargins::read(doc, root),
footnote_separators: NoteSeparators::read(doc, root),
template_styles: if on("linkStyles") && doc.child(root, W, "attachedTemplate").is_none()
{
TemplateStyles::Linked
} else {
TemplateStyles::Kept
},
east_asian_script: doc
.child(root, W, "themeFontLang")
.and_then(|node| doc.attribute(node, Some(W), "eastAsia"))
.and_then(EastAsianScript::of),
punctuation_kerning: if use_fe_layout && !on("noPunctuationKerning") {
PunctuationKerning::On
} else {
PunctuationKerning::Off
},
punctuation: if use_fe_layout && compressed {
Punctuation::Compressed
} else {
Punctuation::Kept
},
gap_spread: GapSpread::of(use_fe_layout),
full_width_spacing: if compat_on("balanceSingleByteDoubleByteWidth") {
FullWidthSpacing::Twice
} else {
FullWidthSpacing::Once
},
space_balance: if use_fe_layout && compat_on("balanceSingleByteDoubleByteWidth") {
SpaceBalance::HalfEm
} else {
SpaceBalance::Own
},
cell_grid: if compat_on("adjustLineHeightInTable") {
CellGrid::Follows
} else {
CellGrid::Own
},
soft_break_lines: SoftBreakLines::of(compat_on("doNotExpandShiftReturn")),
justification: Justification::of(compat_on("wpJustification")),
html_auto_spacing: HtmlAutoSpacing::of(compat_on("doNotUseHTMLParagraphAutoSpacing")),
hyphenation,
page_color: None,
small_frac: small_fractions(doc, root),
space_for_ul: SpaceForUl::of(compat_on("spaceForUL")),
}
}
}
fn small_fractions(doc: &Document, root: NodeId) -> crate::props::SmallFractions {
if doc
.child(root, M, "mathPr")
.and_then(|pr| doc.child(pr, M, "smallFrac"))
.is_some_and(|node| on_off::element(doc, node, M))
{
crate::props::SmallFractions::On
} else {
crate::props::SmallFractions::Off
}
}
#[cfg(test)]
mod tests {
use super::{Settings, Styles, TemplateStyles, Theme};
use crate::mode::{CompatibilityMode, ModeRules};
use crate::ns::{A, M, W};
use crate::numbering::Format;
use crate::params;
use crate::props::{Alignment, EastAsianScript, FontRef, LineSpacing, ParaProps};
use crate::quirks::TemplateFonts;
use crate::reader::PartReader;
use crate::table::{Region, VerticalAlign};
use f_office_fonts::FamilyName;
use f_office_units::Length;
use f_office_xml::{Document, Limits};
const STYLES: &str = r#"<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val="22"/></w:rPr></w:rPrDefault>
<w:pPrDefault><w:pPr><w:spacing w:after="160"/></w:pPr></w:pPrDefault></w:docDefaults>
<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:pPr><w:jc w:val="left"/></w:pPr></w:style>
<w:style w:type="paragraph" w:styleId="Title"><w:basedOn w:val="Normal"/><w:pPr><w:jc w:val="center"/></w:pPr><w:rPr><w:sz w:val="56"/></w:rPr></w:style>
<w:style w:type="paragraph" w:styleId="Loop"><w:basedOn w:val="Loop"/></w:style>
<w:style w:type="character" w:styleId="Strong"><w:rPr><w:b/></w:rPr></w:style>
</w:styles>"#;
fn parse(xml: &str) -> Document {
Document::parse(xml.as_bytes(), &Limits::default()).unwrap()
}
#[test]
fn reads_text_outside_the_kind_of_a_style_as_a_paragraph_style() {
let default_style = |kind: &str| {
let doc = parse(&format!(
r#"<w:styles xmlns:w="{W}"><w:style w:type="{kind}" w:default="1" w:styleId="S"/></w:styles>"#
));
let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
styles.default_paragraph_style().map(str::to_owned)
};
let read = ["paragraph", "Paragraph", "", "list", "table"].map(default_style);
let s = Some("S".to_owned());
assert_eq!(read, [s.clone(), s.clone(), s.clone(), s, None]);
}
#[test]
fn finds_a_style_by_its_name_by_its_name_and_aliases_and_by_its_id() {
let doc = parse(&format!(
r#"<w:styles xmlns:w="{W}"><w:style w:type="paragraph" w:styleId="H2"><w:name w:val="Head Two"/><w:aliases w:val="h2,Second"/></w:style></w:styles>"#
));
let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
let found = ["head two", "HEAD TWO,h2,second", "H2", "h2", "Head Two,h2"]
.map(|name| styles.id_of(name).to_owned());
// An alias alone, or only some of the aliases, names no style.
assert_eq!(found, ["H2", "H2", "H2", "h2", "Head Two,h2"]);
}
#[test]
fn cascades_paragraph_styles() {
let doc = parse(STYLES);
let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
let (para, run) = styles.paragraph(Some("Title"), None);
assert_eq!(para.alignment, Some(Alignment::Center));
assert_eq!(para.after, Length::from_twips(160));
assert_eq!(run.size, Some(56));
}
#[test]
fn puts_a_list_level_right_below_the_style_that_names_the_list() {
// `Base` sets the left indent, `List` names a list and sets the hanging indent, and
// `Item` is based on `List`.
let doc = parse(&format!(
r#"<w:styles xmlns:w="{W}"><w:docDefaults><w:pPrDefault/></w:docDefaults>
<w:style w:type="paragraph" w:styleId="Base"><w:pPr><w:ind w:left="100"/></w:pPr></w:style>
<w:style w:type="paragraph" w:styleId="List"><w:basedOn w:val="Base"/><w:pPr><w:numPr><w:numId w:val="3"/></w:numPr><w:ind w:hanging="50"/></w:pPr></w:style>
<w:style w:type="paragraph" w:styleId="Item"><w:basedOn w:val="List"/><w:pPr><w:spacing w:after="20"/></w:pPr></w:style>
</w:styles>"#
));
let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
let twips = |t: i64| Length::from_twips(t);
let level = crate::props::ParaProps {
indent_left: twips(720),
indent_first: twips(-360),
after: twips(40),
..crate::props::ParaProps::default()
};
let props = styles.paragraph_with_level(Some("Item"), None, &level);
// The level wins over `Base`, and `List` and `Item` win over the level.
assert_eq!(
(props.indent_left, props.indent_first, props.after),
(twips(720), twips(-50), twips(20))
);
// Without a style that names a list, the level comes after all styles.
let props = styles.paragraph_with_level(Some("Base"), None, &level);
assert_eq!(
(props.indent_left, props.indent_first),
(twips(720), twips(-360))
);
}
#[test]
fn spaces_paragraphs_like_word_without_default_paragraph_properties() {
let read = |defaults: &str| {
let doc = parse(&format!(
r#"<w:styles xmlns:w="{W}"><w:docDefaults>{defaults}</w:docDefaults></w:styles>"#
));
let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
let (para, _) = styles.paragraph(None, None);
(para.after, para.line)
};
let word = (Length::from_twips(160), Some(LineSpacing::Auto(278)));
assert_eq!(read(""), word);
// A default that is present, even without spacing, keeps the defaults of ECMA-376.
assert_eq!(read("<w:pPrDefault><w:pPr/></w:pPrDefault>"), (None, None));
}
#[test]
fn kerns_and_joins_ligatures_like_word_without_default_run_properties() {
let read = |styles: &str| {
let doc = parse(&format!(r#"<w:styles xmlns:w="{W}">{styles}</w:styles>"#));
let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
let (_, run) = styles.paragraph(None, None);
(run.kern, run.ligatures)
};
assert_eq!(read(""), (Some(2), Some(true)));
assert_eq!(read("<w:docDefaults/>"), (Some(2), Some(true)));
// A default that is present, even without these properties, keeps them off, and a
// style can turn them off.
let present = "<w:docDefaults><w:rPrDefault><w:rPr/></w:rPrDefault></w:docDefaults>";
assert_eq!(read(present), (None, None));
let normal = r#"<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:rPr><w:kern w:val="0"/></w:rPr></w:style>"#;
assert_eq!(read(normal), (Some(0), Some(true)));
}
#[test]
fn takes_the_template_font_and_size_without_default_run_properties() {
let template = (Some(FontRef::MinorLatin), Some(params::TEMPLATE_FONT_SIZE));
let read = |styles: &str| {
let doc = parse(&format!(r#"<w:styles xmlns:w="{W}">{styles}</w:styles>"#));
let (_, run) =
Styles::read(&mut PartReader::new(&doc), doc.root().unwrap()).paragraph(None, None);
(run.font_ascii, run.size)
};
assert_eq!(read(""), template);
assert_eq!(
read("<w:docDefaults><w:pPrDefault/></w:docDefaults>"),
template
);
// Default run properties that name no font or size keep the defaults of ECMA-376.
let present = "<w:docDefaults><w:rPrDefault><w:rPr/></w:rPrDefault></w:docDefaults>";
assert_eq!(read(present), (None, None));
let (para, run) = Styles::without_part().paragraph(None, None);
assert_eq!((run.font_hansi, run.size), template);
assert_eq!(para.after, Length::from_twips(params::DEFAULT_SPACE_AFTER));
}
#[test]
fn gives_theme_references_the_template_fonts_without_a_theme_part() {
let aptos = Theme::of_template(TemplateFonts::Aptos.minor(), TemplateFonts::Aptos.major());
assert_eq!(aptos.family(&FontRef::MinorLatin), Some("Aptos"));
assert_eq!(aptos.family(&FontRef::MajorLatin), Some("Aptos Display"));
assert_eq!(aptos.latin.minor, None);
let calibri = Theme::of_template(
TemplateFonts::Calibri.minor(),
TemplateFonts::Calibri.major(),
);
assert_eq!(calibri.family(&FontRef::MinorLatin), Some("Calibri"));
assert_eq!(calibri.family(&FontRef::MajorLatin), Some("Calibri Light"));
assert_eq!(Theme::default().family(&FontRef::MinorLatin), None);
}
#[test]
fn a_missing_style_gets_the_defaults() {
let doc = parse(&format!(
r#"<w:styles xmlns:w="{W}"><w:docDefaults/><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:pPr><w:spacing w:after="0"/></w:pPr></w:style></w:styles>"#
));
let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
let (para, _) = styles.paragraph(Some("Heading1"), None);
assert_eq!(
(para.after, para.line, para.style),
(
Length::from_twips(160),
Some(LineSpacing::Auto(278)),
Some("Heading1".to_owned())
)
);
assert_eq!(styles.paragraph(None, None).0.after, Length::from_twips(0));
}
#[test]
fn a_table_style_wins_over_a_template_value_that_the_defaults_give() {
let size_in_table = |default_size: u32| {
let doc = parse(&format!(
r#"<w:styles xmlns:w="{W}"><w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val="{default_size}"/></w:rPr></w:rPrDefault><w:pPrDefault/></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:rPr><w:sz w:val="32"/></w:rPr></w:style><w:style w:type="table" w:styleId="Grid"><w:rPr><w:sz w:val="18"/></w:rPr></w:style></w:styles>"#
));
let mut styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
styles.take_template();
let table = styles.table(Some("Grid"));
let (para, run) = styles.paragraph(None, Some(&table));
(run.size, para.line)
};
assert_eq!(size_in_table(24), (Some(18), Some(LineSpacing::Auto(278))));
assert_eq!(size_in_table(20), (Some(24), Some(LineSpacing::Auto(278))));
}
#[test]
fn gives_a_paragraph_its_own_properties_over_its_style_and_its_table_style() {
// Each level of the cascade sets one value that the level above it sets again: the
// table style the defaults' space after, the paragraph style the table style's
// alignment, and the paragraph its style's left indent. So a level that is missing, or
// that comes in another order, gives another tuple. The helper takes no list level and
// the styles hold no numbering, so its signature keeps it from a list level.
let doc = parse(&format!(
r#"<w:styles xmlns:w="{W}"><w:docDefaults><w:pPrDefault><w:pPr><w:spacing w:after="160"/></w:pPr></w:pPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Normal"/><w:style w:type="paragraph" w:styleId="Kept"><w:pPr><w:keepNext/><w:jc w:val="both"/><w:ind w:left="720"/></w:pPr></w:style><w:style w:type="table" w:styleId="Grid"><w:pPr><w:spacing w:after="0"/><w:jc w:val="center"/></w:pPr></w:style></w:styles>"#
));
let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
let grid = styles.table(Some("Grid"));
let own = ParaProps {
style: Some("Kept".to_owned()),
indent_left: Length::from_twips(360),
..ParaProps::default()
};
// (table style, space after): the table style's space after wins over the defaults'.
let cases = [
(None, Length::from_twips(160)),
(Some(&grid), Some(Length::ZERO)),
];
for (table, after) in cases {
let props = styles.paragraph_properties_without_list_level(&own, table);
let read = (
props.flags().keep_next,
props.style.as_deref(),
props.alignment,
props.indent_left,
props.after,
);
let (both, left) = (Some(Alignment::Both), Length::from_twips(360));
assert_eq!(read, (true, Some("Kept"), both, left, after), "{table:?}");
}
}
#[test]
fn gives_a_reference_to_no_paragraph_style_the_default_paragraph_style() {
let doc = parse(&format!(
r#"<w:styles xmlns:w="{W}"><w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val="20"/></w:rPr></w:rPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:rPr><w:sz w:val="28"/></w:rPr></w:style><w:style w:type="paragraph" w:styleId="Other"><w:basedOn w:val="Normal"/><w:rPr><w:sz w:val="32"/></w:rPr></w:style><w:style w:type="character" w:styleId="BigChar"><w:rPr><w:sz w:val="40"/></w:rPr></w:style><w:style w:type="table" w:styleId="BigTable"><w:rPr><w:sz w:val="36"/></w:rPr></w:style></w:styles>"#
));
let mut styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
let sizes = |styles: &Styles| {
["Other", "BigChar", "BigTable", "Absent"]
.map(|id| styles.paragraph(Some(id), None).1.size)
};
// Each ID takes the chain of what it names; an undefined one only the defaults.
assert_eq!(sizes(&styles), [Some(32), Some(40), Some(36), Some(20)]);
styles.refer_only_paragraph_styles();
// A character style, a table style and an undefined ID give the default paragraph
// style's 14 pt; a paragraph style keeps its own.
assert_eq!(sizes(&styles), [Some(32), Some(28), Some(28), Some(28)]);
let level = ParaProps::default();
let props = styles.paragraph_with_level(Some("BigChar"), None, &level);
assert_eq!(props.style.as_deref(), Some("Normal"));
}
#[test]
fn takes_the_default_style_of_the_template_and_keeps_the_defaults() {
let doc = parse(&format!(
r#"<w:styles xmlns:w="{W}"><w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val="20"/></w:rPr></w:rPrDefault><w:pPrDefault><w:pPr><w:spacing w:after="0" w:line="240"/></w:pPr></w:pPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:pPr><w:spacing w:after="240"/><w:jc w:val="center"/></w:pPr><w:rPr><w:sz w:val="32"/></w:rPr></w:style><w:style w:type="paragraph" w:styleId="Own"><w:basedOn w:val="Normal"/><w:pPr><w:spacing w:after="60"/></w:pPr><w:rPr><w:sz w:val="40"/></w:rPr></w:style><w:style w:type="paragraph" w:styleId="Free"/></w:styles>"#
));
let mut styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
styles.take_template();
let (free, free_run) = styles.paragraph(Some("Free"), None);
assert_eq!(
(free.after, free.line, free_run.size),
(
Length::from_twips(0),
Some(LineSpacing::Auto(240)),
Some(20)
)
);
let (normal, normal_run) = styles.paragraph(None, None);
assert_eq!(
(normal.after, normal.line, normal.alignment),
(Length::from_twips(160), Some(LineSpacing::Auto(278)), None)
);
assert_eq!(normal_run.size, Some(24));
let (own, own_run) = styles.paragraph(Some("Own"), None);
assert_eq!(
(own.after, own.line, own_run.size),
(
Length::from_twips(60),
Some(LineSpacing::Auto(278)),
Some(40)
)
);
}
#[test]
fn reads_whether_the_settings_link_the_styles_to_the_template() {
let read = |inner: &str| {
let doc = parse(&format!(
r#"<w:settings xmlns:w="{W}">{inner}</w:settings>"#
));
Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).template_styles
};
assert_eq!(read("<w:linkStyles/>"), TemplateStyles::Linked);
assert_eq!(read(r#"<w:linkStyles w:val="0"/>"#), TemplateStyles::Kept);
assert_eq!(read(""), TemplateStyles::Kept);
assert_eq!(
read("<w:attachedTemplate/><w:linkStyles/>"),
TemplateStyles::Kept
);
}
#[test]
fn uses_the_default_style_and_stops_cycles() {
let doc = parse(STYLES);
let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
let (normal, normal_run) = styles.paragraph(None, None);
assert_eq!(normal.style.as_deref(), Some("Normal"));
assert_eq!(normal.alignment, Some(Alignment::Start));
assert_eq!(normal_run.size, Some(22));
assert_eq!(styles.character("Strong").bold, Some(true));
assert_eq!(styles.paragraph(Some("Loop"), None).1.size, Some(22));
}
const TABLE_STYLES: &str = r#"<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val="22"/></w:rPr></w:rPrDefault>
<w:pPrDefault><w:pPr><w:spacing w:after="160" w:line="259"/></w:pPr></w:pPrDefault></w:docDefaults>
<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:pPr><w:spacing w:line="288"/></w:pPr></w:style>
<w:style w:type="table" w:default="1" w:styleId="Plain"><w:tblPr><w:tblCellMar><w:left w:w="108" w:type="dxa"/></w:tblCellMar></w:tblPr>
<w:tblStylePr w:type="firstRow"><w:rPr><w:i/></w:rPr></w:tblStylePr></w:style>
<w:style w:type="table" w:styleId="Grid"><w:basedOn w:val="Plain"/><w:pPr><w:spacing w:after="0" w:line="240"/></w:pPr><w:rPr><w:sz w:val="20"/></w:rPr>
<w:tblPr><w:tblBorders><w:top w:val="single" w:sz="4"/></w:tblBorders></w:tblPr>
<w:tblStylePr w:type="firstRow"><w:pPr><w:jc w:val="center"/></w:pPr><w:rPr><w:b/></w:rPr><w:tcPr><w:tcBorders><w:bottom w:val="single" w:sz="12"/></w:tcBorders></w:tcPr></w:tblStylePr>
<w:tblStylePr w:type="lastRow"><w:rPr><w:b/></w:rPr></w:tblStylePr>
<w:tblStylePr w:type="unknown"><w:rPr><w:b/></w:rPr></w:tblStylePr><w:tblStylePr/></w:style>
</w:styles>"#;
#[test]
fn cascades_table_styles() {
let doc = parse(TABLE_STYLES);
let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
let grid = styles.table(Some("Grid"));
assert_eq!(grid.table.margins.left, Length::from_twips(108));
assert!(grid.table.borders.top.is_some());
assert_eq!(grid.run.size, Some(20));
let fallback = styles.table(Some("Missing"));
assert_eq!(fallback, styles.table(None));
assert_eq!(fallback.table.margins.left, Length::from_twips(108));
assert_eq!(fallback.table.borders.top, None);
}
#[test]
fn merges_the_regions_of_a_table_style_chain() {
let doc = parse(TABLE_STYLES);
let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
let grid = styles.table(Some("Grid"));
assert_eq!(grid.regions.len(), 2);
let first = grid.region(Region::FirstRow).unwrap();
assert_eq!((first.run.italic, first.run.bold), (Some(true), Some(true)));
assert_eq!(first.para.alignment, Some(Alignment::Center));
assert!(first.borders.bottom.is_some());
assert_eq!(grid.region(Region::LastRow).unwrap().run.bold, Some(true));
assert_eq!(grid.region(Region::FirstCol), None);
}
#[test]
fn reads_the_cell_alignment_of_a_table_style_and_its_regions() {
let doc = parse(&format!(
r#"<w:styles xmlns:w="{W}">
<w:style w:type="table" w:styleId="Base"><w:tcPr><w:vAlign w:val="center"/></w:tcPr>
<w:tblStylePr w:type="firstRow"><w:tcPr><w:vAlign w:val="bottom"/></w:tcPr></w:tblStylePr></w:style>
<w:style w:type="table" w:styleId="Own"><w:basedOn w:val="Base"/></w:style>
<w:style w:type="table" w:styleId="Odd"><w:tcPr><w:vAlign w:val="middle"/></w:tcPr></w:style>
</w:styles>"#
));
let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
let own = styles.table(Some("Own"));
assert_eq!(own.align, Some(VerticalAlign::Center));
assert_eq!(
own.region(Region::FirstRow).unwrap().align,
Some(VerticalAlign::Bottom)
);
// A value outside `ST_VerticalJc` counts as missing.
assert_eq!(styles.table(Some("Odd")).align, None);
}
#[test]
fn reads_the_cell_shading_of_a_table_style_and_its_regions() {
let doc = parse(&TABLE_STYLES.replace(
r#"<w:tblStylePr w:type="lastRow">"#,
r#"<w:tcPr><w:shd w:val="clear" w:fill="DDDDDD"/></w:tcPr><w:tblStylePr w:type="lastRow"><w:tcPr><w:shd w:val="clear" w:fill="002060"/></w:tcPr>"#,
));
let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
let grid = styles.table(Some("Grid"));
assert_eq!(
grid.shading,
Some(crate::props::Color::Rgb([221, 221, 221]))
);
let last = grid.region(Region::LastRow).unwrap();
assert_eq!(last.shading, Some(crate::props::Color::Rgb([0, 32, 96])));
assert_eq!(grid.region(Region::FirstRow).unwrap().shading, None);
assert_eq!(styles.table(Some("Plain")).shading, None);
}
#[test]
fn puts_the_table_style_between_the_defaults_and_the_paragraph_style() {
let doc = parse(TABLE_STYLES);
let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
let grid = styles.table(Some("Grid"));
let (para, run) = styles.paragraph(None, Some(&grid));
assert_eq!(para.after, Some(Length::ZERO));
assert_eq!(para.line, Some(LineSpacing::Auto(288)));
assert_eq!(run.size, Some(20));
let (para, run) = styles.paragraph(None, None);
assert_eq!(para.after, Length::from_twips(160));
assert_eq!(run.size, Some(22));
}
#[test]
fn reads_theme_fonts() {
let xml = format!(
r#"<a:theme xmlns:a="{A}"><a:themeElements><a:fontScheme><a:majorFont><a:latin typeface="Calibri Light"/></a:majorFont><a:minorFont><a:latin typeface="Calibri"/></a:minorFont></a:fontScheme></a:themeElements></a:theme>"#
);
let doc = parse(&xml);
let theme = Theme::read(&mut PartReader::new(&doc), doc.root().unwrap());
assert_eq!(theme.family(&FontRef::MinorLatin), Some("Calibri"));
assert_eq!(theme.family(&FontRef::MajorLatin), Some("Calibri Light"));
assert_eq!(theme.family(&FontRef::Name("Arial".into())), Some("Arial"));
assert_eq!(theme.family(&FontRef::MinorBidi), None);
}
#[test]
fn picks_the_east_asian_font_of_the_theme_by_language() {
let xml = format!(
r#"<a:theme xmlns:a="{A}"><a:themeElements><a:fontScheme><a:majorFont><a:latin typeface="Calibri Light"/><a:ea typeface="Yu Gothic"/></a:majorFont><a:minorFont><a:latin typeface="Calibri"/><a:ea typeface=""/><a:font script="Jpan" typeface="Yu Mincho"/><a:font script="Hans" typeface="DengXian"/><a:font script="Hant" typeface="PMingLiU"/><a:font script="Hang" typeface="Malgun Gothic"/></a:minorFont></a:fontScheme></a:themeElements></a:theme>"#
);
let doc = parse(&xml);
let theme = Theme::read(&mut PartReader::new(&doc), doc.root().unwrap());
let minor = |lang| theme.family_for(&FontRef::MinorEastAsia, EastAsianScript::of(lang));
assert_eq!(minor("ja-JP"), Some("Yu Mincho"));
assert_eq!(minor("zh-CN"), Some("DengXian"));
assert_eq!(minor("zh-TW"), Some("PMingLiU"));
assert_eq!(minor("ko-KR"), Some("Malgun Gothic"));
assert_eq!(minor("en-US"), None);
// A set `a:ea` typeface wins over the script fonts.
assert_eq!(
theme.family_for(&FontRef::MajorEastAsia, EastAsianScript::of("ja-JP")),
Some("Yu Gothic")
);
assert_eq!(
theme.family_for(&FontRef::MinorLatin, None),
Some("Calibri")
);
}
#[test]
fn reads_the_complex_script_fonts_of_the_theme() {
let xml = format!(
r#"<a:theme xmlns:a="{A}"><a:themeElements><a:fontScheme><a:majorFont><a:latin typeface="Calibri Light"/><a:cs typeface="Tahoma"/></a:majorFont><a:minorFont><a:latin typeface="Calibri"/><a:cs typeface=""/><a:font script="Hebr" typeface="David"/><a:font script="Arab" typeface="Arial"/></a:minorFont></a:fontScheme></a:themeElements></a:theme>"#
);
let doc = parse(&xml);
let theme = Theme::read(&mut PartReader::new(&doc), doc.root().unwrap());
assert_eq!(theme.family(&FontRef::MajorBidi), Some("Tahoma"));
// Without a complex script typeface, the font of the Arabic script stands in.
assert_eq!(theme.family(&FontRef::MinorBidi), Some("Arial"));
}
#[test]
fn reads_alternate_font_names() {
let doc = parse(&format!(
r#"<w:fonts xmlns:w="{W}"><w:font w:name="ArialMT"><w:altName w:val="Arial, Helvetica"/></w:font><w:font w:name="Calibri"/></w:fonts>"#
));
let table = super::FontTable::read(&doc, doc.root().unwrap());
let alternate = |name: &str| {
table
.alternate(&FamilyName::new(name))
.map(FamilyName::as_str)
};
assert_eq!(alternate("ArialMT"), Some("Arial"));
assert_eq!(alternate("Calibri"), None);
// Word finds the entry of a name in another case.
assert_eq!(alternate("arialmt"), Some("Arial"));
assert_eq!(alternate("ARIALMT"), Some("Arial"));
}
#[test]
fn keeps_the_first_of_entries_that_name_one_family() {
use super::EastAsianCharset;
let doc = parse(&format!(
r#"<w:fonts xmlns:w="{W}"><w:font w:name="Probe"><w:altName w:val="Courier New"/><w:charset w:val="80"/></w:font><w:font w:name="PROBE"><w:altName w:val="Arial"/><w:charset w:val="86"/></w:font><w:font w:name="Other"/><w:font w:name="other"><w:altName w:val="Arial"/><w:charset w:val="81"/></w:font></w:fonts>"#
));
let table = super::FontTable::read(&doc, doc.root().unwrap());
let probe = FamilyName::new("probe");
assert_eq!(
table.alternate(&probe).map(FamilyName::as_str),
Some("Courier New")
);
assert_eq!(
table.east_asian_charset(&probe),
Some(EastAsianCharset::ShiftJis)
);
// The first entry of a family counts even when it gives neither field.
let other = FamilyName::new("Other");
assert_eq!(table.alternate(&other), None);
assert_eq!(table.east_asian_charset(&other), None);
}
#[test]
fn knows_the_east_asian_character_sets_of_the_entries() {
use super::EastAsianCharset;
let doc = parse(&format!(
r#"<w:fonts xmlns:w="{W}"><w:font w:name="仿宋_GB2312"><w:charset w:val="86"/></w:font><w:font w:name="標楷體"><w:charset w:val="88"/></w:font><w:font w:name="MS Mincho"><w:charset w:val="80"/></w:font><w:font w:name="Batang"><w:charset w:val="81"/></w:font><w:font w:name="Calibri"><w:charset w:val="00"/></w:font><w:font w:name="Arial"/></w:fonts>"#
));
let table = super::FontTable::read(&doc, doc.root().unwrap());
let cases = [
("仿宋_GB2312", Some(EastAsianCharset::Gb2312)),
("標楷體", Some(EastAsianCharset::Big5)),
("MS Mincho", Some(EastAsianCharset::ShiftJis)),
("Batang", Some(EastAsianCharset::Hangul)),
("ms mincho", Some(EastAsianCharset::ShiftJis)),
("Calibri", None),
("Arial", None),
("Missing", None),
];
for (name, set) in cases {
assert_eq!(
table.east_asian_charset(&FamilyName::new(name)),
set,
"{name}"
);
}
}
#[test]
fn reads_the_default_tab_stop() {
let doc = parse(&format!(
r#"<w:settings xmlns:w="{W}"><w:defaultTabStop w:val="708"/></w:settings>"#
));
let settings = Settings::read(&mut PartReader::new(&doc), doc.root().unwrap());
assert_eq!(Some(settings.default_tab_stop), Length::from_twips(708));
let doc = parse(&format!(r#"<w:settings xmlns:w="{W}"/>"#));
assert_eq!(
Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()),
Settings::default()
);
}
#[test]
fn kerns_punctuation_with_east_asian_layout_unless_the_setting_turns_it_off() {
let read = |inner: &str| {
let doc = parse(&format!(
r#"<w:settings xmlns:w="{W}">{inner}</w:settings>"#
));
Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).punctuation_kerning
};
let layout = "<w:compat><w:useFELayout/></w:compat>";
assert_eq!(read(layout), super::PunctuationKerning::On);
assert_eq!(
read(&format!("<w:noPunctuationKerning/>{layout}")),
super::PunctuationKerning::Off
);
assert_eq!(
read("<w:compat><w:balanceSingleByteDoubleByteWidth/></w:compat>"),
super::PunctuationKerning::Off
);
}
#[test]
fn lets_cells_follow_the_line_grid_only_with_adjust_line_height_in_table() {
let read = |inner: &str| {
let doc = parse(&format!(
r#"<w:settings xmlns:w="{W}">{inner}</w:settings>"#
));
Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).cell_grid
};
assert_eq!(read(""), super::CellGrid::Own);
assert_eq!(
read("<w:compat><w:adjustLineHeightInTable/></w:compat>"),
super::CellGrid::Follows
);
assert_eq!(
read(r#"<w:compat><w:adjustLineHeightInTable w:val="0"/></w:compat>"#),
super::CellGrid::Own
);
}
#[test]
fn compresses_punctuation_only_with_east_asian_layout() {
let read = |inner: &str| {
let doc = parse(&format!(
r#"<w:settings xmlns:w="{W}">{inner}</w:settings>"#
));
Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).punctuation
};
let control = r#"<w:characterSpacingControl w:val="compressPunctuation"/>"#;
assert_eq!(
read(&format!("{control}<w:compat><w:useFELayout/></w:compat>")),
super::Punctuation::Compressed
);
assert_eq!(read(control), super::Punctuation::Kept);
assert_eq!(
read(
r#"<w:characterSpacingControl w:val="doNotCompress"/><w:compat><w:useFELayout/></w:compat>"#
),
super::Punctuation::Kept
);
}
#[test]
fn spreads_gaps_with_east_asian_layout_whatever_the_punctuation() {
let read = |inner: &str| {
let doc = parse(&format!(
r#"<w:settings xmlns:w="{W}">{inner}</w:settings>"#
));
Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).gap_spread
};
assert_eq!(
read(
r#"<w:characterSpacingControl w:val="doNotCompress"/><w:compat><w:useFELayout/></w:compat>"#
),
super::GapSpread::Spread
);
assert_eq!(
read(r#"<w:characterSpacingControl w:val="compressPunctuation"/>"#),
super::GapSpread::Kept
);
}
#[test]
fn balances_byte_widths_only_with_its_own_option() {
let read = |compat: &str| {
let doc = parse(&format!(
r#"<w:settings xmlns:w="{W}"><w:compat>{compat}</w:compat></w:settings>"#
));
Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).full_width_spacing
};
let twice = super::FullWidthSpacing::Twice;
assert_eq!(read("<w:balanceSingleByteDoubleByteWidth/>"), twice);
assert_ne!(
read(r#"<w:balanceSingleByteDoubleByteWidth w:val="0"/>"#),
twice
);
assert_ne!(read("<w:useFELayout/><w:doNotExpandShiftReturn/>"), twice);
}
#[test]
fn keeps_soft_break_lines_unjustified_only_with_its_own_option() {
let read = |compat: &str| {
let doc = parse(&format!(
r#"<w:settings xmlns:w="{W}"><w:compat>{compat}</w:compat></w:settings>"#
));
Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).soft_break_lines
};
let kept = super::SoftBreakLines::AsLastLine;
assert_eq!(read("<w:doNotExpandShiftReturn/>"), kept);
assert_ne!(read(r#"<w:doNotExpandShiftReturn w:val="0"/>"#), kept);
assert_ne!(
read("<w:useFELayout/><w:balanceSingleByteDoubleByteWidth/>"),
kept
);
}
#[test]
fn reads_fixed_automatic_spacing_only_with_its_own_option() {
use crate::props::HtmlAutoSpacing;
let read = |compat: &str| {
let doc = parse(&format!(
r#"<w:settings xmlns:w="{W}"><w:compat>{compat}</w:compat></w:settings>"#
));
Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).html_auto_spacing
};
assert_eq!(
read("<w:doNotUseHTMLParagraphAutoSpacing/>"),
HtmlAutoSpacing::Fixed
);
assert_eq!(
read(r#"<w:doNotUseHTMLParagraphAutoSpacing w:val="0"/>"#),
HtmlAutoSpacing::Html
);
assert_eq!(read("<w:doNotExpandShiftReturn/>"), HtmlAutoSpacing::Html);
}
#[test]
fn balances_spaces_only_with_both_options() {
let read = |compat: &str| {
let doc = parse(&format!(
r#"<w:settings xmlns:w="{W}"><w:compat>{compat}</w:compat></w:settings>"#
));
Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).space_balance
};
let half = super::SpaceBalance::HalfEm;
assert_eq!(
read("<w:balanceSingleByteDoubleByteWidth/><w:useFELayout/>"),
half
);
assert_ne!(read("<w:balanceSingleByteDoubleByteWidth/>"), half);
assert_ne!(read("<w:useFELayout/><w:doNotExpandShiftReturn/>"), half);
assert_ne!(
read(r#"<w:balanceSingleByteDoubleByteWidth/><w:useFELayout w:val="0"/>"#),
half
);
}
#[test]
fn reads_the_open_type_features_setting() {
// As Word 2010 writes it, and turned off.
for (value, on) in [("1", true), ("0", false)] {
let doc = parse(&format!(
r#"<w:settings xmlns:w="{W}"><w:compat><w:compatSetting w:name="compatibilityMode" w:val="14"/><w:compatSetting w:name="enableOpenTypeFeatures" w:val="{value}"/></w:compat></w:settings>"#
));
let rules = Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).mode_rules;
let expected = ModeRules::of(CompatibilityMode::Mode14).with_open_type_features(on);
assert_eq!(rules, expected);
}
}
#[test]
fn reads_the_compatibility_mode() {
let doc = parse(&format!(
r#"<w:settings xmlns:w="{W}"><w:compat><w:compatSetting w:name="other" w:val="1"/><w:compatSetting w:name="compatibilityMode" w:val="14"/></w:compat></w:settings>"#
));
let settings = Settings::read(&mut PartReader::new(&doc), doc.root().unwrap());
assert_eq!(
settings.mode_rules,
ModeRules::of(CompatibilityMode::Mode14)
);
assert!(!settings.even_and_odd_headers);
// Word also reads the setting outside `w:compat`.
let outside = parse(&format!(
r#"<w:settings xmlns:w="{W}"><w:compatSetting w:name="compatibilityMode" w:val="16"/></w:settings>"#
));
let rules =
Settings::read(&mut PartReader::new(&outside), outside.root().unwrap()).mode_rules;
assert_eq!(rules, ModeRules::of(CompatibilityMode::Mode15));
let doc = parse(&format!(
r#"<w:settings xmlns:w="{W}"><w:evenAndOddHeaders/></w:settings>"#
));
assert!(
Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).even_and_odd_headers
);
assert_eq!(settings.notes.endnotes.format, Format::LowerRoman);
let doc = parse(&format!(
r#"<w:settings xmlns:w="{W}"><w:endnotePr><w:numFmt w:val="decimal"/></w:endnotePr></w:settings>"#
));
let settings = Settings::read(&mut PartReader::new(&doc), doc.root().unwrap());
assert_eq!(settings.notes.endnotes.format, Format::Decimal);
}
#[test]
fn reads_whether_the_indent_is_a_tab_stop_for_list_labels() {
let read = |compat: &str| {
let doc = parse(&format!(
r#"<w:settings xmlns:w="{W}"><w:compat>{compat}</w:compat></w:settings>"#
));
Settings::read(&mut PartReader::new(&doc), doc.root().unwrap())
.indent_is_numbering_tab_stop
};
assert!(read(""));
assert!(!read("<w:doNotUseIndentAsNumberingTabStop/>"));
assert!(read(r#"<w:doNotUseIndentAsNumberingTabStop w:val="0"/>"#));
}
#[test]
fn reads_whether_math_settings_turn_on_small_fractions() {
use crate::props::SmallFractions;
let read = |inner: &str| {
let doc = parse(&format!(
r#"<w:settings xmlns:w="{W}" xmlns:m="{M}">{inner}</w:settings>"#
));
Settings::read(&mut PartReader::new(&doc), doc.root().unwrap()).small_frac
};
assert_eq!(read(""), SmallFractions::Off);
assert_eq!(
read(r#"<m:mathPr><m:smallFrac m:val="0"/></m:mathPr>"#),
SmallFractions::Off
);
assert_eq!(
read(r#"<m:mathPr><m:smallFrac m:val="1"/></m:mathPr>"#),
SmallFractions::On
);
assert_eq!(
read("<m:mathPr><m:smallFrac/></m:mathPr>"),
SmallFractions::On
);
}
#[test]
fn each_enumeration_table_holds_each_name_of_its_type() {
// The names of each simple type in ISO/IEC 29500-4:2016 (Transitional), wml.xsd.
// ST_StyleType
crate::enumerations::assert_names(super::STYLE_KIND, "paragraph character table numbering");
// ST_CharacterSpacing
crate::enumerations::assert_names(
super::CHARACTER_SPACING,
"doNotCompress compressPunctuation compressPunctuationAndJapaneseKana",
);
}
#[test]
fn toggle_properties_xor_across_style_layers() {
let doc = parse(&format!(
concat!(
r#"<w:styles xmlns:w="{W}">"#,
r#"<w:style w:type="paragraph" w:styleId="PNoBold"/>"#,
r#"<w:style w:type="paragraph" w:styleId="PBold"><w:rPr><w:b/></w:rPr></w:style>"#,
r#"<w:style w:type="character" w:styleId="COn"><w:rPr><w:b/></w:rPr></w:style>"#,
r#"<w:style w:type="character" w:styleId="COff"><w:rPr><w:b w:val="0"/></w:rPr></w:style>"#,
r#"<w:style w:type="character" w:styleId="CChildOff"><w:basedOn w:val="COn"/><w:rPr><w:b w:val="0"/></w:rPr></w:style>"#,
r#"<w:style w:type="character" w:styleId="CGrandOn"><w:basedOn w:val="COn"/><w:rPr><w:b/></w:rPr></w:style>"#,
r#"<w:style w:type="table" w:styleId="TBold"><w:rPr><w:b/></w:rPr></w:style>"#,
r#"</w:styles>"#,
),
W = W,
));
let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
let table = styles.table(Some("TBold"));
let cases = [
("PBold", false, None, true),
("PBold", false, Some("COn"), false),
("PBold", false, Some("COff"), true),
("PBold", false, Some("CChildOff"), true),
("PBold", false, Some("CGrandOn"), false),
("PNoBold", false, Some("COn"), true),
("PNoBold", true, None, true),
("PBold", true, None, false),
("PNoBold", true, Some("COn"), false),
("PBold", true, Some("COn"), true),
];
let got: Vec<bool> = cases
.iter()
.map(|&(ps, use_tbl, cs, _)| {
let (_, mut run) = styles.paragraph(Some(ps), use_tbl.then_some(&table));
if let Some(cs) = cs {
styles.apply_character(&mut run, cs);
}
run.bold.unwrap_or(false)
})
.collect();
let want: Vec<bool> = cases.iter().map(|c| c.3).collect();
assert_eq!(got, want);
}
#[test]
fn toggle_properties_overlay_without_xor_when_doc_defaults_enable_them() {
let dd_doc = parse(&format!(
concat!(
r#"<w:styles xmlns:w="{W}">"#,
r#"<w:docDefaults><w:rPrDefault><w:rPr><w:b/></w:rPr></w:rPrDefault></w:docDefaults>"#,
r#"<w:style w:type="paragraph" w:styleId="POn"><w:rPr><w:b/></w:rPr></w:style>"#,
r#"<w:style w:type="paragraph" w:styleId="POff"><w:rPr><w:b w:val="0"/></w:rPr></w:style>"#,
r#"<w:style w:type="character" w:styleId="COn"><w:rPr><w:b/></w:rPr></w:style>"#,
r#"<w:style w:type="character" w:styleId="COff"><w:rPr><w:b w:val="0"/></w:rPr></w:style>"#,
r#"</w:styles>"#,
),
W = W,
));
let dd_styles = Styles::read(&mut PartReader::new(&dd_doc), dd_doc.root().unwrap());
let (_, mut r1) = dd_styles.paragraph(Some("POn"), None);
dd_styles.apply_character(&mut r1, "COn");
let (_, r2) = dd_styles.paragraph(Some("POff"), None);
let (_, mut r3) = dd_styles.paragraph(None, None);
dd_styles.apply_character(&mut r3, "COff");
assert_eq!(
(r1.bold, r2.bold, r3.bold),
(Some(true), Some(false), Some(false))
);
}
#[test]
fn table_style_with_table_properties_drops_forward_based_on() {
let doc = parse(&format!(
concat!(
r#"<w:styles xmlns:w="{W}">"#,
r#"<w:style w:type="table" w:styleId="FNone"><w:basedOn w:val="Base"/></w:style>"#,
r#"<w:style w:type="table" w:styleId="FEmptyTblPr"><w:basedOn w:val="Base"/><w:tblPr/></w:style>"#,
r#"<w:style w:type="table" w:styleId="FPPr"><w:basedOn w:val="Base"/><w:pPr><w:jc w:val="left"/></w:pPr></w:style>"#,
r#"<w:style w:type="table" w:styleId="FRPr"><w:basedOn w:val="Base"/><w:rPr><w:b/></w:rPr></w:style>"#,
r#"<w:style w:type="table" w:styleId="FTblPr"><w:basedOn w:val="Base"/><w:tblPr><w:tblInd w:w="0" w:type="dxa"/></w:tblPr></w:style>"#,
r#"<w:style w:type="table" w:styleId="FTrPr"><w:basedOn w:val="Base"/><w:trPr><w:cantSplit/></w:trPr></w:style>"#,
r#"<w:style w:type="table" w:styleId="FTcPr"><w:basedOn w:val="Base"/><w:tcPr><w:vAlign w:val="top"/></w:tcPr></w:style>"#,
r#"<w:style w:type="table" w:styleId="FRegion"><w:basedOn w:val="Base"/><w:tblStylePr w:type="lastRow"><w:rPr><w:i/></w:rPr></w:tblStylePr></w:style>"#,
r#"<w:style w:type="table" w:styleId="Base"><w:rPr><w:sz w:val="32"/></w:rPr><w:tblPr><w:tblCellMar><w:left w:w="240" w:type="dxa"/></w:tblCellMar></w:tblPr></w:style>"#,
r#"<w:style w:type="table" w:styleId="BTblPr"><w:basedOn w:val="Base"/><w:tblPr><w:tblInd w:w="0" w:type="dxa"/></w:tblPr></w:style>"#,
r#"<w:style w:type="paragraph" w:styleId="PChild"><w:basedOn w:val="PBase"/><w:pPr><w:spacing w:after="0"/></w:pPr></w:style>"#,
r#"<w:style w:type="paragraph" w:styleId="PBase"><w:pPr><w:ind w:left="720"/></w:pPr></w:style>"#,
r#"<w:style w:type="character" w:styleId="CChild"><w:basedOn w:val="CBase"/><w:rPr><w:b/></w:rPr></w:style>"#,
r#"<w:style w:type="character" w:styleId="CBase"><w:rPr><w:sz w:val="36"/></w:rPr></w:style>"#,
r#"</w:styles>"#,
),
W = W,
));
let styles = Styles::read(&mut PartReader::new(&doc), doc.root().unwrap());
let left = Length::from_twips(240);
let got: Vec<_> = [
"FNone",
"FEmptyTblPr",
"FPPr",
"FRPr",
"BTblPr",
"FTblPr",
"FTrPr",
"FTcPr",
"FRegion",
]
.into_iter()
.map(|id| {
let t = styles.table(Some(id));
(t.resolved, t.table.margins.left, t.run.size)
})
.collect();
let want = [
(true, left, Some(32)),
(true, left, Some(32)),
(true, left, Some(32)),
(true, left, Some(32)),
(true, left, Some(32)),
(true, None, None),
(true, None, None),
(true, None, None),
(true, None, None),
];
assert_eq!(got, want);
assert_eq!(
(
styles.table(None).resolved,
styles.table(Some("Missing")).resolved,
styles.paragraph(Some("PChild"), None).0.indent_left,
styles.character("CChild").size,
),
(false, false, Length::from_twips(720), Some(36))
);
}
}