feat(layout): lay out Japanese line rules, compressed punctuation, grid indents, right-to-left line ends, endnotes down the page and Arabic's letters side by side where round 26 shows Word's way, as Word does (#3726)

* feat(layout): lay out Japanese line rules, compressed punctuation, grid indents, right-to-left line ends, endnotes down the page and Arabic's letters side by side where round 26 shows Word's way, as Word does

Word's PDFs of round 26 (word-stops-east-asian3.ts and word-stops-arabic2.ts) show that Word's strict rules keep each small kana and the prolonged sound mark from the start of a line of Japanese, in place of the document's own list, and change nothing in Chinese or Korean; that compressed punctuation leaves justified Japanese and left-aligned Chinese as they are; that indents of part of a cell on a grid that snaps to characters are rounded up line by line, before the margin too, with tabs to their stops; that the space after a line's last right-to-left word takes room beside left-to-right text in a right-to-left run and between right-to-left words in any run; that endnotes after text that runs down the page run down it, and end with their section before text that runs another way; and that Word doesn't kern Arabic's letters in Arial and Times New Roman, every pair being as wide as its forms to 8 thousandths of an em. The layout follows each, and keeps a narrowed stop where a case is still open: half-width small katakana and the document's own lists beyond the strict list, distributed Japanese and justified or distributed Chinese and Korean with compression, indents a character or more before the margin, endnotes from a section followed by one that runs as it does before a change of direction, and Calibri's Arabic, which Word kerns by pairs of glyphs.

* docs: say Word doesn't kern Arabic's letters side by side in the fonts of the tables, and spell tatweels

The fonts paragraph of docs/usage/layout.md still said Word kerns them in Arial, Times New Roman and Cambria by pairs not yet known, so only Courier New's Arabic is laid out, which round 26's AR4 PDF showed to be wrong, and the probe README's ignore list lacked tatweels, which failed CSpell.

* fix: fail the Arabic kerning reader on a PDF without its probe, or a paragraph without its 42 words

Otherwise a PDF with no AR4 labels wrote {} and exited 0, and the checker reported nothing.

* fix(layout): measure Arabic's letters in their joined forms as drawn too, with ligatures or kerning on

measureTextWidthAsDrawn measured each Arabic letter in its isolated form where measureTextWidth has the forms the letters beside them join them in, so a word of Arabic in Arial with ligatures on, which no longer stops, was nearly twice as wide as Word draws it. It now takes the joined widths by each glyph's index among the characters, as the plain measurement does.
This commit is contained in:
Dolan
2026-10-06 21:30:57 +01:00
committed by GitHub
parent 0c0f1f07b9
commit a1215475f7
35 changed files with 727 additions and 273 deletions
+7 -8
View File
File diff suppressed because one or more lines are too long
+4 -3
View File
@@ -7,9 +7,10 @@
* each letter in each form, parted by zero-width non-joiners, and the form joined to tatweels: a form's width is how far
* apart Word puts its copies, less the tatweels'. In Arial, Times New Roman, which Word draws Cambria's Arabic in, and
* Courier New, that is the width of the glyph Word draws for the form, as the font has it, and a line of Arabic prose is
* as wide as its glyphs, to within 0.25 points (AR2). Word kerns the letters side by side, by pairs these widths don't
* have, in all but Courier New (see `src/text-layout/arabic-shaping.ts`), and Calibri's too: an alef before a zero-width
* non-joiner and an alef 34 thousandths of an em narrower, so Calibri isn't in them. Italic isn't in the PDF.
* as wide as its glyphs, to within 0.25 points (AR2), and so is every pair of the letters, joined as initial and final
* and as medials, to 8 thousandths of an em: Word doesn't kern them (word-stops-arabic2.ts AR4). Calibri's it kerns, by
* pairs of glyphs, by as much as 268 thousandths of an em, and with the spaces beside them (AR4), so Calibri isn't in
* them. Italic isn't in the PDF.
*
* Usage:
* python3 scripts/layout-probes/stops2/word-stops-arabic.py scripts/layout-probes/stops2/word-stops-arabic.pdf --json \
+27 -11
View File
@@ -1,6 +1,6 @@
# The stops batch (lay-stops2)
<!-- cspell:ignore pdftocairo Poppler poppler hhea GPOS -->
<!-- cspell:ignore pdftocairo Poppler poppler hhea GPOS tatweel tatweels -->
Probe documents for the stops of docx/layout that no Word PDF saved before 2026-10-04 settled, made in one batch from
docx at `master` a871df8a25 and saved from Word 16 for Mac on 2026-10-04, 2026-10-05 and 2026-10-06 (Save As, PDF,
@@ -44,6 +44,8 @@ committed here are the ones a change to docx/layout has followed, with Word's PD
| `word-stops-text3.ts` | RF31e to PB7j | RF31e to RF31l: phonetic guides' lines as tall as the guide raised; TA12: a picture or a word after tabs in a row takes the tab on, a word breaks after a list number's tab, centred text ends at the end of the line, stops past the end with a right indent; SH18: the longer part squeezed with twice the room, not distributed, no kerning or ligatures across a soft hyphen; JU5: spaces beside en spaces squeezed; RF24, RF32: shadows and frames of other styles, pictures in borders; RF29: fitted text wider than its line or of two sizes; PB7h to PB7j: a grid's room above footnotes |
| `word-stops-edges.ts` | DH2a to DH2d, PB9a to PB9f, HR2, TA9 | DH2a to DH2d: a header's picture against its paragraph or line, at the header's top, and against a column of several, from the margin; the header's lines go round it. PB9a, PB9b, PB9d, PB9e: Normal paragraphs leave out contextual space beside cells and rows, and after a table. HR2: header rows go to the next column, and a heading with them. TA9: a left tab past the line in an indented paragraph |
| `word-stops-notes2.ts` | NT2c to NT21, NE4 to NE7 | NT2c to NT21: a footnote's rest before a continuous section shows its footer; a line or row whose footnote can't go with it stays or goes on, the footnote on the next page, those after it continued past its end; in columns, after one that continues; NT16: footnotes in columns of their own; NT18, NT19: numbering; NT20: below the text; NE4 to NE7: endnotes in columns, own marks, at sections' ends, separators |
| `word-stops-east-asian3.ts` | EA5 to GR15e | EA5, EA5L: strict rules keep each small kana and ー from starting a line of Japanese, in place of the document's own list, nothing in Chinese or Korean; EA6a, EA6e: compression leaves justified Japanese and left-aligned Chinese as they are; GR17: indents of part of a cell rounded up line by line; AR3: a space after a right-to-left word takes room beside left-to-right text in a right-to-left run and between right-to-left words in any run; GR15d, GR15e: endnotes after text down the page run down it, and end with their section before a change of direction |
| `word-stops-arabic2.ts` | AR4 | AR4: every pair of the 42 letters, joined as initial and final and as medials, in Arial and Times New Roman, plain and bold, as wide as its forms to 8 thousandths of an em: Word doesn't kern them. Calibri's it kerns by pairs of their glyphs, by as much as 268 thousandths, and with the spaces beside them, which still stops. Read with `word-stops-arabic-kerning.py`, and check the layout's forms by it with `word-stops-arabic-kerning.ts` |
`word-stops-thai-and-compat.ts` writes `word-stops-top-spacing` (ST1 to ST5), whose PDF showed `suppressTopSpacing`
leaving all but 9.6 points above the text of the first line of a page or column at exact and at-least spacing, and
@@ -144,17 +146,31 @@ borders that meet of which Word draws the wider, or the next cell's over none, a
that snaps to characters (GR14), the cases around GR3, GR5, GR7, GR8 and GR10 on grids (GR16), which change of grid or
direction sends endnotes to the end of their own section (GR15), and the strict rules and compression in text in Japanese
(EA4). Its PDFs, from the final batch, round 25, showed what the table says, and that a change of direction, but not of
grid, ends endnotes with their own section (GR15b), which isn't followed yet. `word-stops-east-asian3.ts` has what they
and `word-stops-arabic.ts` left open, for a later batch: each character the strict rules may keep from the start of a
line, in Japanese, Chinese and Korean, and with the document's own list (EA5), compressed punctuation justified and in
other fonts and languages (EA6), indents of part of a character Word's PDFs didn't round (GR17), lines that end between
right-to-left and left-to-right text, in Hebrew and in a right-to-left paragraph (AR3), and endnotes after text that runs
down the page (GR15d, GR15e). `word-stops-arabic.ts` has the widths of
grid, ends endnotes with their own section (GR15b), now followed. `word-stops-east-asian3.ts` has what they and
`word-stops-arabic.ts` left open: each character the strict rules may keep from the start of a line, in Japanese, Chinese
and Korean, and with the document's own list (EA5, `word-stops-strict2`, `-strict-list`), compressed punctuation justified
and in other fonts and languages (EA6, `word-stops-compress2`, `-compress-kana2`, whose PDFs are the same but for a byte),
indents of part of a character Word's PDFs didn't round (GR17, `word-stops-grid-indents2`), lines that end between
right-to-left and left-to-right text, in Hebrew and in a right-to-left paragraph (AR3, `word-stops-rtl-ends`), and endnotes
after text that runs down the page (GR15d, GR15e, `word-stops-endnotes-down2`, `-down3`). Their PDFs, saved from Word on
2026-10-06 (round 26), showed what the table says. EA5's half-width small katakana fitted at the ends of their lines, so
whether the strict rules keep them from the start of one is still open, and EA6b showed Word fitting more on the lines of
a distributed paragraph with compression: a full stop or closing bracket at the end of a line took half its width, and a
line 4 twips too long was squeezed on, which isn't followed. `word-stops-east-asian4.ts` has the cases those leave open,
for the next batch (EA7, EA8, GR18, GR15f and VL1), with no PDF from Word yet: the half-width small katakana on a line
they don't fit, the document's own lists beyond the strict list, distributed lines a few twips too long with and without
compression, in Japanese and Chinese, indents a character or more before the margin, endnotes from a section followed by
one that runs as it does before one that runs another way, and lines of Latin text down the page, which Word's PDFs put
278 twips apart in Calibri 11 where across the page they are 268.55 (GR15e, `word-stops-east-asian` VD5), which isn't
followed either. `word-stops-arabic.ts` has the widths of
Arabic's letters in each form Word joins them in (AR1), which `word-stops-more-widths` and `word-stops-thai` TH3b, ten of
each letter in a row, showed joined, and lines of Arabic prose to check them by (AR2). Word kerns Arabic's letters side
by side, by pairs, in Arial and Times New Roman (as ten joined copies of a letter in `word-stops-more-widths` show) and in
Calibri, which isn't followed yet: `word-stops-arabic2.ts` writes every pair of the letters, for a later batch
(`word-stops-arabic-kerning`, AR4). Read Word's PDF of it with `word-stops-arabic.py`, which
each letter in a row, showed joined, and lines of Arabic prose to check them by (AR2). `word-stops-arabic2.ts` writes
every pair of the letters, as a word of the two and between tatweels (`word-stops-arabic-kerning`, AR4), whose PDF, from
round 26, showed Word drawing each as wide as its forms in Arial and Times New Roman: it doesn't kern them, and ten joined
copies of a letter in `word-stops-more-widths` W are as wide as their glyphs too, read again. Calibri's letters it kerns,
by pairs of their glyphs, by as much as 268 thousandths of an em, differently in the two contexts, and with the spaces
beside them, so Calibri's Arabic still stops. Read Word's PDF of it with `word-stops-arabic-kerning.py`, and check the
layout's forms by it with `word-stops-arabic-kerning.ts`. Read `word-stops-arabic`'s with `word-stops-arabic.py`, which
reads `word-stops-arabic.json`, and `scripts/generate-arabic-widths.ts` writes `src/text-layout/arabic-widths.ts` from
what it reads. `word-stops-more-widths.ts` writes
the same characters as its W in Office's other fonts with `STOPS_FONTS=office` (`word-stops-more-widths-office`), and in
@@ -0,0 +1,118 @@
# Reads how Word kerns Arabic's letters from a PDF of word-stops-arabic2.ts saved from Word (AR4): each paragraph, after
# its label in Calibri 6 such as "AR4 Arial 0628 p", is a right-to-left run of 42 words, one for each second letter in
# the order of the letters, each the first letter and the second (p) or the two between tatweels (t), with a space between
# each. A word's kerning is how far its glyphs' advances, which the PDF's font widths give, fall short of how wide Word
# draws it, from its first glyph to the end of its last, in thousandths of an em of its size, 10 points.
#
# python3 word-stops-arabic-kerning.py word-stops-arabic-kerning.pdf [--json]
#
# It reads the PDF with word-stops-more-widths.py's functions. Glyphs the PDF's ToUnicode maps to nothing, as Calibri's
# letters mostly are, are letters all the same, and those of no width are marks, which take no room. Without --json it
# prints, for each face and context, the words found, the largest kerning and how many words are kerned by more than
# 10 thousandths, and fails when the PDF has no AR4 paragraph or one of them hasn't 42 words; with --json it writes each word's drawn width and its glyphs' advances, by face, context and pair, for
# word-stops-arabic-kerning.ts to check the layout's widths of the forms by.
# cspell:ignore tatweel tatweels
import importlib.util
import json
import os
import re
import sys
sys.dont_write_bytecode = True
spec = importlib.util.spec_from_file_location(
"more_widths", os.path.join(os.path.dirname(os.path.abspath(__file__)), "word-stops-more-widths.py")
)
pdf = importlib.util.module_from_spec(spec)
spec.loader.exec_module(pdf)
SIZE = 10
LABEL_SIZE = 6
# The letters, in the order of the words of each paragraph
LETTERS = [chr(code) for code in [*range(0x621, 0x63B), *range(0x641, 0x64B), 0x67E, 0x686, 0x698, 0x6A9, 0x6AF, 0x6CC]]
LABEL = re.compile(r"AR4 (.+?)( bold)? ([0-9a-f]{4}) ([pt])")
def is_label(glyph):
return abs(glyph["size"] - LABEL_SIZE) < 0.5
def paragraphs_of(glyphs):
"""Each paragraph's label and the glyphs after it, in the order they are drawn"""
paragraphs = []
index = 0
while index < len(glyphs):
if is_label(glyphs[index]):
label = ""
while index < len(glyphs) and is_label(glyphs[index]):
label += glyphs[index]["text"]
index += 1
paragraphs.append((label.strip(), []))
else:
if paragraphs:
paragraphs[-1][1].append(glyphs[index])
index += 1
return paragraphs
def words_of(glyphs):
"""A paragraph's words in the order of the letters: its lines from the top, each right to left, split at the spaces"""
drawn = sorted((glyph for glyph in glyphs if glyph["width"] > 0), key=lambda glyph: -glyph["y"])
lines = []
for glyph in drawn:
if lines and abs(lines[-1][0]["y"] - glyph["y"]) * 20 < 120:
lines[-1].append(glyph)
else:
lines.append([glyph])
words = []
for line in lines:
line.sort(key=lambda glyph: glyph["x"])
of_line = []
word = []
for glyph in line:
if glyph["text"] == " ":
if word:
of_line.append(word)
word = []
else:
word.append(glyph)
if word:
of_line.append(word)
words.extend(reversed(of_line))
return words
def main(path):
found = pdf.objects(open(path, "rb").read())
glyphs = [glyph for page in pdf.pages_of(found) for glyph in pdf.glyphs_of(found, page)]
read = {}
for label, drawn in paragraphs_of(glyphs):
match = LABEL.match(label)
if not match:
continue
face = match.group(1) + (" bold" if match.group(2) else "")
first, context = chr(int(match.group(3), 16)), match.group(4)
words = words_of(drawn)
if len(words) != len(LETTERS):
sys.exit(f"{face} {context} {match.group(3)}: {len(words)} words, not {len(LETTERS)}")
for second, word in zip(LETTERS, words):
last = word[-1]
extent = (last["x"] + last["width"] / 1000 * SIZE - word[0]["x"]) * 1000 / SIZE
read.setdefault(face, {}).setdefault(context, {})[first + second] = {
"width": round(extent, 1),
"advances": [round(glyph["width"], 1) for glyph in reversed(word)],
}
if not read:
sys.exit(f"No AR4 paragraphs in {path}")
if "--json" in sys.argv:
print(json.dumps(read, ensure_ascii=False, sort_keys=True, separators=(",", ":")))
return
for face, contexts in read.items():
for context, words in contexts.items():
kerning = {pair: word["width"] - sum(word["advances"]) for pair, word in words.items()}
most = max(kerning, key=lambda pair: abs(kerning[pair]))
kerned = sum(1 for amount in kerning.values() if abs(amount) > 10)
print(f"{face} {context}: {len(words)} words, kerned by {kerning[most]:.1f} at most ({most}), {kerned} by more than 10")
if __name__ == "__main__":
main(sys.argv[1])
@@ -0,0 +1,46 @@
/**
* Checks the layout's widths of Arabic's joined forms against Word's PDF of `word-stops-arabic2.ts` (AR4), as
* `word-stops-arabic-kerning.py --json` reads it: each pair of the letters as a word of the two, and between tatweels,
* measured in the forms the layout joins them in, against how wide Word draws it, in the faces whose widths the layout has.
*
* Usage:
* python3 scripts/layout-probes/stops2/word-stops-arabic-kerning.py scripts/layout-probes/stops2/word-stops-arabic-kerning.pdf --json \
* > build/word-probes/word-stops-arabic-kerning.word.json
* npm run run-ts -- scripts/layout-probes/stops2/word-stops-arabic-kerning.ts build/word-probes/word-stops-arabic-kerning.word.json
*/
// cspell:ignore tatweel tatweels
import { readFileSync } from "node:fs";
import { arabicFaceOf, joinedWidthsOf } from "../../../src/text-layout/arabic-shaping";
const [path] = process.argv.slice(2);
if (!path) {
console.error("Usage: npm run run-ts -- scripts/layout-probes/stops2/word-stops-arabic-kerning.ts <Word's widths, as JSON>");
process.exit(1);
}
type Read = Readonly<Record<string, Readonly<Record<string, Readonly<Record<string, { readonly width: number }>>>>>>;
const read: Read = JSON.parse(readFileSync(path, "utf8"));
const TATWEEL = "ـ";
for (const [faceName, contexts] of Object.entries(read)) {
const bold = faceName.endsWith(" bold");
const face = arabicFaceOf(bold ? faceName.slice(0, -" bold".length) : faceName, bold, false);
if (face === undefined) {
console.log(`${faceName}: no widths in the layout`);
continue;
}
for (const [context, words] of Object.entries(contexts)) {
const differences = Object.entries(words).map(([pair, { width }]) => {
const characters = [...(context === "p" ? pair : `${TATWEEL}${pair}${TATWEEL}`)];
const widths = joinedWidthsOf(characters, face);
const predicted = characters.reduce((sum, _, index) => sum + widths.get(index)!, 0);
return { pair, difference: width - predicted };
});
const most = differences.reduce((largest, next) => (Math.abs(next.difference) > Math.abs(largest.difference) ? next : largest));
const mean = differences.reduce((sum, { difference }) => sum + difference, 0) / differences.length;
console.log(
`${faceName} ${context}: ${differences.length} words, ${most.difference.toFixed(1)} thousandths from the layout's at most (${most.pair}), ${mean.toFixed(2)} on average`,
);
}
}
@@ -3,7 +3,9 @@
* letter's forms as wide as their glyphs in Arial, Times New Roman (which Word draws Cambria's Arabic in) and Courier New,
* but `word-stops-more-widths.ts` (W) showed ten copies of a letter joined in a word as much as 23 thousandths of an em a
* letter wider or narrower than their forms in the first two, so Word kerns their letters by pairs, which docx/layout stops
* at. Calibri's were kerned in AR1 too, an alef before a zero-width non-joiner and alef 34 thousandths narrower.
* at. Calibri's were kerned in AR1 too, an alef before a zero-width non-joiner and alef 34 thousandths narrower. Its PDF, saved in round 26, showed Word drawing every pair as wide as its
* forms in Arial and Times New Roman, so it doesn't kern them there; Calibri's it kerns by pairs of their glyphs (see the
* README).
*
* word-stops-arabic-kerning.docx, in Arial, Times New Roman and Calibri, plain and bold, at 10 points, in right-to-left
* runs:
@@ -0,0 +1,209 @@
/**
* Probes of what Word's PDFs of `word-stops-east-asian3.ts` (round 26) left open, for a later batch Word saves. Japanese
* in MS Mincho 10.5, 42 ideographs to a line of 9026 twips, as there.
*
* word-stops-strict3.docx, with Word's strict rules (w:strictFirstAndLastChars):
* EA7a: each half-width small katakana and the half-width prolonged sound mark after 42 ideographs, in a paragraph
* indented 200 twips from the right, so that it doesn't fit on the first line (EA5's did): whether it starts the
* second, or Word keeps it from the start of a line, moving the ideograph before it with it
* word-stops-strict-list2.docx, with the strict rules and the document's own list of the characters that can't start a
* line of Japanese, 、, 。 and あ, which Word's strict list doesn't have (EA7b): あ and ぁ after 42 ideographs: whether
* Word keeps あ from the start of a line by the document's list too, or takes its strict list alone, as EA5L showed for ぁ
* word-stops-strict-list3.docx, with the strict rules and the document's own list of the characters that can't end a line
* of Japanese, 、 alone (EA7c): 「 as the 42nd character: whether it ends the line, as the document's list lets it, or
* moves on, as Word's keeps it from the end of one
* word-stops-compress3.docx, with punctuation compressed (w:characterSpacingControl compressPunctuation), each paragraph
* after a line that names it:
* EA8a: 43 ideographs distributed, 9030 twips, in paragraphs indented 0, 2, 6, 16, 36 and 96 twips from the right, so
* that they are 4, 6, 10, 20, 40 and 100 twips too long for their line: how far over its width a line Word squeezes on
* is (EA6b's was 4 twips too long)
* EA8b, EA8c: 42 ideographs, 。 (b) or 」 (c) and 10 ideographs, distributed: whether the punctuation ends the first
* line, as it took half its width at the end of EA6b's lines
* EA8d: EA8b's text aligned left, and EA8e justified
* EA8f, EA8g: EA8a's first paragraph and EA8b's text in Chinese, in SimSun (zh-CN), distributed; EA8h: EA8b's text in
* Chinese justified
* word-stops-distribute.docx: EA8a to EA8c again, with punctuation not compressed (EA8i to EA8k), to tell what
* distribution does alone
* word-stops-grid-indents3.docx, on GR14's grid that snaps to characters, of cells of 225.65 twips (GR18):
* GR18a: indented 1.5 characters before the margin (leftChars -150); GR18b: 2.5 before it (leftChars -250)
* GR18c: indented half a character before the margin and hanging one (leftChars -50, hangingChars 100)
* GR18d: indented 1.2 characters and its first line 0.9 more (leftChars 120, firstLineChars 90): whether the first
* line is at the 3rd cell or the 4th
* word-stops-endnotes-down4.docx (GR15f): an endnote from a section running down the page, followed by one down it too,
* then one across it: whether Word ends it with its own section, with the second, or at the end of the document
* word-stops-vertical-lines.docx (VL1), sections running down the page: how far apart Word puts their lines, which its
* PDFs showed 278 twips in Calibri 11 (GR15e, `word-stops-east-asian.ts` VD5) where across the page they are 268.55:
* VL1a: 12 paragraphs of a line each, in Calibri 11; VL1b: a paragraph of prose of several lines in Calibri 11; VL1c,
* VL1d, VL1e: the prose in Arial, Times New Roman and Courier New 11; VL1f: in Calibri 14; VL1g: 12 lines of Japanese
* in MS Mincho 10.5 after a label in Calibri 10.5, one with a word of Calibri 11 and one with a superscript
*
* Usage: npm run run-ts -- scripts/layout-probes/stops2/word-stops-east-asian4.ts [folder]
*/
import {
AlignmentType,
DocumentGridType,
EndnoteReferenceRun,
type ISectionOptions,
PageTextDirectionType,
Paragraph,
SectionType,
TextRun,
} from "docx";
import { PAGE, injectIntoParagraph, line, marker, prose, settings, write } from "./kit";
const MINCHO = { font: { eastAsia: "MS Mincho", ascii: "Calibri", hAnsi: "Calibri" }, size: 21 } as const;
const SIMSUN = { font: { eastAsia: "SimSun", ascii: "Calibri", hAnsi: "Calibri" }, size: 21 } as const;
const JAPANESE = "測量は夏に船と徒歩で行われ、灯台から河口まで続いた。記録には見つかったものが書かれている。";
const IDEOGRAPH = "永";
const LABEL = { size: 14 } as const;
/** A paragraph of text in a font and language, in MS Mincho 10.5 and Japanese by default */
const inLanguage = (text: string, language = "ja-JP", run: object = MINCHO, options: object = {}): Paragraph =>
new Paragraph({ ...options, children: [new TextRun({ text, ...run, language: { eastAsia: language } })] });
const hex = (character: string): string => character.codePointAt(0)!.toString(16).padStart(4, "0");
// EA7: the strict rules' cases still open
// cspell:disable-next-line
const HALF_WIDTH = [..."ァィゥェォャュョッー"];
await write({
name: "word-stops-strict3",
children: HALF_WIDTH.flatMap((character) => [
line(`EA7a S ja-JP ${hex(character)}`, {}, LABEL),
inLanguage(`${IDEOGRAPH.repeat(42)}${character}${IDEOGRAPH.repeat(3)}`, "ja-JP", MINCHO, { indent: { right: 200 } }),
]),
injections: [settings("<w:strictFirstAndLastChars/>")],
});
await write({
name: "word-stops-strict-list2",
children: [..."あぁ"].flatMap((character) => [
line(`EA7b S ja-JP ${hex(character)}`, {}, LABEL),
inLanguage(`${IDEOGRAPH.repeat(42)}${character}${IDEOGRAPH.repeat(3)}`),
]),
injections: [settings('<w:noLineBreaksBefore w:lang="ja-JP" w:val="、。あ"/>', "<w:strictFirstAndLastChars/>")],
});
await write({
name: "word-stops-strict-list3",
children: [line("EA7c E ja-JP 300c", {}, LABEL), inLanguage(`${IDEOGRAPH.repeat(41)}「${IDEOGRAPH.repeat(4)}`)],
injections: [settings('<w:noLineBreaksAfter w:lang="ja-JP" w:val="、"/>', "<w:strictFirstAndLastChars/>")],
});
// EA8: distributed and justified lines with and without compression
const OVER = [0, 2, 6, 16, 36, 96];
const distributed = { alignment: AlignmentType.DISTRIBUTE } as const;
const squeezed = (name: string, run: object = MINCHO, language = "ja-JP"): readonly Paragraph[] =>
OVER.flatMap((indent) => [
line(`${name} ${indent} above`),
inLanguage(IDEOGRAPH.repeat(43), language, run, { ...distributed, indent: { right: indent } }),
]);
const ended = (name: string, punctuation: string, options: object, run: object = MINCHO, language = "ja-JP"): readonly Paragraph[] => [
line(`${name} above`),
inLanguage(`${IDEOGRAPH.repeat(42)}${punctuation}${IDEOGRAPH.repeat(10)}`, language, run, options),
];
await write({
name: "word-stops-compress3",
children: [
...squeezed("EA8a"),
...ended("EA8b", "。", distributed),
...ended("EA8c", "」", distributed),
...ended("EA8d", "。", {}),
...ended("EA8e", "。", { alignment: AlignmentType.JUSTIFIED }),
line("EA8f 0 above"),
inLanguage(IDEOGRAPH.repeat(43), "zh-CN", SIMSUN, distributed),
...ended("EA8g", "。", distributed, SIMSUN, "zh-CN"),
...ended("EA8h", "。", { alignment: AlignmentType.JUSTIFIED }, SIMSUN, "zh-CN"),
line("EA8 below"),
],
injections: [settings('<w:characterSpacingControl w:val="compressPunctuation"/>')],
});
await write({
name: "word-stops-distribute",
children: [...squeezed("EA8i"), ...ended("EA8j", "。", distributed), ...ended("EA8k", "」", distributed), line("EA8 below")],
});
// GR18: indents on a grid that snaps to characters, a character or more before the margin, and a first line rounded otherwise
const SNAP = { type: DocumentGridType.SNAP_TO_CHARS, linePitch: 360, charSpace: 210 } as const;
const INDENTS: readonly (readonly [string, string])[] = [
["GR18a", '<w:ind w:left="-315" w:leftChars="-150"/>'],
["GR18b", '<w:ind w:left="-525" w:leftChars="-250"/>'],
["GR18c", '<w:ind w:left="-105" w:leftChars="-50" w:hanging="210" w:hangingChars="100"/>'],
["GR18d", '<w:ind w:left="252" w:leftChars="120" w:firstLine="189" w:firstLineChars="90"/>'],
];
await write({
name: "word-stops-grid-indents3",
sections: [
{
properties: { ...PAGE, grid: SNAP } as never,
children: [
line("GR18 above"),
...INDENTS.map(
([name]) =>
new Paragraph({ children: [new TextRun({ text: `${name} ${JAPANESE.repeat(2)}`, ...MINCHO }), marker(name)] }),
),
line("GR18 below"),
],
},
],
injections: INDENTS.map(([name, indent]) => injectIntoParagraph(name, { pPr: indent })),
});
// GR15f and VL1: sections whose text runs down the page
const DOWN = { textDirection: PageTextDirectionType.TOP_TO_BOTTOM_RIGHT_TO_LEFT };
const section = (name: string, children: readonly Paragraph[], down: boolean): ISectionOptions => ({
properties: {
...PAGE,
type: SectionType.NEXT_PAGE,
page: { ...PAGE.page, ...(down ? DOWN : {}) },
} as never,
children: [line(`${name} above`), ...children, line(`${name} below`)],
});
await write({
name: "word-stops-endnotes-down4",
options: {
endnotes: { 1: { children: [new Paragraph({ children: [new TextRun({ text: `GR15f endnote ${JAPANESE}`, ...MINCHO })] })] } },
},
sections: [
section(
"GR15f",
[new Paragraph({ children: [new TextRun({ text: `GR15f ${JAPANESE}`, ...MINCHO }), new EndnoteReferenceRun(1)] })],
true,
),
section("GR15f down", [line("GR15f down section")], true),
section("GR15f across", [line("GR15f across section")], false),
],
});
const PROSE = prose(150);
const inFont = (name: string, font: string, size = 22): Paragraph =>
new Paragraph({ children: [new TextRun({ text: `${name} ${PROSE}`, font, size })] });
await write({
name: "word-stops-vertical-lines",
sections: [
section(
"VL1a",
Array.from({ length: 12 }, (_, index) => line(`VL1a line ${index + 1}`)),
true,
),
section("VL1b", [inFont("VL1b", "Calibri")], true),
section("VL1c", [inFont("VL1c", "Arial")], true),
section("VL1d", [inFont("VL1d", "Times New Roman")], true),
section("VL1e", [inFont("VL1e", "Courier New")], true),
section("VL1f", [inFont("VL1f", "Calibri", 28)], true),
section(
"VL1g",
[
...Array.from(
{ length: 10 },
(_, index) => new Paragraph({ children: [new TextRun({ text: `VL1g ${index + 1} ${JAPANESE}`, ...MINCHO })] }),
),
new Paragraph({
children: [new TextRun({ text: `VL1g 11 ${JAPANESE}`, ...MINCHO }), new TextRun({ text: " lighthouse", size: 22 })],
}),
new Paragraph({
children: [new TextRun({ text: `VL1g 12 ${JAPANESE}`, ...MINCHO }), new TextRun({ text: "2", superScript: true })],
}),
],
true,
),
],
});
Binary file not shown.
Binary file not shown.
Binary file not shown.
+94 -42
View File
@@ -5443,7 +5443,7 @@ describe("readDocument", () => {
expect(paragraphOf(across("31", { "w:vertCompress": 1 })).unsupported).to.equal("text across in vertical text");
});
it("should read footnotes of text that runs down the page, and stop at its endnotes, which Word ends with their section before text that runs another way (VD6, GR13, GR15b)", () => {
it("should read footnotes and endnotes of text that runs down the page, ending endnotes with their section before text that runs another way (VD6, GR13, GR15b, GR15d, GR15e)", () => {
const noted = (kind: "footnotes" | "endnotes"): DocumentContent =>
readWritten({
[kind]: { 1: { children: [new Paragraph("Note")] } },
@@ -5464,10 +5464,14 @@ describe("readDocument", () => {
const footnoted = noted("footnotes");
expect(footnoted.unsupported).to.equal(undefined);
expect([...footnoted.footnotes.values()][0][0].unsupported).to.equal(undefined);
expect(noted("endnotes").unsupported).to.equal("endnotes after text that runs down the page");
// And from text across the page that text down it follows, or down the page that text across it follows
// Endnotes after text that runs down the page go at the end of the document, down the page too (GR15d)
const endnotedDown = noted("endnotes");
expect(endnotedDown.unsupported).to.equal(undefined);
expect(endnotedDown.endnotesAfter).to.equal(undefined);
// Those from text across the page that text down it follows, or down the page that text across it follows, end
// with their own section, whether or not the last section runs as theirs does (GR13, GR15b, GR15e)
const DOWN = { page: { textDirection: PageTextDirectionType.TOP_TO_BOTTOM_RIGHT_TO_LEFT } };
const endnoted = (...properties: readonly ISectionOptions["properties"][]): string | undefined =>
const endnoted = (...properties: readonly ISectionOptions["properties"][]): DocumentContent =>
readWritten({
endnotes: { 1: { children: [new Paragraph("Note")] } },
sections: [
@@ -5477,21 +5481,38 @@ describe("readDocument", () => {
},
...properties.slice(1).map((more) => ({ properties: more, children: [new Paragraph("More")] })),
],
}).unsupported;
const STOP = "endnotes from a section followed by one whose text runs another way";
expect(endnoted(undefined, DOWN, undefined)).to.equal(STOP);
expect(endnoted(DOWN, undefined)).to.equal(STOP);
expect(endnoted(DOWN, DOWN)).to.equal("endnotes after text that runs down the page");
// But not text down the page before theirs
expect(endnoted(DOWN, undefined, undefined)).to.equal(STOP);
});
/** The sections the endnotes' blocks, their separator's and the note's, go at the end of */
const endsOf = (content: DocumentContent): readonly (number | undefined)[] | undefined => {
expect(content.unsupported).to.equal(undefined);
expect(content.endnotesAfter?.length ?? content.endnotes.length).to.equal(content.endnotes.length);
return content.endnotesAfter === undefined ? undefined : [...new Set(content.endnotesAfter)];
};
expect(endsOf(endnoted(undefined, DOWN, undefined))).to.deep.equal([0]);
expect(endsOf(endnoted(DOWN, undefined))).to.deep.equal([0]);
expect(endsOf(endnoted(DOWN, undefined, DOWN))).to.deep.equal([0]);
expect(endsOf(endnoted(undefined, DOWN, DOWN))).to.deep.equal([0]);
// Not after one that runs as it does, which may run on before a change (GR15a, GR15c), or to the end of the document
expect(endsOf(endnoted(DOWN, DOWN))).to.equal(undefined);
expect(endsOf(endnoted(undefined, undefined))).to.equal(undefined);
// Where that section is followed by one that runs another way hasn't been seen
expect(endnoted(DOWN, DOWN, undefined).unsupported).to.equal(
"endnotes from a section followed by one whose text runs as it does, before one whose text runs another way",
);
expect(endnoted(undefined, undefined, DOWN, DOWN).unsupported).to.equal(
"endnotes from a section followed by one whose text runs as it does, before one whose text runs another way",
);
// Text down the page before theirs doesn't end them
expect(
readWritten({
endnotes: { 1: { children: [new Paragraph("Note")] } },
sections: [
{ properties: DOWN, children: [new Paragraph("First")] },
{ children: [new Paragraph({ children: [new TextRun("Text"), new EndnoteReferenceRun(1)] })] },
],
}).unsupported,
endsOf(
readWritten({
endnotes: { 1: { children: [new Paragraph("Note")] } },
sections: [
{ properties: DOWN, children: [new Paragraph("First")] },
{ children: [new Paragraph({ children: [new TextRun("Text"), new EndnoteReferenceRun(1)] })] },
],
}),
),
).to.equal(undefined);
});
});
@@ -5564,46 +5585,77 @@ describe("readDocument", () => {
// cspell:enable
});
it("should break Japanese by Word's strict rules, and leave its punctuation compressed as it is, aligned left, and stop at the cases Word hasn't been seen with (EA4)", () => {
const inLanguage = (language: string, text = "「測量」は"): object =>
p(r(rPr({ "w:lang": { _attr: { "w:eastAsia": language } } }), t(text)));
it("should break Japanese by Word's strict rules, with Word's list in place of the document's, leave its punctuation compressed as it is, aligned left or justified, and stop at the cases Word hasn't been seen with (EA4, EA5, EA6)", () => {
const inLanguage = (language: string, text = "「測量」は", alignment?: string): object =>
p(
...(alignment === undefined ? [] : [pPr(value("w:jc", alignment))]),
r(rPr({ "w:lang": { _attr: { "w:eastAsia": language } } }), t(text)),
);
const japanese = inLanguage("ja-JP");
const inNoLanguage = p(r(t("「測量」は")));
const strict = { "w:strictFirstAndLastChars": {} };
// Word's strict rules, which keep small kana from the start of a line (word-stops-east-asian2.ts EA4a)
// Word's strict rules, which keep small kana from the start of a line of Japanese (word-stops-east-asian2.ts EA4a),
// and change nothing in Chinese or Korean (word-stops-east-asian3.ts EA5)
const strictly = readWithSettings([japanese], [strict]);
expect(paragraphOf(strictly).unsupported).to.equal(undefined);
expect(strictly.breakRules).to.deep.equal({ strict: true });
expect(paragraphOf(readWithSettings([inLanguage("zh-CN")], [strict])).unsupported).to.equal(
"the strict rules for the characters that can't start a line, in text in Chinese or Korean",
);
const JAPANESE_STOP =
"the strict rules for the characters that can't start a line of Japanese, with the document's own list of them or before half-width small katakana";
expect(paragraphOf(readWithSettings([inLanguage("zh-CN")], [strict])).unsupported).to.equal(undefined);
expect(paragraphOf(readWithSettings([inLanguage("ko-KR")], [strict])).unsupported).to.equal(undefined);
// Whether they keep half-width small katakana from the start of a line hasn't been seen
// cspell:disable-next-line
expect(paragraphOf(readWithSettings([inLanguage("ja-JP", "記録ァ")], [strict])).unsupported).to.equal(JAPANESE_STOP);
const ownList = { "w:noLineBreaksBefore": { _attr: { "w:lang": "ja-JP", "w:val": "、。" } } };
const listed = readWithSettings([japanese], [strict, ownList]);
expect(paragraphOf(listed).unsupported).to.equal(JAPANESE_STOP);
expect(paragraphOf(readWithSettings([inLanguage("ja-JP", "記録ァ")], [strict])).unsupported).to.equal(
"the strict rules for the characters that can't start a line of Japanese, before half-width small katakana",
);
// Word takes its strict list in place of the document's own list of the characters that can't start a line (EA5L),
// but one with characters its list doesn't have, or the document's own list of those that can't end one, hasn't
// been seen with them
const ownList = (name: string, val: string): object => ({ [name]: { _attr: { "w:lang": "ja-JP", "w:val": val } } });
const listed = readWithSettings([japanese], [strict, ownList("w:noLineBreaksBefore", "、。")]);
expect(paragraphOf(listed).unsupported).to.equal(undefined);
expect(listed.breakRules).to.deep.equal({ lists: { japanese: { noLineStart: "、。" } }, strict: true });
// Punctuation compressed, and kana, left as it is in Japanese aligned left (EA4b, EA4c)
const BEYOND =
"the strict rules for the characters that can't start a line of Japanese, with the document's own list of those that can't end one, or of those that can't start one with characters Word's strict list doesn't have";
expect(paragraphOf(readWithSettings([japanese], [strict, ownList("w:noLineBreaksBefore", "、。永")])).unsupported).to.equal(
BEYOND,
);
expect(paragraphOf(readWithSettings([japanese], [strict, ownList("w:noLineBreaksAfter", "「")])).unsupported).to.equal(BEYOND);
expect(
paragraphOf(readWithSettings([inLanguage("zh-CN")], [strict, ownList("w:noLineBreaksAfter", "「")])).unsupported,
).to.equal(undefined);
expect(paragraphOf(readWithSettings([japanese], [ownList("w:noLineBreaksAfter", "「")])).unsupported).to.equal(undefined);
// Punctuation compressed, and kana, left as it is in Japanese aligned left, centred and justified (EA4b, EA4c, EA6a)
// and in Chinese aligned left (EA6e), but not in distributed Japanese, which fits more (EA6b), nor in justified or
// distributed Chinese, or in Korean, which haven't been seen
const compressed = value("w:characterSpacingControl", "compressPunctuationAndJapaneseKana");
expect(paragraphOf(readWithSettings([japanese], [compressed])).unsupported).to.equal(undefined);
const centred = p(pPr(value("w:jc", "center")), r(rPr({ "w:lang": { _attr: { "w:eastAsia": "ja-JP" } } }), t("「測量」は")));
expect(paragraphOf(readWithSettings([centred], [compressed])).unsupported).to.equal(undefined);
expect(paragraphOf(readWithSettings([inLanguage("ko-KR")], [compressed])).unsupported).to.equal(
"punctuation compressed in text in Chinese or Korean",
expect(paragraphOf(readWithSettings([inLanguage("ja-JP", "「測量」は", "center")], [compressed])).unsupported).to.equal(
undefined,
);
const justified = p(pPr(value("w:jc", "both")), r(rPr({ "w:lang": { _attr: { "w:eastAsia": "ja-JP" } } }), t("「測量」は")));
expect(paragraphOf(readWithSettings([justified], [compressed])).unsupported).to.equal(
"punctuation compressed in a justified or distributed paragraph of text in Japanese",
expect(paragraphOf(readWithSettings([inLanguage("ja-JP", "「測量」は", "both")], [compressed])).unsupported).to.equal(
undefined,
);
expect(paragraphOf(readWithSettings([inLanguage("ja-JP", "「測量」は", "distribute")], [compressed])).unsupported).to.equal(
"punctuation compressed in a distributed paragraph of text in Japanese",
);
expect(paragraphOf(readWithSettings([inLanguage("zh-CN")], [compressed])).unsupported).to.equal(undefined);
expect(paragraphOf(readWithSettings([inLanguage("zh-TW", "「測量」は", "both")], [compressed])).unsupported).to.equal(
"punctuation compressed in a justified or distributed paragraph of text in Chinese",
);
expect(paragraphOf(readWithSettings([inLanguage("ko-KR")], [compressed])).unsupported).to.equal(
"punctuation compressed in text in Korean",
);
expect(paragraphOf(readWithSettings([inLanguage("ko-KR", "「測量」は", "both")], [compressed])).unsupported).to.equal(
"punctuation compressed in text in Korean",
);
// Word lays out Japanese in no language as it does without them (word-stops-east-asian.ts EA1 to EA3)
const content = readWithSettings([inNoLanguage], [strict, value("w:characterSpacingControl", "compressPunctuation")]);
expect(content.unsupported).to.equal(undefined);
expect(paragraphOf(content).unsupported).to.equal(undefined);
expect(paragraphOf(readWithSettings([justified], [value("w:characterSpacingControl", "doNotCompress")])).unsupported).to.equal(
undefined,
);
expect(
paragraphOf(
readWithSettings([inLanguage("ja-JP", "「測量」は", "both")], [value("w:characterSpacingControl", "doNotCompress")]),
).unsupported,
).to.equal(undefined);
});
it("should mark a document printed as a booklet folded the other way round, or whose styles Word updates from its template, as unsupported", () => {
+67 -44
View File
@@ -26,6 +26,7 @@ import {
type ParagraphFormat,
READING_CONTEXT,
type RunFormat,
STRICT_JAPANESE_LIST,
TWIPS_PER_POINT,
type TabStop,
type TabStopSetting,
@@ -5473,17 +5474,25 @@ const joinedAcrossRuns = (items: readonly LayoutItem[]): boolean => {
type EastAsianRules = {
readonly strict: boolean;
readonly compressed: boolean;
/** Whether the document has its own list of the characters that can't start or end a line of Japanese */
readonly ownJapaneseList: boolean;
/**
* Whether the document's own list of the characters that can't start a line of Japanese has characters Word's strict
* list doesn't, or it has its own list of those that can't end one
*/
readonly ownJapaneseListBeyondStrict: boolean;
};
/** The document's settings for text in an East Asian language that Word lays out only in some of it, when it has any */
const readEastAsianRules = (settings: readonly XmlObject[]): EastAsianRules | undefined => {
const spacingControl = valueOf(settings, "w:characterSpacingControl");
const { japanese } = readKinsokuLists(settings);
const rules = {
strict: onOff(settings, "w:strictFirstAndLastChars") === true,
compressed: spacingControl !== undefined && spacingControl !== "doNotCompress",
ownJapaneseList: readKinsokuLists(settings).japanese !== undefined,
ownJapaneseListBeyondStrict:
japanese !== undefined &&
// A list without its own characters that can't end a line has those that can't start one
(japanese.noLineEnd !== undefined ||
[...japanese.noLineStart!].some((character) => !STRICT_JAPANESE_LIST.noLineStart.includes(character))),
};
return rules.strict || rules.compressed ? rules : undefined;
};
@@ -5498,12 +5507,19 @@ const HALF_WIDTH_SMALL_KANA = /[ァ-ッー]/u;
* can't. Word left the lines of Japanese text in no language as they are with them, as it leaves out its rules for the
* characters that can't start or end a line there (scripts/layout-probes/stops2/word-stops-east-asian.ts EA1 to EA3:
* small kana, iteration marks and closing brackets started lines, and opening brackets ended them, at 42 ideographs a
* line). In text in Japanese, its strict rules kept small kana from starting a line: lines of 37 ideographs and kana where
* 42 fit, ended before the ideograph before them (`word-stops-east-asian2.ts` EA4a). Punctuation compressed, or punctuation
* and kana, Word left as it is in Japanese text aligned left: lines of 41 ideographs, kana and brackets, as many as without
* (EA4b, EA4c). Those rules in Chinese and Korean text haven't been seen, nor the strict ones with the document's own list
* for Japanese, or before the half-width small katakana they may keep from the start of a line, nor compressed punctuation
* in a justified or distributed line, which may squeeze it to fit more.
* line). In text in Japanese, its strict rules kept each small kana and the prolonged sound mark from starting a line:
* lines of 41 ideographs where 42 fit, ended before the ideograph before them (`word-stops-east-asian2.ts` EA4a,
* `word-stops-east-asian3.ts` EA5), and with the document's own list of the characters that can't start one too, in
* place of which Word takes its strict list (EA5L). In Chinese and Korean they changed nothing: small kana and the
* prolonged sound mark started lines, as without them (EA5). Whether they keep the half-width small katakana, which
* Word's normal list lets start a line, from the start of one hasn't been seen, as EA5's fitted at the ends of their
* lines, nor the document's own list of the characters that can't end a line of Japanese with them, or its own list of
* those that can't start one with characters the strict list doesn't have. Punctuation compressed, or punctuation and
* kana, Word left as it is in Japanese aligned left and justified: lines of 41 ideographs, kana and brackets, as many as
* without, as far apart (EA4b, EA4c, EA6a), and in Chinese aligned left (EA6e). In a distributed paragraph of Japanese it
* fits more: a full stop or closing bracket at the end of a line takes half its width, and a line 4 twips too long is
* squeezed on (EA6b), which isn't followed. Compression in Japanese of other alignments, in justified or distributed
* Chinese, and in Korean hasn't been seen.
*/
const unknownEastAsianRules = (
rules: EastAsianRules | undefined,
@@ -5516,19 +5532,25 @@ const unknownEastAsianRules = (
return undefined;
}
const japanese = texts.filter((item) => kinsokuLanguageOf(item.language) === "japanese");
const otherLanguage = [...languages].some((language) => language !== "japanese");
if (rules.strict && (otherLanguage || rules.ownJapaneseList || japanese.some((item) => HALF_WIDTH_SMALL_KANA.test(item.text)))) {
return otherLanguage
? "the strict rules for the characters that can't start a line, in text in Chinese or Korean"
: "the strict rules for the characters that can't start a line of Japanese, with the document's own list of them or before half-width small katakana";
if (rules.strict && japanese.some((item) => HALF_WIDTH_SMALL_KANA.test(item.text))) {
return "the strict rules for the characters that can't start a line of Japanese, before half-width small katakana";
}
if (rules.strict && japanese.length > 0 && rules.ownJapaneseListBeyondStrict) {
return "the strict rules for the characters that can't start a line of Japanese, with the document's own list of those that can't end one, or of those that can't start one with characters Word's strict list doesn't have";
}
if (!rules.compressed) {
return undefined;
}
const stretched = alignment !== undefined && alignment !== "left" && alignment !== "center" && alignment !== "right";
if (rules.compressed && (otherLanguage || stretched)) {
return otherLanguage
? "punctuation compressed in text in Chinese or Korean"
: "punctuation compressed in a justified or distributed paragraph of text in Japanese";
if (languages.has("korean")) {
return "punctuation compressed in text in Korean";
}
return undefined;
if (stretched && (languages.has("simplifiedChinese") || languages.has("traditionalChinese"))) {
return "punctuation compressed in a justified or distributed paragraph of text in Chinese";
}
return stretched && alignment !== "justified" && japanese.length > 0
? "punctuation compressed in a distributed paragraph of text in Japanese"
: undefined;
};
/**
@@ -5932,9 +5954,6 @@ export const readContent = (writtenBody: XmlObject, writtenParts: DocumentParts,
// The section of each of the endnotes' blocks' references
// eslint-disable-next-line functional/prefer-readonly-type
const endnoteBlockSections: number[] = [];
// The section of each endnote's reference
// eslint-disable-next-line functional/prefer-readonly-type
const endnoteSections: number[] = [];
const endnoteNumbers = new Map<Block, string>();
// Each section's properties, which come after its paragraphs, so its notes are numbered as it says as they are read
const sectionElements = elements.flatMap((element) => {
@@ -6023,8 +6042,6 @@ export const readContent = (writtenBody: XmlObject, writtenParts: DocumentParts,
/** Keeps a note's blocks, by the marker at its reference, with the number it shows there */
const keepNote = (kind: NoteKind, marker: string, content: readonly Block[], label: string): void => {
if (kind === "endnote") {
// eslint-disable-next-line functional/immutable-data
endnoteSections.push(sections.length);
// eslint-disable-next-line functional/immutable-data
endnotes.push(...content);
// eslint-disable-next-line functional/immutable-data
@@ -6189,24 +6206,41 @@ export const readContent = (writtenBody: XmlObject, writtenParts: DocumentParts,
// Where the endnotes go: at the end of the document, as Word puts them where the settings don't put them at the end of
// each section, though its sections do (`word-stops-endnotes.docx` NE2), or, where the settings do, at the end of each
// section, but those of a section that suppresses its own (`w:noEndnote`), which go at the end of the next that
// doesn't, or of the document (stops2/word-stops-notes2.ts NE6)
// doesn't, or of the document (stops2/word-stops-notes2.ts NE6). Those of a section followed by one whose text runs
// another way, down the page or across it, end with their own section, before it, whether or not a later section runs
// as theirs does again, and after text that runs down the page they run down it too (word-stops-east-asian.ts GR13,
// word-stops-east-asian2.ts GR15b, word-stops-east-asian3.ts GR15d, GR15e). Sections on other grids don't end them
// (GR15a, GR15c). Where those of a section followed by one that runs as it does, before one that runs another way, go
// hasn't been seen
const endnotesAtSectionEnds =
(readNoteProperties(find(settings, "w:endnotePr")).position ?? NOTE_DEFAULTS.endnote.position) === "sectEnd";
/** Whether a section's text runs another way than the one before it */
const runsAnotherWay = (section: number): boolean => sections[section].textRunsDown !== sections[section - 1].textRunsDown;
/**
* The section at whose end each endnote's block goes, where the settings put them at the end of each section: its own,
* or the next that doesn't suppress its own, found once for each section from the last back, however many in a row do
* The section at whose end the endnotes referred to from each section go: where the settings put them at the end of each
* section, its own, or the next that doesn't suppress its own, and otherwise its own where the next section's text runs
* another way, or the last, found once for each section from the last back, however many in a row do
*/
const endnoteEnds = (): readonly number[] => {
const ends = sections.map((_, section) => section);
for (let section = sections.length - 2; section >= 0; section--) {
if (onOff(childrenOf(sectionElements[section]), "w:noEndnote") === true) {
if (
endnotesAtSectionEnds ? onOff(childrenOf(sectionElements[section]), "w:noEndnote") === true : !runsAnotherWay(section + 1)
) {
// eslint-disable-next-line functional/immutable-data
ends[section] = ends[section + 1];
}
}
return endnoteBlockSections.map((section) => ends[section]);
return ends;
};
const endnotesAfter = endnotesAtSectionEnds ? endnoteEnds() : [];
const endnoteEndsOfSections = endnoteEnds();
const endnotesAfter = endnoteBlockSections.map((section) => endnoteEndsOfSections[section]);
// Endnotes from a section followed by one that runs as it does, before one that runs another way, go at the end of
// neither their own section nor the last, where Word hasn't been seen putting them
const endnoteEndsUnsupported =
!endnotesAtSectionEnds && endnotesAfter.some((end, index) => end !== endnoteBlockSections[index] && end !== sections.length - 1)
? "endnotes from a section followed by one whose text runs as it does, before one whose text runs another way"
: undefined;
/**
* Why the notes of a kind can't be laid out yet, when Word numbers or places them in a way not yet followed: endnotes
@@ -6225,7 +6259,7 @@ export const readContent = (writtenBody: XmlObject, writtenParts: DocumentParts,
: kind === "footnote" &&
all.some(({ position }, section) => position === "beneathText" && sections[section].columns.length > 1)
? "footnotes below the text of columns"
: kind === "endnote" && endnotesAtSectionEnds && endnotesAfter.some((section) => onPageBefore(section + 1))
: kind === "endnote" && endnotesAfter.some((section) => onPageBefore(section + 1))
? "endnotes at the end of a section before one that starts on its page"
: undefined;
};
@@ -6246,7 +6280,7 @@ export const readContent = (writtenBody: XmlObject, writtenParts: DocumentParts,
if (endnotes.length === 0) {
return { endnotes: [] };
}
if (!endnotesAtSectionEnds) {
if (!endnotesAtSectionEnds && endnotesAfter.every((end) => end === sections.length - 1)) {
return { endnotes: [...readEndnoteSeparator("separator"), ...endnotes] };
}
const ends = [...new Set(endnotesAfter)];
@@ -6286,18 +6320,7 @@ export const readContent = (writtenBody: XmlObject, writtenParts: DocumentParts,
documentContent.unsupported ??
(footnotes.size > 0 ? notesUnsupported("footnote") : undefined) ??
(endnotes.length > 0 ? notesUnsupported("endnote") : undefined) ??
// Endnotes follow the last section's text, on its grid, after sections on other grids too
// (stops2/word-stops-east-asian2.ts GR15a, GR15c). Word ends those of a section followed by one whose text runs
// another way, down the page or across it, with their own section, rather than at the end of the document
// (word-stops-east-asian.ts GR13, word-stops-east-asian2.ts GR15b), which isn't followed. Where they go
// after text that runs down the page hasn't been seen without that
(endnoteSections.some((section) =>
sections.slice(section + 1).some(({ textRunsDown }) => textRunsDown !== sections[section].textRunsDown),
)
? "endnotes from a section followed by one whose text runs another way"
: endnoteSections.length > 0 && sections[sections.length - 1].textRunsDown !== undefined
? "endnotes after text that runs down the page"
: undefined) ??
endnoteEndsUnsupported ??
(unwrittenNumber ? "notes numbered in a format not yet written" : undefined) ??
unseenNumbering,
}),
+1 -18
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { arabicFaceOf, isJoinedLetter, joinedWidthsOf, joinsAcross, unknownArabicKerning } from "./arabic-shaping";
import { arabicFaceOf, isJoinedLetter, joinedWidthsOf, joinsAcross } from "./arabic-shaping";
// cspell:disable
@@ -75,23 +75,6 @@ describe("isJoinedLetter", () => {
});
});
describe("unknownArabicKerning", () => {
it("should find Arabic letters side by side in the fonts Word kerns them in, but not across a space, tatweel or zero-width non-joiner", () => {
const KERNED = "Arabic letters side by side, which Word kerns by pairs not yet known";
expect(unknownArabicKerning("بلا", "Arial")).to.equal(KERNED);
expect(unknownArabicKerning("ب\u064eب", "Times New Roman")).to.equal(KERNED);
expect(unknownArabicKerning("ب ب", "Cambria")).to.equal(undefined);
expect(unknownArabicKerning("بـب", "Arial")).to.equal(undefined);
expect(unknownArabicKerning("ب\u200cب", "Arial")).to.equal(undefined);
// Nor lam and an alef, which Word joins into one glyph, but the letter before them
expect(unknownArabicKerning("لا", "Arial")).to.equal(undefined);
expect(unknownArabicKerning("ل\u064eأ", "Times New Roman")).to.equal(undefined);
expect(unknownArabicKerning("بلا", "Arial")).to.equal(KERNED);
// Nor in Courier New, which Word doesn't kern
expect(unknownArabicKerning("بلا", "Courier New")).to.equal(undefined);
});
});
describe("joinsAcross", () => {
it("should find Arabic letters that join from one run's text to the next's, across marks", () => {
expect(joinsAcross("كتب", "ب")).to.equal(true);
+4 -29
View File
@@ -96,41 +96,16 @@ export const arabicFaceOf = (name: string, bold: boolean, italic: boolean): Arab
return font === undefined || italic ? undefined : decodeFace(bold ? font.bold : font.regular, font.drawnIn);
};
// The fonts whose Arabic Word kerns by pairs of letters, whether the text asks for kerning or not: it draws ten copies of a
// letter joined in a word as much as 23 thousandths of an em a letter wider or narrower than their forms, keheh's wider
// and ain's narrower, and beh's 6 wider, where the same forms with tatweels or a zero-width non-joiner between them are as
// wide as they are (scripts/layout-probes/stops2/word-stops-more-widths.ts W, word-stops-arabic.ts AR1). Courier New's
// copies are as wide as their forms, to a tenth of a thousandth
const KERNED = new Set(["Arial", "Times New Roman", "Cambria"]);
/**
* Why Word's widths of Arabic text in a font of the tables aren't known, when they aren't: letters side by side, with
* nothing but marks between them, which Word kerns by pairs the widths don't have, in a font it kerns them in, but for lam
* and an alef, which it joins into one glyph
*/
export const unknownArabicKerning = (text: string, name: string): string | undefined => {
if (!KERNED.has(name)) {
return undefined;
}
// Lam and the alef after it are one glyph, the ligature, whose width is known
const letters = [...text].filter((character) => joiningOf(character) !== "T");
const kerned = letters.some(
(character, index) =>
index > 0 &&
ARABIC_LETTERS.includes(character) &&
ARABIC_LETTERS.includes(letters[index - 1]) &&
!(letters[index - 1] === LAM && LAM_ALEFS.includes(character)),
);
return kerned ? "Arabic letters side by side, which Word kerns by pairs not yet known" : undefined;
};
/** Whether a character is one of Arabic's letters the widths have, or the tatweel */
export const isJoinedLetter = (character: string): boolean => character === TATWEEL || ARABIC_LETTERS.includes(character);
/**
* The widths of the letters of text Word joins, by the index of each among its characters, in thousandths of an em: each
* letter in the form the letters beside it join it in, in the text, as Word joins those of a word, and lam and an alef
* after it as a ligature, whose width is lam's, the alef taking none. A letter joins the letter before it when it joins
* after it as a ligature, whose width is lam's, the alef taking none. Word doesn't kern the letters side by side in these
* fonts: every pair of the 42 letters, joined as initial and final and as medials, in Arial and Times New Roman, plain and
* bold, is as wide as its forms to 8 thousandths of an em, and ten copies of a letter joined are as wide as theirs
* (scripts/layout-probes/stops2/word-stops-arabic2.ts AR4, word-stops-more-widths.ts W). A letter joins the letter before it when it joins
* either way, or only that one, and that letter joins the next too, or is a tatweel, and the letter after it when it joins
* both and that letter joins the one before it; marks between them leave them joined.
*/
+14 -5
View File
@@ -74,15 +74,24 @@ describe("findLineBreaks", () => {
expect(breaksOf("永、永「永", "ja-JP", { kinsoku: false })).to.deep.equal([1, 2, 3, 4]);
});
it("should keep small kana and the prolonged sound mark from starting a line of Japanese by Word's strict rules (EA4a)", () => {
it("should keep each small kana and the prolonged sound mark from starting a line of Japanese by Word's strict rules, in place of the document's own list (EA4a, EA5, EA5L)", () => {
expect(breaksOf("記録ぁぃ記ーァ", "ja-JP")).to.deep.equal([1, 2, 3, 4, 5, 6]);
expect(breaksOf("記録ぁぃ記ーァ", "ja-JP", { strict: true })).to.deep.equal([1, 4]);
// Not in Chinese, nor half-width small katakana
// Each of the small kana, but not the small ka and ke of hiragana, which Word's list doesn't have
// cspell:disable-next-line
for (const kana of "ぁぃぅぇぉっゃゅょゎァィゥェォッャュョヮヵヶー") {
expect(breaksOf(`記録${kana}`, "ja-JP", { strict: true }), kana).to.deep.equal([1]);
}
expect(breaksOf("記録ゕゖ", "ja-JP", { strict: true })).to.deep.equal([1, 2, 3]);
// Not in Chinese or Korean, nor half-width small katakana
expect(breaksOf("記録ぁ", "zh-CN", { strict: true })).to.deep.equal([1, 2]);
expect(breaksOf("記録ぁ", "ko-KR", { strict: true })).to.deep.equal([1, 2]);
expect(breaksOf("記録ァ", "ja-JP", { strict: true })).to.deep.equal([1, 2]);
// The document's own list takes their place
expect(breaksOf("記録ぁ", "ja-JP", { strict: true, lists: { japanese: { noLineEnd: "" } } })).to.deep.equal([1]);
expect(breaksOf("記録ぁ", "ja-JP", { strict: true, lists: { japanese: { noLineStart: "" } } })).to.deep.equal([1, 2]);
// Word's strict list takes the place of the document's own, which keeps only 、 and 。 from the start of a line (EA5L)
expect(breaksOf("記録ぁー」", "ja-JP", { strict: true, lists: { japanese: { noLineStart: "、。" } } })).to.deep.equal([1]);
expect(breaksOf("記録ぁ", "ja-JP", { strict: true, lists: { japanese: { noLineStart: "" } } })).to.deep.equal([1]);
expect(breaksOf("記録ぁ「永", "ja-JP", { strict: true, lists: { japanese: { noLineEnd: "" } } })).to.deep.equal([1, 3]);
expect(breaksOf("記録ぁ", "zh-CN", { strict: true, lists: { japanese: { noLineStart: "" } } })).to.deep.equal([1, 2]);
});
it("should take the document's own lists in place of Word's", () => {
+20 -7
View File
@@ -60,7 +60,7 @@ export type LineBreakRules = {
readonly lists?: Partial<Record<KinsokuLanguage, KinsokuList>>;
/**
* Whether Word's strict rules keep small kana and the prolonged sound mark from starting a line of Japanese too
* (`w:strictFirstAndLastChars`). Default is off
* (`w:strictFirstAndLastChars`), with Word's list of the other characters in place of the document's own. Default is off
*/
readonly strict?: boolean;
/**
@@ -99,12 +99,24 @@ const WORD_LISTS: Readonly<Record<KinsokuLanguage, Required<KinsokuList>>> = {
};
// What Word's strict rules add to its list of the characters that can't start a line of Japanese: the small kana and the
// prolonged sound mark, as its strict list of them (the specification's for `w:strictFirstAndLastChars`) has them, which its
// normal list lets start a line (word-unicode2.ts S). Its PDF showed small hiragana kept from the start of a line with them
// (scripts/layout-probes/stops2/word-stops-east-asian2.ts EA4a). The half-width small katakana that list has too, its normal
// list, unlike the specification's, lets start a line, so whether its strict list keeps them from it isn't known
// normal list lets start a line (word-unicode2.ts S). Its PDFs showed each of them kept from the start of a line with them,
// and the small ka and ke of hiragana (ゕ, ゖ), which the list doesn't have, starting one
// (scripts/layout-probes/stops2/word-stops-east-asian2.ts EA4a, word-stops-east-asian3.ts EA5). The half-width small
// katakana that list has too, its normal list, unlike the specification's, lets start a line, so whether its strict list
// keeps them from it isn't known. The rules change nothing in Chinese or Korean, whose lists are as without them (EA5)
const STRICT_JAPANESE_NO_LINE_START = "ぁぃぅぇぉっゃゅょゎァィゥェォッャュョヮヵヶー";
/* cspell:enable */
/**
* Word's strict list of the characters that can't start or end a line of Japanese, which its strict rules take in place of
* the document's own list: ぁ, ー and 」 are kept from the start of a line with them where the document's own list has only
* 、 and 。 (scripts/layout-probes/stops2/word-stops-east-asian3.ts EA5L)
*/
export const STRICT_JAPANESE_LIST: Required<KinsokuList> = {
noLineStart: WORD_LISTS.japanese.noLineStart + STRICT_JAPANESE_NO_LINE_START,
noLineEnd: WORD_LISTS.japanese.noLineEnd,
};
// 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 =
@@ -160,9 +172,10 @@ type Kinsoku = { readonly noLineStart: ReadonlySet<string>; readonly noLineEnd:
const NO_KINSOKU: Kinsoku = { noLineStart: new Set(), noLineEnd: new Set() };
const listOf = (language: KinsokuLanguage, { lists = {}, strict = false }: LineBreakRules): Kinsoku => {
const words = WORD_LISTS[language];
const wordsStart = strict && language === "japanese" ? words.noLineStart + STRICT_JAPANESE_NO_LINE_START : words.noLineStart;
const { noLineStart = wordsStart, noLineEnd = words.noLineEnd } = lists[language] ?? {};
// Word's strict rules take their own list of Japanese, in place of the document's
const words = strict && language === "japanese" ? STRICT_JAPANESE_LIST : WORD_LISTS[language];
const { noLineStart = words.noLineStart, noLineEnd = words.noLineEnd } =
strict && language === "japanese" ? {} : (lists[language] ?? {});
return { noLineStart: new Set(noLineStart), noLineEnd: new Set(noLineEnd) };
};
+41 -23
View File
@@ -2149,24 +2149,34 @@ describe("layoutLines on a document grid, as Word lays it out (scripts/layout-pr
expect(countsOf([mincho(IDEOGRAPH.repeat(80))], { ...GR14, format: { indentRight: 1.5 * cell } })).to.deep.equal([38, 38, 4]);
});
it("should stop at indents of part of a cell Word hasn't been seen rounding, and at a tab in a paragraph with one", () => {
it("should round a first line indent of part of a cell beside a left indent of part of one, and an indent before the margin, each on its own, and stop at one a cell or more before it (GR17)", () => {
const cell = WIDTH / 40;
const GR14 = { grid: { linePitch: 18, characterPitch: cell } };
expect(
unsupportedOf([mincho(IDEOGRAPH)], { ...GR14, format: { indentLeft: 1.2 * cell, firstLineIndent: 0.5 * cell } }),
).to.equal("a first line indent of part of a character beside a left indent of part of one on a grid that snaps to characters");
expect(unsupportedOf([mincho(IDEOGRAPH)], { ...GR14, format: { indentLeft: 0.5 * cell, firstLineIndent: -cell } })).to.equal(
"an indent of part of a character before the margin on a grid that snaps to characters",
);
expect(unsupportedOf([mincho(IDEOGRAPH)], { ...GR14, format: { indentLeft: -0.5 * cell } })).to.equal(
"an indent of part of a character before the margin on a grid that snaps to characters",
);
const GR17 = { grid: { linePitch: 18, characterPitch: cell } };
const startsOf = (format: LineLayoutOptions["format"]): readonly (number | undefined)[] =>
linesOf([mincho(IDEOGRAPH.repeat(80))], { ...GR17, format }).map(({ start }) =>
start === undefined ? start : Math.round((start / cell) * 1e6) / 1e6,
);
// 1.2 characters, and its first line half a character more: every line at the 3rd cell (GR17a)
expect(startsOf({ indentLeft: 1.2 * cell, firstLineIndent: 0.5 * cell })).to.deep.equal([2, 2, 2]);
expect(startsOf({ indentLeft: 1.2 * cell, firstLineIndent: 0.9 * cell })).to.deep.equal([3, 2, 2]);
// Half a character, hanging one: the first line at the 2nd cell, and the others at the 3rd (GR17b)
expect(startsOf({ indentLeft: 1.5 * cell, firstLineIndent: -cell })).to.deep.equal([1, 2, 2]);
// Half a character before the margin: the 1st cell (GR17c)
expect(startsOf({ indentLeft: -0.5 * cell })).to.deep.equal([0, 0]);
// A tab in such a paragraph goes to its stop, and the text after it starts at the next cell (GR17d, GR17e)
expect(
unsupportedOf([mincho(IDEOGRAPH), { type: "tab", font: {} }, mincho(IDEOGRAPH)], {
...GR14,
...GR17,
format: { indentLeft: 0.5 * cell },
}),
).to.equal("a tab in a paragraph indented part of a character on a grid that snaps to characters");
).to.equal(undefined);
// An indent a character or more before the margin, by part of one, hasn't been seen
const BEFORE = "an indent of part of a character, a character or more before the margin, on a grid that snaps to characters";
expect(unsupportedOf([mincho(IDEOGRAPH)], { ...GR17, format: { indentLeft: -1.5 * cell } })).to.equal(BEFORE);
expect(
unsupportedOf([mincho(IDEOGRAPH)], { ...GR17, format: { indentLeft: 0.5 * cell, firstLineIndent: -2 * cell } }),
).to.equal(BEFORE);
expect(unsupportedOf([mincho(IDEOGRAPH)], { ...GR17, format: { indentLeft: -cell } })).to.equal(undefined);
});
it("should start text after a left tab at the next of the grid's cells, and stop at other tabs and text (GR10a, GR16c)", () => {
@@ -2398,9 +2408,6 @@ describe("right-to-left text, as Word lays it out (scripts/layout-probes/stops2/
layoutLines(items, { width: 21, format });
const textsOf = (items: readonly InlineItem[], format: ParagraphFormat = {}): readonly string[] =>
linesOf(items, format).map((line) => line.text);
const UNKNOWN =
"a word beside right-to-left text that fits on its line only without the space after it, which Word hasn't been seen breaking";
it("should take the space after the last of a line's right-to-left words into the line, in a right-to-left run when a right-to-left word follows it (AR2)", () => {
// Two words and the space between them, 19.674 points, fit in 21, but not with the space after them
expect(textsOf([arabic(`${WORD} ${WORD} ${WORD}`)])).to.deep.equal([`${WORD} `, `${WORD} ${WORD}`]);
@@ -2425,13 +2432,24 @@ describe("right-to-left text, as Word lays it out (scripts/layout-probes/stops2/
expect(starts.map((line) => line.unsupported)).to.deep.equal([undefined, undefined]);
});
it("should stop at a word that fits only without the space after it where Word hasn't been seen breaking it", () => {
// In a right-to-left run beside left-to-right text, and between right-to-left words in a run that isn't right to left
expect(linesOf([arabic(`${WORD} ${WORD} `), arabic("abc", { font: "Arial", size: 10 })])[0].unsupported).to.equal(UNKNOWN);
expect(linesOf([arabic(`${WORD} ${WORD} ${WORD}`, { font: "Arial", size: 10 })])[0].unsupported).to.equal(UNKNOWN);
// But not where it fits with it too, nor where it doesn't fit without it
expect(layoutLines([arabic(`${WORD} ${WORD} abc`)], { width: 30 })[0].unsupported).to.equal(undefined);
expect(layoutLines([arabic(`${WORD} ${WORD} abc`)], { width: 18 })[0].unsupported).to.equal(undefined);
it("should take the space after the last of a line's right-to-left words into the line beside left-to-right text in a right-to-left run, and between right-to-left words in a run that isn't (AR3)", () => {
const plain = { font: "Arial", size: 10 } as const;
// Arabic before Latin text, the space in the Arabic's right-to-left run: the second word goes on to the next line (AR3a)
expect(textsOf([arabic(`${WORD} ${WORD} `), arabic("a", plain)])).to.deep.equal([`${WORD} `, `${WORD} a`]);
// Latin text before Arabic, the space in the Arabic's run: "ab abc", 30.02 points, fits in 31 only without it (AR3b)
expect(layoutLines([arabic("ab abc", plain), arabic(` ${WORD}`)], { width: 31 }).map((line) => line.text)).to.deep.equal([
"ab ",
`abc ${WORD}`,
]);
expect(layoutLines([arabic("ab abc ", plain), arabic(WORD)], { width: 31 }).map((line) => line.text)).to.deep.equal([
"ab abc ",
WORD,
]);
// Arabic before Arabic in a run that isn't right to left (AR3e), as in one that is (AR2)
expect(textsOf([arabic(`${WORD} ${WORD} ${WORD}`, plain)])).to.deep.equal([`${WORD} `, `${WORD} ${WORD}`]);
// Where it fits with it too, or doesn't fit without it, as elsewhere
expect(layoutLines([arabic(`${WORD} ${WORD} abc`)], { width: 40 })[0].text).to.equal(`${WORD} ${WORD} abc`);
expect(layoutLines([arabic(`${WORD} ${WORD} abc`)], { width: 18 })[0].text).to.equal(`${WORD} `);
});
// cspell:enable
});
+36 -60
View File
@@ -1396,34 +1396,34 @@ const rightToLeftAt = (pieces: readonly Piece[], edge: "start" | "end"): boolean
/**
* What the space between two words is at the end of a line, in a left-to-right paragraph, as Word breaks it: room the
* line has for it, when it is in a right-to-left run between right-to-left words, as a word of Arabic that fits only
* without it goes on to the next line, where Word puts those that fit with it (stops2/word-stops-arabic.ts AR2e, AR2h,
* AR2i), or hanging past the end of the line, as it does between left-to-right words, and between right-to-left and
* left-to-right ones, either way, in runs that aren't right to left: Hebrew's last letters, and a label before the
* next, end lines a space short of the margin (stops2/word-stops-more-widths.ts W139, W278). Word breaks the lines of a
* right-to-left paragraph where it breaks those of a left-to-right one (scripts/layout-probes/word-unicode.ts R2, R8). Where
* it hasn't been seen, it is unknown: in a right-to-left run beside left-to-right text, and between right-to-left words
* in a run that isn't right to left
* line has for it, between right-to-left words, in a right-to-left run or not, and between a right-to-left word and a
* left-to-right one, either way, when it is in a right-to-left run, as a word of Arabic that fits only without it goes on
* to the next line, where Word puts those that fit with it (stops2/word-stops-arabic.ts AR2e, AR2h, AR2i,
* word-stops-east-asian3.ts AR3a to AR3c, AR3e: Arabic before Latin, Latin before Arabic, Hebrew before Hebrew, and Arabic
* before Arabic in a run that isn't right to left); or hanging past the end of the line, as it does between left-to-right
* words, and between right-to-left and left-to-right ones, either way, in runs that aren't right to left: Hebrew's last
* letters, and a label before the next, end lines a space short of the margin (stops2/word-stops-more-widths.ts W139,
* W278). Word breaks the lines of a right-to-left paragraph where it breaks those of a left-to-right one, the space after
* its last word hanging past the end of the line (scripts/layout-probes/word-unicode.ts R2, R8, AR3d)
*/
const spaceAtEnd = (before: readonly Piece[], space: readonly Piece[], after: readonly Piece[]): "room" | "hanging" | "unknown" => {
const spaceAtEnd = (before: readonly Piece[], space: readonly Piece[], after: readonly Piece[]): "room" | "hanging" => {
const [end, start] = [rightToLeftAt(before, "end"), rightToLeftAt(after, "start")];
if (!end && !start) {
return "hanging";
}
const inRightToLeftRun = space.some(({ font }) => font.rightToLeft === true);
return end && start ? (inRightToLeftRun ? "room" : "unknown") : inRightToLeftRun ? "unknown" : "hanging";
return (end && start) || ((end || start) && space.some(({ font }) => font.rightToLeft === true)) ? "room" : "hanging";
};
/**
* A paragraph's indents on a grid that snaps to characters, whose lines start on its cells: the cell an indent of part of
* one ends in, as Word rounds it up, and a hanging indent's other lines that many more cells in, rounded up too. On a grid
* of cells of 225.65 twips, a paragraph indented 1.2, 1.5 or 1.7 characters, or 300 twips, starts its lines at the 3rd
* cell, one with a first line indent of half a character starts its first line at the 2nd and the others at the 1st, and
* one indented 2 characters and hanging half a character starts its first line at the 3rd and the others at the 4th, past
* its left indent (scripts/layout-probes/stops2/word-stops-east-asian.ts GR6, word-stops-east-asian2.ts GR14a to GR14e). A
* right indent of part of a cell leaves the line the cells before it, as the cells that fit do (GR14f). It says why when
* Word's way with them isn't known: a first line indent of part of a cell beside a left indent of part of one, which may
* be rounded together or apart, and a line that starts before the margin.
* one ends in, as Word rounds it up, each line's on its own. On a grid of cells of 225.65 twips, a paragraph indented 1.2,
* 1.5 or 1.7 characters, or 300 twips, starts its lines at the 3rd cell, one with a first line indent of half a character
* starts its first line at the 2nd and the others at the 1st, one indented 1.2 characters and its first line half a
* character more starts every line at the 3rd, and one indented half a character before the margin starts them at the
* 1st (scripts/layout-probes/stops2/word-stops-east-asian.ts GR6, word-stops-east-asian2.ts GR14a to GR14d,
* word-stops-east-asian3.ts GR17a, GR17c). With a hanging indent, the first line starts at the cell its indent is rounded
* up to and the others that many cells more, rounded up too: indented 2 characters and hanging half a character, the
* first line at the 3rd cell and the others at the 4th, past its left indent, and indented half a character and hanging
* one, at the 2nd and the 3rd (GR14e, GR17b). A right indent of part of a cell leaves the line the cells before it, as
* the cells that fit do (GR14f). It says why when Word's way with them isn't known: a line that starts a character or
* more before the margin, by part of one.
*/
const indentsOnCells = (
format: ParagraphFormat,
@@ -1435,22 +1435,18 @@ const indentsOnCells = (
if (cell === undefined || (whole(indentLeft) && whole(firstLineIndent))) {
return { format };
}
const cells = (length: number): number => (whole(length) ? Math.round(length / cell) : Math.ceil(length / cell)) * cell;
const cells = (length: number): number => (whole(length) ? Math.round(length / cell) : Math.ceil(length / cell)) * cell || 0;
const first = indentLeft + firstLineIndent;
if (Math.min(indentLeft, first) < -TOLERANCE) {
return { format, unsupported: "an indent of part of a character before the margin on a grid that snaps to characters" };
if (Math.min(indentLeft, first) < TOLERANCE - cell) {
return {
format,
unsupported: "an indent of part of a character, a character or more before the margin, on a grid that snaps to characters",
};
}
if (firstLineIndent < 0) {
const hanging = cells(-firstLineIndent);
return { format: { ...format, indentLeft: cells(first) + hanging, firstLineIndent: -hanging }, rounded: true };
}
if (!whole(indentLeft) && !whole(firstLineIndent)) {
return {
format,
unsupported:
"a first line indent of part of a character beside a left indent of part of one on a grid that snaps to characters",
};
}
return { format: { ...format, indentLeft: cells(indentLeft), firstLineIndent: cells(first) - cells(indentLeft) }, rounded: true };
};
@@ -1577,13 +1573,7 @@ export const layoutLines = (
)
? "ligatures on a document grid of characters"
: undefined;
const unknownOnGrid =
onCells.unsupported ??
(onCells.rounded && items.some((item) => item.type === "tab")
? "a tab in a paragraph indented part of a character on a grid that snaps to characters"
: undefined) ??
spaced?.unsupported ??
shapedOnGrid;
const unknownOnGrid = onCells.unsupported ?? spaced?.unsupported ?? shapedOnGrid;
// How tall a line as tall as the paragraph's mark is, measured only where it counts, as a layout stops at a mark in a
// font the measurer doesn't know
let markHeight: number | undefined;
@@ -1940,7 +1930,7 @@ export const layoutLines = (
* Puts a word or picture on the line, or on the next, or breaks it across lines. A word is kerned with the text
* before it on the line by `kern`, unless it starts the next line
*/
const placeWord = (token: Extract<Token, { readonly type: "word" | "box" }>, kern = 0, after = 0, unsureAfter = false): void => {
const placeWord = (token: Extract<Token, { readonly type: "word" | "box" }>, kern = 0, after = 0): void => {
// On a grid that snaps to characters the kerning with the text before is in the cells the word takes, after the
// other text on the line it is kerned with
const kernOn = (state: LineState): number => (state.latin === undefined ? 0 : kern);
@@ -1965,21 +1955,7 @@ export const layoutLines = (
const leadOf = (state: LineState, wrapped = false): number =>
roomBetween(state.border, startBorderOf(token)) + (wrapped || snapping ? 0 : kern);
const boxEnd = endBorderOf(token)?.room ?? 0;
const needs = leadOf(line) + tokenWidth + boxEnd + (unsureAfter ? 0 : after);
// A word that fits only without the space after it, where whether Word lets that space hang past the end of the
// line isn't known
if (
unsureAfter &&
line.position + needs <= endOf(line) + TOLERANCE &&
line.position + needs + after > endOf(line) + TOLERANCE
) {
line = {
...line,
unsupported:
line.unsupported ??
"a word beside right-to-left text that fits on its line only without the space after it, which Word hasn't been seen breaking",
};
}
const needs = leadOf(line) + tokenWidth + boxEnd + after;
const hyphens = token.type === "word" ? (token.hyphens ?? []).filter(({ at }) => at > 0 && at < lengthOf(token.pieces)) : [];
const skipped = skipRooms(needs, hyphens.length > 0);
// A justified line Word can squeeze the word onto takes it whole, as it does a word without soft hyphens: at its
@@ -1998,13 +1974,13 @@ export const layoutLines = (
}
const rest = breakAtHyphen(token, hyphens, kern);
if (rest !== undefined) {
placeWord(rest, 0, after, unsureAfter);
placeWord(rest, 0, after);
return;
}
if (line.started && line.tabsOnly !== true) {
// No part of it fits with a hyphen: it goes on to the next line, where it may break again
line = wrap(line);
placeWord(token, 0, after, unsureAfter);
placeWord(token, 0, after);
return;
}
// Not even its first part fits on a line of its own, or after the tabs that start it: Word breaks it after the
@@ -2451,14 +2427,14 @@ export const layoutLines = (
continue;
}
// The space after a word at the end of a line, beside right-to-left text in a left-to-right paragraph: taking
// room on the line, when it is between right-to-left words in a right-to-left run, or hanging past its end
// room on the line, or hanging past its end (see `spaceAtEnd`)
const [space, nextWord] = token.type === "word" && format.rightToLeft !== true ? nextTwo(tokens, index) : [];
const spaceAt =
token.type === "word" && space?.type === "space" && nextWord?.type === "word"
? spaceAtEnd(token.pieces, space.pieces, nextWord.pieces)
: "hanging";
const spaceWidth = spaceAt !== "hanging" && space?.type === "space" ? widthOf(space.pieces, measurer) : 0;
placeWord(token, kerning[index], spaceWidth, spaceAt === "unknown");
const spaceWidth = spaceAt === "room" && space?.type === "space" ? widthOf(space.pieces, measurer) : 0;
placeWord(token, kerning[index], spaceWidth);
}
if (!end) {
+18 -5
View File
@@ -632,13 +632,26 @@ describe("kerning and ligatures", () => {
expect(comma).to.be.closeTo(-0.68, 0.02);
});
it("should say where Word's kerning or ligatures aren't known, so a layout stops there", () => {
// Arabic letters side by side, which Word kerns in Arial, Times New Roman and Cambria however the text asks
// (stops2/word-stops-more-widths.ts W), but not in Courier New, nor a letter alone
it("should measure Arabic's letters in their joined forms as drawn, with ligatures or kerning on, as without them (AR4)", () => {
const arial = { font: "Arial", size: 10 } as const;
// cspell:disable
expect(unknownShaping("بلا", { font: "Arial", size: 10 })).to.equal(
"Arabic letters side by side, which Word kerns by pairs not yet known",
expect(measureTextWidthAsDrawn("بلا كتاب", { ...arial, ligatures: "standardContextual" })).to.equal(
measureTextWidth("بلا كتاب", arial),
);
expect(measureTextWidthAsDrawn("بلا", { ...arial, kerning: 1 })).to.equal(measureTextWidth("بلا", arial));
expect(measureTextWidthAsDrawn("ab\tبلا", { ...arial, ligatures: "standard" })).to.equal(measureTextWidth("ab\tبلا", arial));
// Not Calibri's, whose forms aren't in the tables
expect(measureTextWidthAsDrawn("بلا", { font: "Calibri", ligatures: "standard" })).to.equal(
measureTextWidth("بلا", { font: "Calibri" }),
);
// cspell:enable
});
it("should say where Word's kerning or ligatures aren't known, so a layout stops there", () => {
// Not Arabic letters side by side, which Word doesn't kern in Arial, Times New Roman and Cambria, nor in Courier New
// (stops2/word-stops-arabic2.ts AR4)
// cspell:disable
expect(unknownShaping("بلا", { font: "Arial", size: 10 })).to.equal(undefined);
expect(unknownShaping("بلا", { font: "Courier New" })).to.equal(undefined);
expect(unknownShaping("ب و", { font: "Times New Roman" })).to.equal(undefined);
expect(unknownShaping("بلا", { font: "Calibri" })).to.equal(undefined);
+18 -17
View File
@@ -10,7 +10,7 @@
* @module
*/
// cspell:ignore caladea Aptos
import { type ArabicFace, arabicFaceOf, isJoinedLetter, joinedWidthsOf, unknownArabicKerning } from "./arabic-shaping";
import { type ArabicFace, arabicFaceOf, isJoinedLetter, joinedWidthsOf } from "./arabic-shaping";
import { FALLBACK_FACES, FONT_WIDTHS, FONT_WIDTH_RANGES, type FontWidths } from "./font-widths";
import { type FaceShaping, type Glyph, hasLigatures, joinLetters, kerningBetween, rulesOf, shapingOf } from "./kerning";
import { FALLBACK_FONTS, MORE_WIDTHS, MORE_WIDTH_RANGES } from "./more-widths";
@@ -764,7 +764,7 @@ export const measureTextWidthAsDrawn = (text: string, font: TextFont = {}, start
return measureTextWidth(text, font, start);
}
// The fonts of the tables, whose kerning and ligatures they have, aren't monospaced East Asian fonts
const { widths, more } = measuresOf(font);
const { widths, more, arabic } = measuresOf(font);
const widthOf = (character: string): number => characterWidth(widths, more, character);
const size = sizeOf(font);
const { characterSpacing = 0, scale = 100 } = font;
@@ -773,16 +773,22 @@ export const measureTextWidthAsDrawn = (text: string, font: TextFont = {}, start
text.split("\t").reduce((position, part, index) => {
const at = index === 0 ? position : (Math.floor(position / TAB_STOP) + 1) * TAB_STOP;
const glyphs = glyphsOf(part, font, shaping);
return glyphs.reduce((total, glyph, glyphIndex) => {
const next = glyphs[glyphIndex + 1];
// Kerning a pair it doesn't know is left out, where a layout has stopped at it (`unknownShaping`)
const kerning = kerned && next !== undefined ? kerningBetween(shaping, glyph, next) || 0 : 0;
return (
total +
(((glyph.width ?? widthOf(glyph.text)) + kerning) * size * scale) / 100000 +
characterSpacing * [...glyph.text].length
);
}, at);
// Arabic's letters are as wide as the forms the letters beside them join them in, as `measureTextWidth` measures
// them: the ligatures join Latin letters only, so each is a glyph of its own, at its index among the characters
const joined = joinedIn([...part], arabic);
return glyphs.reduce(
({ total, character }, glyph, glyphIndex) => {
const next = glyphs[glyphIndex + 1];
// Kerning a pair it doesn't know is left out, where a layout has stopped at it (`unknownShaping`)
const kerning = kerned && next !== undefined ? kerningBetween(shaping, glyph, next) || 0 : 0;
const width = joined?.get(character) ?? glyph.width ?? widthOf(glyph.text);
return {
total: total + ((width + kerning) * size * scale) / 100000 + characterSpacing * [...glyph.text].length,
character: character + [...glyph.text].length,
};
},
{ total: at, character: 0 },
).total;
}, start) - start
);
};
@@ -827,11 +833,6 @@ const LATIN_LETTER = /^\p{Script=Latin}$/u;
* and monospaced East Asian fonts, aren't kerned, and nor is text with ligatures in a face Word kerns only without them.
*/
export const unknownShaping = (text: string, font: TextFont = {}): string | undefined => {
// Arabic, which Word kerns whether the text asks for kerning or not (see `arabic-shaping.ts`)
const arabic = measuresOf(font).arabic === undefined ? undefined : unknownArabicKerning(text, widthsOf(font.font).name);
if (arabic !== undefined) {
return arabic;
}
const ligatures = hasLigatures(font);
if ((!isKerned(font) && !ligatures) || eastAsianFontOf(font.font ?? DEFAULT_FONT)?.monospaced === true) {
return undefined;