feat(layout): stop at text in an embedded font that Office also offers, as Word draws it in Office's own copy (#3710)

* feat(layout): stop at text in a font from a file that Office also offers, as Word draws it in Office's copy

Word for Mac drew Pacifico, which a document embedded, in Office's own cloud
copy of it rather than the embedded file. docx/layout now stops at text in a
font embedded or given as a file when Office offers a font of that name, but
for Office's fonts of the width tables, and measures the file when guessing,
noting the guess.

The names come from Office's catalog of its cloud fonts (version 4.42),
cross-checked against Microsoft's published list, generated by
scripts/generate-office-cloud-fonts.ts. The layout demos of embedded fonts
and fonts from files move from Pacifico to Kaushan Script, which Office
doesn't offer.

* fix(layout): stop at Latin text in an East Asian font Office offers, given as a file

The width tables have the East Asian characters of fonts such as Microsoft
YaHei but not their Latin letters, so offeredByOffice now takes the text
being measured, and Latin text in such a font from a file stops as Office's
copy may draw it differently.

* fix(scripts): strip every angle bracket and unescape & last in the cloud fonts generator

CodeQL flagged the published list's cell text: one pass of tag stripping could
leave part of a tag, and unescaping & before   could unescape twice.
The generated list is unchanged.

* fix(scripts): read the text between a cell's tags in the cloud fonts generator

CodeQL still read removing tags with a replace as incomplete sanitization,
so the cell's text is now collected from between its tags rather than by
removing them. The generated list is unchanged.
This commit is contained in:
Dolan
2026-10-05 23:06:45 +01:00
committed by GitHub
parent 0e7b7f75d4
commit 72ebbb1be7
14 changed files with 1631 additions and 43 deletions
Binary file not shown.
+8 -6
View File
@@ -1,8 +1,10 @@
// Page numbers worked out by docx/layout for text in a font the document embeds, which it measures from the embedded
// file, as Word draws the text in it, with nothing more given to estimatePageNumbers. The text is in Pacifico, which isn't
// in the width tables, so without the file the layout would stop at it. It is one of the documents
// scripts/compare-layout.sh checks against LibreOffice. See docs/usage/layout.md.
// cspell:ignore Pacifico
// file, as Word draws the text in it, with nothing more given to estimatePageNumbers. The text is in Kaushan Script, which
// isn't in the width tables, so without the file the layout would stop at it. It isn't one of the fonts Office offers
// either: Word for Mac draws text in one of those, such as Pacifico, in Office's own copy of it, rather than in the file
// the document embeds, so the layout stops at it. It is one of the documents scripts/compare-layout.sh checks against
// LibreOffice. See docs/usage/layout.md.
// cspell:ignore Kaushan Pacifico
import * as fs from "fs";
import { CharacterSet, Document, HeadingLevel, Packer, Paragraph, TableOfContents, TextRun } from "docx";
@@ -16,10 +18,10 @@ const heading = (title: string): Paragraph => new Paragraph({ heading: HeadingLe
const doc = new Document({
pageNumbers: estimatePageNumbers,
fonts: [{ name: "Pacifico", data: fs.readFileSync("./demo/assets/Pacifico.ttf"), characterSet: CharacterSet.ANSI }],
fonts: [{ name: "Kaushan Script", data: fs.readFileSync("./demo/assets/KaushanScript-Regular.ttf"), characterSet: CharacterSet.ANSI }],
styles: {
default: {
document: { run: { font: "Pacifico", size: 22 }, paragraph: { spacing: { after: 160 } } },
document: { run: { font: "Kaushan Script", size: 22 }, paragraph: { spacing: { after: 160 } } },
heading1: {
run: { font: "Calibri", size: 32, color: "2F5496" },
paragraph: { spacing: { before: 240, after: 0 }, keepNext: true },
+7 -7
View File
@@ -1,14 +1,14 @@
// Page numbers worked out by docx/layout for text in a font it measures from the font's file, rather than as the most
// similar font it knows. The text is in Pacifico, which the document embeds so it is drawn in it, with kerning on in
// some paragraphs. It is one of the documents scripts/compare-layout.sh checks against LibreOffice. See
// similar font it knows. The text is in Kaushan Script, which the document embeds so it is drawn in it, with kerning on
// in some paragraphs. It is one of the documents scripts/compare-layout.sh checks against LibreOffice. See
// docs/usage/layout.md.
// cspell:ignore Pacifico
// cspell:ignore Kaushan
import * as fs from "fs";
import { CharacterSet, Document, HeadingLevel, Packer, Paragraph, TableOfContents, TextRun } from "docx";
import { estimatePageNumbersWith } from "docx/layout";
const pacifico = fs.readFileSync("./demo/assets/Pacifico.ttf");
const kaushan = fs.readFileSync("./demo/assets/KaushanScript-Regular.ttf");
const WORDS =
"the lighthouse keeper wrote to the harbour master about the storm that took the jetty and the boats that came back to the bay".split(
@@ -20,11 +20,11 @@ const text = (words: number, seed: number): string =>
const heading = (title: string): Paragraph => new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun(title)] });
const doc = new Document({
pageNumbers: estimatePageNumbersWith({ fonts: [{ data: pacifico }] }),
fonts: [{ name: "Pacifico", data: pacifico, characterSet: CharacterSet.ANSI }],
pageNumbers: estimatePageNumbersWith({ fonts: [{ data: kaushan }] }),
fonts: [{ name: "Kaushan Script", data: kaushan, characterSet: CharacterSet.ANSI }],
styles: {
default: {
document: { run: { font: "Pacifico", size: 22 }, paragraph: { spacing: { after: 160 } } },
document: { run: { font: "Kaushan Script", size: 22 }, paragraph: { spacing: { after: 160 } } },
heading1: {
run: { font: "Calibri", size: 32, color: "2F5496" },
paragraph: { spacing: { before: 240, after: 0 }, keepNext: true },
+8 -6
View File
@@ -1,6 +1,6 @@
# Layout
<!-- cspell:ignore Aptos chenglou Carlito GPOS -->
<!-- cspell:ignore Aptos chenglou Carlito GPOS Kaushan -->
!> Layout requires an understanding of [Table of Contents](usage/table-of-contents.md) and [Bookmarks](usage/bookmarks.md).
@@ -246,6 +246,7 @@ It stops at the first thing it can't lay out yet, and the page numbers of the he
- a table whose rows give a column different widths, when its width is a share of the page, it has space between its cells and its layout is fixed, or a row starts past its first column; a table whose width is a share of more than the width it is in; a table given no widths of more than 63 columns, more than Word allows; a table whose cells' margins are wider than the room for it, such as one in a narrow cell; and a word longer than a table can make room for, when the table's width is a share of less than all of it, a cell is merged across columns, or a column's cells have different margins
- a long word in a cell merged across columns, which Word makes room for in a way not yet followed: a word longer than those columns' longest words together, with or without more text beside it, when a table given no widths is narrowed to fit, and one whose share would leave a column narrower than its longest line or its width
- text in a font that isn't in the width tables, isn't given as a file (see [Measuring fonts from their files](#measuring-fonts-from-their-files)) and isn't embedded in the document, such as Garamond, Segoe UI or Roboto, so its lines may not be where Word puts them: Word draws it with the font's own widths, or in another font when it doesn't have it, such as Cambria on the Mac. Bold text in a font given or embedded without a bold face stops too: Word makes the bold face itself, each character 20 thousandths of an em wider, but from a file of its own, as it drew Pacifico, which a document embedded, in the copy of it Office downloads, whose letters are narrower
- text in a font given as a file or embedded in the document that Office also offers, such as Pacifico, Roboto or Lato, but for those of the width tables, such as Aptos, and the East Asian characters of the East Asian fonts in them, such as Microsoft YaHei, whose Latin letters stop: Word for Mac draws it in Office's own copy of the font, which it downloads, rather than in the file, as it drew Pacifico, whose letters in Office's copy are narrower and whose lines are shorter than in `demo/assets/Pacifico.ttf`'s. The fonts Office offers are those of Office's catalog of its cloud fonts, which has every font of Microsoft's list, [Cloud fonts in Office](https://support.microsoft.com/en-us/office/cloud-fonts-in-office-f7b009fe-037f-45ed-a556-b5fe6ede6adb), and those it has added since
- kerning and ligatures Word's PDFs haven't shown (see [Kerning and ligatures](#kerning-and-ligatures)): kerned text in a font whose kerning isn't known, such as Carlito or an East Asian font that isn't monospaced, or with a character outside Windows-1252, such as Greek or Cyrillic, or one that takes no room, such as a zero-width space or a combining mark; kerned Cambria before a hyphen, en dash, no-break space, ™, backslash or à; kerned text with ligatures other than standard and contextual ones in a font Word kerns only without ligatures, such as Trebuchet MS; Times New Roman's discretional ligatures, kerned, beside some characters; ligatures in a font whose ligatures aren't known, of a setting Word's Font dialog doesn't write, in regular Cambria, or beside a character outside Windows-1252 but for a Latin letter; kerning and ligatures across a soft hyphen, and kerned text before one in its font, with which the hyphen Word draws at the end of a line may be kerned; a word longer than its line with ligatures, as Word may break it inside one; text kerned or with ligatures on a document grid of characters; and in a font's file, substitutions other than ligatures in the setting's features, such as contextual ones. Text with OpenType number forms or spacing, stylistic sets or contextual alternates (`w14:numForm`, `w14:numSpacing`, `w14:stylisticSets`, `w14:cntxtAlts`) stops too, as their widths aren't known, but for lining tabular figures in regular Calibri and Cambria, and old-style tabular ones in regular Calibri, which are as wide as the font's default figures
- a character whose width in its font isn't known, so its line may not be where Word puts it: a letter or symbol its font doesn't have, or its font's file has no glyph for, which Word draws in a font whose widths aren't in the tables, such as most mathematical symbols, which Word draws in Cambria Math, or in Arial or Times New Roman where their line gap could make the line taller than the font's own, which no Word PDF has shown, such as Gill Sans MT's and Franklin Gothic Book's IPA letters and Hebrew in Arial; a few that Word drew in a way their widths can't be read from, such as Ž and Ё in Courier New; Arabic and Devanagari letters, which Word joins into forms of other widths, and Cambria's and Times New Roman's Devanagari digits, which Word draws in a font whose lines' height isn't known; and Hebrew, Thai, box drawing, shapes such as `docx`'s bullets ● ○ ■, symbols and dingbats in the italics of Office's other fonts, such as Aptos, so a list of `docx`'s bullets in italic Aptos stops at its bullet; and a symbol font's own symbol, such as Wingdings' tick (`SymbolRun`), or a symbol whose character isn't four hexadecimal digits
- in a document that hyphenates its words, a line Word may end with a part of the next word and a hyphen: one with room for the word's first two letters and a hyphen, or its first letter in a language other than English, when the word has five letters or more, or two in such a language. A word longer than its line, a word squeezed onto a distributed line, and a table sized to its text whose columns are narrowed past a word Word may hyphenate, or given less than one, stop it too, as Word sizes columns to the parts of the words it hyphenates
@@ -292,7 +293,7 @@ const doc = new Document({
Its guesses, by what it would stop at:
- text in a font that isn't in the width tables, isn't given as a file and isn't embedded is measured as the most similar font that is: Segoe UI as Calibri, a serif font such as Garamond as Times New Roman, a monospaced one as Courier New, and the others, such as Roboto, as Arial. Word draws them with their own widths, when it has them: in Word's PDF, Segoe UI was 1% wider than its guess and Garamond 3% narrower (`word-watertight-text.docx` TX18). Bold text in a font given or embedded without a bold face is measured as the most similar font of the tables too. A character whose width in its font isn't known is measured as an average letter of the font
- text in a font that isn't in the width tables, isn't given as a file and isn't embedded is measured as the most similar font that is: Segoe UI as Calibri, a serif font such as Garamond as Times New Roman, a monospaced one as Courier New, and the others, such as Roboto, as Arial. Word draws them with their own widths, when it has them: in Word's PDF, Segoe UI was 1% wider than its guess and Garamond 3% narrower (`word-watertight-text.docx` TX18). Bold text in a font given or embedded without a bold face is measured as the most similar font of the tables too, and text in a font given or embedded that Office also offers is measured from the file. A character whose width in its font isn't known is measured as an average letter of the font
- kerning and ligatures Word's PDFs haven't shown are measured as the layout measures the rest: a pair whose kerning isn't known as if not kerned, a word longer than its line with ligatures with them, and text either side of a soft hyphen as one word
- a date or time is measured as it is written, where Word writes the date and time it opens the document
- a setting or formatting the layout doesn't follow, such as hyphenation, a compatibility setting or mode, a document grid, a text frame or an indent in characters it hasn't seen, is laid out as if it weren't there, a page number in a format it can't write is written in figures, and a table whose widths it can't work out as Word does is sized as it sizes others. A table that text wraps around where Word's way with it hasn't been seen is laid out in the text, as one it doesn't wrap around
@@ -326,7 +327,7 @@ Where Word's PDFs don't show how it kerns or joins text, the layout stops, as [W
## How close it is
Text in fonts made with the same widths as those five is measured exactly as them: Carlito as Calibri, Caladea as Cambria, Liberation Sans, Arimo and Helvetica as Arial, Liberation Serif and Tinos as Times New Roman, and Liberation Mono and Cousine as Courier New. Text in the fonts the document embeds (`fonts`) is measured from their files, as Word draws it in them, but where Office has its own copy of the font: Word for Mac drew Pacifico, which a document embedded, in the copy Office downloads, whose letters are narrower than `demo/assets/Pacifico.ttf`'s. Text in Aptos, Office's default font since 2023, and Office's other fonts of the tables is measured with Word's own files of them: each word of a line of prose in each of them but Verdana, whose line Word's PDF broke in two, kerned and with ligatures as Word's Normal template has them, is within half a point of where Word puts it, across lines of 1,100 to 1,400 points. Text in other fonts, such as Garamond, stops the layout (see [What it leaves blank](#what-it-leaves-blank)), unless their files are given (see [Measuring fonts from their files](#measuring-fonts-from-their-files)). Hebrew, Thai, the Arabic-Indic and Devanagari digits, box drawing, shapes such as the bullets ● and ■, symbols and dingbats are measured as Word draws them in each font of the tables, plain and bold, and in Calibri's, Cambria's, Arial's, Times New Roman's and Courier New's italics, but for Cambria's and Times New Roman's Devanagari digits, and stop the layout in the italics of Office's other fonts, whose widths of them Word's PDFs haven't shown, as those Devanagari digits do. Arabic and Devanagari letters, which Word joins into forms of other widths, stop it too. Other characters the width tables don't have, such as Armenian letters and emoji, are measured as an average letter of the font, or an em for emoji. The Latin letters of the East Asian fonts that aren't monospaced, such as Yu Gothic, and East Asian fonts Office doesn't have stop the layout too.
Text in fonts made with the same widths as those five is measured exactly as them: Carlito as Calibri, Caladea as Cambria, Liberation Sans, Arimo and Helvetica as Arial, Liberation Serif and Tinos as Times New Roman, and Liberation Mono and Cousine as Courier New. Text in the fonts the document embeds (`fonts`) is measured from their files, as Word draws it in them, but for fonts Office also offers, which stop the layout: Word for Mac drew Pacifico, which a document embedded, in the copy Office downloads, whose letters are narrower than `demo/assets/Pacifico.ttf`'s. Text in Aptos, Office's default font since 2023, and Office's other fonts of the tables is measured with Word's own files of them: each word of a line of prose in each of them but Verdana, whose line Word's PDF broke in two, kerned and with ligatures as Word's Normal template has them, is within half a point of where Word puts it, across lines of 1,100 to 1,400 points. Text in other fonts, such as Garamond, stops the layout (see [What it leaves blank](#what-it-leaves-blank)), unless their files are given (see [Measuring fonts from their files](#measuring-fonts-from-their-files)). Hebrew, Thai, the Arabic-Indic and Devanagari digits, box drawing, shapes such as the bullets ● and ■, symbols and dingbats are measured as Word draws them in each font of the tables, plain and bold, and in Calibri's, Cambria's, Arial's, Times New Roman's and Courier New's italics, but for Cambria's and Times New Roman's Devanagari digits, and stop the layout in the italics of Office's other fonts, whose widths of them Word's PDFs haven't shown, as those Devanagari digits do. Arabic and Devanagari letters, which Word joins into forms of other widths, stop it too. Other characters the width tables don't have, such as Armenian letters and emoji, are measured as an average letter of the font, or an em for emoji. The Latin letters of the East Asian fonts that aren't monospaced, such as Yu Gothic, and East Asian fonts Office doesn't have stop the layout too.
Each change to `docx/layout` is checked against LibreOffice's layout of a set of documents, and against the pages Word marked in documents it saved. Word lays out some things differently from LibreOffice, so turn `updateFields` on if the page numbers must be Word's own once the document is opened in Word: Word then asks to update the fields, and works them out again. LibreOffice rounds the height of each line to whole twips, 269 for Calibri 11, so where a line only just fits on a page, it can be on the next page in LibreOffice and on this one in Word, and in `docx/layout`, which follows Word.
@@ -420,6 +421,7 @@ In a browser, give it the bytes of a file the page fetched, such as `await (awai
- **The files** are TrueType or OpenType fonts (`.ttf` or `.otf`), or collections of them (`.ttc`), as bytes: a `Uint8Array`, such as a Node `Buffer`, or an `ArrayBuffer`. Web fonts (`.woff` and `.woff2`) are compressed, and can't be read.
- **Each file is one face of a font,** such as Aptos Bold, **or a collection of faces,** such as Cambria and Cambria Math in `cambria.ttc`, each of which is measured. The name of each face and whether it is bold or italic are read from it. Give a file for each face the document uses. Bold text in a font without a bold file is measured as it would be without the files, so it stops the layout when the font isn't in the width tables, as Word makes the bold face itself, and italic text without an italic file is measured with the upright one. To measure a font with a file of another name, give the name the document uses, such as `{ data: carlito, name: "Calibri" }`, which every face in the file is given.
- **Widths** are the font's own. The layout stops at a character the file has no glyph for, as Word draws it in another font (see [What it leaves blank](#what-it-leaves-blank)).
- **Fonts Office offers**, such as Pacifico, Roboto or Lato, stop the layout, given as a file or not, as Word for Mac draws them in Office's own copy of them, which may not be the file given (see [Fonts the document embeds](#fonts-the-document-embeds)). Office's fonts of the width tables, such as Aptos, are measured from the file given.
- **Kerning** is applied as Word applies it: only to text that asks for it, with `kern` on a run or a style (`w:kern`), and only to text of that size or larger. `kern: 2` kerns text from 1 point, as Word's own Normal template does. The pairs are the font's, from its `GPOS` table, or its `kern` table when its `GPOS` table doesn't kern Latin text, and pairs across runs in the same font are kerned too. Text with ligatures in a font kerned by its `kern` table alone isn't kerned, as Word leaves it.
- **Ligatures** join letters as Word joins them, in text that asks for them (`w14:ligatures`): with the ligatures of the font's `GSUB` table of the kinds the setting names, such as the standard ligatures of Aptos's `ff`, `fi` and `fl` for Word's Normal template's standard and contextual ligatures. The layout stops at text a substitution of another kind in those features could change, such as Cambria's contextual ones.
- **The height of a line** is the font's, as Word for Mac works it out: the ascender, descender and line gap of its `hhea` table, or its typographic ascent, descent and line gap when the font says to use them, as Aptos does. The line goes that descent below its baseline, with the gap above the text, which is what a line of it and another font, or a picture, is made from.
@@ -428,7 +430,7 @@ Text in fonts without files is measured as it is without them: with the width ta
### Fonts the document embeds
Text in the fonts a document embeds is measured from the files it embeds, with nothing more given to the estimator: the fonts `docx` embeds with the `fonts` option, each as the regular face of the font of the name it is given, and those a template Word saved embeds ("Embed fonts in the file"), each as the face Word embedded it as. Bold text in a font embedded without a bold face stops the layout, as it does with a file given without one. Where Office has a copy of its own of a font, Word for Mac may draw the text in that rather than in the file the document embeds: it drew Pacifico in Office's copy, whose letters are narrower, so the page numbers of text in it may not be Word's there. A file the document embeds that isn't a font, or is damaged, is left out, so text in its font stops the layout. When a font the document embeds is given as a file too, the document's own file is measured.
Text in the fonts a document embeds is measured from the files it embeds, with nothing more given to the estimator: the fonts `docx` embeds with the `fonts` option, each as the regular face of the font of the name it is given, and those a template Word saved embeds ("Embed fonts in the file"), each as the face Word embedded it as. Bold text in a font embedded without a bold face stops the layout, as it does with a file given without one. Text in a font Office also offers, such as Pacifico, Roboto or Lato, stops the layout, embedded or given as a file, but for Office's fonts of the width tables, such as Aptos: Word for Mac draws it in Office's own copy of the font rather than in the file, as it drew Pacifico in Office's copy, whose letters are narrower, so the page numbers of text in it wouldn't be Word's. Guessing (see [Guessing past what it can't lay out](#guessing-past-what-it-cant-lay-out)), it is measured from the file, as other apps, such as LibreOffice, draw it. A file the document embeds that isn't a font, or is damaged, is left out, so text in its font stops the layout. When a font the document embeds is given as a file too, the document's own file is measured.
```ts
import { readFile } from "node:fs/promises";
@@ -437,8 +439,8 @@ import { estimatePageNumbers } from "docx/layout";
const doc = new Document({
pageNumbers: estimatePageNumbers,
fonts: [{ name: "Pacifico", data: await readFile("Pacifico.ttf") }],
styles: { default: { document: { run: { font: "Pacifico", size: 22 } } } },
fonts: [{ name: "Kaushan Script", data: await readFile("KaushanScript-Regular.ttf") }],
styles: { default: { document: { run: { font: "Kaushan Script", size: 22 } } } },
sections: [...],
});
```
+133
View File
@@ -0,0 +1,133 @@
/**
* Generates src/text-layout/office-cloud-fonts.ts: the names of the fonts Office offers as cloud fonts, which Office
* downloads when a document uses one. Word for Mac draws text in such a font in Office's copy of it, even where the
* document embeds a file of its own of the font: it drew Pacifico, which a document embedded, in Office's copy, whose
* letters are narrower and whose lines are shorter (scripts/layout-probes/stops2/word-stops-office-fonts.ts MB4a, MB4b).
*
* The names are read from Office's own catalog of its cloud fonts, which Office for Mac keeps in
* ~/Library/Group Containers/UBF8T346G9.Office/FontCache/4/Catalog/ListAll_hier.Json: each font's family name, its
* localized family names, such as 游ゴシック for Yu Gothic, and the family name of each of its faces, such as Aptos Black,
* as documents name them. The catalog is the list of every font Office offers, not of those it has downloaded. It is
* cross-checked against Microsoft's published list, "Cloud fonts in Office"
* (https://support.microsoft.com/en-us/office/cloud-fonts-in-office-f7b009fe-037f-45ed-a556-b5fe6ede6adb), which has fewer
* fonts than the catalog: none of those Office has offered from Google Fonts since, such as Pacifico and Roboto. The faces
* of the published list that the catalog doesn't name are kept too, and written in the generated file's header.
*
* To refresh the list when Office's catalog changes, open Word for Mac's font menu once so Office fetches its catalog
* again, then run this, and commit the generated file.
*
* Usage:
* npm run run-ts -- scripts/generate-office-cloud-fonts.ts [catalog] [published list's page, saved as HTML]
*/
// cspell:ignore UBF8T346G9 Aptos hier
import { execSync } from "node:child_process";
import { readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
const OUTPUT = "src/text-layout/office-cloud-fonts.ts";
const DEFAULT_CATALOG = join(homedir(), "Library/Group Containers/UBF8T346G9.Office/FontCache/4/Catalog/ListAll_hier.Json");
const PUBLISHED = "https://support.microsoft.com/en-us/office/cloud-fonts-in-office-f7b009fe-037f-45ed-a556-b5fe6ede6adb";
/** A font of Office's catalog: its family name (`f`), its localized family names (`fam`), and its faces (`sf`) */
type CatalogFont = {
readonly f: string;
readonly fam: readonly { readonly ltx: string }[];
readonly sf: readonly {
/** The face's family name, as documents name it, such as "Aptos Black" */
readonly gn: string;
/** Its full name, such as "Aptos Black Italic" */
readonly dn: string;
readonly ful: readonly { readonly ltx: string }[];
}[];
};
type Catalog = { readonly MajorVersion: number; readonly MinorVersion: number; readonly Fonts: readonly CatalogFont[] };
const catalogPath = process.argv[2] ?? DEFAULT_CATALOG;
// The catalog is written with a byte order mark
const catalog = JSON.parse(readFileSync(catalogPath, "utf8").replace(/^/, "")) as Catalog;
const version = `${catalog.MajorVersion}.${catalog.MinorVersion}`;
/** A face's name as the published list and the catalog both may write it: without case, spaces, or "Regular" at its end */
const comparable = (name: string): string =>
name
.toLowerCase()
.replace(/\s+/g, "")
.replace(/regular$/, "");
// Every name of every face the catalog has, to find those of the published list in
const catalogued = new Set(
catalog.Fonts.flatMap((font) => [
font.f,
...font.fam.map(({ ltx }) => ltx),
...font.sf.flatMap(({ gn, dn, ful }) => [gn, dn, ...ful.map(({ ltx }) => ltx)]),
]).map(comparable),
);
const page = process.argv[3] === undefined ? await (await fetch(PUBLISHED)).text() : readFileSync(process.argv[3], "utf8");
/**
* The text of a cell: the text between its tags, with the entities its names are written with, `&amp;` last, so that
* what it makes isn't read as another
*/
const unescaped = (cell: string): string =>
[...`>${cell}<`.matchAll(/>([^<>]*)(?=<)/g)]
.map(([, text]) => text)
.join("")
.replace(/&nbsp;/g, " ")
.replace(/&amp;/g, "&")
.trim();
// The published list is a table of each face's name, file and version, after a table of where cloud fonts are offered
const published = [...page.matchAll(/<tr[^>]*>([\s\S]*?)<\/tr>/g)]
.map(([, row]) => [...row.matchAll(/<t[dh][^>]*>([\s\S]*?)<\/t[dh]>/g)].map(([, cell]) => unescaped(cell)))
.filter((cells) => cells.length === 3 && cells[0] !== "Font name")
.map(([name]) => name);
if (published.length === 0) {
throw new Error("The published list has no fonts: its page has changed");
}
const missing = published.filter((name) => !catalogued.has(comparable(name)));
// The faces of the published list the catalog doesn't name are kept too, as documents may name them
const names = [
...new Set([
...catalog.Fonts.flatMap((font) => [font.f, ...font.fam.map(({ ltx }) => ltx), ...font.sf.map(({ gn }) => gn)]),
...missing,
]),
].sort((one, other) => (one.toLowerCase() < other.toLowerCase() ? -1 : one.toLowerCase() > other.toLowerCase() ? 1 : 0));
const today = new Date().toISOString().slice(0, 10);
/** Paragraphs of a comment, wrapped to lines of up to 120 characters */
const commented = (paragraphs: readonly string[]): string =>
paragraphs
.map((paragraph) =>
paragraph
.split(" ")
.reduce<readonly string[]>(
(lines, word) =>
lines.length > 0 && ` * ${lines[lines.length - 1]} ${word}`.length <= 120
? [...lines.slice(0, -1), `${lines[lines.length - 1]} ${word}`]
: [...lines, word],
[],
)
.map((line) => ` * ${line}`)
.join("\n"),
)
.join("\n *\n");
// The names aren't words, and the header names fonts too
const source = `/* cspell:disable */
/**
${commented([
"The names of the fonts Office offers as cloud fonts, which Word for Mac draws text in from Office's copy of them, even where a document embeds a file of its own of the font.",
`Generated by scripts/generate-office-cloud-fonts.ts on ${today} from Office's catalog of its cloud fonts, version ${version} (Office for Mac's FontCache/4/Catalog/ListAll_hier.Json): ${catalog.Fonts.length} fonts, with their localized family names and the family names of their faces. Cross-checked against Microsoft's published list, "Cloud fonts in Office" (${PUBLISHED}), whose ${published.length} faces are all in the catalog${missing.length === 0 ? "" : ` but for ${missing.join(", ")}, which are kept too`}. Do not edit by hand.`,
"@module",
])}
*/
/** The names of the fonts Office offers as cloud fonts, as documents name them */
export const OFFICE_CLOUD_FONTS: readonly string[] = ${JSON.stringify(names)};
`;
writeFileSync(OUTPUT, source);
execSync(`npx prettier --write ${OUTPUT}`, { stdio: "inherit" });
console.log(
`${names.length} names of ${catalog.Fonts.length} fonts, catalog ${version}; ${missing.length} published faces not in it:`,
missing,
);
+18
View File
@@ -44,6 +44,7 @@ import {
} from "docx";
import { buildTestFont, buildTestFontCollection, tableOffset } from "tests/font-file";
import { OFFICE_COPY } from "../text-layout";
import { estimatePageNumbers, estimatePageNumbersWith } from "./estimate-page-numbers";
import { layoutDocument } from "./layout-document";
import type { FontToMeasure } from "./measure-width";
@@ -1023,6 +1024,23 @@ describe("estimatePageNumbersWith", () => {
expect(pageNumbersOf(bold)).to.deep.equal({ first: "1" });
});
it("should stop at text in a font Office offers a copy of its own of, given or embedded, and measure the file guessing", () => {
// Word for Mac drew Pacifico, which a document embedded, in Office's copy of it (word-stops-office-fonts.docx MB4)
const given = estimatePageNumbersWith({ fonts: [{ data: WIDE, name: "Pacifico" }] });
expect(pageNumbersOf(document("Pacifico"), given)).to.deep.equal({ first: "1" });
const guessing = estimatePageNumbersWith({ fonts: [{ data: WIDE, name: "Pacifico" }], guess: true });
expect(pageNumbersOf(document("Pacifico"), guessing)).to.deep.include({ first: "1", last: "8" });
const embedded = new Document({ ...document("Pacifico"), fonts: [{ name: "Pacifico", data: Buffer.from(WIDE) }] });
expect(layoutDocument(embedded).stoppedAt).to.equal(OFFICE_COPY);
const { pages, stoppedAt } = layoutDocument(embedded, { guess: true });
expect(stoppedAt).to.equal(undefined);
expect(pages).to.have.length(8);
expect(pages[0].guesses).to.deep.equal([OFFICE_COPY]);
// Office's fonts of the width tables are measured from the file, as before
const aptos = new Document({ ...document("Aptos"), fonts: [{ name: "Aptos", data: Buffer.from(WIDE) }] });
expect(layoutDocument(aptos).pages).to.have.length(8);
});
it("should measure the fonts a template embeds from their files, once patchDocument has patched it", async () => {
// docx obfuscates the fonts it embeds, with a key of its own for each, as Word does
const template = await Packer.toBuffer(
+8 -4
View File
@@ -64,7 +64,7 @@ const estimateWith = (content: DocumentContent | undefined, measurer: TextMeasur
*
* The pages are laid out with the widths and heights of the fonts Word documents use most, such as Calibri, Cambria,
* Arial and Times New Roman, and of those made as wide, such as Carlito, and text in the fonts the document embeds is
* measured from their files. To measure text in other fonts, such as Aptos, from their files, use
* measured from their files, but for fonts Office also offers. To measure text in other fonts, such as Aptos, from their files, use
* {@link estimatePageNumbersWith}. It follows paragraphs' spacing, indents, line spacing, tab stops and keep settings, widow
* and orphan control, lists, pictures in the line, tables, whose rows break across pages, footnotes and endnotes, page,
* column and section breaks, and each section's page size, margins, columns, headers, footers and page numbering.
@@ -72,7 +72,8 @@ const estimateWith = (content: DocumentContent | undefined, measurer: TextMeasur
* It stops at the first thing it can't lay out yet: a drawing or table that text flows around, a text box or frame, an
* equation, a footnote that continues on the next page, columns evened out before a continuous section break, a line in
* a table cell that is taller than a page, text in a font that isn't in the width tables and isn't embedded, such as
* Aptos, a character whose width in its font isn't known, such as a mathematical symbol in Calibri, which Word draws in
* Garamond, text in a font the document embeds that Office also offers, such as Pacifico, which Word for Mac draws in
* Office's own copy of it, a character whose width in its font isn't known, such as a mathematical symbol in Calibri, which Word draws in
* Cambria Math, a word Word may hyphenate, in a document that hyphenates its words, as which parts Word breaks it into
* is in its own dictionaries, or a date in the text, which Word writes when it opens the document. The page references
* to bookmarks after it are left blank, for Word to fill in when it updates the fields. A document in compatibility
@@ -128,7 +129,9 @@ export type EstimatePageNumbersOptions = {
* without files is measured as it is without them, and so is bold text, or text that isn't bold, in a font without a
* file for it, which stops the layout when the font isn't in the width tables. Italic text in a font without an italic
* file is measured with the upright one. The layout stops at a character a font's file has no glyph for, as Word draws
* it in another font. A font the document embeds is measured from the document's own file
* it in another font. A font the document embeds is measured from the document's own file. Text in a font Office also
* offers, such as Pacifico, stops the layout, as Word for Mac draws it in Office's own copy of the font, but for
* Office's fonts of the width tables, such as Aptos
*/
readonly fonts?: readonly FontFile[];
/**
@@ -141,7 +144,8 @@ export type EstimatePageNumbersOptions = {
/**
* Whether to lay out past what the layout can't lay out as Word does yet with the best guess it has, rather than
* leave the page numbers after it blank. Text in a font that isn't in the width tables, and isn't given as a file or
* embedded, is measured as the most similar font that is, such as Aptos as Arial, and a character whose width isn't
* embedded, is measured as the most similar font that is, such as Roboto as Arial, text in a font given as a file or
* embedded that Office also offers is measured from the file, and a character whose width isn't
* known as an average letter of its font. A date is measured as it is written, and a setting or formatting the layout
* doesn't follow, such as hyphenation or a compatibility setting, is left as if it weren't there. What it can't read,
* such as a drawing that text flows around or an equation, is left out, and a page laid out as the rule it follows
+2 -1
View File
@@ -51,7 +51,8 @@ const firstMoved = (pagination: Pagination, before: Pagination): number => {
* way with a number and the other way without it, none can be written, so it gives the first pass, laid out without them,
* as not settled. Guessing (`guess`), it lays the pages out past what it can't lay out as Word does yet, and when the
* numbers still change, it gives the last pass, with the guess noted on the first page they moved on. Text in the fonts
* the document embeds is measured from their files, and the rest with `measurer`.
* the document embeds is measured from their files, but for those Office also offers, which it stops at, or guessing,
* measures from the files too, and the rest with `measurer`.
*/
export const layOutPasses = (
content: DocumentContent,
+10
View File
@@ -7777,6 +7777,16 @@ describe("paginate with automatic hyphenation", () => {
]);
});
it("should stop at, or guess, text in a font where the measurer says why it doesn't know how Word draws it", () => {
const OFFICE: TextMeasurer = { ...MEASURER, unknownFont: ({ font }) => (font === "Offered" ? "Office's copy" : false) };
const content = document([
withItems(paragraph("a", 1), [{ type: "text", text: " x", font: { font: "Offered" } }]),
paragraph("b", 1),
]);
expect(numbersOf(content, OFFICE).stoppedAt).to.equal("Office's copy");
expect(guessed(content, OFFICE)).to.deep.equal({ guesses: [["Office's copy"]], bookmarks: { a: "1", b: "1" } });
});
it("should measure a character whose width the measurer doesn't know as it measures it", () => {
const CHARACTERS: TextMeasurer = { ...MEASURER, unknownCharacter: (value) => (value.includes("∑") ? "∑" : undefined) };
const content = document([withItems(paragraph("a", 1), [{ type: "text", text: " ∑", font: {} }]), paragraph("b", 1)]);
+13 -11
View File
@@ -471,20 +471,22 @@ const KEPT_ROW_IN_COLUMNS = "a table row kept together taller than a column";
const stoppingMeasurers = new WeakMap<TextMeasurer, TextMeasurer>();
/**
* A measurer that calls `atUnknown` where it would measure text in a font it doesn't know, or the height of a line in
* one, as it measures them as another font, where Word draws them in their own, or in another again when it doesn't have
* them (`word-watertight-text.docx` TX18). Otherwise, and after `atUnknown` when it returns, it measures as the measurer
* does: such a font as the most similar font it knows
* A measurer that calls `atUnknown`, with why, where it would measure text in a font it doesn't know, or the height of a
* line in one, as it measures them as another font, where Word draws them in their own, or in another again when it
* doesn't have them (`word-watertight-text.docx` TX18), or from a file Word may not draw them from, as for a font Office
* offers a copy of its own of. Otherwise, and after `atUnknown` when it returns, it measures as the measurer does: such a
* font as the most similar font it knows, or from its file
*/
const atUnknownFonts = (measurer: TextMeasurer, atUnknown: () => void): TextMeasurer => {
const atUnknownFonts = (measurer: TextMeasurer, atUnknown: (reason: string) => void): TextMeasurer => {
const { unknownFont } = measurer;
if (unknownFont === undefined) {
return measurer;
}
/** The font, once `atUnknown` is called when the measurer doesn't know it, or this text in it */
const known = (font: TextFont, text?: string): TextFont => {
if (unknownFont(font, text)) {
atUnknown();
const unknown = unknownFont(font, text);
if (unknown !== false) {
atUnknown(unknown === true ? UNKNOWN_FONT : unknown);
}
return font;
};
@@ -500,8 +502,8 @@ const atUnknownFonts = (measurer: TextMeasurer, atUnknown: () => void): TextMeas
const stoppingAtUnknownFonts = (measurer: TextMeasurer): TextMeasurer => {
const stopping =
stoppingMeasurers.get(measurer) ??
atUnknownFonts(measurer, () => {
throw new Unsupported(UNKNOWN_FONT);
atUnknownFonts(measurer, (reason) => {
throw new Unsupported(reason);
});
stoppingMeasurers.set(measurer, stopping);
return stopping;
@@ -1014,8 +1016,8 @@ export const paginate = (
defaultTabStop,
markFont: paragraph.markFont,
measurer: guess
? atUnknownFonts(measurer, () => {
guessed ??= UNKNOWN_FONT;
? atUnknownFonts(measurer, (reason) => {
guessed ??= reason;
})
: measuring,
breakRules,
+41 -2
View File
@@ -2,11 +2,11 @@ import { describe, expect, it } from "vitest";
import { type TestFontOptions, buildTestFont, buildTestFontCollection, tableOffset } from "tests/font-file";
import { createFontFileMeasurer, readFontFile } from "./font-file";
import { OFFICE_COPY, createFontFileMeasurer, offeredByOffice, readFontFile } from "./font-file";
import { DEFAULT_MEASURER } from "./line-breaking";
import type { TextFont } from "./text-width";
// cspell:ignore hhea hmtx cmap Aptos aptos GPOS DFLT clig dlig ffjo ffofi GSUB liga offio offjo Toffio
// cspell:ignore hhea hmtx cmap Aptos aptos Pacifico pacifico Kaiti GPOS DFLT clig dlig ffjo ffofi GSUB liga offio offjo Toffio
// A font of 1000 units to the em, whose letters are as wide as their place in the alphabet, in hundreds of units
const LETTERS: TestFontOptions["advances"] = Object.fromEntries([
@@ -451,6 +451,45 @@ describe("createFontFileMeasurer", () => {
expect(withoutUnknown.unknownFont!({ font: "Roboto" })).to.equal(false);
});
it("should not know how Word draws text in a font Office offers a copy of its own of, as it draws it in that copy", () => {
// Word for Mac drew Pacifico, which a document embedded, in Office's copy (word-stops-office-fonts.docx MB4)
const measurer = createFontFileMeasurer(fonts({ advances: LETTERS, name: "Pacifico" }));
expect(measurer.unknownFont!({ font: "Pacifico" }, "AB")).to.equal(OFFICE_COPY);
expect(measurer.unknownFont!({ font: "pacifico", italic: true })).to.equal(OFFICE_COPY);
// It is still measured from its file, for a layout that guesses
expect(measurer.measureWidth("ABC", { font: "Pacifico", size: 10 })).to.be.closeTo(6, 1e-9);
// Bold text without a bold face is measured as the fallback does, which doesn't know the font
expect(measurer.unknownFont!({ font: "Pacifico", bold: true }, "AB")).to.equal(true);
// Office's fonts of the width tables are measured as Word draws them, given as files or not
const aptos = createFontFileMeasurer(fonts({ advances: LETTERS, name: "Aptos" }));
expect(aptos.unknownFont!({ font: "Aptos" }, "AB")).to.equal(false);
// Microsoft YaHei's East Asian characters are in the width tables, but not its Latin letters
const yaHei = createFontFileMeasurer(fonts({ advances: LETTERS, name: "Microsoft YaHei" }));
expect(yaHei.unknownFont!({ font: "Microsoft YaHei" }, "AB")).to.equal(OFFICE_COPY);
expect(yaHei.unknownFont!({ font: "Microsoft YaHei" }, "\u4E2D\u6587")).to.equal(false);
expect(yaHei.unknownFont!({ font: "Microsoft YaHei" })).to.equal(false);
// A measurer that falls back on one with such a font says why it doesn't know it
const outer = createFontFileMeasurer(fonts({ advances: LETTERS }), measurer);
expect(outer.unknownFont!({ font: "Pacifico" }, "AB")).to.equal(OFFICE_COPY);
expect(outer.unknownFont!({ font: "Probe Sans" }, "AB")).to.equal(false);
});
it("should know which fonts Office offers as cloud fonts, other than those of the width tables", () => {
expect(offeredByOffice("Pacifico")).to.equal(true);
expect(offeredByOffice("ROBOTO")).to.equal(true);
// A face's own family name, as documents name it, and a localized name: STKaiti's Chinese name
expect(offeredByOffice("Aptos Black")).to.equal(true);
expect(offeredByOffice("\u534E\u6587\u6977\u4F53")).to.equal(true);
expect(offeredByOffice("Aptos")).to.equal(false);
expect(offeredByOffice("Calibri")).to.equal(false);
// Yu Gothic's Japanese name, as the tables have it
expect(offeredByOffice("\u6E38\u30B4\u30B7\u30C3\u30AF")).to.equal(false);
expect(offeredByOffice("Probe Sans")).to.equal(false);
// An East Asian font of the tables, for the Latin letters the tables don't have
expect(offeredByOffice("Microsoft YaHei")).to.equal(false);
expect(offeredByOffice("Microsoft YaHei", "AB")).to.equal(true);
});
it("should move a tab typed in the text to the next half inch from the start of the text", () => {
const measurer = createFontFileMeasurer(fonts({ advances: LETTERS }));
// A is a point wide at 10 points, so the tab moves to 36, and B is 2 more
+34 -3
View File
@@ -7,7 +7,8 @@
// cspell:ignore hhea hmtx cmap fsSelection ttcf OTTO GPOS DFLT Aptos clig dlig GSUB hlig liga
import { hasLigatures } from "./kerning";
import { DEFAULT_MEASURER, type TextMeasurer } from "./line-breaking";
import { DEFAULT_FONT, DEFAULT_FONT_SIZE, type Ligatures, type TextFont, isKerned, takesNoRoom } from "./text-width";
import { OFFICE_CLOUD_FONTS } from "./office-cloud-fonts";
import { DEFAULT_FONT, DEFAULT_FONT_SIZE, type Ligatures, type TextFont, isKerned, takesNoRoom, unknownFont } from "./text-width";
/**
* A font file's bytes: a TrueType or OpenType font (`.ttf` or `.otf`), or a collection of them (`.ttc`).
@@ -666,6 +667,29 @@ export const readFontFile = (data: FontData): readonly FontFace[] => {
// Half an inch, in points
const TAB_STOP = 36;
/**
* Why a layout stops at text in a font from a file that Office offers as a cloud font: Word for Mac draws it in Office's
* copy of the font, even where the document embeds a file of its own of it, as it drew Pacifico, which a document
* embedded, in Office's copy, whose letters are narrower and whose lines are shorter (`word-stops-office-fonts.docx` MB4)
*/
export const OFFICE_COPY = "a font from a file that Office offers a copy of its own of, which Word may draw the text in instead";
// The names of Office's cloud fonts, in lower case, made when a font from a file is first measured
const cloudFonts = new Set<string>();
/**
* Whether Office offers a font as a cloud font, other than one of the width tables, such as Aptos, which are measured as
* Word draws them already, or this text in it: the Latin letters of an East Asian font of the tables that isn't
* monospaced, such as Microsoft YaHei, aren't in them
*/
export const offeredByOffice = (font: string, text?: string): boolean => {
if (cloudFonts.size === 0) {
// eslint-disable-next-line functional/immutable-data
OFFICE_CLOUD_FONTS.forEach((name) => cloudFonts.add(name.toLowerCase()));
}
return cloudFonts.has(font.toLowerCase()) && unknownFont({ font }, text);
};
/**
* Measures text in the fonts of these faces with their own widths, kerning and line height, and text in other fonts with
* `fallback`. Text that is bold, or not, is measured with a face that is too, and with one that is italic, or not, as the
@@ -674,7 +698,8 @@ const TAB_STOP = 36;
* whose widths aren't known, unless `fallback` knows them: Word makes that face itself, each glyph 20 thousandths of an em
* wider than the face it makes it from, but which face it makes it from isn't known, as it drew Pacifico, which a document
* embedded, in Office's own copy of it, whose letters are narrower (scripts/layout-probes/stops2/word-stops-office-fonts.ts
* MB4).
* MB4). For the same reason, text in a font Office offers as a cloud font, such as Pacifico, is in a font whose widths
* aren't known, for {@link OFFICE_COPY}, but for those of the width tables: measured from its file, it is a best guess.
*/
export const createFontFileMeasurer = (faces: readonly FontFace[], fallback: TextMeasurer = DEFAULT_MEASURER): TextMeasurer => {
// The face of each font, bold or not, and italic or not, as text is measured many times in each
@@ -760,7 +785,13 @@ export const createFontFileMeasurer = (faces: readonly FontFace[], fallback: Tex
)
: fallback.unknownCharacter?.(text, font);
},
unknownFont: (font, text) => faceOf(font) === undefined && fallback.unknownFont?.(font, text) === true,
unknownFont: (font, text) => {
const face = faceOf(font);
if (face === undefined) {
return fallback.unknownFont?.(font, text) ?? false;
}
return offeredByOffice(face.name, text) ? OFFICE_COPY : false;
},
// Word kerns with the font's own pairs (word-fonts.docx F1 and F2), and joins letters with its ligatures, but for
// substitutions other than ligatures, such as contextual ones, which aren't followed yet
unknownShaping: (text, font) => {
+4 -3
View File
@@ -56,10 +56,11 @@ export type TextMeasurer = {
readonly unknownCharacter?: (text: string, font: TextFont) => string | undefined;
/**
* Whether this measurer measures text in a font as another font, as it doesn't know the font's own widths, so a layout
* stops there rather than guessing. Without text, whether it knows the height and descent of the font's lines. A
* measurer without it measures every font as best it can
* stops there rather than guessing, or why it doesn't know whether Word draws the text with the widths it measures it
* with, as for a font from a file that Office offers a copy of its own of. Without text, whether it knows the height
* and descent of the font's lines, or why not. A measurer without it measures every font as best it can
*/
readonly unknownFont?: (font: TextFont, text?: string) => boolean;
readonly unknownFont?: (font: TextFont, text?: string) => boolean | string;
/**
* Why this measurer doesn't know how Word kerns text in a font, or joins its letters into ligatures, when it doesn't,
* so a layout stops there rather than guessing. A measurer without it measures them as best it can
File diff suppressed because it is too large Load Diff