fix: write Normal as the default paragraph style, so Pages draws math at its size, and draw angle brackets in LibreOffice (#3554)

This commit is contained in:
Dolan
2026-09-27 20:29:16 +01:00
committed by GitHub
parent 7ada74f6d1
commit edb96fb088
38 changed files with 184 additions and 20 deletions
+1 -1
View File
@@ -442,7 +442,7 @@ new Paragraph({
Word is the reference. Other applications differ:
- **LibreOffice** centres every column of a matrix, centres the rows of an equation array without lining them up, and shows the `&` between parts and the `#` before equation numbers.
- **Pages** centres every column of a matrix and shows the `#` before equation numbers. It draws all math very small unless the document's default paragraph style has a size, which `docx` doesn't write.
- **Pages** centres every column of a matrix and shows the `#` before equation numbers.
- **Word 2013 and older** show the `#` before equation numbers.
## Demo
+13
View File
@@ -152,6 +152,19 @@ const doc = new Document({
Setting document defaults acts like a `*` rule in CSS: it applies to every paragraph and run in the document, but at a low priority level. Other styles affecting this property will override these defaults.
### The Normal style
Paragraphs that don't name a style use the default paragraph style, `Normal`, which the headings and other built-in styles are based on. `docx` writes a `Normal` with no formatting of its own, so paragraphs take the document defaults. To format it, give a paragraph style with the id `Normal`. It takes the place of `docx`'s and stays the default:
```ts
const doc = new Document({
styles: {
paragraphStyles: [{ id: "Normal", name: "Normal", run: { font: "Calibri", size: 22 } }],
},
sections: [],
});
```
## Advanced formatting
### Style inheritance
Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 68 KiB

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 48 KiB

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 48 KiB

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 50 KiB

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 75 KiB

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 38 KiB

@@ -20,14 +20,14 @@ describe("MathAngledBrackets", () => {
{
"m:begChr": {
_attr: {
"m:val": "〈",
"m:val": "⟨",
},
},
},
{
"m:endChr": {
_attr: {
"m:val": "〉",
"m:val": "⟩",
},
},
},
@@ -39,8 +39,9 @@ export class MathAngledBrackets extends XmlComponent {
this.root.push(
createMathBracketProperties({
characters: {
beginningCharacter: "〈",
endingCharacter: "〉",
// UnicodeMath's \langle and \rangle (U+27E8, U+27E9). LibreOffice doesn't draw U+2329 and U+232A
beginningCharacter: "⟨",
endingCharacter: "⟩",
},
}),
);
+7 -2
View File
@@ -28,6 +28,7 @@ import {
type IBaseParagraphStyleOptions,
ListParagraph,
StrongStyle,
StyleForParagraph,
TitleStyle,
} from "./style";
import type { IStylesOptions } from "./styles";
@@ -88,13 +89,17 @@ export type IDefaultStylesOptions = {
};
/**
* docx's default styles, each under the option of `styles.default` that configures it.
* docx's default styles, each under the option of `styles.default` that configures it, and Normal.
*
* @internal
*/
export const createDefaultStyles = (
options: IDefaultStylesOptions = {},
): { readonly [Key in keyof IDefaultStylesOptions]-?: XmlComponent } => ({
): { readonly normal: XmlComponent } & { readonly [Key in keyof IDefaultStylesOptions]-?: XmlComponent } => ({
// The style of paragraphs that don't name one, which the headings and others are based on. It has no formatting, so
// it changes nothing in Word, which takes Normal as the default paragraph style anyway. A style with its id, such as
// one in paragraphStyles or externalStyles, takes its place
normal: new StyleForParagraph({ id: "Normal", name: "Normal", quickFormat: true }),
document: new DocumentDefaults(options.document ?? {}),
title: new TitleStyle({
run: {
+84 -1
View File
@@ -186,7 +186,7 @@ describe("Styles", () => {
{ "w:latentStyles": { _attr: { "w:defQFormat": "0" } } },
{
"w:style": [
{ _attr: { "w:type": "paragraph", "w:styleId": "Normal" } },
{ _attr: { "w:type": "paragraph", "w:styleId": "Normal", "w:default": "1" } },
{ "w:name": { _attr: { "w:val": "Normal" } } },
],
},
@@ -194,6 +194,89 @@ describe("Styles", () => {
});
});
describe("the default paragraph style", () => {
const stylesOf = (styles: Styles): readonly { readonly id: string; readonly attributes: Record<string, unknown> }[] => {
const children: readonly any[] = new Formatter().format(styles)["w:styles"];
return children
.filter((child) => child["w:style"])
.map((child) => {
const attributes = [child["w:style"]].flat().find((part: any) => part._attr)._attr;
return { id: attributes["w:styleId"], attributes };
});
};
const defaults = (styles: Styles): readonly string[] =>
stylesOf(styles)
.filter(({ attributes }) => attributes["w:default"] !== undefined)
.map(({ id }) => id);
const external = (xml: string): Styles =>
new Styles(new ExternalStylesFactory().newInstance(`<w:styles xmlns:w="main">${xml}</w:styles>`));
it("is docx's own Normal, which has no formatting and comes first", () => {
const styles = new Styles(new DefaultStylesFactory().newInstance());
const tree = new Formatter().format(styles)["w:styles"];
expect(tree[2]).to.deep.equal({
"w:style": [
{ _attr: { "w:type": "paragraph", "w:styleId": "Normal", "w:default": "1" } },
{ "w:name": { _attr: { "w:val": "Normal" } } },
{ "w:qFormat": EMPTY_OBJECT },
],
});
expect(defaults(styles)).to.deep.equal(["Normal"]);
});
it("is a Normal from paragraphStyles, which takes the place of docx's", () => {
const styles = new Styles({
...new DefaultStylesFactory().newInstance(),
paragraphStyles: [{ id: "Normal", name: "Normal", run: { size: 24 } }],
});
expect(defaults(styles)).to.deep.equal(["Normal"]);
expect(stylesOf(styles).filter(({ id }) => id === "Normal")).to.have.length(1);
});
it("is left as it is when another style is marked as the default", () => {
const styles = external(
'<w:style w:type="paragraph" w:default="1" w:styleId="Body"/><w:style w:type="paragraph" w:styleId="Normal"/>',
);
expect(defaults(styles)).to.deep.equal(["Body"]);
});
it("counts a style without a type as a paragraph style, as the schema does", () => {
expect(
defaults(external('<w:style w:default="true" w:styleId="Body"/><w:style w:type="paragraph" w:styleId="Normal"/>')),
).to.deep.equal(["Body"]);
expect(defaults(external('<w:style w:styleId="Normal"/>'))).to.deep.equal(["Normal"]);
});
it("doesn't count a style marked off, or a default of another type", () => {
for (const off of ["0", "false", "off"]) {
expect(
defaults(
external(
`<w:style w:type="paragraph" w:default="${off}" w:styleId="Body"/><w:style w:type="paragraph" w:styleId="Normal"/>`,
),
),
off,
).to.deep.equal(["Body", "Normal"]);
}
expect(
defaults(
external(
'<w:style w:type="character" w:default="1" w:styleId="DefaultParagraphFont"/><w:style w:type="paragraph" w:styleId="Normal"/>',
),
),
).to.deep.equal(["DefaultParagraphFont", "Normal"]);
});
it("isn't a character or table style called Normal", () => {
expect(defaults(external('<w:style w:type="character" w:styleId="Normal"/>'))).to.deep.equal([]);
expect(defaults(new Styles({ characterStyles: [{ id: "Normal", name: "Normal" }] }))).to.deep.equal([]);
});
it("isn't marked when there is no Normal", () => {
expect(defaults(new Styles({ paragraphStyles: [{ id: "Body", name: "Body" }] }))).to.deep.equal([]);
});
});
it("should write styles with nothing in them as an empty element", () => {
expect(new Formatter().format(new Styles({}))).to.deep.equal({ "w:styles": EMPTY_OBJECT });
});
+35 -3
View File
@@ -44,8 +44,28 @@ export type IStylesOptions = {
/** The name of a formatted element, such as `w:style`, or `_attr` for its parent's attributes */
const nameOf = (child: unknown): string | undefined => (typeof child === "object" ? Object.keys(child as object)[0] : undefined);
/** The attributes of a formatted `w:style` */
const attributesOf = (style: IXmlableObject): Record<string, unknown> | undefined =>
[style["w:style"]].flat().find((part) => part._attr)?._attr;
/** The id of a formatted `w:style` */
const styleIdOf = (style: IXmlableObject): string | undefined => [style["w:style"]].flat().find((part) => part._attr)?._attr["w:styleId"];
const styleIdOf = (style: IXmlableObject): string | undefined => attributesOf(style)?.["w:styleId"] as string | undefined;
/** Whether a formatted `w:style` is a paragraph style marked as the default for paragraphs */
const isDefaultParagraphStyle = (style: IXmlableObject): boolean => {
const attributes = attributesOf(style);
// A style's type is paragraph when it isn't given, and ST_OnOff is off as 0, false or off
return (
(attributes?.["w:type"] ?? "paragraph") === "paragraph" &&
attributes?.["w:default"] !== undefined &&
!["0", "false", "off"].includes(String(attributes["w:default"]))
);
};
/** A formatted `w:style`, marked as the default for its type */
const markedAsDefault = (style: IXmlableObject): IXmlableObject => ({
"w:style": [style["w:style"]].flat().map((part) => (part._attr ? { _attr: { ...part._attr, "w:default": "1" } } : part)),
});
/**
* Represents the styles definitions in a WordprocessingML document.
@@ -116,7 +136,8 @@ export class Styles extends XmlComponent {
* Writes the styles in the schema's order: the document defaults, the latent styles, then the styles. A style id
* can only be used once, so a style replaces an earlier one with its id. That way external styles replace docx's
* default styles, and paragraph and character styles replace the default and imported ones. Of several document
* defaults, or several latent styles, the last is kept.
* defaults, or several latent styles, the last is kept. Normal is marked as the default paragraph style when no
* style is.
*/
public prepForXml(context: IContext): IXmlableObject {
const xml = super.prepForXml(context) as IXmlableObject;
@@ -126,11 +147,22 @@ export class Styles extends XmlComponent {
}
const named = (name: string): readonly unknown[] => children.filter((child) => nameOf(child) === name);
const ids = children.map((child) => (nameOf(child) === "w:style" ? styleIdOf(child) : undefined));
const styles = children.filter(
const kept = children.filter(
(child, index) =>
!["_attr", "w:docDefaults", "w:latentStyles"].includes(nameOf(child) as string) &&
(ids[index] === undefined || ids.lastIndexOf(ids[index]) === index),
);
// Word takes Normal as the default paragraph style when no style is marked as the default, such as when Normal
// comes from paragraphStyles. Other applications need the mark: Pages draws math tiny without it
const styles = kept.some((child) => nameOf(child) === "w:style" && isDefaultParagraphStyle(child))
? kept
: kept.map((child) =>
nameOf(child) === "w:style" &&
styleIdOf(child) === "Normal" &&
(attributesOf(child)?.["w:type"] ?? "paragraph") === "paragraph"
? markedAsDefault(child)
: child,
);
return {
"w:styles": [...named("_attr"), ...named("w:docDefaults").slice(-1), ...named("w:latentStyles").slice(-1), ...styles],
};
+25 -3
View File
@@ -42,10 +42,11 @@ describe("getTextStyles", () => {
expect(getTextStyles(context)).to.equal(getTextStyles(context));
});
it("should use the style marked as the default, or Normal", () => {
expect(stylesOf({}).defaultParagraphStyle).to.equal(undefined);
it("should use the style marked as the default, which is Normal unless another is", () => {
// docx writes Normal as the default paragraph style, and one in paragraphStyles takes its place
expect(stylesOf({}).defaultParagraphStyle).to.equal("Normal");
expect(stylesOf({ paragraphStyles: [{ id: "Normal", name: "Normal" }] }).defaultParagraphStyle).to.equal("Normal");
// A character style called Normal isn't the default for paragraphs
// A character style called Normal isn't the default for paragraphs, and replaces docx's Normal, as ids are unique
expect(stylesOf({ characterStyles: [{ id: "Normal", name: "Normal" }] }).defaultParagraphStyle).to.equal(undefined);
const imported = getTextStyles(
@@ -67,6 +68,27 @@ describe("getTextStyles", () => {
expect(imported.defaultCharacterStyle).to.equal("DefaultParagraphFont");
});
it("should take a style without a type as a paragraph style, as the schema does and as Styles writes it", () => {
const styles = getTextStyles(
contextOf(
new File({
externalStyles: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:style w:default="1" w:styleId="Body"><w:name w:val="Body"/><w:rPr><w:sz w:val="28"/></w:rPr></w:style>
<w:style w:styleId="Quote"><w:name w:val="Quote"/><w:basedOn w:val="Body"/><w:rPr><w:b/></w:rPr></w:style>
</w:styles>`,
sections: [],
}),
),
);
expect(styles.defaultParagraphStyle).to.equal("Body");
expect(readOne(new Paragraph({ children: [new TextRun("Body")] }), styles).spans).to.deep.equal([{ text: "Body", size: 14 }]);
// Quote is based on Body, and neither has a type
expect(readOne(new Paragraph({ style: "Quote", children: [new TextRun("Quote")] }), styles).spans).to.deep.equal([
{ text: "Quote", size: 14, bold: true },
]);
});
it("should read styles imported from another document, whose values are text", () => {
const styles = getTextStyles(
contextOf(
+14 -6
View File
@@ -37,7 +37,7 @@ type ThemeFonts = {
const OFFICE_THEME_FONTS: ThemeFonts = { headings: "Calibri Light", body: "Calibri" };
type StyleDefinition = {
readonly type?: string;
readonly type: string;
readonly basedOn?: string;
readonly run: RunFormat;
readonly paragraph: ParagraphFormat;
@@ -61,9 +61,16 @@ export type TextStyles = {
};
/**
* No styles: text is measured in Word's own defaults, 10pt Times New Roman with single spacing, and Office's theme.
* Word's own defaults: 10pt Times New Roman with single spacing, Office's theme, and a Normal paragraph style with no
* formatting as the default, as `docx` writes it.
*/
export const WORD_DEFAULT_STYLES: TextStyles = { run: {}, paragraph: {}, styles: new Map(), themeFonts: OFFICE_THEME_FONTS };
export const WORD_DEFAULT_STYLES: TextStyles = {
run: {},
paragraph: {},
styles: new Map([["Normal", { type: "paragraph", run: {}, paragraph: {} }]]),
defaultParagraphStyle: "Normal",
themeFonts: OFFICE_THEME_FONTS,
};
// Small capitals are drawn as capitals at 80% of the size of the text, as LibreOffice draws them
const SMALL_CAPS_SCALE = 0.8;
@@ -228,7 +235,8 @@ export const readTextStyles = (xml: XmlObject, themeFonts: ThemeFonts = OFFICE_T
id: stringOf(attributes["w:styleId"]),
isDefault: attributes["w:default"] !== undefined && !isOff(attributes["w:default"]),
definition: {
type: stringOf(attributes["w:type"]),
// A style without a type is a paragraph style, as Styles takes it
type: stringOf(attributes["w:type"]) ?? "paragraph",
basedOn: valueOf(children, "w:basedOn"),
run: readRunFormat(find(children, "w:rPr"), themeFonts),
paragraph: readParagraphFormat(find(children, "w:pPr")),
@@ -244,8 +252,8 @@ export const readTextStyles = (xml: XmlObject, themeFonts: ThemeFonts = OFFICE_T
run: combine(defaults.map((children) => readRunFormat(find(childrenOf(find(children, "w:rPrDefault")), "w:rPr"), themeFonts))),
paragraph: combine(defaults.map((children) => readParagraphFormat(find(childrenOf(find(children, "w:pPrDefault")), "w:pPr")))),
styles: byId,
// Word uses "Normal" for paragraphs when no paragraph style is marked as the default
defaultParagraphStyle: defaultStyle("paragraph") ?? (byId.get("Normal")?.type === "paragraph" ? "Normal" : undefined),
// Styles marks Normal as the default when no paragraph style is, as Word takes it
defaultParagraphStyle: defaultStyle("paragraph"),
defaultCharacterStyle: defaultStyle("character"),
themeFonts,
};