feat(layout): break and measure Chinese, Japanese, Korean, Thai and right-to-left text as Word does (#3621)

* feat(layout): break lines of Chinese, Japanese and Korean, and measure East Asian and right-to-left text, as Word does

* refactor(layout): keep the language and East Asian marks of text out of shapes' spans

* test(layout): cover the remaining branches, and check docx/layout against Word's kinsoku probes

* docs(layout): list word-unicode and word-unicode2 among the layout probes

* style(layout): format the wrapping of a word wider than a line

* fix(layout): keep a character with its marks and what a zero-width joiner joins to it when a long word is split, across runs

A word wider than a line was split after the last character that fits, grouping each character with its marks only within
one run, and breaking after a zero-width joiner, where findLineBreaks never breaks. An accent in a run of its own, or a
joined emoji, could be split across lines.
This commit is contained in:
Dolan
2026-10-02 01:12:45 +01:00
committed by GitHub
parent 66b5b330f2
commit dec8a497ee
25 changed files with 1843 additions and 127 deletions
+1
View File
@@ -38,6 +38,7 @@
"Initializable",
"iroha",
"JOHAB",
"kinsoku",
"jsonify",
"jszip",
"NUMPAGES",
+5 -4
View File
@@ -65,9 +65,10 @@ The page numbers are written into:
## What it follows
The pages are laid out with the widths and heights of the characters of the fonts Word documents use most: Calibri, Cambria, Arial, Times New Roman and Courier New. It follows:
The pages are laid out with the widths and heights of the characters of the fonts Word documents use most: Calibri, Cambria, Arial, Times New Roman and Courier New, and the heights of the lines of the Chinese, Japanese and Korean fonts Office has, such as MS Mincho, Yu Gothic, SimSun, Microsoft YaHei, PMingLiU and Malgun Gothic. It follows:
- the document's styles, and each paragraph's and run's own formatting: fonts, sizes, bold, capitals, and hidden text
- the document's styles, and each paragraph's and run's own formatting: fonts, sizes, bold, capitals, and hidden text. Chinese, Japanese and Korean are in the run's East Asian font (`font: { eastAsia }`), or in MS Mincho when that font has none of their characters, as Word draws them. A right-to-left run (`rightToLeft`) is in the run's font, size and bold for complex scripts (`font: { cs }`, `sizeComplexScript`, `boldComplexScript`), as Word draws it
- where lines break, as Word breaks them: at spaces, after hyphens, en and em dashes and zero-width spaces, and between Chinese and Japanese characters. In text in Japanese or Chinese (`language: { eastAsia: "ja-JP" }`), Word's lists keep characters such as closing brackets and `、` from starting a line, and opening brackets from ending one, so the character before moves to the next line with it. Text with no East Asian language, or in Korean or English, has no such rules in Word. Korean, Thai and the other scripts without spaces between words break at their spaces, as Word breaks them, and a word wider than the line breaks after the last character that fits. A paragraph's `wordWrap`, which writes Word's "Allow Latin text to wrap in the middle of a word", lets the words of runs in an East Asian font or language break anywhere, as Word breaks them. Right-to-left paragraphs (`bidirectional`) break where left-to-right ones do
- spacing before and after paragraphs, line spacing, indents and tab stops. A line in one font is as tall as Word makes it, to a fraction of a twip (a twentieth of a point): 268.55 twips for Calibri 11. A line in several fonts is as tall as the tallest of them. Contextual spacing (`contextualSpacing`) leaves out only its paragraph's own share of the space between it and a paragraph of the same style, as Word does: all of its space after, or as much of its space before as is more than the space after the paragraph above it
- keeping a paragraph with the next, keeping its lines together, widow and orphan control, and page breaks
- numbered and bulleted lists, including those a paragraph's style numbers it in
@@ -91,7 +92,7 @@ It stops at the first thing it can't lay out yet, and the page numbers of the he
- a footnote in a table row that holds back lines of a cell beside it, which would fit on the page above the footnote, and a table row that fits on an empty page, but not with its footnote
- a table whose rows give a column different widths, a table given no widths of more than 63 columns, more than Word allows, and, in a table whose cells all have widths, a word longer than the table can make room for, a long word in a table wider than its cells, or one in a table with cells merged across its columns
- a long word in a cell merged across the columns of a table given no widths, which Word makes room for in a way not yet followed: a word longer than those columns' longest words together, when the table is narrowed to fit, or than their longest lines together, when more than one of them has anything in it
- a document that hyphenates its words
- a document that hyphenates its words, compresses its punctuation, or uses Word's strict rules for the characters that can't start a line
- page numbers in Thai and Hindi words (`thaiCounting` and `hindiCounting`), and page numbers Word writes as an error: any in `none`, 0 in Hebrew, Arabic, Thai and Hindi digits and Chicago's symbols, and those past where a format's letters run out, such as 781 in letters. Page numbers in Hebrew past 100, and in Hindi letters past 75 (`hindiVowels`) and 37 (`hindiConsonants`), haven't been checked in Word yet
- a chapter number from a heading in a table
@@ -99,7 +100,7 @@ A wrong page number is worse than a blank one, so it doesn't guess.
## How close it is
Text in fonts other than those five is measured as the most similar of them, so its page numbers are rougher. Aptos, Office's default font since 2023, is measured as Arial. In a browser, text can be measured in the fonts the page has instead (see [Measuring with a page's fonts](#measuring-with-a-pages-fonts)).
Text in fonts other than those five is measured as the most similar of them, so its page numbers are rougher. Aptos, Office's default font since 2023, is measured as Arial. In a browser, text can be measured in the fonts the page has instead (see [Measuring with a page's fonts](#measuring-with-a-pages-fonts)). Letters the fonts have no widths for, such as Greek, Cyrillic, Hebrew, Arabic and Thai, are measured as an average letter of the font, and East Asian fonts Office doesn't have as MS Mincho or MS Gothic.
Each change to `docx/layout` is checked against LibreOffice's layout of a set of documents. Word lays out some things differently from LibreOffice, so keep `updateFields` on if the page numbers must be exact once the document is opened in Word. 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.
+30 -21
View File
@@ -1,6 +1,6 @@
# Layout probes
<!-- cspell:ignore fsplit soffice Poppler pdftocairo -->
<!-- cspell:ignore fsplit soffice Poppler pdftocairo autoSpace -->
Documents made to find out how Word lays out pages, where its rules aren't written down. docx/layout follows what they
showed. Each line of text names its probe, such as `Q3a fill 12`, so it can be found in a PDF of the document, and each
@@ -11,26 +11,28 @@ from Word 16 for Mac on 2026-09-30 and 2026-10-01 (Save As, PDF, Best for printi
now, so the committed `.docx` is the one each PDF is of: `word-rules` and `word-tables` were made before docx wrote a
table style and each cell's width.
| Probe | What it settles | Reader |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ |
| `word-rules` | P0 to P10: the space before the first paragraph and at the top of a page, the space between paragraphs and contextual spacing, widow and orphan control, the height of headers and footers and of table rows, the line pitch of each font and size, footnotes that don't fit on the page, table rows broken across pages, columns, and paragraphs of only spaces | `word-rules.py` |
| `word-rules2` | Q1 to Q7: contextual spacing with each paragraph's share, the space before a section's first paragraph on a new page, keepLines and widow control inside table rows, header rows in columns, sections that start in the next column, footnotes in columns, and columns of different widths | `word-rules2.py` |
| `word-balance` | W1 to W9: how the columns before a continuous section break are evened out, with column breaks, space after, paragraphs kept together or with the next, tables, lines of two sizes, columns that go on to the next page or start low on it, and a page of exactly 51 lines before a new section | `word-balance.py` |
| `word-balance2` | S1 to S7 and C1 to C2: the space after columns and before the next section, which the empty paragraph that ends a section keeps, and column breaks in columns that are evened out | `word-balance.py` |
| `word-keep-together` | K1 to K5: a paragraph kept together that is taller than a column, which Word lays out down only the first column of each page, from a new page unless it is at the top of one, and what follows it | `word-balance.py` |
| `word-next-column` | N1 to N6: where a section that starts in the next column starts after columns of other numbers and widths, the space before its first paragraph there, three in a row, and in columns below text, followed by a continuous section break | `word-next-column.py` |
| `word-column-widths` | R1 to R6: widow control in a paragraph that goes on into a column of another width, where its lines are broken again, and the widths of a table sized to its text that goes on into a wider column | `word-column-widths.py` |
| `word-contextual` | X1 and Y1: contextual spacing next to the empty paragraph that ends a section, whose space after is never on the page itself, and with `doNotUseHTMLParagraphAutoSpacing`. `word-contextual-adding` is the second document it writes, with that setting | `word-contextual.py` |
| `word-tables` | T1 to T13: the widths Word gives table columns from `columnWidths`, cell widths and table widths, and a word longer than its column (T7) | `pagelines.py` |
| `word-autofit` | A1 to D1: the widths Word gives the columns of tables whose cells have no widths, which it sizes to their text | `word-autofit.py` |
| `word-long-words` | L1 to L8: how Word widens a column for a word longer than its cells give it, in tables whose cells all have widths, and what it takes from the other columns. `word-long-words-layout.ts` prints docx/layout's widths for them | `word-autofit.py` |
| `word-probes` | U1 to U8: the widths of tables given no widths with merged cells or tables in cells, footnotes continued, footnotes in table rows and in columns, rows with merged cells, a table in a cell or a set height across pages, rows taller than a page, the space before a continuous section's first paragraph with a page break before it, and lines of only spaces before a break | `word-probes.py` |
| `word-header-columns` | H1 to H8: a table's header rows repeated at the top of each column, in columns evened out before a continuous section break and on a second page, the columns of a table that goes on from the page before evened out, and the line of the empty paragraph that ends a section after a table | `word-header-columns.py` |
| `word-footnotes-in-columns` | N1 to N12: footnotes in columns, which Word lays out in the columns too, one after the other from the first and evened out, whichever column they are referred to from, with every column ending above them. Below columns that start below text across the page, or are evened out above it, a footnote that wraps in a column, one too long for the room below its reference, and footnotes referred to from text across the page and from columns below it | `word-footnotes-in-columns.py` |
| `word-line-heights` | H and T1 to T4: the height of lines in each font, size and line spacing, measured over a page, and how a table row breaks across pages: with room for the table's bottom border below it and for the space after a cell's paragraph, rows of an at-least height with less room than their height, and a page that ends between rows | `word-line-heights.py` |
| `word-page-number-formats` | P: page numbers and page references in each number format at 4, 1234 and 0, L: lists in each format from 1 to 60 and at larger numbers, and C1 to C11: chapter numbers, with each separator, from headings of each level and numbering, before and after a heading on the same page | `word-page-number-formats.py` |
| `word-page-number-formats2` | P: page numbers in each format where its letters run out and at 0, and C12 to C15: chapter numbers after a heading that isn't numbered, from one numbered on its own too, from a level with no number in its text, and from a style based on heading 1 | `word-page-number-formats.py` |
| `fsplit` | How a footnote that doesn't fit below its reference goes on to the next page. Laid out in LibreOffice only, so it has no PDF from Word: Word's split of an 8-line footnote is `word-rules` P7b | `pagelines.py` |
| Probe | What it settles | Reader |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------ |
| `word-rules` | P0 to P10: the space before the first paragraph and at the top of a page, the space between paragraphs and contextual spacing, widow and orphan control, the height of headers and footers and of table rows, the line pitch of each font and size, footnotes that don't fit on the page, table rows broken across pages, columns, and paragraphs of only spaces | `word-rules.py` |
| `word-rules2` | Q1 to Q7: contextual spacing with each paragraph's share, the space before a section's first paragraph on a new page, keepLines and widow control inside table rows, header rows in columns, sections that start in the next column, footnotes in columns, and columns of different widths | `word-rules2.py` |
| `word-balance` | W1 to W9: how the columns before a continuous section break are evened out, with column breaks, space after, paragraphs kept together or with the next, tables, lines of two sizes, columns that go on to the next page or start low on it, and a page of exactly 51 lines before a new section | `word-balance.py` |
| `word-balance2` | S1 to S7 and C1 to C2: the space after columns and before the next section, which the empty paragraph that ends a section keeps, and column breaks in columns that are evened out | `word-balance.py` |
| `word-keep-together` | K1 to K5: a paragraph kept together that is taller than a column, which Word lays out down only the first column of each page, from a new page unless it is at the top of one, and what follows it | `word-balance.py` |
| `word-next-column` | N1 to N6: where a section that starts in the next column starts after columns of other numbers and widths, the space before its first paragraph there, three in a row, and in columns below text, followed by a continuous section break | `word-next-column.py` |
| `word-column-widths` | R1 to R6: widow control in a paragraph that goes on into a column of another width, where its lines are broken again, and the widths of a table sized to its text that goes on into a wider column | `word-column-widths.py` |
| `word-contextual` | X1 and Y1: contextual spacing next to the empty paragraph that ends a section, whose space after is never on the page itself, and with `doNotUseHTMLParagraphAutoSpacing`. `word-contextual-adding` is the second document it writes, with that setting | `word-contextual.py` |
| `word-tables` | T1 to T13: the widths Word gives table columns from `columnWidths`, cell widths and table widths, and a word longer than its column (T7) | `pagelines.py` |
| `word-autofit` | A1 to D1: the widths Word gives the columns of tables whose cells have no widths, which it sizes to their text | `word-autofit.py` |
| `word-long-words` | L1 to L8: how Word widens a column for a word longer than its cells give it, in tables whose cells all have widths, and what it takes from the other columns. `word-long-words-layout.ts` prints docx/layout's widths for them | `word-autofit.py` |
| `word-probes` | U1 to U8: the widths of tables given no widths with merged cells or tables in cells, footnotes continued, footnotes in table rows and in columns, rows with merged cells, a table in a cell or a set height across pages, rows taller than a page, the space before a continuous section's first paragraph with a page break before it, and lines of only spaces before a break | `word-probes.py` |
| `word-header-columns` | H1 to H8: a table's header rows repeated at the top of each column, in columns evened out before a continuous section break and on a second page, the columns of a table that goes on from the page before evened out, and the line of the empty paragraph that ends a section after a table | `word-header-columns.py` |
| `word-footnotes-in-columns` | N1 to N12: footnotes in columns, which Word lays out in the columns too, one after the other from the first and evened out, whichever column they are referred to from, with every column ending above them. Below columns that start below text across the page, or are evened out above it, a footnote that wraps in a column, one too long for the room below its reference, and footnotes referred to from text across the page and from columns below it | `word-footnotes-in-columns.py` |
| `word-line-heights` | H and T1 to T4: the height of lines in each font, size and line spacing, measured over a page, and how a table row breaks across pages: with room for the table's bottom border below it and for the space after a cell's paragraph, rows of an at-least height with less room than their height, and a page that ends between rows | `word-line-heights.py` |
| `word-page-number-formats` | P: page numbers and page references in each number format at 4, 1234 and 0, L: lists in each format from 1 to 60 and at larger numbers, and C1 to C11: chapter numbers, with each separator, from headings of each level and numbering, before and after a heading on the same page | `word-page-number-formats.py` |
| `word-page-number-formats2` | P: page numbers in each format where its letters run out and at 0, and C12 to C15: chapter numbers after a heading that isn't numbered, from one numbered on its own too, from a level with no number in its text, and from a style based on heading 1 | `word-page-number-formats.py` |
| `word-unicode` | K, E, L, H, N, W, A, P, KR, T, R and G: which characters Word keeps from starting or ending a line of Chinese and Japanese, with no language and in each language, hanging punctuation, kinsoku and wordWrap off, Latin words and numbers after ideographs, breaks after dashes, slashes and zero-width spaces, the space between ideographs and Latin text, punctuation compression, Korean and Thai, right-to-left paragraphs and runs, and the height of lines of East Asian, Thai and Hebrew fonts | `word-unicode.read.ts` |
| `word-unicode2` | S, E, H, A, W, T, F and G: every character of Word's lists in Japanese, Chinese, Korean and English, hanging punctuation and the space around Latin text in Japanese, wordWrap off, zero-width spaces, Thai without marks above or below its letters, the font and size of Hebrew and Latin in runs that are right to left and runs that aren't, and the height of lines of 21 East Asian fonts. `word-unicode2-layout.ts` compares where docx/layout breaks the lines of S and E with where Word does | `word-unicode2.read.ts` |
| `fsplit` | How a footnote that doesn't fit below its reference goes on to the next page. Laid out in LibreOffice only, so it has no PDF from Word: Word's split of an 8-line footnote is `word-rules` P7b | `pagelines.py` |
## Make a probe's `.docx`
@@ -69,6 +71,13 @@ pdftotext -bbox-layout scripts/layout-probes/word-rules2.pdf build/word-probes/w
python3 scripts/layout-probes/word-rules2.py build/word-probes/word-rules2.html
```
`word-unicode.read.ts` and `word-unicode2.read.ts` are TypeScript, for `Intl.Segmenter`, which they check Thai's line breaks with:
```bash
pdftotext -bbox-layout scripts/layout-probes/word-unicode2.pdf build/word-probes/word-unicode2.html
npm run run-ts -- scripts/layout-probes/word-unicode2.read.ts build/word-probes/word-unicode2.html
```
`word-page-number-formats.py` reads both page number probes, from the text of `pdftotext -layout` rather than where each
line is:
Binary file not shown.
Binary file not shown.
+166
View File
@@ -0,0 +1,166 @@
// cspell:disable
// Reads the probes of word-unicode.ts from pdftotext -bbox-layout's HTML of a PDF of it, and prints what each shows.
//
// Usage: pdftotext -bbox-layout scripts/layout-probes/word-unicode.pdf build/word-probes/word-unicode.html
// npm run run-ts -- scripts/layout-probes/word-unicode.read.ts build/word-probes/word-unicode.html
import * as fs from "fs";
type Word = { readonly xMin: number; readonly xMax: number; readonly text: string };
type Line = {
readonly page: number;
readonly xMin: number;
readonly yMin: number;
readonly xMax: number;
readonly yMax: number;
readonly text: string;
readonly words: readonly Word[];
};
const unescape = (text: string): string =>
text
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'")
.replace(/&amp;/g, "&");
const html = fs.readFileSync(process.argv[2], "utf8");
const LINES: readonly Line[] = [...html.matchAll(/<page[\s\S]*?<\/page>/g)].flatMap(([page], index) =>
[...page.matchAll(/<line xMin="([\d.]+)" yMin="([\d.]+)" xMax="([\d.]+)" yMax="([\d.]+)">([\s\S]*?)<\/line>/g)].map(
([, xMin, yMin, xMax, yMax, content]) => {
const words = [...content.matchAll(/<word xMin="([\d.]+)" yMin="[\d.]+" xMax="([\d.]+)" yMax="[\d.]+">([^<]*)<\/word>/g)].map(
([, left, right, text]) => ({ xMin: Number(left), xMax: Number(right), text: unescape(text) }),
);
return {
page: index + 1,
xMin: Number(xMin),
yMin: Number(yMin),
xMax: Number(xMax),
yMax: Number(yMax),
text: words.map((word) => word.text).join(" "),
words,
};
},
),
);
// Labels are in 7-point Calibri, and start with the probe's name
const isLabel = (line: Line): boolean => line.yMax - line.yMin < 9.5 && /^([A-Z]+\d+|end)\b/.test(line.text);
/** A label's name, with the character it tests in place of its code point */
const named = (label: string): string =>
label.replace(/U\+([0-9A-F]{4,5})/g, (_, code: string) => String.fromCodePoint(Number.parseInt(code, 16)));
const LABELS = LINES.flatMap((line, index) => (isLabel(line) ? [index] : []));
const PROBES = new Map(LABELS.map((start, i) => [LINES[start].text, LINES.slice(start + 1, LABELS[i + 1] ?? LINES.length)] as const));
const EM = 12;
const LEFT = 63.5;
const RIGHT = LEFT + 485;
const em = (line: Line): string => ((line.xMax - line.xMin) / EM).toFixed(2);
const characters = (text: string): readonly string[] => [...text.replace(/ /g, "")];
const twips = (points: number): string => (points * 20).toFixed(1);
const probesStarting = (prefix: string): readonly (readonly [string, readonly Line[]])[] =>
[...PROBES].filter(([name]) => name.startsWith(prefix));
/** Where the character tested falls: at the start of the second line, or the end of the first */
const placement = (name: string, lines: readonly Line[]): string => {
const [first, second] = lines;
if (!first || !second) {
return `${lines.length} line(s): ${lines.map((line) => line.text).join(" / ")}`;
}
const character = String.fromCodePoint(Number.parseInt(name.split(" ").pop()!.slice(2), 16));
const one = characters(first.text);
const two = characters(second.text);
const at =
one[one.length - 1] === character ? "ends line 1" : two[0] === character ? "starts line 2" : `before ${two.slice(0, 2).join("")}`;
const overhang = first.xMax > RIGHT + 0.5 ? `, ${(first.xMax - RIGHT).toFixed(1)}pt past the margin` : "";
return `line 1: ${one.length} characters, ${em(first)} em${overhang}; line 2 starts ${two.slice(0, 2).join("")}: ${at}`;
};
const section = (title: string): void => console.log(`\n== ${title}`);
section("K, E, L, H, N: where a character falls at the end of a line of 40 ideographs");
for (const [name, lines] of [...PROBES].filter(([probe]) => /^[KELHN]\d/.test(probe))) {
console.log(` ${named(name).padEnd(22)} ${placement(name, lines)}`);
}
section("W: Latin words with wordWrap off, and after ideographs");
for (const [name, lines] of probesStarting("W")) {
console.log(` ${name}`);
for (const line of lines) {
console.log(` ${em(line).padStart(6)} em ${line.text.slice(0, 90)}`);
}
}
section("A: the space between ideographs and Calibri letters and numbers");
for (const [name, lines] of probesStarting("A")) {
console.log(` ${name}: ${lines.length} line(s), the first ${em(lines[0])} em`);
if (!name.includes("fit")) {
for (const word of lines[0].words) {
console.log(` ${word.xMin.toFixed(2)} to ${word.xMax.toFixed(2)} ${word.text}`);
}
}
}
section("P: pairs of punctuation, 3 lines uncompressed");
for (const [name, lines] of probesStarting("P")) {
console.log(` ${named(name)}: ${lines.length} lines of ${lines.map((line) => characters(line.text).length).join(", ")} characters`);
}
section("KR: Korean words of 7 syllables. A line ending inside one breaks inside words");
for (const [name, lines] of probesStarting("KR")) {
const inside = lines.slice(0, -1).filter((line) => characters(line.text.split(" ").pop()!).length !== 7).length;
console.log(` ${name}: ${lines.length} lines, ${inside} of them ending inside a word`);
for (const line of lines) {
console.log(` ${em(line).padStart(6)} em ...${line.text.slice(-24)}`);
}
}
section("T: Thai. Whether each line ends where Intl.Segmenter finds a word boundary");
const segmenter = new Intl.Segmenter("th", { granularity: "word" });
for (const [name, lines] of probesStarting("T")) {
const texts = lines.map((line) => line.text);
const joined = texts.join("");
const boundaries = new Set([...segmenter.segment(joined)].map(({ index }) => index));
let offset = 0;
console.log(` ${name}: ${lines.length} lines`);
for (const text of texts.slice(0, -1)) {
offset += text.length;
const before = [...segmenter.segment(joined.slice(0, offset))].pop()!.segment;
const after = [...segmenter.segment(joined.slice(offset))][0]?.segment ?? "";
console.log(` ${boundaries.has(offset) ? "at a boundary " : "INSIDE A WORD "} ...${before} | ${after}...`);
}
}
section("R1 to R3: Latin in left-to-right and right-to-left paragraphs. Words on each line");
for (const [name, lines] of probesStarting("R").filter(([probe]) => /^R[123]\b/.test(probe))) {
console.log(` ${name}: ${lines.map((line) => line.text.split(" ").length).join(", ")}`);
}
/** The pitch of lines, from the tops of those after each other on a page, and their height */
const pitchOf = (parts: readonly Line[]): string => {
// Text in two scripts on one line can be two lines of pdftotext's, and not one after the other
const sorted = [...parts].sort((a, b) => a.page - b.page || a.yMin - b.yMin);
const lines = sorted.filter((line, i) => i === 0 || line.page !== sorted[i - 1].page || Math.abs(line.yMin - sorted[i - 1].yMin) > 1);
const steps = lines.slice(1).flatMap((line, i) => (line.page === lines[i].page ? [line.yMin - lines[i].yMin] : []));
const pitch = steps.reduce((total, step) => total + step, 0) / steps.length;
return `pitch ${twips(pitch)} twips over ${steps.length} lines, glyphs ${twips(lines[0].yMax - lines[0].yMin)} twips tall`;
};
section("R4, R5 and G: the height of lines");
for (const [name, lines] of [...PROBES].filter(([probe]) => /^(R4|R5|G\d+)\b/.test(probe))) {
console.log(` ${name.padEnd(36)} ${pitchOf(lines)}`);
}
section("R6 and R7: the width of an rtl run bold for complex scripts, and of one not bold");
for (const [name, lines] of probesStarting("R").filter(([probe]) => /^R[67]\b/.test(probe))) {
console.log(` ${name}: ${(lines[0].xMax - lines[0].xMin).toFixed(2)}pt`);
}
section("R8 and R9: Hebrew and Arabic paragraphs");
for (const [name, lines] of probesStarting("R").filter(([probe]) => /^R[89]\b/.test(probe))) {
console.log(` ${name}: ${lines.length} lines`);
for (const line of lines) {
console.log(` ${line.xMin.toFixed(2)} to ${line.xMax.toFixed(2)} ${line.text.slice(0, 60)}`);
}
}
+288
View File
@@ -0,0 +1,288 @@
// cspell:disable
// Probes of how Word breaks lines of Chinese, Japanese, Korean and Thai text, and lays out right-to-left text, for
// docx/layout's line breaking (src/text-layout/line-breaking.ts). Each probe has a label before it, in 7-point Calibri,
// so its lines can be found in a PDF saved from Word: word-unicode.read.ts reads pdftotext -bbox-layout's HTML of it.
// Labels name the characters they test by their code points, so they have no characters Calibri doesn't have.
//
// The text is 485 points wide, so 40 ideographs of 12-point MS Mincho fit on a line, and neither a 41st nor half of one.
//
// K: which characters can't start a line, with no language set: 40 ideographs, the character, then 3 more
// E: which characters can't end a line: 39 ideographs, the character, then 4 more
// L: K and E for the characters Word's lists for Japanese, Chinese and Korean differ on, in each of those languages
// H: punctuation that hangs past the end of the line, with overflowPunct on and off
// N: K and E with kinsoku off
// W: wordWrap off, which lets Latin words break anywhere, and Latin words and numbers after ideographs
// A: the space Word adds between ideographs and Latin letters or numbers (autoSpaceDE and autoSpaceDN)
// P: whether punctuation next to punctuation is compressed, in a document that doesn't ask for it
// KR: whether Korean breaks inside words
// T: where Thai breaks
// R: right-to-left paragraphs and runs: where they break, and the size and bold of complex scripts
// G: the height of lines of East Asian, Thai and Hebrew text in their fonts
//
// Usage: npm run run-ts -- scripts/layout-probes/word-unicode.ts, which writes build/word-probes/word-unicode.docx
import * as fs from "fs";
import JSZip from "jszip";
import { Document, Packer, Paragraph, TextRun } from "docx";
const IDEOGRAPH = "永";
const ideographs = (count: number): string => IDEOGRAPH.repeat(count);
const MINCHO = { font: "MS Mincho", size: 24 };
/** Paragraph properties docx doesn't write, put in after the paragraph's style by its id */
const INJECTED: Readonly<Record<string, string>> = {
KinsokuOff: '<w:kinsoku w:val="0"/>',
HangOff: '<w:overflowPunct w:val="0"/>',
HangOn: '<w:overflowPunct w:val="1"/>',
AutoSpaceOff: '<w:autoSpaceDE w:val="0"/><w:autoSpaceDN w:val="0"/>',
AutoSpaceOn: '<w:autoSpaceDE w:val="1"/><w:autoSpaceDN w:val="1"/>',
};
const label = (text: string): Paragraph => new Paragraph({ keepNext: true, children: [new TextRun({ text, size: 14 })] });
/** A character by its code point, as labels name them, so they are all in Calibri */
const codePoint = (character: string): string => `U+${character.codePointAt(0)!.toString(16).toUpperCase().padStart(4, "0")}`;
type Options = { readonly language?: string; readonly style?: string; readonly wordWrap?: boolean };
const mincho = (text: string, { language, style, wordWrap }: Options = {}): Paragraph =>
new Paragraph({
...(style ? { style } : {}),
...(wordWrap ? { wordWrap } : {}),
children: [new TextRun({ text, ...MINCHO, ...(language ? { language: { eastAsia: language } } : {}) })],
});
/** A character at the start of the second line, after a full line of ideographs */
const atStart = (name: string, character: string, options: Options = {}): readonly Paragraph[] => [
label(`${name} start ${codePoint(character)}`),
mincho(`${ideographs(40)}${character}${ideographs(3)}`, options),
];
/** A character at the end of the first line, the 40th */
const atEnd = (name: string, character: string, options: Options = {}): readonly Paragraph[] => [
label(`${name} end ${codePoint(character)}`),
mincho(`${ideographs(39)}${character}${ideographs(4)}`, options),
];
const numbered = (prefix: string, index: number): string => `${prefix}${String(index + 1).padStart(2, "0")}`;
// Word's lists for Japanese (the first two lines, and the small kana of its strict list), Chinese and Korean, and
// characters Unicode's line breaking rules keep from starting a line that none of them has
const CANT_START = [
..."!%),.:;?]}¢°’”‰′″℃、。々〉》」』】〕゛゜ゝゞ・ヽヾ",
..."!%),.:;?]}。」、・゙゚¢",
..."っャァーッー",
..."·ˇ―‖…〃〗〞︶﹚"'`|~›∶¨",
..."—–•‥‧﹐﹑︰",
..."〜‐゠〙‼⁉",
];
const CANT_END = [..."([{$£¥‘“〈《「『【〔$([{「£¥〖〝﹙﹛﹝\\\₩¿¡«·〘"];
const LANGUAGES = ["ja-JP", "zh-CN", "zh-TW", "ko-KR"];
const BY_LANGUAGE_START = [..."々・…〃〗~―—‥¢っ‰"];
const BY_LANGUAGE_END = [..."‘\₩〖﹙·"];
const HANGING = [..."、。,.)」!?:;"];
const PROSE = "the survey of the coast was made in the summer by boat and on foot from the lighthouse to the river mouth".split(" ");
const LONG_WORD = "abcdefghijklmnopqrstuvwxyzab";
const prose = (words: number): string => Array.from({ length: words }, (_, i) => PROSE[(i * 5) % PROSE.length]).join(" ");
const HEBREW = ["זהו משפט לדוגמה בעברית", "הטקסט נכתב מימין לשמאל", "השורות נשברות ברווחים בין המילים"];
const ARABIC = ["هذا نص تجريبي باللغة العربية", "يكتب النص من اليمين إلى اليسار", "وتنكسر الأسطر عند المسافات بين الكلمات"];
const THAI = [
"ภาษาไทยเป็นภาษาที่ไม่เว้นวรรคระหว่างคำ",
"โปรแกรมจึงต้องใช้พจนานุกรมเพื่อหาขอบเขตของคำ",
"วันนี้อากาศดีมากเราจึงไปเที่ยวทะเลกับครอบครัว",
"นักเรียนทุกคนต้องอ่านหนังสือก่อนสอบ",
"กรุงเทพมหานครเป็นเมืองหลวงของประเทศไทย",
"ประเทศไทยมีจังหวัดทั้งหมดเจ็ดสิบเจ็ดจังหวัด",
"คนไทยชอบกินข้าวเหนียวกับมะม่วงในฤดูร้อน",
];
const KOREAN_WORD = "가나다라마바사";
const repeated = (sentences: readonly string[], times: number, separator: string): string =>
Array.from({ length: times }, (_, round) =>
sentences.map((_, i) => sentences[(i + round * 3) % sentences.length]).join(separator),
).join(separator);
/** Eleven one-line paragraphs, for the height of a line */
const pitch = (name: string, text: string, run: ConstructorParameters<typeof TextRun>[0] & object): readonly Paragraph[] =>
Array.from({ length: 11 }, (_, i) => new Paragraph({ children: [new TextRun({ ...run, text: `${name} ${i + 1} ${text}` })] }));
const MIXED_FONT = { ascii: "Calibri", hAnsi: "Calibri", eastAsia: "MS Mincho", cs: "Calibri" };
const HEIGHT_FONTS: readonly (readonly [string, string])[] = [
["MS Mincho", ideographs(8)],
["MS Gothic", ideographs(8)],
["Yu Mincho", ideographs(8)],
["Yu Gothic", ideographs(8)],
["SimSun", ideographs(8)],
["Microsoft YaHei", ideographs(8)],
["DengXian", ideographs(8)],
["PMingLiU", ideographs(8)],
["Malgun Gothic", "가나다라마바사"],
["Batang", "가나다라마바사"],
["Calibri", ideographs(8)],
["Tahoma", "ภาษาไทยเป็นภาษา"],
["Cordia New", "ภาษาไทยเป็นภาษา"],
["Arial", "זהו משפט לדוגמה"],
];
const doc = new Document({
styles: {
default: { document: { run: { font: "Calibri", size: 22 }, paragraph: { spacing: { before: 0, after: 0, line: 240 } } } },
paragraphStyles: Object.keys(INJECTED).map((id) => ({ id, name: id, basedOn: "Normal" })),
},
sections: [
{
properties: {
page: { size: { width: 12240, height: 15840 }, margin: { top: 1080, bottom: 1080, left: 1270, right: 1270 } },
},
children: [
...CANT_START.flatMap((character, i) => atStart(numbered("K", i), character)),
...CANT_END.flatMap((character, i) => atEnd(numbered("E", i), character)),
...LANGUAGES.flatMap((language) => [
...BY_LANGUAGE_START.flatMap((character, i) => atStart(`${numbered("L", i)} ${language}`, character, { language })),
...BY_LANGUAGE_END.flatMap((character, i) => atEnd(`${numbered("L", i + 20)} ${language}`, character, { language })),
]),
...HANGING.flatMap((character, i) => [
...atStart(`${numbered("H", i)} on`, character, { style: "HangOn" }),
...atStart(`${numbered("H", i)} off`, character, { style: "HangOff" }),
]),
...[..."、。)」ーっ!"].flatMap((character, i) => atStart(numbered("N", i), character, { style: "KinsokuOff" })),
...[..."(「$"].flatMap((character, i) => atEnd(numbered("N", i + 10), character, { style: "KinsokuOff" })),
// W1 and W2: a Latin paragraph with wordWrap off, and without. W3 to W8: a Latin word or number that doesn't
// fit at the end of a line of ideographs, after a space, with wordWrap off, and with no space
label("W1 Latin, wordWrap off"),
new Paragraph({ wordWrap: true, children: [new TextRun(prose(120))] }),
label("W2 Latin"),
new Paragraph({ children: [new TextRun(prose(120))] }),
label("W3 space internationalization"),
mincho(`${ideographs(35)} internationalization${ideographs(2)}`),
label("W4 space internationalization, wordWrap off"),
mincho(`${ideographs(35)} internationalization${ideographs(2)}`, { wordWrap: true }),
label("W5 abcd"),
mincho(`${ideographs(39)}abcd${ideographs(2)}`),
label("W6 1234"),
mincho(`${ideographs(39)}1234${ideographs(2)}`),
label("W7 full-width 1234"),
mincho(`${ideographs(39)}1234${ideographs(2)}`),
label("W8 full-width abcd"),
mincho(`${ideographs(39)}abcd${ideographs(2)}`),
// W9 to W14: a Calibri word joined to another by a dash, slash or zero-width space at the end of a line. The
// line ends after the join where Word breaks there, and before the first word where it doesn't
...[
["W9 em dash", "\u2014"],
["W10 en dash", "\u2013"],
["W11 hyphen", "-"],
["W12 Unicode hyphen", "\u2010"],
["W13 slash", "/"],
["W14 zero-width space", "\u200B"],
].flatMap(([name, join]) => [
label(name),
new Paragraph({ children: [new TextRun({ text: `${prose(9)} ${LONG_WORD}${join}${LONG_WORD}`, size: 24 })] }),
]),
// A1 to A3: ideographs, then Calibri letters and numbers, with autoSpaceDE and autoSpaceDN as Word has them,
// off and on. A4 to A6: 39 ideographs and "ab", 480 points, then 3 more ideographs, which only fit on the
// first line with less than 2.5 points around "ab"
...(["", "AutoSpaceOff", "AutoSpaceOn"] as const).flatMap((style, i) => [
label(`A${i + 1} ${style || "default"}`),
new Paragraph({
...(style ? { style } : {}),
children: [
new TextRun({ text: `${ideographs(5)}abc${ideographs(5)}123${ideographs(5)}`, font: MIXED_FONT, size: 24 }),
],
}),
]),
...(["", "AutoSpaceOff", "AutoSpaceOn"] as const).flatMap((style, i) => [
label(`A${i + 4} ${style || "default"} fit`),
new Paragraph({
...(style ? { style } : {}),
children: [new TextRun({ text: `${ideographs(20)}ab${ideographs(22)}`, font: MIXED_FONT, size: 24 })],
}),
]),
// P1 to P4: 82 characters, 27 of them pairs of punctuation. Uncompressed they take 3 lines, and 2 with the pairs
// compressed
...["」「", "。」", "、「", ")("].flatMap((pair, i) => [
label(`P${i + 1} ${[...pair].map(codePoint).join(" ")}`),
mincho(`${`${IDEOGRAPH}${pair}`.repeat(27)}${IDEOGRAPH}`),
]),
// KR1 to KR3: words of 7 syllables, with no language, in Korean, and with wordWrap off
...([{}, { language: "ko-KR" }, { wordWrap: true }] as const).flatMap((options, i) => [
label(`KR${i + 1}`),
new Paragraph({
...("wordWrap" in options ? { wordWrap: true } : {}),
children: [
new TextRun({
text: Array.from({ length: 30 }, () => KOREAN_WORD).join(" "),
font: "Malgun Gothic",
size: 24,
...("language" in options ? { language: { eastAsia: options.language } } : {}),
}),
],
}),
]),
// T1 to T3: Thai in Tahoma with no spaces, with spaces between sentences, and in Calibri, which has no Thai
label("T1 Thai, no spaces"),
new Paragraph({ children: [new TextRun({ text: repeated(THAI, 2, ""), font: "Tahoma", size: 24 })] }),
label("T2 Thai, spaces between sentences"),
new Paragraph({ children: [new TextRun({ text: repeated(THAI, 2, " "), font: "Tahoma", size: 24 })] }),
label("T3 Thai in Calibri"),
new Paragraph({ children: [new TextRun({ text: repeated(THAI, 2, ""), size: 24 })] }),
// R1 to R3: the same Latin words in a left-to-right paragraph, a right-to-left one of right-to-left runs, and a
// right-to-left one of left-to-right runs
label("R1 Latin"),
new Paragraph({ children: [new TextRun(prose(150))] }),
label("R2 Latin, bidi paragraph, rtl runs"),
new Paragraph({ bidirectional: true, children: [new TextRun({ text: prose(150), rightToLeft: true })] }),
label("R3 Latin, bidi paragraph"),
new Paragraph({ bidirectional: true, children: [new TextRun(prose(150))] }),
// R4: rtl runs of 11 points and 22 for complex scripts. R5: Hebrew in runs that aren't rtl, the same
label("R4 rtl runs, sz 22 szCs 44"),
...pitch("R4", "the line", { rightToLeft: true, size: 22, sizeComplexScript: 44 }),
label("R5 Hebrew, sz 22 szCs 44"),
...pitch("R5", HEBREW[0], { font: "Arial", size: 22, sizeComplexScript: 44 }),
// R6 and R7: an rtl run bold only for complex scripts, and one not bold, to compare their widths
label("R6 rtl run, bCs"),
new Paragraph({
children: [new TextRun({ text: `R6 ${prose(12)}`, rightToLeft: true, bold: false, boldComplexScript: true })],
}),
label("R7 rtl run"),
new Paragraph({ children: [new TextRun({ text: `R7 ${prose(12)}`, rightToLeft: true })] }),
// R8 and R9: Hebrew and Arabic paragraphs
label("R8 Hebrew"),
new Paragraph({
bidirectional: true,
children: [new TextRun({ text: repeated(HEBREW, 6, " "), font: "Arial", rightToLeft: true })],
}),
label("R9 Arabic"),
new Paragraph({
bidirectional: true,
children: [new TextRun({ text: repeated(ARABIC, 6, " "), font: "Arial", rightToLeft: true })],
}),
// G: 11 lines of 12-point text in each font, and of 11-point Calibri letters with MS Mincho ideographs
...HEIGHT_FONTS.flatMap(([font, text], i) => [label(`G${i + 1} ${font}`), ...pitch(`G${i + 1}`, text, { font, size: 24 })]),
label(`G${HEIGHT_FONTS.length + 1} Calibri 11 and MS Mincho`),
...pitch(`G${HEIGHT_FONTS.length + 1}`, `abc${ideographs(5)}`, { font: MIXED_FONT, size: 22 }),
label("end"),
],
},
],
});
Packer.toBuffer(doc).then(async (buffer) => {
const zip = await JSZip.loadAsync(buffer);
const xml = await zip.file("word/document.xml")!.async("string");
const injected = Object.entries(INJECTED).reduce(
(all, [style, properties]) => all.split(`<w:pStyle w:val="${style}"/>`).join(`<w:pStyle w:val="${style}"/>${properties}`),
xml,
);
zip.file("word/document.xml", injected);
fs.mkdirSync("build/word-probes", { recursive: true });
fs.writeFileSync("build/word-probes/word-unicode.docx", await zip.generateAsync({ type: "nodebuffer" }));
});
@@ -0,0 +1,45 @@
// cspell:disable
// Lays out the probes of word-unicode2.ts's S and E with docx/layout, and compares where each line breaks with Word's,
// as word-unicode2.read.ts prints them from Word's PDF.
//
// Usage: npm run run-ts -- scripts/layout-probes/word-unicode2.read.ts build/word-probes/word-unicode2.html > build/word-probes/word-unicode2.out
// npm run run-ts -- scripts/layout-probes/word-unicode2-layout.ts build/word-probes/word-unicode2.out
import * as fs from "fs";
import { type InlineItem, layoutLines } from "../../src/text-layout";
const IDEOGRAPH = "永";
const FONT = { font: "MS Mincho", size: 6 };
/**
* Where docx/layout puts the character a probe tests, as the reader writes it: "." where it starts the second line (S) or
* ends the first (E), and "X" where it doesn't: where the ideograph before it moves to the second line with it (S), or it
* moves there itself (E). A bookmark before what moves shows which line it is on.
*/
const verdictOf = (kind: string, character: string, language: string): string => {
const text = (value: string): InlineItem => ({ type: "text", text: value, font: FONT, language });
const items: readonly InlineItem[] =
kind === "S"
? [text(IDEOGRAPH.repeat(39)), { type: "marker", name: "moved" }, text(`${IDEOGRAPH}${character}${IDEOGRAPH.repeat(3)}`)]
: [text(IDEOGRAPH.repeat(39)), { type: "marker", name: "moved" }, text(`${character}${IDEOGRAPH.repeat(4)}`)];
const lines = layoutLines(items, { width: 241 });
return lines.findIndex(({ markers }) => markers.includes("moved")) === 0 ? "." : "X";
};
const output = fs.readFileSync(process.argv[2], "utf8").split("\n");
const header = output.findIndex((line) => line.includes("ja-JP zh-CN"));
const languages = output[header].trim().split(/\s+/);
const rows = output.slice(header + 1).flatMap((line) => {
const match = /^\s+([SE]) (\S+) U\+[0-9A-F]+\s+(.*)$/.exec(line);
return match ? [{ kind: match[1], character: match[2], word: match[3].trim().split(/\s+/) }] : [];
});
const differences = rows.flatMap(({ kind, character, word }) =>
languages.flatMap((language, index) => {
const ours = verdictOf(kind, character, language);
return ours === word[index] ? [] : [`${kind} ${character} ${language}: Word ${word[index]}, docx/layout ${ours}`];
}),
);
console.log(`${rows.length * languages.length - differences.length} of ${rows.length * languages.length} as Word breaks them`);
for (const difference of differences) {
console.log(` ${difference}`);
}
Binary file not shown.
Binary file not shown.
+159
View File
@@ -0,0 +1,159 @@
// cspell:disable
// Reads the probes of word-unicode2.ts from pdftotext -bbox-layout's HTML of a PDF of it, and prints what each shows.
//
// Usage: pdftotext -bbox-layout scripts/layout-probes/word-unicode2.pdf build/word-probes/word-unicode2.html
// npm run run-ts -- scripts/layout-probes/word-unicode2.read.ts build/word-probes/word-unicode2.html
import * as fs from "fs";
type Line = {
readonly page: number;
readonly xMin: number;
readonly yMin: number;
readonly xMax: number;
readonly yMax: number;
readonly text: string;
};
const unescape = (text: string): string =>
text
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'")
.replace(/&amp;/g, "&");
const html = fs.readFileSync(process.argv[2], "utf8");
const LINES: readonly Line[] = [...html.matchAll(/<page[\s\S]*?<\/page>/g)].flatMap(([page], index) =>
[...page.matchAll(/<line xMin="([\d.]+)" yMin="([\d.]+)" xMax="([\d.]+)" yMax="([\d.]+)">([\s\S]*?)<\/line>/g)].map(
([, xMin, yMin, xMax, yMax, content]) => ({
page: index + 1,
xMin: Number(xMin),
yMin: Number(yMin),
xMax: Number(xMax),
yMax: Number(yMax),
text: [...content.matchAll(/<word[^>]*>([^<]*)<\/word>/g)].map(([, text]) => unescape(text)).join(" "),
}),
),
);
const characterOf = (code: string): string => String.fromCodePoint(Number.parseInt(code.slice(2), 16));
const characters = (text: string): readonly string[] => [...text.replace(/ /g, "")];
const twips = (points: number): string => (points * 20).toFixed(1);
// S and E: the lines below each label in its column, up to the next label
console.log("== S and E: whether each character can start (S) or end (E) a line, by language");
console.log(" . it can, X the ideograph before it moves to the next line with it, H it hangs past the end of the line\n");
const SE_LABEL = /^([SE]) (\S+) (U\+[0-9A-F]+)$/;
const labels = LINES.filter((line) => SE_LABEL.test(line.text));
const verdicts = new Map<string, Map<string, string>>();
const languages: string[] = [];
for (const label of labels) {
const [, kind, language, code] = SE_LABEL.exec(label.text)!;
const character = characterOf(code);
const below = LINES.filter(
(line) => line.page === label.page && Math.abs(line.xMin - label.xMin) < 3 && line.yMin > label.yMax - 1 && line !== label,
).sort((a, b) => a.yMin - b.yMin);
const next = below.findIndex((line) => SE_LABEL.test(line.text));
const [first, second] = next === -1 ? below : below.slice(0, next);
let verdict = "?";
if (first && second) {
const one = characters(first.text);
const two = characters(second.text);
const width = (first.xMax - first.xMin) / 6;
if (kind === "S") {
verdict = two[0] === character ? "." : one[one.length - 1] === character ? "H" : width < 39.5 ? "X" : width > 40.1 ? "H" : ".";
} else {
verdict = one[one.length - 1] === character ? "." : two[0] === character ? "X" : width < 39.05 ? "X" : ".";
}
}
const key = `${kind} ${character} ${code}`;
if (!verdicts.has(key)) {
verdicts.set(key, new Map());
}
verdicts.get(key)!.set(language, verdict);
if (!languages.includes(language)) {
languages.push(language);
}
}
console.log(` ${"".padEnd(12)} ${languages.map((language) => language.padEnd(6)).join(" ")}`);
const order = (key: string): string => `${key[0]}${key.split(" ")[2].slice(2).padStart(5, "0")}`;
for (const [key, byLanguage] of [...verdicts].sort(([a], [b]) => order(a).localeCompare(order(b)))) {
console.log(` ${key.padEnd(12)} ${languages.map((language) => (byLanguage.get(language) ?? "-").padEnd(6)).join(" ")}`);
}
// The other probes, in the order of the document, with a label before each
const isLabel = (line: Line): boolean => line.yMax - line.yMin < 9.5 && /^([A-Z]+\d+|end)\b/.test(line.text);
const rest = LINES.filter((line) => !SE_LABEL.test(line.text) && line.page > (labels[labels.length - 1]?.page ?? 0));
const starts = rest.flatMap((line, index) => (isLabel(line) ? [index] : []));
const PROBES = new Map(starts.map((start, i) => [rest[start].text, rest.slice(start + 1, starts[i + 1] ?? rest.length)] as const));
const probes = (pattern: RegExp): readonly (readonly [string, readonly Line[]])[] => [...PROBES].filter(([name]) => pattern.test(name));
const named = (label: string): string => label.replace(/U\+([0-9A-F]{4,5})/g, (code) => characterOf(code));
console.log("\n== H: 40 ideographs and punctuation, in Japanese");
for (const [name, lines] of probes(/^H\d/)) {
const [first, second] = lines;
const overhang = first.xMax - (63.5 + 485);
console.log(
` ${named(name).padEnd(22)} line 1: ${characters(first.text).length} characters, ${((first.xMax - first.xMin) / 12).toFixed(2)} em` +
`${overhang > 0.5 ? `, ${overhang.toFixed(1)}pt past the margin` : ""}; line 2 starts ${characters(second?.text ?? "")
.slice(0, 2)
.join("")}`,
);
}
console.log("\n== A: ideographs, Calibri letters and numbers, in Japanese. 215.37pt with no space between them");
for (const [name, lines] of probes(/^A\d/)) {
console.log(` ${name}: ${lines.length} line(s), ${(lines[0].xMax - lines[0].xMin).toFixed(2)}pt`);
}
console.log("\n== W: wordWrap off, and a zero-width space");
for (const [name, lines] of probes(/^W\d/)) {
console.log(` ${name}`);
for (const line of lines.slice(0, 4)) {
console.log(` ${((line.xMax - line.xMin) / 12).toFixed(2).padStart(6)} em ${line.text.slice(-40)}`);
}
}
console.log("\n== T: Thai words. Whether each line ends where Intl.Segmenter finds a word boundary");
const segmenter = new Intl.Segmenter("th", { granularity: "word" });
for (const [name, lines] of probes(/^T\d/)) {
// A line's marks can be lines of their own
const texts = lines.filter((line) => characters(line.text).length > 1).map((line) => line.text.replace(/[ \u200B]/g, ""));
const joined = texts.join("");
const boundaries = new Set([...segmenter.segment(joined)].map(({ index }) => index));
let offset = 0;
let inside = 0;
console.log(` ${name}: ${texts.length} lines`);
for (const text of texts.slice(0, -1)) {
offset += text.length;
const before = [...segmenter.segment(joined.slice(0, offset))].pop()!.segment;
const after = [...segmenter.segment(joined.slice(offset))][0]?.segment ?? "";
inside += boundaries.has(offset) ? 0 : 1;
console.log(` ${boundaries.has(offset) ? "at a boundary " : "INSIDE A WORD "} ...${before} | ${after}...`);
}
console.log(` ${inside} of ${texts.length - 1} inside words`);
}
console.log("\n== F: the width of 44 Hebrew letters, and of 26 Latin ones, in 11 points and 22 for complex scripts");
console.log(
" Courier New is 0.6 em a letter: 290.4pt for the Hebrew at 11 points, 580.8 at 22 (past the line), 343.2 for the Latin at 22",
);
for (const [name, lines] of probes(/^F\d/)) {
console.log(` ${name}: ${lines.map((line) => `${(line.xMax - line.xMin).toFixed(2)}pt`).join(", ")}`);
}
/** The pitch of lines, from the tops of those after each other on a page */
const pitchOf = (parts: readonly Line[], size: number): string => {
// Text in two scripts on one line can be two lines of pdftotext's, and not one after the other
const sorted = [...parts].sort((a, b) => a.page - b.page || a.yMin - b.yMin);
const lines = sorted.filter((line, i) => i === 0 || line.page !== sorted[i - 1].page || Math.abs(line.yMin - sorted[i - 1].yMin) > 1);
const runs = lines.slice(1).flatMap((line, i) => (line.page === lines[i].page ? [line.yMin - lines[i].yMin] : []));
const pitch = runs.reduce((total, step) => total + step, 0) / runs.length;
return `pitch ${twips(pitch)} twips over ${runs.length} lines, ${((pitch / size) * 1000).toFixed(1)} thousandths of an em`;
};
console.log("\n== G: the height of lines");
for (const [name, lines] of probes(/^G\d/)) {
const size = /10\.5$/.test(name) ? 10.5 : /9$/.test(name) ? 9 : 12;
console.log(` ${name.padEnd(40)} ${pitchOf(lines, size)}`);
}
+233
View File
@@ -0,0 +1,233 @@
// cspell:disable
// More probes of how Word breaks and measures East Asian, Thai and right-to-left text, after word-unicode.ts, whose PDF
// from Word showed that Word keeps characters from starting or ending a line only in text with an East Asian language,
// that Korean breaks at spaces, and that lines of East Asian fonts are about 1.3 times as tall as the font's height.
// word-unicode2.read.ts reads pdftotext -bbox-layout's HTML of its PDF.
//
// S and E: every character of Word's lists for Japanese, Chinese and Korean, as docx/layout has them, at the start and at
// the end of a line, in each language and in English. In 6-point MS Mincho, in 2 columns 241 points wide, so 40
// ideographs fit on a line, and neither a 41st nor a sixth of one
// H: punctuation that can't start a line, in Japanese, with overflowPunct as Word has it, on and off
// A: the space between ideographs and Latin letters and numbers, in Japanese
// W: wordWrap off in paragraphs with and without ideographs, and a zero-width space between two long words
// T: Thai words without marks above or below their letters, whose text pdftotext reads, with no language, in Thai, and with
// zero-width spaces between them
// F: which font and size Hebrew and Latin text are in, in runs that are right to left and runs that aren't: Courier New for
// complex scripts, whose letters are all 0.6 em wide, and Calibri for the rest
// G: 20 lines of 12-point text in each font, for the height of its lines, and of ideographs in fonts without them
//
// Usage: npm run run-ts -- scripts/layout-probes/word-unicode2.ts, which writes build/word-probes/word-unicode2.docx
import * as fs from "fs";
import JSZip from "jszip";
import { Document, Packer, Paragraph, SectionType, TextRun } from "docx";
const IDEOGRAPH = "永";
const ideographs = (count: number): string => IDEOGRAPH.repeat(count);
/** Paragraph properties docx doesn't write, put in after the paragraph's style by its id */
const INJECTED: Readonly<Record<string, string>> = {
HangOff: '<w:overflowPunct w:val="0"/>',
HangOn: '<w:overflowPunct w:val="1"/>',
AutoSpaceOff: '<w:autoSpaceDE w:val="0"/><w:autoSpaceDN w:val="0"/>',
AutoSpaceOn: '<w:autoSpaceDE w:val="1"/><w:autoSpaceDN w:val="1"/>',
};
const codePoint = (character: string): string => `U+${character.codePointAt(0)!.toString(16).toUpperCase().padStart(4, "0")}`;
const label = (text: string, size = 14): Paragraph => new Paragraph({ keepNext: true, children: [new TextRun({ text, size })] });
type Options = { readonly language?: string; readonly style?: string; readonly size?: number };
const mincho = (text: string, { language, style, size = 24 }: Options = {}): Paragraph =>
new Paragraph({
...(style ? { style } : {}),
children: [new TextRun({ text, font: "MS Mincho", size, ...(language ? { language: { eastAsia: language } } : {}) })],
});
const START = [
..."!%),.:;?]}¢°’”‰′″℃、。々〉》」』】〕゛゜ゝゞ・ヽヾ!%),.:;?]}。」、・゙゚¢·ˇˉ―‖…›∶〃〗〞︶︺︾﹀﹄﹚﹜﹞"'`|~–—•‥‧",
..."﹏﹐﹑﹒﹔﹕﹖﹗︰︱︳︴︸︼﹂ぁぃぅぇぉっゃゅょゎァィゥェォッャュョヮヵヶーァィゥェォャュョッー〟〜゠〙〛‼⁉ゕゖ",
];
const END = [..."$([\\{£¥‘“〈《「『【〔$([{「£¥·〖〝﹙﹛﹝.‵︴\₩〘〚«‹¿¡#@"];
const LANGUAGES = ["ja-JP", "zh-CN", "zh-TW", "ko-KR", "en-US"];
// Thai words with no marks above or below their letters
const THAI_WORDS = ["เรา", "ไป", "หา", "ปลา", "ตาม", "ทาง", "นาน", "ภาษาไทย", "ราคา", "แมว", "หมา", "ขาว", "ดาว", "เขา", "มา", "ทะเล"];
const thai = (count: number, separator: string): string =>
Array.from({ length: count }, (_, i) => THAI_WORDS[(i * 7 + Math.floor(i / 16)) % THAI_WORDS.length]).join(separator);
const PROSE = "the survey of the coast was made in the summer by boat and on foot from the lighthouse to the river mouth".split(" ");
const prose = (words: number): string => Array.from({ length: words }, (_, i) => PROSE[(i * 5) % PROSE.length]).join(" ");
const LONG_WORD = "abcdefghijklmnopqrstuvwxyzab";
const HEBREW_LETTERS = "אבגדהוזחטיכלמנסעפצקרשת".repeat(2);
const SLOTS = { ascii: "Calibri", hAnsi: "Calibri", eastAsia: "Calibri", cs: "Courier New" };
const MIXED_FONT = { ascii: "Calibri", hAnsi: "Calibri", eastAsia: "MS Mincho", cs: "Calibri" };
/** Twenty one-line paragraphs, for the height of a line */
const pitch = (name: string, text: string, run: ConstructorParameters<typeof TextRun>[0] & object, lines = 20): readonly Paragraph[] =>
Array.from({ length: lines }, (_, i) => new Paragraph({ children: [new TextRun({ ...run, text: `${name} ${i + 1} ${text}` })] }));
const HEIGHT_FONTS: readonly (readonly [string, string])[] = [
["MS Mincho", ideographs(8)],
["MS Gothic", ideographs(8)],
["MS PMincho", ideographs(8)],
["MS PGothic", ideographs(8)],
["Yu Mincho", ideographs(8)],
["Yu Gothic", ideographs(8)],
["Meiryo", ideographs(8)],
["SimSun", ideographs(8)],
["NSimSun", ideographs(8)],
["SimHei", ideographs(8)],
["Microsoft YaHei", ideographs(8)],
["DengXian", ideographs(8)],
["KaiTi", ideographs(8)],
["FangSong", ideographs(8)],
["PMingLiU", ideographs(8)],
["MingLiU", ideographs(8)],
["Microsoft JhengHei", ideographs(8)],
["Malgun Gothic", "가나다라마바사"],
["Batang", "가나다라마바사"],
["Gulim", "가나다라마바사"],
["Dotum", "가나다라마바사"],
];
const doc = new Document({
styles: {
default: { document: { run: { font: "Calibri", size: 22 }, paragraph: { spacing: { before: 0, after: 0, line: 240 } } } },
paragraphStyles: Object.keys(INJECTED).map((id) => ({ id, name: id, basedOn: "Normal" })),
},
sections: [
{
properties: {
page: { size: { width: 12240, height: 15840 }, margin: { top: 1080, bottom: 1080, left: 940, right: 940 } },
column: { count: 2, space: 720 },
},
children: LANGUAGES.flatMap((language) => [
...START.flatMap((character) => [
label(`S ${language} ${codePoint(character)}`, 8),
mincho(`${ideographs(40)}${character}${ideographs(3)}`, { language, size: 12 }),
]),
...END.flatMap((character) => [
label(`E ${language} ${codePoint(character)}`, 8),
mincho(`${ideographs(39)}${character}${ideographs(4)}`, { language, size: 12 }),
]),
]),
},
{
properties: {
type: SectionType.NEXT_PAGE,
page: { size: { width: 12240, height: 15840 }, margin: { top: 1080, bottom: 1080, left: 1270, right: 1270 } },
},
children: [
// H: 40 ideographs of 12-point MS Mincho, then the character, in Japanese, with overflowPunct as Word has it,
// on and off
...(["", "HangOn", "HangOff"] as const).flatMap((style) =>
[..."、。,.)」!?"].flatMap((character, i) => [
label(`H${i + 1} ${style || "default"} ${codePoint(character)}`),
mincho(`${ideographs(40)}${character}${ideographs(3)}`, { language: "ja-JP", ...(style ? { style } : {}) }),
]),
),
// A: ideographs, then Calibri letters and numbers, in Japanese, with autoSpaceDE and autoSpaceDN as Word has
// them, off and on
...(["", "AutoSpaceOff", "AutoSpaceOn"] as const).flatMap((style, i) => [
label(`A${i + 1} ${style || "default"}`),
new Paragraph({
...(style ? { style } : {}),
children: [
new TextRun({
text: `${ideographs(5)}abc${ideographs(5)}123${ideographs(5)}`,
font: MIXED_FONT,
size: 24,
language: { eastAsia: "ja-JP" },
}),
],
}),
]),
// W1: wordWrap off, a Calibri word after ideographs. W2: MS Mincho Latin words. W3: Calibri words after one
// ideograph. W4: Calibri words in Japanese. W5: a zero-width space between two words too long for the line
label("W1 wordWrap off, Calibri after ideographs"),
new Paragraph({
wordWrap: true,
children: [new TextRun({ text: `${ideographs(35)} internationalization${ideographs(2)}`, font: MIXED_FONT, size: 24 })],
}),
label("W2 wordWrap off, MS Mincho Latin"),
new Paragraph({ wordWrap: true, children: [new TextRun({ text: prose(80), font: "MS Mincho", size: 24 })] }),
label("W3 wordWrap off, an ideograph then Calibri"),
new Paragraph({
wordWrap: true,
children: [new TextRun({ text: `${IDEOGRAPH} ${prose(80)}`, font: MIXED_FONT, size: 24 })],
}),
label("W4 wordWrap off, Calibri in Japanese"),
new Paragraph({
wordWrap: true,
children: [new TextRun({ text: prose(80), size: 24, language: { eastAsia: "ja-JP" } })],
}),
label("W5 zero-width space"),
new Paragraph({ children: [new TextRun({ text: `${prose(9)} ${LONG_WORD}\u200B${LONG_WORD}${LONG_WORD}`, size: 24 })] }),
// T: Thai words in Tahoma, without spaces, in Thai, and with zero-width spaces between them
label("T1 Thai"),
new Paragraph({ children: [new TextRun({ text: thai(150, ""), font: "Tahoma", size: 24 })] }),
label("T2 Thai in Thai"),
new Paragraph({
children: [new TextRun({ text: thai(150, ""), font: "Tahoma", size: 24, language: { bidirectional: "th-TH" } })],
}),
label("T3 Thai, zero-width spaces"),
new Paragraph({ children: [new TextRun({ text: thai(150, "\u200B"), font: "Tahoma", size: 24 })] }),
// F1 and F2: Hebrew letters in a run that isn't right to left, and in one that is. F3: Latin letters in a
// right-to-left run. 11 points, and 22 for complex scripts
label("F1 Hebrew"),
new Paragraph({ children: [new TextRun({ text: HEBREW_LETTERS, font: SLOTS, size: 22, sizeComplexScript: 44 })] }),
label("F2 Hebrew, rtl"),
new Paragraph({
children: [new TextRun({ text: HEBREW_LETTERS, font: SLOTS, size: 22, sizeComplexScript: 44, rightToLeft: true })],
}),
label("F3 Latin, rtl"),
new Paragraph({
children: [
new TextRun({
text: "abcdefghijklmnopqrstuvwxyz",
font: SLOTS,
size: 22,
sizeComplexScript: 44,
rightToLeft: true,
}),
],
}),
// G1 to G21: 12-point text in each font. G22 and G23: MS Mincho at 10.5 and 9 points. G24 to G28: ideographs in
// Calibri, which has none, with no language, in English, Japanese, Chinese and Korean. G29 to G31:
// ideographs, Thai and Hebrew in the theme's font for body text
...HEIGHT_FONTS.flatMap(([font, text], i) => [label(`G${i + 1} ${font}`), ...pitch(`G${i + 1}`, text, { font, size: 24 })]),
label("G22 MS Mincho 10.5"),
...pitch("G22", ideographs(8), { font: "MS Mincho", size: 21 }),
label("G23 MS Mincho 9"),
...pitch("G23", ideographs(8), { font: "MS Mincho", size: 18 }),
...([undefined, "en-US", "ja-JP", "zh-CN", "ko-KR"] as const).flatMap((language, i) => [
label(`G${24 + i} Calibri ideographs ${language ?? "no language"}`),
...pitch(`G${24 + i}`, ideographs(8), { size: 24, ...(language ? { language: { eastAsia: language } } : {}) }),
]),
...[ideographs(8), "ภาษาไทยเป็นภาษา", "זהו משפט לדוגמה"].flatMap((text, i) => [
label(`G${29 + i} theme body`),
...pitch(`G${29 + i}`, text, { font: { theme: "body" }, size: 24 }),
]),
label("end"),
],
},
],
});
Packer.toBuffer(doc).then(async (buffer) => {
const zip = await JSZip.loadAsync(buffer);
const xml = await zip.file("word/document.xml")!.async("string");
const injected = Object.entries(INJECTED).reduce(
(all, [style, properties]) => all.split(`<w:pStyle w:val="${style}"/>`).join(`<w:pStyle w:val="${style}"/>${properties}`),
xml,
);
zip.file("word/document.xml", injected);
fs.mkdirSync("build/word-probes", { recursive: true });
fs.writeFileSync("build/word-probes/word-unicode2.docx", await zip.generateAsync({ type: "nodebuffer" }));
});
+20
View File
@@ -141,6 +141,26 @@ describe("paginate", () => {
expect(pagesOf(document([twice, paragraph("b", 1)]))).to.deep.equal({ a: "1", b: "2" });
});
it("should break lines by the document's own lists of the characters that can't start a line", () => {
// cspell:disable
const japanese = (text: string): LayoutItem => ({ type: "text", text, font: {}, language: "ja-JP" });
// Each document's own paragraphs, as their lines are kept with them
const blocks = (): readonly Block[] => [
paragraph("before", 6),
{
type: "paragraph",
items: [japanese("永".repeat(7)), { type: "marker", name: "eighth" }, japanese("永、")],
format: { widowControl: false },
tabStops: [],
markFont: {},
},
];
// cspell:enable
// The full stop can't start a line, so the character before it starts the next line, on the next page
expect(pagesOf(document(blocks()))).to.deep.include({ eighth: "2" });
expect(pagesOf(document(blocks(), { breakRules: { lists: { japanese: { noLineStart: "" } } } }))).to.deep.include({ eighth: "1" });
});
describe("widow and orphan control", () => {
it("should move a paragraph's first line to the next page rather than leave it alone at the bottom", () => {
expect(pagesOf(document([paragraph("a", 6), paragraph("b", 4)]))).to.deep.equal({ a: "1", b: "2" });
+3
View File
@@ -242,6 +242,7 @@ export const paginate = (
footnoteSeparator,
footnoteContinuationSeparator,
endnotes,
breakRules,
} = content;
// The body, and then its endnotes, which Word lays out after it
const blocks = [...content.blocks, ...endnotes.map((block) => ({ block, section: sections.length - 1 }))];
@@ -279,6 +280,7 @@ export const paginate = (
defaultTabStop,
markFont: paragraph.markFont,
measurer,
breakRules,
});
if (paragraph.items.some(({ type }) => type === "pageReference" || type === "pageCount")) {
return layOut();
@@ -332,6 +334,7 @@ export const paginate = (
tabStops: block.tabStops,
defaultTabStop,
measurer,
breakRules,
});
return { min: Math.max(widths.min, min), max: Math.max(widths.max, max) };
},
+49
View File
@@ -73,6 +73,21 @@ describe("readDocument", () => {
expect(paragraphOf(content).style).to.equal("Heading1");
});
it("should read East Asian text in its run's East Asian font, with its language, and right-to-left runs in the font of complex scripts", () => {
const fonts = { "w:rFonts": { _attr: { "w:ascii": "Arial", "w:eastAsia": "SimSun", "w:cs": "Times New Roman" } } };
const content = readBody([
p(
r(rPr(fonts, { "w:lang": { _attr: { "w:eastAsia": "zh-CN" } } }), t("a永")),
r(rPr(fonts, { "w:rtl": {} }, value("w:szCs", 28)), t("b")),
),
]);
expect(itemsOf(content)).to.deep.equal([
{ type: "text", text: "a", font: { font: "Arial" }, language: "zh-CN", eastAsian: true },
{ type: "text", text: "永", font: { font: "SimSun" }, language: "zh-CN", eastAsian: true },
{ type: "text", text: "b", font: { font: "Times New Roman", size: 14 }, eastAsian: true },
]);
});
it("should read an empty paragraph", () => {
expect(paragraphOf(readBody([{ "w:p": {} }]))).to.deep.include({ items: [], style: "Normal" });
});
@@ -1087,6 +1102,40 @@ describe("readDocument", () => {
it("should mark a document that hyphenates its words as unsupported", () => {
expect(readBody([], { hyphenation: { autoHyphenation: true } }).unsupported).to.equal("hyphenation");
});
/** Reads a document whose settings are these elements, which docx doesn't write */
const readSettings = (...settings: readonly object[]): DocumentContent => {
const file = new File({ sections: [] });
const withSettings = Object.create(file, { Settings: { value: { prepForXml: () => ({ "w:settings": settings }) } } }) as File;
return readDocument({ "w:body": [] } as IXmlableObject, contextOf(withSettings));
};
it("should read the document's own lists of the characters that can't start or end a line, for their languages", () => {
const kinsoku = (name: string, lang: string, val?: string): object => ({
[name]: { _attr: { "w:lang": lang, ...(val === undefined ? {} : { "w:val": val }) } },
});
// cspell:disable
const content = readSettings(
kinsoku("w:noLineBreaksBefore", "ja-JP", "、。"),
kinsoku("w:noLineBreaksAfter", "ja-JP", "「"),
kinsoku("w:noLineBreaksAfter", "zh-TW"),
kinsoku("w:noLineBreaksBefore", "en-US", "!"),
);
expect(content.breakRules).to.deep.equal({
lists: { japanese: { noLineStart: "、。", noLineEnd: "「" }, traditionalChinese: { noLineEnd: "" } },
});
// cspell:enable
expect(content.unsupported).to.equal(undefined);
expect(readBody([]).breakRules).to.equal(undefined);
});
it("should mark a document with Word's strict rules for the first and last characters of lines, or that compresses punctuation, as unsupported", () => {
expect(readSettings({ "w:strictFirstAndLastChars": {} }).unsupported).to.equal(
"the strict rules for the characters that can't start a line",
);
expect(readSettings(value("w:characterSpacingControl", "compressPunctuation")).unsupported).to.equal("punctuation compressed");
expect(readSettings(value("w:characterSpacingControl", "doNotCompress")).unsupported).to.equal(undefined);
});
});
it("should read headings as they are written, with their bookmarks from the table of contents", () => {
+44 -6
View File
@@ -11,6 +11,8 @@ import type { IContext, IXmlableObject } from "docx";
import {
type InlineItem,
type KinsokuList,
type LineBreakRules,
type ParagraphFormat,
READING_CONTEXT,
type RunFormat,
@@ -26,8 +28,10 @@ import {
find,
fontOf,
getTextStyles,
isEastAsianRun,
isObject,
isOff,
kinsokuLanguageOf,
numberOf,
onOff,
readCellMargins,
@@ -189,6 +193,8 @@ export type DocumentContent = {
readonly footnoteContinuationSeparator: readonly Block[];
/** The endnotes the body refers to, in order, after their separator: they follow the body, as Word lays them out */
readonly endnotes: readonly Block[];
/** Where its lines break: the characters that can't start or end a line, where it gives its own */
readonly breakRules?: LineBreakRules;
/** Why none of it can be laid out, when a setting of the whole document changes its lines in ways not yet followed */
readonly unsupported?: string;
};
@@ -432,10 +438,14 @@ const readRun = (element: XmlObject, paragraphRun: RunFormat, reader: Reader): r
.filter((part) => typeof part === "string")
.join(""),
format,
).map((span) => {
const { text, ...spanFont } = span;
return { type: "text" as const, text, font: spanFont };
});
).map(({ text, ...spanFont }) => ({
type: "text" as const,
text,
font: spanFont,
// Where its lines break depends on its language, and whether its run is East Asian
...(format.eastAsianLanguage === undefined ? {} : { language: format.eastAsianLanguage }),
...(isEastAsianRun(format) ? { eastAsian: true } : {}),
}));
case "w:tab":
case "w:ptab":
return format.hidden ? [] : [{ type: "tab", font }];
@@ -968,18 +978,46 @@ const readNumbering = (context: IContext, styles: TextStyles): ReadonlyMap<strin
return new Map([...byNumber, ...placeholders]);
};
/**
* The document's own lists of the characters that can't start a line (`w:noLineBreaksBefore`) and can't end one
* (`w:noLineBreaksAfter`), which take the place of Word's for their language.
*/
const readKinsokuLists = (settings: readonly XmlObject[]): NonNullable<LineBreakRules["lists"]> =>
settings.reduce<NonNullable<LineBreakRules["lists"]>>((lists, child) => {
const name = nameOf(child);
const attributes = attributesOf(child[name]);
const language = kinsokuLanguageOf(stringOf(attributes["w:lang"]));
if ((name !== "w:noLineBreaksBefore" && name !== "w:noLineBreaksAfter") || language === undefined) {
return lists;
}
const list: KinsokuList = { [name === "w:noLineBreaksBefore" ? "noLineStart" : "noLineEnd"]: String(attributes["w:val"] ?? "") };
return { ...lists, [language]: { ...lists[language], ...list } };
}, {});
/**
* Reads the parts of the document's settings (`w:settings`) that change how it is laid out.
*/
const readSettings = (
context: IContext,
): Pick<DocumentContent, "defaultTabStop" | "evenAndOddHeaders" | "addsParagraphSpacing" | "unsupported"> => {
): Pick<DocumentContent, "defaultTabStop" | "evenAndOddHeaders" | "addsParagraphSpacing" | "breakRules" | "unsupported"> => {
const settings = childrenOf((context.file.Settings.prepForXml(READING_CONTEXT) as XmlObject)["w:settings"]);
const lists = readKinsokuLists(settings);
const spacingControl = valueOf(settings, "w:characterSpacingControl");
// Word's strict rules, and its compression of punctuation, aren't known yet
const unsupported =
onOff(settings, "w:autoHyphenation") === true
? "hyphenation"
: onOff(settings, "w:strictFirstAndLastChars") === true
? "the strict rules for the characters that can't start a line"
: spacingControl !== undefined && spacingControl !== "doNotCompress"
? "punctuation compressed"
: undefined;
return {
defaultTabStop: twips(attributesOf(find(settings, "w:defaultTabStop"))["w:val"]) ?? 36,
evenAndOddHeaders: onOff(settings, "w:evenAndOddHeaders") === true,
addsParagraphSpacing: onOff(childrenOf(find(settings, "w:compat")), "w:doNotUseHTMLParagraphAutoSpacing") === true,
...(onOff(settings, "w:autoHyphenation") === true ? { unsupported: "hyphenation" } : {}),
...(Object.keys(lists).length > 0 ? { breakRules: { lists } } : {}),
...(unsupported ? { unsupported } : {}),
};
};
+1
View File
@@ -1,3 +1,4 @@
export * from "./text-width";
export * from "./text-styles";
export * from "./line-breaking";
export * from "./line-break-rules";
+96
View File
@@ -0,0 +1,96 @@
import { describe, expect, it } from "vitest";
import { extendsCharacter, findLineBreaks, isEastAsian, kinsokuLanguageOf } from "./line-break-rules";
// cspell:disable
/** Where a line can break in text in one run */
const breaksOf = (text: string, language?: string, rules = {}): readonly number[] =>
[...findLineBreaks([{ text, ...(language ? { language } : {}) }], rules)].sort((a, b) => a - b);
describe("findLineBreaks", () => {
it("should break Latin text only after hyphens and dashes, but not before a number, as Word does", () => {
expect(breaksOf("abcdef")).to.deep.equal([]);
expect(breaksOf("ab-cd")).to.deep.equal([3]);
expect(breaksOf("ab-12")).to.deep.equal([]);
expect(breaksOf("ab—cd–ef‐gh")).to.deep.equal([3, 6, 9]);
// Word doesn't break after a slash
expect(breaksOf("ab/cd")).to.deep.equal([]);
});
it("should break after a zero-width space, and not around no-break spaces and the word joiner", () => {
expect(breaksOf("ab\u200bcd")).to.deep.equal([3]);
expect(breaksOf("永\u00a0永\u2060永")).to.deep.equal([]);
});
it("should break between Chinese and Japanese characters, and between them and Latin words", () => {
expect(breaksOf("永永かな")).to.deep.equal([1, 2, 3]);
expect(breaksOf("永ab永")).to.deep.equal([1, 3]);
// Full-width letters and numbers break as ideographs do
expect(breaksOf("12")).to.deep.equal([1]);
});
it("should keep a character and the marks on it together", () => {
expect(breaksOf("か\u3099か")).to.deep.equal([2]);
expect(breaksOf("永\u200d永")).to.deep.equal([]);
// Variation selectors, skin tones and tags go with the character before them
expect(breaksOf("永\ufe0f永")).to.deep.equal([2]);
expect(breaksOf("永\u{1f3fb}永")).to.deep.equal([2]);
expect(breaksOf("永\u{e0020}永")).to.deep.equal([2]);
expect(extendsCharacter("\u0301")).to.equal(true);
expect(extendsCharacter("a")).to.equal(false);
});
it("should break Korean, Thai and the other scripts only at their spaces, as Word does", () => {
expect(breaksOf("가나다라")).to.deep.equal([]);
expect(breaksOf("ภาษาไทยเป็นภาษา")).to.deep.equal([]);
expect(breaksOf("ภาษา\u200bไทย")).to.deep.equal([5]);
// An ideograph next to Korean breaks around it
expect(breaksOf("가永나")).to.deep.equal([1, 2]);
expect(isEastAsian("가")).to.equal(true);
});
it("should keep Word's characters from starting or ending a line only in Japanese and Chinese", () => {
// 、 can't start a line, and 「 can't end one
expect(breaksOf("永、永「永", "ja-JP")).to.deep.equal([2, 3]);
expect(breaksOf("永、永「永")).to.deep.equal([1, 2, 3, 4]);
expect(breaksOf("永、永「永", "en-US")).to.deep.equal([1, 2, 3, 4]);
expect(breaksOf("永、永「永", "ko-KR")).to.deep.equal([1, 2, 3, 4]);
expect(breaksOf("永、永「永", "zh-CN")).to.deep.equal([2, 3]);
// Each language has its own list: ~ can start a line in Traditional Chinese, not in Simplified, and 々 only in
// Chinese
expect(breaksOf("永~永", "zh-CN")).to.deep.equal([2]);
expect(breaksOf("永~永", "zh-TW")).to.deep.equal([1, 2]);
expect(breaksOf("永々永", "ja-JP")).to.deep.equal([2]);
expect(breaksOf("永々永", "zh-HK")).to.deep.equal([1, 2]);
// And not with kinsoku off
expect(breaksOf("永、永「永", "ja-JP", { kinsoku: false })).to.deep.equal([1, 2, 3, 4]);
});
it("should take the document's own lists in place of Word's", () => {
// The document's list of characters that can't start a line, with Word's of those that can't end one
const lists = { japanese: { noLineStart: "永" } };
expect(breaksOf("永、永「永", "ja-JP", { lists })).to.deep.equal([1, 3]);
expect(breaksOf("永、永「永", "zh-CN", { lists })).to.deep.equal([2, 3]);
});
it("should break the words of East Asian runs anywhere with word wrap off, keeping to the characters that can't start a line", () => {
expect([...findLineBreaks([{ text: "abc", eastAsian: true }], { wordWrap: false })]).to.deep.equal([1, 2]);
expect([...findLineBreaks([{ text: "abc" }], { wordWrap: false })]).to.deep.equal([]);
expect([...findLineBreaks([{ text: "ab", eastAsian: true }, { text: "cd" }], { wordWrap: false })]).to.deep.equal([1]);
expect([...findLineBreaks([{ text: "ab,", eastAsian: true, language: "ja-JP" }], { wordWrap: false })]).to.deep.equal([1]);
expect([...findLineBreaks([{ text: "abc", eastAsian: true }])]).to.deep.equal([]);
});
});
describe("kinsokuLanguageOf", () => {
it("should find Word's list for a language by its tag", () => {
expect(kinsokuLanguageOf("ja-JP")).to.equal("japanese");
expect(kinsokuLanguageOf("zh-CN")).to.equal("simplifiedChinese");
expect(kinsokuLanguageOf("zh-Hant")).to.equal("traditionalChinese");
expect(kinsokuLanguageOf("ZH-MO")).to.equal("traditionalChinese");
expect(kinsokuLanguageOf("ko-KR")).to.equal("korean");
expect(kinsokuLanguageOf("en-US")).to.equal(undefined);
expect(kinsokuLanguageOf(undefined)).to.equal(undefined);
});
});
+197
View File
@@ -0,0 +1,197 @@
/**
* Where a line of text can break, as Word breaks it: after spaces and zero-width spaces, between Chinese and Japanese
* characters, and after hyphens and dashes. Korean, Thai and the other scripts break at their spaces, as Latin words do.
* In text in Japanese or Chinese, Word's East Asian rules keep some characters, such as closing brackets and the
* ideographic full stop, from starting a line, and others, such as opening brackets, from ending one (kinsoku). With word
* wrap off, the words of East Asian runs break anywhere.
*
* The rules are adapted from Pretext's (https://github.com/chenglou/pretext, `src/analysis.ts`), which break text as
* browsers do: its ranges of East Asian characters, the characters that join the words around them, keeping a character
* and the marks on it together, and keeping the characters that can't start a line with the one before them. Where Word
* differs from browsers, they follow Word, as its PDFs of scripts/layout-probes/word-unicode.ts and word-unicode2.ts
* showed: the characters that can't start or end a line are Word's lists, or the document's, and only in Japanese and
* Chinese; Korean breaks at its spaces; and Thai, Lao, Khmer and Myanmar break only at spaces and zero-width spaces, rather
* than between their words as browsers break them with a dictionary.
*
* Pretext's license:
*
* MIT License
*
* Copyright (c) 2026 Pretext contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @module
*/
/**
* The characters that can't start a line, and those that can't end one, for text in a language.
*/
export type KinsokuList = {
/** The characters that can't start a line (`w:noLineBreaksBefore`) */
readonly noLineStart?: string;
/** The characters that can't end a line (`w:noLineBreaksAfter`) */
readonly noLineEnd?: string;
};
/** The languages Word has lists of the characters that can't start or end a line for */
export type KinsokuLanguage = "japanese" | "simplifiedChinese" | "traditionalChinese" | "korean";
/**
* How a paragraph's lines break.
*/
export type LineBreakRules = {
/** Whether Word's East Asian rules keep characters from starting or ending a line (`w:kinsoku`). Default is on */
readonly kinsoku?: boolean;
/** Whether lines break between words (`w:wordWrap`), or, when off, anywhere in the words of East Asian runs. Default is on */
readonly wordWrap?: boolean;
/** The document's own lists, which take the place of Word's for their language */
readonly lists?: Partial<Record<KinsokuLanguage, KinsokuList>>;
};
/** A piece of text, with what of its run changes where its lines break */
export type LanguagePiece = {
readonly text: string;
/** The East Asian language of its run (`w:lang w:eastAsia`), such as `"ja-JP"` */
readonly language?: string;
/** Whether its run is East Asian, by its East Asian font or language, so its words break anywhere with word wrap off */
readonly eastAsian?: boolean;
};
/* cspell:disable */
// Word's lists, as Word's PDF of scripts/layout-probes/word-unicode2.ts showed them. Word has none for Korean
const WORD_LISTS: Readonly<Record<KinsokuLanguage, Required<KinsokuList>>> = {
japanese: {
noLineStart: "!%),.:;?]}¢°’”‰′″℃、。々〉》」』】〕゛゜ゝゞ・ヽヾ!%),.:;?]}。」、・゙゚¢",
noLineEnd: "$([\\{£¥‘“〈《「『【〔$([{「£¥",
},
simplifiedChinese: {
noLineStart: "!%),.:;?]}¢°·ˇˉ―‖’”…‰′″›℃∶、。〃〉》」』】〕〗〞︶︺︾﹀﹄﹚﹜﹞!"%'),.:;?]`|}~¢",
noLineEnd: "$([{£¥·‘“〈《「『【〔〖〝﹙﹛﹝$(.[{£¥",
},
traditionalChinese: {
noLineStart: "!),.:;?]}¢·’”•‥…‧′﹏﹐﹑﹒﹔﹕﹖﹗﹚﹜﹞!),.:;?]}|、。〉》」』】〕〞︰︱︳︴︶︸︺︼︾﹀﹂﹄、",
noLineEnd: "([{£¥‘“‵〈《「『【〔〝﹙﹛﹝({",
},
korean: { noLineStart: "", noLineEnd: "" },
};
/* cspell:enable */
// Chinese, Japanese and Korean characters: Pretext's ranges, with the compatibility forms and enclosed letters and numbers
// of CJK, and the scripts of Han, kana and Hangul outside them
const EAST_ASIAN =
/[\u1100-\u11ff\u2e80-\u2fff\u3000-\u30ff\u3130-\u318f\u31c0-\u33ff\u3400-\u4dbf\u4e00-\u9fff\ua960-\ua97f\uac00-\ud7ff\uf900-\ufaff\ufe30-\ufe4f\uff00-\uffef\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
// Korean, whose words Word keeps together, breaking lines at the spaces between them, as it does Latin words
const HANGUL = /\p{Script=Hangul}/u;
// Dashes a line can break after, as after a hyphen
const DASHES = new Set(["-", "\u2010", "\u2013", "\u2014"]);
// What joins the characters on either side of it: no-break spaces and the word joiner
const GLUE = new Set(["\u00a0", "\u202f", "\u2007", "\u2060", "\ufeff"]);
// What belongs to the character before it: marks, the zero-width joiner, variation selectors, skin tones and tags
const isExtender = (character: string): boolean => {
const code = character.codePointAt(0)!;
return (
/\p{M}/u.test(character) ||
code === 0x200d ||
(code >= 0xfe00 && code <= 0xfe0f) ||
(code >= 0x1f3fb && code <= 0x1f3ff) ||
(code >= 0xe0020 && code <= 0xe007f)
);
};
const ZERO_WIDTH_SPACE = "\u200b";
/** Whether a character is Chinese, Japanese or Korean, or East Asian punctuation, which Word draws in a run's East Asian font */
export const isEastAsian = (character: string): boolean => EAST_ASIAN.test(character);
/** Whether a line can break before and after a character: Chinese and Japanese characters, but not Korean */
const breaksAround = (character: string): boolean => EAST_ASIAN.test(character) && !HANGUL.test(character);
/** Whether a character belongs to the one before it, so a line never breaks between them */
export const extendsCharacter = isExtender;
/** Whether a character joins the one after it to the one before it, as the zero-width joiner joins emoji */
export const joinsNext = (character: string): boolean => character === "\u200d";
/**
* The list of Word's for a language, by its tag, such as `"zh-TW"`. Text in another language, or with none, has none: Word
* lets any character start or end its lines.
*/
export const kinsokuLanguageOf = (language: string | undefined): KinsokuLanguage | undefined => {
const tag = (language ?? "").toLowerCase();
if (tag.startsWith("zh")) {
return /^zh-(tw|hk|mo|hant)/.test(tag) ? "traditionalChinese" : "simplifiedChinese";
}
if (tag.startsWith("ja")) {
return "japanese";
}
return tag.startsWith("ko") ? "korean" : undefined;
};
type Kinsoku = { readonly noLineStart: ReadonlySet<string>; readonly noLineEnd: ReadonlySet<string> };
const NO_KINSOKU: Kinsoku = { noLineStart: new Set(), noLineEnd: new Set() };
const listOf = (language: KinsokuLanguage, { lists = {} }: LineBreakRules): Kinsoku => {
const { noLineStart = WORD_LISTS[language].noLineStart, noLineEnd = WORD_LISTS[language].noLineEnd } = lists[language] ?? {};
return { noLineStart: new Set(noLineStart), noLineEnd: new Set(noLineEnd) };
};
/**
* Where a line can break inside text that has no spaces in it: before which of its characters, by their index, counted
* in characters rather than UTF-16 code units. A line can always break after spaces, which aren't in it.
*
* @param pieces - The text's pieces, with the language of their runs
*/
export const findLineBreaks = (pieces: readonly LanguagePiece[], rules: LineBreakRules = {}): ReadonlySet<number> => {
const anywhere = rules.wordWrap === false && pieces.some(({ eastAsian }) => eastAsian);
const text = pieces.map((piece) => piece.text).join("");
if (!anywhere && ![...text].some((character) => character.codePointAt(0)! > 0x2ff) && !text.includes("-")) {
// Latin text breaks only at its spaces and hyphens
return new Set();
}
const characters = pieces.flatMap(({ text: piece }) => [...piece]);
const runs = pieces.flatMap(({ text: piece, language, eastAsian }) =>
[...piece].map(() => ({ language: kinsokuLanguageOf(language), anywhere: rules.wordWrap === false && eastAsian === true })),
);
const kinsoku = rules.kinsoku ?? true;
const lists = new Map<KinsokuLanguage | undefined, Kinsoku>([[undefined, NO_KINSOKU]]);
const listAt = (index: number): Kinsoku => {
const { language } = runs[index];
if (!lists.has(language)) {
// eslint-disable-next-line functional/immutable-data
lists.set(language, listOf(language!, rules));
}
return lists.get(language)!;
};
const breaks = new Set<number>();
for (let index = 1; index < characters.length; index++) {
const before = characters[index - 1];
const after = characters[index];
if (isExtender(after) || joinsNext(before) || GLUE.has(before) || GLUE.has(after)) {
continue;
}
const opportunity =
before === ZERO_WIDTH_SPACE ||
(DASHES.has(before) && !/[\d-]/.test(after)) ||
breaksAround(before) ||
breaksAround(after) ||
(runs[index - 1].anywhere && runs[index].anywhere);
if (opportunity && !(kinsoku && (listAt(index).noLineStart.has(after) || listAt(index - 1).noLineEnd.has(before)))) {
// eslint-disable-next-line functional/immutable-data
breaks.add(index);
}
}
return breaks;
};
+65 -5
View File
@@ -1,6 +1,13 @@
import { describe, expect, it } from "vitest";
import { DEFAULT_MEASURER, type InlineItem, type TextMeasurer, layoutLines, measureContentWidths } from "./line-breaking";
import {
DEFAULT_MEASURER,
type InlineItem,
type LineLayoutOptions,
type TextMeasurer,
layoutLines,
measureContentWidths,
} from "./line-breaking";
import { measureLineHeight, measureTextWidth } from "./text-width";
// Every character is 10 points wide, and a line is as tall as its font's size
@@ -161,16 +168,57 @@ describe("layoutLines", () => {
expect(heightsOf([text("aaa "), text("bbb-", 20), text("ccc")])).to.deep.equal([20, 10]);
});
it("should break between Chinese and Japanese characters, but not before closing punctuation", () => {
it("should break between Chinese and Japanese characters", () => {
// cspell:disable
expect(heightsOf([text("漢字漢字漢字漢字漢字漢字")])).to.deep.equal([10, 10]);
// The full stop stays with the character before it, which moves to the next line with it
expect(heightsOf([text("漢字漢字漢字漢字漢字。")])).to.deep.equal([10, 10]);
expect(layoutLines([text("漢字漢字漢字漢字漢字。")], { width: 100, measurer: MEASURER })).to.have.length(2);
expect(heightsOf([text("漢字"), text("かな")])).to.deep.equal([10]);
// cspell:enable
});
describe("in Japanese and Chinese", () => {
// cspell:disable
/** The lines of ten ideographs and a full stop, with a bookmark before the tenth, and the line the bookmark is on */
const markedLine = (language?: string, options: Partial<LineLayoutOptions> = {}): number => {
const lines = layoutLines(
[
{ type: "text", text: "永".repeat(9), font: {}, ...(language ? { language } : {}) },
{ type: "marker", name: "tenth" },
{ type: "text", text: "永。", font: {}, ...(language ? { language } : {}) },
],
{ width: 100, measurer: MEASURER, ...options },
);
return lines.findIndex(({ markers }) => markers.includes("tenth"));
};
it("should move the character before one that can't start a line to the next line with it, as Word does", () => {
expect(markedLine("ja-JP")).to.equal(1);
expect(markedLine("zh-TW")).to.equal(1);
});
it("should let any character start a line in text with no East Asian language, or with kinsoku off, as Word does", () => {
expect(markedLine()).to.equal(0);
expect(markedLine("ko-KR")).to.equal(0);
expect(markedLine("ja-JP", { format: { kinsoku: false } })).to.equal(0);
expect(markedLine("ja-JP", { format: { kinsoku: false }, breakRules: { kinsoku: true } })).to.equal(0);
expect(markedLine("ja-JP", { breakRules: { kinsoku: false } })).to.equal(0);
});
it("should take the document's list of the characters that can't start a line", () => {
expect(markedLine("ja-JP", { breakRules: { lists: { japanese: { noLineStart: "" } } } })).to.equal(0);
});
// cspell:enable
});
it("should break the words of East Asian runs anywhere with word wrap off", () => {
const latin: InlineItem = { type: "text", text: "aaaaaa bbbbbb cccccc", font: {}, eastAsian: true };
const linesOf = (item: InlineItem, format = {}): number => layoutLines([item], { width: 100, measurer: MEASURER, format }).length;
// Filled to the end of each line: "aaaaaa bbb" and "bbb cccccc"
expect(linesOf(latin, { wordWrap: false })).to.equal(2);
// Broken between its words with word wrap on, and in a run that isn't East Asian
expect(linesOf(latin)).to.equal(3);
expect(linesOf({ ...latin, eastAsian: false }, { wordWrap: false })).to.equal(3);
});
it("should break a word wider than a line across as many lines as it needs", () => {
expect(heightsOf([text("a".repeat(25))])).to.deep.equal([10, 10, 10]);
expect(heightsOf([text("bb "), text("a".repeat(20), 12)])).to.deep.equal([10, 12, 12]);
@@ -197,6 +245,18 @@ describe("layoutLines", () => {
expect(layoutLines(tabbed, { width: 100, measurer: MEASURER })).to.have.length(2);
});
it("should break a word wider than a line after the last character that fits on each line, as Word does", () => {
// Each letter is 30 points, so 3 fit on a line of 100, and 10 take 4 lines
const wide: TextMeasurer = { measureWidth: (value) => [...value].length * 30, measureLineHeight: () => 10 };
expect(layoutLines([text("a".repeat(10))], { width: 100, measurer: wide })).to.have.length(4);
// An accent stays with its letter: "aa" and "a\u0301a"
expect(layoutLines([text("aaa\u0301a")], { width: 100, measurer: wide })).to.have.length(2);
// Also when the accent is in a run of its own: "a", "a\u0301" and "a" on lines of 70
expect(layoutLines([text("aa"), text("\u0301a", 12)], { width: 70, measurer: wide })).to.have.length(3);
// And a character joined to the one before it by a zero-width joiner stays with it: "a\u200db" and "aa"
expect(layoutLines([text("a\u200dbaa")], { width: 70, measurer: wide })).to.have.length(2);
});
it("should lay out pictures in the line, and wrap them as a word", () => {
expect(heightsOf([text("aaaa "), { type: "box", width: 30, height: 50 }, text(" bbbb")])).to.deep.equal([50, 10]);
expect(heightsOf([text("aaaaaaaa "), { type: "box", width: 30, height: 50 }])).to.deep.equal([10, 50]);
+113 -71
View File
@@ -2,12 +2,13 @@
* Breaks a paragraph into lines as Word breaks it, for laying out pages: where each line wraps, how tall it is, and
* which bookmarks start on it.
*
* Lines break at spaces, after hyphens, and between Chinese, Japanese and Korean characters. Tabs move to the
* paragraph's tab stops, or to the document's default ones. Each line is as tall as the tallest text or picture on
* it, with the paragraph's line spacing.
* Lines break at spaces, after hyphens, between Chinese, Japanese and Korean characters, and between the words of Thai and
* the other scripts without spaces, as {@link findLineBreaks} finds. Tabs move to the paragraph's tab stops, or to the
* document's default ones. Each line is as tall as the tallest text or picture on it, with the paragraph's line spacing.
*
* @module
*/
import { type LineBreakRules, extendsCharacter, findLineBreaks, joinsNext } from "./line-break-rules";
import { type LineSpacing, type ParagraphFormat, type TextFont, measureLineHeight, measureTextWidth } from "./text-width";
/**
@@ -29,7 +30,11 @@ export const DEFAULT_MEASURER: TextMeasurer = {
* A piece of a paragraph's content, in the order it is written.
*/
export type InlineItem =
| { readonly type: "text"; readonly text: string; readonly font: TextFont }
/**
* Text, with the East Asian language of its run, which decides which characters can't start or end a line, and whether
* its run is East Asian, whose words break anywhere with word wrap off
*/
| { readonly type: "text"; readonly text: string; readonly font: TextFont; readonly language?: string; readonly eastAsian?: boolean }
| { readonly type: "tab"; readonly font: TextFont }
/** A line break, or a page or column break, which ends the line and starts the rest on a new page or column */
| { readonly type: "break"; readonly kind: "line" | "page" | "column"; readonly font: TextFont }
@@ -64,6 +69,8 @@ export type LineLayoutOptions = {
/** The font of the paragraph's mark, which sets the height of a line with no text on it, such as an empty paragraph's */
readonly markFont?: TextFont;
readonly measurer?: TextMeasurer;
/** The document's rules for where lines break. The paragraph's `kinsoku` takes the place of the rules' */
readonly breakRules?: LineBreakRules;
};
/**
@@ -100,87 +107,96 @@ const DEFAULT_TAB_STOP = 36;
// How far past its end a line may go before it wraps, for the rounding of the widths
const TOLERANCE = 0.01;
// Letters of Chinese, Japanese and Korean, between which a line can break
const CJK_LETTER = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
// Characters that don't start a line, such as closing punctuation and small kana, and those that don't end one
// cspell:disable-next-line
const NO_LINE_START = new Set([..."、。,.:;?!)」』】〕〉》ー々ぁぃぅぇぉっゃゅょゎァィゥェォッャュョヮヵヶ,.:;?!)]}"]);
// cspell:disable-next-line
const NO_LINE_END = new Set([..."(「『【〔〈《([{"]);
type TextItem = Extract<InlineItem, { readonly type: "text" }>;
/**
* Whether a line can break between two characters with no space between them: after a hyphen that isn't before a
* digit, and before or after a Chinese, Japanese or Korean letter.
* Turns text next to each other into words and the spaces between them. Pieces of words next to each other in different
* fonts are one word, unless the line can break between them.
*/
const canBreakBetween = (before: string, after: string): boolean =>
!NO_LINE_START.has(after) &&
!NO_LINE_END.has(before) &&
((before === "-" && !/[\d-]/.test(after)) || CJK_LETTER.test(before) || CJK_LETTER.test(after));
/**
* Splits text into words and the spaces between them, and words where a line can break inside them.
*/
type TextPart = { readonly text: string; readonly isSpace: boolean };
const splitText = (text: string): readonly TextPart[] =>
text
.split(/( +)/)
.filter((part) => part.length > 0)
.flatMap((part): readonly TextPart[] => {
if (part.startsWith(" ")) {
return [{ text: part, isSpace: true }];
const tokenizeText = (items: readonly TextItem[], rules: LineBreakRules): readonly Token[] => {
const breaks = findLineBreaks(items, rules);
// eslint-disable-next-line functional/prefer-readonly-type
const tokens: { readonly type: "word" | "space"; readonly pieces: Piece[] }[] = [];
let index = 0;
for (const { text, font } of items) {
for (const character of text) {
const type = character === " " ? "space" : "word";
const last = tokens[tokens.length - 1];
if (last?.type !== type || (type === "word" && breaks.has(index))) {
// eslint-disable-next-line functional/immutable-data
tokens.push({ type, pieces: [{ text: character, font }] });
} else {
const piece = last.pieces[last.pieces.length - 1];
// eslint-disable-next-line functional/immutable-data
last.pieces[last.pieces.length - 1 + (piece.font === font ? 0 : 1)] = {
text: piece.font === font ? piece.text + character : character,
font,
};
}
const characters = [...part];
return characters
.reduce<readonly string[]>(
(words, character, index) =>
index > 0 && canBreakBetween(characters[index - 1], character)
? [...words, character]
: [...words.slice(0, -1), `${words[words.length - 1] ?? ""}${character}`],
[],
)
.map((word) => ({ text: word, isSpace: false }));
});
const lastCharacter = (text: string): string => [...text].pop()!;
index++;
}
}
return tokens;
};
/**
* Turns a part of a paragraph into tokens. Pieces of words next to each other in different fonts are one word, unless
* the line can break between them.
* Turns a part of a paragraph into tokens.
*/
const tokenize = (items: readonly InlineItem[]): readonly Token[] =>
items.reduce<readonly Token[]>((tokens, item) => {
const tokenize = (items: readonly InlineItem[], rules: LineBreakRules): readonly Token[] => {
// eslint-disable-next-line functional/prefer-readonly-type
const tokens: Token[] = [];
// eslint-disable-next-line functional/prefer-readonly-type
let text: TextItem[] = [];
for (const item of items) {
if (item.type === "text") {
return splitText(item.text).reduce<readonly Token[]>((all, { text, isSpace }) => {
const last = all[all.length - 1];
const type = isSpace ? "space" : "word";
const joins =
last?.type === type &&
(isSpace || !canBreakBetween(lastCharacter(last.pieces[last.pieces.length - 1].text), [...text][0]));
return joins
? [...all.slice(0, -1), { type, pieces: [...last.pieces, { text, font: item.font }] }]
: [...all, { type, pieces: [{ text, font: item.font }] }];
}, tokens);
// eslint-disable-next-line functional/immutable-data
text.push(item);
} else {
// eslint-disable-next-line functional/immutable-data
tokens.push(...tokenizeText(text, rules), item as Exclude<InlineItem, { readonly type: "text" | "break" }>);
text = [];
}
// The breaks are taken out before the parts between them are tokenized
return [...tokens, item as Exclude<InlineItem, { readonly type: "text" | "break" }>];
}, []);
}
return [...tokens, ...tokenizeText(text, rules)];
};
/**
* Splits a paragraph's content at its breaks.
*/
const segmentsOf = (items: readonly InlineItem[]): readonly Segment[] => {
const segmentsOf = (items: readonly InlineItem[], rules: LineBreakRules): readonly Segment[] => {
const breaks = items.flatMap((item, index) => (item.type === "break" ? [index] : []));
const starts = [0, ...breaks.map((index) => index + 1)];
return starts.map((start, index) => {
const end = breaks[index];
return {
tokens: tokenize(items.slice(start, end)),
tokens: tokenize(items.slice(start, end), rules),
end: end === undefined ? undefined : (items[end] as Segment["end"]),
};
});
};
/**
* A word's characters, each with the marks on it and anything a zero-width joiner joins to it, which a line never breaks
* between, in the pieces of the fonts they are in.
*/
const charactersOf = (pieces: readonly Piece[]): readonly (readonly Piece[])[] =>
pieces.reduce<readonly (readonly Piece[])[]>(
(all, { text, font }) =>
[...text].reduce((characters, character) => {
const last = characters[characters.length - 1];
const lastPiece = last?.[last.length - 1];
if (!lastPiece || !(extendsCharacter(character) || joinsNext([...lastPiece.text].pop()!))) {
return [...characters, [{ text: character, font }]];
}
const joined =
lastPiece.font === font
? [...last.slice(0, -1), { text: `${lastPiece.text}${character}`, font }]
: [...last, { text: character, font }];
return [...characters.slice(0, -1), joined];
}, all),
[],
);
const widthOf = (pieces: readonly Piece[], measurer: TextMeasurer): number =>
pieces.reduce((total, { text, font }) => total + measurer.measureWidth(text, font), 0);
@@ -262,6 +278,13 @@ const stopsOf = (
return { stops, firstLineStops };
};
/** The rules for where a paragraph's lines break: the document's, with the paragraph's own */
const rulesOf = ({ kinsoku, wordWrap }: ParagraphFormat, rules: LineBreakRules = {}): LineBreakRules => ({
...rules,
...(kinsoku === undefined ? {} : { kinsoku }),
...(wordWrap === undefined ? {} : { wordWrap }),
});
/** How wide a paragraph is, in points, with its indents */
export type ContentWidths = {
/** The narrowest it can be: its widest word or picture, which a line can't break */
@@ -283,11 +306,12 @@ export const measureContentWidths = (
tabStops = [],
defaultTabStop = DEFAULT_TAB_STOP,
measurer = DEFAULT_MEASURER,
breakRules,
}: Omit<LineLayoutOptions, "width" | "markFont">,
): ContentWidths => {
const { indentLeft = 0, indentRight = 0, firstLineIndent = 0 } = format;
const { stops, firstLineStops } = stopsOf(tabStops, format);
return segmentsOf(items).reduce<ContentWidths>(
return segmentsOf(items, rulesOf(format, breakRules)).reduce<ContentWidths>(
(widths, { tokens }, segmentIndex) => {
const first = segmentIndex === 0;
let position = indentLeft + (first ? firstLineIndent : 0);
@@ -329,12 +353,20 @@ export const measureContentWidths = (
*/
export const layoutLines = (
items: readonly InlineItem[],
{ width, format = {}, tabStops = [], defaultTabStop = DEFAULT_TAB_STOP, markFont = {}, measurer = DEFAULT_MEASURER }: LineLayoutOptions,
{
width,
format = {},
tabStops = [],
defaultTabStop = DEFAULT_TAB_STOP,
markFont = {},
measurer = DEFAULT_MEASURER,
breakRules,
}: LineLayoutOptions,
): readonly LaidOutLine[] => {
const { indentLeft = 0, indentRight = 0, firstLineIndent = 0, lineSpacing } = format;
const markHeight = measurer.measureLineHeight(markFont);
const { stops, firstLineStops } = stopsOf(tabStops, format);
const parts = segmentsOf(items);
const parts = segmentsOf(items, rulesOf(format, breakRules));
// A page break at the end of a paragraph has the paragraph's mark on its line, as Word lays it out from Word 2013,
// rather than on a line of its own on the next page. A column break's mark is on a line at the top of the next column,
// in Word and LibreOffice
@@ -417,13 +449,23 @@ export const layoutLines = (
line = wrap(line);
}
line = place(line);
// A word wider than a line is broken across as many lines as it needs, each as long as it is
let rest = tokenWidth;
while (token.type === "word" && line.position + rest > limitOf() + TOLERANCE && limitOf() - indentLeft > 0) {
rest -= limitOf() - line.position;
line = wrap({ ...line, natural: Math.max(line.natural, tokenHeight), started: true });
if (token.type === "word" && line.position + tokenWidth > limitOf() + TOLERANCE && limitOf() - indentLeft > 0) {
// A word wider than a line is broken across as many lines as it needs, after the last character that fits
// on each, and never between a character and the marks on it or what a zero-width joiner joins to it
let placed = false;
for (const character of charactersOf(token.pieces)) {
const characterWidth = widthOf(character, measurer);
// Each line is as long as it is, for lines of different widths, and one with no room takes the rest
if (placed && line.position + characterWidth > limitOf() + TOLERANCE && limitOf(lines.length + 1) - indentLeft > 0) {
line = wrap({ ...line, natural: Math.max(line.natural, tokenHeight), started: true });
}
line = { ...line, position: line.position + characterWidth };
placed = true;
}
} else {
line = { ...line, position: line.position + tokenWidth };
}
line = { ...line, position: line.position + rest, natural: Math.max(line.natural, tokenHeight), started: true };
line = { ...line, natural: Math.max(line.natural, tokenHeight), started: true };
}
if (!end) {
+110 -1
View File
@@ -8,8 +8,10 @@ import {
fontOf,
getTextStyles,
hasDefaultParagraphSpacing,
isEastAsianRun,
readParagraphFormat,
readRunFormat,
spansOf,
styleChain,
} from "./text-styles";
@@ -27,7 +29,14 @@ describe("getTextStyles", () => {
const styles = stylesOf({
default: { document: { run: { font: "Calibri", size: 22 }, paragraph: { spacing: { after: 160, line: 259 } } } },
});
expect(styles.run).to.deep.equal({ font: "Calibri", size: 11 });
// A font given by name is the font of East Asian text and of complex scripts too, and a size the size of both
expect(styles.run).to.deep.equal({
font: "Calibri",
size: 11,
eastAsiaFont: "Calibri",
complexScriptFont: "Calibri",
complexScriptSize: 11,
});
expect(styles.paragraph).to.deep.equal({ spaceAfter: 8, lineSpacing: { rule: "multiple", multiple: 259 / 240 } });
});
@@ -241,3 +250,103 @@ describe("readParagraphFormat", () => {
});
});
});
describe("readParagraphFormat with East Asian typography", () => {
it("should read whether characters are kept from starting or ending lines, and whether lines break between words", () => {
expect(
readParagraphFormat([{ "w:kinsoku": { _attr: { "w:val": "0" } } }, { "w:wordWrap": { _attr: { "w:val": 0 } } }]),
).to.deep.equal({
kinsoku: false,
wordWrap: false,
});
});
});
describe("readRunFormat with East Asian text and complex scripts", () => {
const THEME = { headings: "Cambria", body: "Calibri" };
it("should read the fonts, size and boldness of East Asian text and complex scripts, and the run's direction and language", () => {
expect(
readRunFormat(
[
{ "w:rFonts": { _attr: { "w:ascii": "Arial", "w:eastAsia": "MS Mincho", "w:cs": "Times New Roman" } } },
{ "w:b": {} },
{ "w:bCs": { _attr: { "w:val": "0" } } },
{ "w:sz": { _attr: { "w:val": 22 } } },
{ "w:szCs": { _attr: { "w:val": "28" } } },
{ "w:rtl": {} },
{ "w:cs": {} },
{ "w:lang": { _attr: { "w:val": "en-US", "w:eastAsia": "ja-JP" } } },
],
THEME,
),
).to.deep.equal({
font: "Arial",
size: 11,
bold: true,
eastAsiaFont: "MS Mincho",
complexScriptFont: "Times New Roman",
complexScriptSize: 14,
complexScriptBold: false,
rightToLeft: true,
complexScript: true,
eastAsianLanguage: "ja-JP",
});
});
it("should read the theme's fonts for East Asian text and complex scripts", () => {
expect(
readRunFormat([{ "w:rFonts": { _attr: { "w:eastAsiaTheme": "minorEastAsia", "w:cstheme": "majorBidi" } } }], THEME),
).to.deep.equal({
eastAsiaFont: "Calibri",
complexScriptFont: "Cambria",
});
});
});
describe("isEastAsianRun", () => {
it("should be whether a run has an East Asian font or language", () => {
expect(isEastAsianRun({ eastAsiaFont: "SimSun" })).to.equal(true);
expect(isEastAsianRun({ eastAsiaFont: "Calibri", eastAsianLanguage: "ko-KR" })).to.equal(true);
expect(isEastAsianRun({ eastAsiaFont: "Calibri", eastAsianLanguage: "en-US" })).to.equal(false);
expect(isEastAsianRun({})).to.equal(false);
});
});
describe("spansOf", () => {
// cspell:disable
it("should put Chinese, Japanese and Korean in the run's East Asian font, or in MS Mincho where that has none, as Word does", () => {
expect(spansOf("ab永永", { font: "Calibri", size: 12, eastAsiaFont: "Yu Mincho" })).to.deep.equal([
{ font: "Calibri", size: 12, text: "ab" },
{ font: "Yu Mincho", size: 12, text: "永永" },
]);
expect(spansOf("永a", { font: "Calibri", eastAsiaFont: "Calibri" })).to.deep.equal([
{ font: "MS Mincho", text: "永" },
{ font: "Calibri", text: "a" },
]);
});
it("should put all of a right-to-left run in the font, size and boldness of complex scripts, and Hebrew in other runs in the run's", () => {
const format = { font: "Calibri", size: 11, bold: true, complexScriptFont: "Arial", complexScriptSize: 14 };
expect(spansOf("ab שלום", { ...format, rightToLeft: true })).to.deep.equal([{ font: "Arial", size: 14, text: "ab שלום" }]);
expect(spansOf("ab", { ...format, complexScript: true, complexScriptBold: true })).to.deep.equal([
{ font: "Arial", size: 14, bold: true, text: "ab" },
]);
expect(spansOf("שלום", format)).to.deep.equal([{ font: "Calibri", size: 11, bold: true, text: "שלום" }]);
});
it("should keep marks in the font of the character they are on, and write capitals and small capitals in each font", () => {
expect(spansOf("\u0301か\u3099a", {})).to.deep.equal([{ text: "\u0301" }, { font: "MS Mincho", text: "か\u3099" }, { text: "a" }]);
expect(spansOf("ab永", { allCaps: true, size: 10 })).to.deep.equal([
{ size: 10, text: "AB" },
{ font: "MS Mincho", size: 10, text: "永" },
]);
expect(spansOf("aB永", { smallCaps: true })).to.deep.equal([
{ size: 8, text: "A" },
{ text: "B" },
{ font: "MS Mincho", text: "永" },
]);
expect(spansOf("a", { hidden: true })).to.deep.equal([]);
});
// cspell:enable
});
+86 -12
View File
@@ -10,7 +10,8 @@
*/
import type { IContext } from "docx";
import type { LineSpacing, ParagraphFormat, TabStopSetting, TextFont, TextSpan } from "./text-width";
import { isEastAsian, kinsokuLanguageOf } from "./line-break-rules";
import { type LineSpacing, type ParagraphFormat, type TabStopSetting, type TextFont, type TextSpan, isEastAsianFont } from "./text-width";
export type XmlObject = Readonly<Record<string, unknown>>;
@@ -24,6 +25,17 @@ export type RunFormat = Omit<TextFont, "size"> & {
readonly smallCaps?: boolean;
/** Hidden text takes up no room */
readonly hidden?: boolean;
/** The font of Chinese, Japanese and Korean text (`w:eastAsia`) */
readonly eastAsiaFont?: string;
/** The font, size in points and boldness of complex scripts, such as Arabic, Hebrew and Thai (`w:cs`, `w:szCs`, `w:bCs`) */
readonly complexScriptFont?: string;
readonly complexScriptSize?: number;
readonly complexScriptBold?: boolean;
/** Whether the run is right to left (`w:rtl`), or of a complex script (`w:cs`), so all of it is in the complex script's formatting */
readonly rightToLeft?: boolean;
readonly complexScript?: boolean;
/** The East Asian language of the run (`w:lang w:eastAsia`), which decides which characters can't start or end a line */
readonly eastAsianLanguage?: string;
};
/**
@@ -184,6 +196,13 @@ export const readRunFormat = (element: unknown, themeFonts: ThemeFonts): RunForm
hidden: onOff(children, "w:vanish"),
characterSpacing: scaled(numberOf(attributesOf(find(children, "w:spacing"))["w:val"]), TWIPS_PER_POINT),
scale: numberOf(attributesOf(find(children, "w:w"))["w:val"]),
eastAsiaFont: themeFontOf(fonts["w:eastAsiaTheme"], themeFonts) ?? stringOf(fonts["w:eastAsia"]),
complexScriptFont: themeFontOf(fonts["w:cstheme"], themeFonts) ?? stringOf(fonts["w:cs"]),
complexScriptSize: scaled(numberOf(attributesOf(find(children, "w:szCs"))["w:val"]), 2),
complexScriptBold: onOff(children, "w:bCs"),
rightToLeft: onOff(children, "w:rtl"),
complexScript: onOff(children, "w:cs"),
eastAsianLanguage: stringOf(attributesOf(find(children, "w:lang"))["w:eastAsia"]),
});
};
@@ -253,6 +272,8 @@ export const readParagraphFormat = (element: unknown): ParagraphFormat => {
pageBreakBefore: onOff(children, "w:pageBreakBefore"),
widowControl: onOff(children, "w:widowControl"),
tabs: readTabs(find(children, "w:tabs")),
kinsoku: onOff(children, "w:kinsoku"),
wordWrap: onOff(children, "w:wordWrap"),
});
};
@@ -379,25 +400,78 @@ export const styleChain = ({ styles }: TextStyles, id: string | undefined, type:
export const fontOf = ({ font, size, bold, italic, characterSpacing, scale }: RunFormat): TextFont =>
withoutUndefined({ font, size, bold, italic, characterSpacing, scale });
type FontSlot = "latin" | "eastAsian" | "complex";
/**
* A span of text in its formatting: capitals for all caps, and smaller capitals for the small letters of small caps.
* Which of a run's fonts Word draws a character in: the font for complex scripts, in their size and boldness, for all of a
* run that is right to left or of a complex script; the East Asian font for Chinese, Japanese and Korean; the run's font
* for the rest. Hebrew in a run that isn't right to left is in the run's size, as Word lays it out. A mark is drawn in the
* font of the character it is on.
*/
const slotOf = (character: string, previous: FontSlot, complexRun: boolean): FontSlot => {
if (complexRun) {
return "complex";
}
if (isEastAsian(character)) {
return "eastAsian";
}
return /\p{M}/u.test(character) ? previous : "latin";
};
// The font Word draws Chinese, Japanese and Korean in when the run's East Asian font has none, such as Calibri
const FALLBACK_EAST_ASIAN_FONT = "MS Mincho";
/**
* The font of a character of a run, by the run's font Word draws it in. Complex scripts have their own size and boldness,
* and Word's defaults where the run doesn't give them.
*/
const fontOfSlot = (format: RunFormat, slot: FontSlot): TextFont => {
const font = fontOf(format);
if (slot === "latin") {
return font;
}
const { eastAsiaFont, complexScriptFont, complexScriptSize, complexScriptBold } = format;
return slot === "eastAsian"
? { ...font, font: isEastAsianFont(eastAsiaFont) ? eastAsiaFont : FALLBACK_EAST_ASIAN_FONT }
: withoutUndefined({ ...font, font: complexScriptFont, size: complexScriptSize, bold: complexScriptBold });
};
/**
* A span of text in its formatting: in the run's font for its script, capitals for all caps, and smaller capitals for the
* small letters of small caps.
*/
export const spansOf = (text: string, format: RunFormat): readonly TextSpan[] => {
const { allCaps, smallCaps, hidden } = format;
const font = fontOf(format);
const { allCaps, smallCaps, hidden, rightToLeft, complexScript } = format;
if (hidden) {
return [];
}
if (allCaps || !smallCaps) {
return [{ ...font, text: allCaps ? text.toUpperCase() : text }];
}
const small = { ...font, size: (font.size ?? 10) * SMALL_CAPS_SCALE };
return text
.split(/(\p{Ll}+)/u)
.filter((part) => part.length > 0)
.map((part) => (/^\p{Ll}/u.test(part) ? { ...small, text: part.toUpperCase() } : { ...font, text: part }));
const complexRun = rightToLeft === true || complexScript === true;
// The parts of the text in each of the run's fonts
const parts = [...text].reduce<readonly { readonly slot: FontSlot; readonly text: string }[]>((all, character) => {
const last = all[all.length - 1];
const slot = slotOf(character, last?.slot ?? "latin", complexRun);
return last?.slot === slot ? [...all.slice(0, -1), { slot, text: last.text + character }] : [...all, { slot, text: character }];
}, []);
return parts.flatMap(({ slot, text: part }) => {
const font = fontOfSlot(format, slot);
if (allCaps || !smallCaps) {
return [{ ...font, text: allCaps ? part.toUpperCase() : part }];
}
const small = { ...font, size: (font.size ?? 10) * SMALL_CAPS_SCALE };
return part
.split(/(\p{Ll}+)/u)
.filter((piece) => piece.length > 0)
.map((piece) => (/^\p{Ll}/u.test(piece) ? { ...small, text: piece.toUpperCase() } : { ...font, text: piece }));
});
};
/**
* Whether a run is East Asian, by its East Asian font or language, so its words break anywhere with word wrap off, as
* Word breaks them.
*/
export const isEastAsianRun = ({ eastAsiaFont, eastAsianLanguage }: RunFormat): boolean =>
isEastAsianFont(eastAsiaFont) || kinsokuLanguageOf(eastAsianLanguage) !== undefined;
/**
* Whether a paragraph in the default style, without formatting of its own, has space before or after it.
*/
+32 -1
View File
@@ -38,7 +38,10 @@ describe("measureTextWidth", () => {
for (const character of ["\u1100", "\uac00", "\uf900", "\ufe30", "\uff01", "\uffe0", "\u{1f600}"]) {
expect(measureTextWidth(character, { size: 10 })).to.equal(10);
}
expect(measureTextWidth("́", { size: 10 })).to.equal(0);
expect(measureTextWidth("\u0301", { size: 10 })).to.equal(0);
// Half-width katakana, Thai vowels above the letters, and zero-width spaces
expect(measureTextWidth("\uff71", { size: 10 })).to.equal(5);
expect(measureTextWidth("\u0e31\u200b", { size: 10 })).to.equal(0);
const average = measureTextWidth("abcdefghijklmnopqrstuvwxyz") / 26;
expect(measureTextWidth("Ж")).to.be.closeTo(average, 0.001);
});
@@ -63,6 +66,34 @@ describe("measureLineHeight", () => {
});
});
describe("East Asian fonts", () => {
// cspell:disable
it("should make their lines as tall as Word does, about 1.3 times the font's height", () => {
expect(measureLineHeight({ font: "MS Mincho", size: 12 })).to.be.closeTo(15.564, 0.0001);
expect(measureLineHeight({ font: "ms gothic", size: 10 })).to.be.closeTo(12.97, 0.0001);
// By the name Office's theme gives it
expect(measureLineHeight({ font: "游明朝", size: 10 })).to.be.closeTo(14.33, 0.0001);
expect(measureLineHeight({ font: "Malgun Gothic", size: 10 })).to.be.closeTo(17.3, 0.0001);
});
it("should measure East Asian fonts that aren't in the table as MS Mincho or MS Gothic, and not Latin fonts that look like them", () => {
expect(measureLineHeight({ font: "Hiragino Mincho ProN", size: 10 })).to.be.closeTo(12.97, 0.0001);
expect(measureTextWidth("ab", { font: "ヒラギノ角ゴシック", size: 10 })).to.equal(10);
expect(measureLineHeight({ font: "Century Gothic", size: 10 })).to.equal(measureLineHeight({ font: "Arial", size: 10 }));
});
it("should make the Latin letters of monospaced ones half an em, and their ideographs and symbols an em", () => {
expect(measureTextWidth("ab", { font: "MS Mincho", size: 12 })).to.equal(12);
expect(measureTextWidth("‘永→", { font: "MS Mincho", size: 12 })).to.equal(36);
expect(measureTextWidth("e\u0301", { font: "SimSun", size: 12 })).to.equal(6);
// The Latin letters of the others are measured with the most similar font in the table
expect(measureTextWidth("ab永", { font: "Yu Gothic", size: 12 })).to.equal(
measureTextWidth("ab", { font: "Arial", size: 12 }) + 12,
);
});
// cspell:enable
});
describe("measureText", () => {
const line = measureLineHeight();
+100 -6
View File
@@ -81,6 +81,10 @@ export type ParagraphFormat = {
readonly widowControl?: boolean;
/** The tab stops the paragraph, or its style, sets or clears. Those of its styles are added to them */
readonly tabs?: readonly TabStopSetting[];
/** Whether Word's East Asian rules keep characters from starting or ending its lines (`w:kinsoku`). Default is on */
readonly kinsoku?: boolean;
/** Whether its lines break between words (`w:wordWrap`), or, when off, anywhere in the words of East Asian runs */
readonly wordWrap?: boolean;
};
/**
@@ -115,6 +119,68 @@ const CHARACTER_INDEX: ReadonlyMap<number, number> = new Map(
const AVERAGE_LETTER_INDEXES = [..."abcdefghijklmnopqrstuvwxyz"].map((letter) => CHARACTER_INDEX.get(letter.codePointAt(0)!)!);
/**
* A font for Chinese, Japanese or Korean text, and how Word lays it out.
*/
type EastAsianFont = {
readonly name: string;
/** The names it is also known by, in its own language, as Office's theme names them */
readonly aliases: readonly string[];
/** The height of its lines, in thousandths of an em: about 1.3 times the font's height, as Word lays them out */
readonly lineHeight: number;
/** Whether its Latin letters are all half an em wide */
readonly monospaced?: boolean;
/** The font in the table its Latin letters are measured with, when they aren't monospaced */
readonly latin: string;
};
/* cspell:disable */
// The heights of their lines are Word's, from its PDF of scripts/layout-probes/word-unicode2.ts, over 20 lines of each.
// Their Chinese, Japanese and Korean characters are an em wide
const EAST_ASIAN_FONTS: readonly EastAsianFont[] = [
{ name: "MS Mincho", aliases: ["MS 明朝", "MS 明朝"], lineHeight: 1297, monospaced: true, latin: "Times New Roman" },
{ name: "MS Gothic", aliases: ["MS ゴシック", "MS ゴシック"], lineHeight: 1297, monospaced: true, latin: "Arial" },
{ name: "MS PMincho", aliases: ["MS P明朝", "MS P明朝"], lineHeight: 1297, latin: "Times New Roman" },
{ name: "MS PGothic", aliases: ["MS Pゴシック", "MS Pゴシック"], lineHeight: 1297, latin: "Arial" },
{ name: "Yu Mincho", aliases: ["游明朝"], lineHeight: 1433, latin: "Times New Roman" },
{ name: "Yu Gothic", aliases: ["游ゴシック", "游ゴシック Light", "Yu Gothic Light"], lineHeight: 1434, latin: "Arial" },
{ name: "Meiryo", aliases: ["メイリオ"], lineHeight: 1950, latin: "Arial" },
{ name: "SimSun", aliases: ["宋体"], lineHeight: 1297, monospaced: true, latin: "Times New Roman" },
{ name: "NSimSun", aliases: ["新宋体"], lineHeight: 1296, monospaced: true, latin: "Times New Roman" },
{ name: "SimHei", aliases: ["黑体"], lineHeight: 1297, monospaced: true, latin: "Arial" },
{ name: "KaiTi", aliases: ["楷体"], lineHeight: 1297, monospaced: true, latin: "Times New Roman" },
{ name: "FangSong", aliases: ["仿宋"], lineHeight: 1297, monospaced: true, latin: "Times New Roman" },
{ name: "Microsoft YaHei", aliases: ["微软雅黑"], lineHeight: 1714, latin: "Arial" },
{ name: "DengXian", aliases: ["等线", "等线 Light", "DengXian Light"], lineHeight: 1354, latin: "Arial" },
{ name: "PMingLiU", aliases: ["新細明體"], lineHeight: 1300, latin: "Times New Roman" },
{ name: "MingLiU", aliases: ["細明體"], lineHeight: 1301, monospaced: true, latin: "Times New Roman" },
{ name: "Microsoft JhengHei", aliases: ["微軟正黑體"], lineHeight: 1730, latin: "Arial" },
{ name: "Malgun Gothic", aliases: ["맑은 고딕"], lineHeight: 1730, latin: "Arial" },
{ name: "Batang", aliases: ["바탕"], lineHeight: 1300, latin: "Times New Roman" },
{ name: "Gulim", aliases: ["굴림"], lineHeight: 1301, latin: "Arial" },
{ name: "Dotum", aliases: ["돋움"], lineHeight: 1301, latin: "Arial" },
];
// East Asian fonts that aren't in the table, which are measured as MS Gothic, or MS Mincho for those with serifs
const EAST_ASIAN_NAME =
/[\u3040-\u30ff\u3400-\u9fff\uac00-\ud7af]|hiragino|cjk|source han|pingfang|songti|heiti|kaiti|fangsong|mincho|mingliu|simhei|gungsuh|nanum/i;
const EAST_ASIAN_SANS = /gothic|ゴシック|hei|黑|黒|sans|고딕|pingfang/i;
/* cspell:enable */
/**
* The East Asian font a font is, or is measured as, by its name. Undefined for other fonts.
*/
const eastAsianFontOf = (font: string): EastAsianFont | undefined => {
const name = font.toLowerCase();
const known = EAST_ASIAN_FONTS.find((candidate) =>
[candidate.name, ...candidate.aliases].some((alias) => alias.toLowerCase() === name),
);
const similar = EAST_ASIAN_SANS.test(font) ? "MS Gothic" : "MS Mincho";
return known ?? (EAST_ASIAN_NAME.test(font) ? EAST_ASIAN_FONTS.find((candidate) => candidate.name === similar) : undefined);
};
/** Whether a font is one for Chinese, Japanese or Korean text */
export const isEastAsianFont = (font: string | undefined): boolean => font !== undefined && eastAsianFontOf(font) !== undefined;
/**
* The widths to measure a font with: its own, or those of the most similar font in the table.
* Sans-serif fonts that aren't in the table, such as Aptos and Helvetica, are measured as Arial.
@@ -136,11 +202,18 @@ const isWide = (code: number): boolean =>
(code >= 0xffe0 && code <= 0xffe6) ||
code >= 0x1f300;
// Half-width katakana, Hangul and symbols
const isHalfWidth = (code: number): boolean => code >= 0xff61 && code <= 0xffdc;
// Marks, which go on the character before them, and characters that only change how the text around them is laid out
const takesNoRoom = (character: string): boolean => /[\p{Mn}\p{Me}\p{Cf}]/u.test(character);
/**
* The width of a character in thousandths of an em. Characters that aren't in the table are as wide as an average
* lowercase letter, or a whole em for wide characters, and combining accents take no space.
* lowercase letter, a whole em for wide characters and half an em for half-width ones, and marks take no space.
*/
const characterWidth = (widths: readonly number[], code: number): number => {
const characterWidth = (widths: readonly number[], character: string): number => {
const code = character.codePointAt(0)!;
const index = CHARACTER_INDEX.get(code);
if (index !== undefined) {
return widths[index];
@@ -148,11 +221,29 @@ const characterWidth = (widths: readonly number[], code: number): number => {
if (isWide(code)) {
return 1000;
}
return code >= 0x300 && code <= 0x36f
if (isHalfWidth(code)) {
return 500;
}
return takesNoRoom(character)
? 0
: AVERAGE_LETTER_INDEXES.reduce((total, letter) => total + widths[letter], 0) / AVERAGE_LETTER_INDEXES.length;
};
// Symbols that monospaced Japanese and Chinese fonts have as wide as their ideographs, as MS Mincho does
const FULL_WIDTH_SYMBOLS = new Set([..."§¨°±´¶×÷‐―‖‘’“”†‡‥…‰′″※℃Å"]);
/**
* The width of a character of a monospaced East Asian font, in thousandths of an em: an em for ideographs and the symbols
* of Japanese and Chinese, and half an em for the rest.
*/
const monospacedWidth = (character: string): number => {
const code = character.codePointAt(0)!;
if (takesNoRoom(character)) {
return 0;
}
return isWide(code) || FULL_WIDTH_SYMBOLS.has(character) || (code >= 0x2190 && code <= 0x26ff) ? 1000 : 500;
};
const sizeOf = ({ size = DEFAULT_FONT_SIZE }: TextFont): number => size;
/**
@@ -161,8 +252,10 @@ const sizeOf = ({ size = DEFAULT_FONT_SIZE }: TextFont): number => size;
* @param start - Where the text starts on its line, in points
*/
export const measureTextWidth = (text: string, font: TextFont = {}, start = 0): number => {
const { regular, bold } = widthsOf(font.font);
const eastAsian = eastAsianFontOf(font.font ?? DEFAULT_FONT);
const { regular, bold } = widthsOf(eastAsian?.latin ?? font.font);
const widths = font.bold ? bold : regular;
const widthOf = eastAsian?.monospaced ? monospacedWidth : (character: string): number => characterWidth(widths, character);
const size = sizeOf(font);
const { characterSpacing = 0, scale = 100 } = font;
return (
@@ -170,7 +263,7 @@ export const measureTextWidth = (text: string, font: TextFont = {}, start = 0):
(position, character) =>
character === "\t"
? (Math.floor(position / TAB_STOP) + 1) * TAB_STOP
: position + (characterWidth(widths, character.codePointAt(0)!) * size * scale) / 100000 + characterSpacing,
: position + (widthOf(character) * size * scale) / 100000 + characterSpacing,
start,
) - start
);
@@ -179,7 +272,8 @@ export const measureTextWidth = (text: string, font: TextFont = {}, start = 0):
/**
* How tall a line of single-spaced text is, in points.
*/
export const measureLineHeight = (font: TextFont = {}): number => (widthsOf(font.font).lineHeight * sizeOf(font)) / 1000;
export const measureLineHeight = (font: TextFont = {}): number =>
((eastAsianFontOf(font.font ?? DEFAULT_FONT) ?? widthsOf(font.font)).lineHeight * sizeOf(font)) / 1000;
/**
* The size of text laid out in lines, in points.