fix(layout): lay out rows that repeat their table's properties, split rows at multiple line spacing and overfull text boxes, as Word does (#3918)

* fix(layout): lay out rows that repeat their table's properties, split rows at multiple line spacing and overfull text boxes, as Word does

estimatePageNumbers stopped at three things report templates have (#3912):

- A row whose w:tblPrEx repeats the table's own w:tblW, w:tblLayout or
  w:tblInd. Properties that are the same as the table's change nothing,
  so only those that differ still stop the layout.
- A cell's line at multiple spacing at the foot of a row that breaks
  across pages, where it fits only without the space below its text.
  word-split-rows-and-boxes.docx shows Word moves it to the next page,
  unlike in the body: 69 probes, with and without borders and above a
  cell's bottom margin, all now on Word's pages.
- An inline VML text box of its own height whose text is taller than
  it. Word cuts the text off and keeps the box's height (OB1 in the same
  probe), so the box is laid out at its own height.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(layout): compare a row's table properties with the table's whatever order their attributes are in

XML gives attributes no order, so a row's w:tblPrEx written with
w:type before w:w is the same as the table's w:tblW written the other
way round. The comparison now sorts each element's attributes first,
as a text frame's are compared, rather than stopping the layout there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(layout): put the probe's text box shape type before whichever box ONLY leaves first

The shape type was added to OB1a's box, so a run with ONLY=OB1b wrote a
box referring to a shape type the document didn't declare. It now goes
before the first box in the document, whichever that is. A full run
writes the same document as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Dolan
2026-11-19 04:14:34 +00:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 660532044d
commit 5f626c02ba
9 changed files with 209 additions and 46 deletions
+6 -6
View File
File diff suppressed because one or more lines are too long
+1
View File
@@ -63,6 +63,7 @@ table style and each cell's width.
| `word-table-formats` | BS, BC, CS, BB, KR, VT, HM, CF and TI: the room each style of border takes, borders that disagree, left and right borders beside text, space between cells with borders and in tables sized to their text, cells' borders where a table breaks across pages, rows kept with the next, text that runs up a cell, `hideMark`, every part of a table style for some cells with `w:tblLook` on, off, not given and as `w:val`, and indented tables | `word-table-formats.py` |
| `word-table-formats2` | MG, BS, BC, VT, CF, KR and CS: what `word-table-formats` left open: cells of a row with different margins, borders at half a point and 3 points, left and right borders beside text, text running up a cell in other sizes, the corners and bands of rows of a table style, a row kept by its second cell, and space between cells of different widths, beside borders and across pages | `word-table-formats.py` |
| `word-merged-cell-margins` | A, B and C: how the margins of a cell merged down rows size the rows below its first, made with `rowSpan`, by hand with `verticalMerge`, and by hand with no margins in the second row. Saved from Word 16 for Mac on 2026-10-15, in docx's default document rather than the probes' Calibri 11 on A4 | Read by eye from the page |
| `word-split-rows-and-boxes` | SR1 to SR3: a table row across pages whose cell's line at 1.15 lines fits at the foot of the page only without the space its multiple spacing adds below its text, which Word moves on to the next page, unlike in the body, with or without borders and above a cell's margin below; OB1: a text box in the line of its own height with more text than fits in it, whose text Word cuts off, the box as tall as it says. Opened in Word 16 for Mac on 2026-11-19 and read with the AppleScript beside it, rather than saved as a PDF | Read through AppleScript |
| `word-justify` | J00 to J18: when Word squeezes a justified line to fit one more word on it: lines of 19, 6 and 2 spaces ending with short, medium and long words, in other fonts, last lines, lines before a line break, distributed and the other justifications, tabs, no-break spaces, spaces at the start of a line, and ideographs | `word-justify.py` |
| `word-justify2` | K00 to K12: when Word squeezes a distributed line, and Latin text justified for Thai or with a low kashida, as J01 to J07 and J04 for justified ones, and justified and distributed lines with one space | `word-justify.py` |
| `word-mixed-heights` | MH1 to MH7: how tall Word makes a line of two fonts, or with a picture, where `word-watertight-text`'s TX8 and TX9 left it open: multiple and at-least spacing over two fonts, the line gap above the text, a picture alone or beside text at 0.8 to 1.5 lines, the font of a picture's run, the descent of each East Asian font, and a picture shorter than its line | `word-mixed-heights.py` |
@@ -0,0 +1,21 @@
-- Reads where Word lays out each paragraph of word-split-rows-and-boxes.docx, open in Word as its active document: its text,
-- its page and how far down it it starts, in points from the top of the page, a line each, separated by tabs.
--
-- Usage: osascript scripts/layout-probes/word-split-rows-and-boxes.applescript > word-split-rows-and-boxes.tsv
on run argv
set out to ""
tell application "Microsoft Word"
set d to active document
set n to count of paragraphs of d
repeat with i from 1 to n
set r to text object of paragraph i of d
set t to content of r
if length of t > 1 then set t to text 1 thru -2 of t
set pg to get range information r information type active end adjusted page number
set rs to create range d start (start of content of r) end (start of content of r)
set y to get range information rs information type vertical position relative to page
set out to out & t & tab & pg & tab & y & linefeed
end repeat
end tell
return out
end run
Binary file not shown.
@@ -0,0 +1,108 @@
/**
* Probes of two stops docx/layout met in reports laid out from Word templates (#3912):
*
* - "a table row across pages whose line's multiple spacing goes below the page": whether a cell's line at 1.15 lines that
* fits at the foot of its row's part on the page only without the space its multiple spacing adds below its text goes
* on that page, as in the body (`word-mixed-heights.docx` MH1c), or on to the next (SR1 to SR3)
* - "a text box whose text is taller than it": a text box in the line, of its own height, with more text than fits in it
* (OB1)
*
* Calibri 11 on A4 with inch margins, so the text is 13958 twips tall; each probe on a page of its own.
*
* SR1a to SR1w: below its line above, a paragraph exactly 11299 twips tall, less 5 for each probe after the first, so
* the row below it starts 5 twips further up the page each time, then a table of one row and one cell, 9026 wide, with
* no borders and no margins above or below, of 10 paragraphs at 1.15 lines (`w:line="276"`, auto), each a line
* SR2a to SR2w: as SR1, with single borders of half a point all round
* SR3a to SR3w: as SR1, its cell with a margin of 300 below
* OB1a: a text box in the line, `width:150pt;height:30pt`, with no insets and no outline, not sized to its text, of 5
* lines; OB1b: the same with 1 line; OB1c: as OB1a, with Word's insets and an outline of 0.75 points; OB1d: as OB1c with
* 1 line. Each box is in a paragraph of its own, after a line of text and before another
*
* Opened in Word 16 for Mac on 2026-11-19 and read with `word-split-rows-and-boxes.applescript`, which writes each
* paragraph's page and how far down it it starts. Word put 7 of SR1's lines on the probe's first page up to SR1q and 8
* from SR1r, 7 of SR2's up to SR2u and 8 from SR2v, and 6 of SR3's up to SR3o and 7 from SR3p: a line goes on the page
* only when all of it fits, the space below its text too, as docx/layout now lays out all 69. Letting that space go below
* the page, as in the body, would put SR1's eighth line on the page from SR1i. The line below OB1a is where it is below
* OB1b, and below OB1c where it is below OB1d: Word cuts off the text that doesn't fit, and the box is as tall as it says.
*
* Usage: npm run run-ts -- scripts/layout-probes/word-split-rows-and-boxes.ts [folder]
*/
import { LineRuleType, Paragraph, Table, TableBorders, TableCell, TableRow, WidthType } from "docx";
import { ALL_BORDERS, type Child, TEXT_WIDTH, line, marker, probe, replaceMarkerRun, replaceText, write } from "./stops2/kit";
const STEPS = 23;
const LETTERS = "abcdefghijklmnopqrstuvwxyz";
/** A table of one row and one cell of 10 lines at 1.15 lines, with the borders and the margin below given */
const splitRow = (name: string, { bordered, marginBottom }: { readonly bordered: boolean; readonly marginBottom: number }): Table =>
new Table({
width: { size: TEXT_WIDTH, type: WidthType.DXA },
columnWidths: [TEXT_WIDTH],
borders: bordered ? ALL_BORDERS : TableBorders.NONE,
rows: [
new TableRow({
children: [
new TableCell({
width: { size: TEXT_WIDTH, type: WidthType.DXA },
margins: { top: 0, bottom: marginBottom, left: 108, right: 108 },
children: Array.from({ length: 10 }, (_, index) =>
line(`${name} line ${index + 1}`, { spacing: { line: 276, lineRule: LineRuleType.AUTO } }),
),
}),
],
}),
],
});
const splitRows = (prefix: string, options: { readonly bordered: boolean; readonly marginBottom: number }): Child[] =>
Array.from({ length: STEPS }, (_, step) => {
const name = `${prefix}${LETTERS[step]}`;
return probe(name, [
line(`${name} spacer`, { spacing: { line: 11299 - 5 * step, lineRule: LineRuleType.EXACT } }),
splitRow(name, options),
]);
}).flat();
/** A text box in the line, 150 by 30 points, of lines of text, as VML, not sized to its text */
const box = (name: string, count: number, framed: boolean): string => {
const text = Array.from(
{ length: count },
(_, index) => `<w:p><w:r><w:t xml:space="preserve">${name} box ${index + 1}</w:t></w:r></w:p>`,
).join("");
const outline = framed ? `strokeweight=".75pt"` : `stroked="f"`;
const inset = framed ? "" : ` inset="0,0,0,0"`;
return (
`<w:r><w:pict><v:shape id="${name}" type="#_x0000_t202" style="width:150pt;height:30pt" ${outline}>` +
`<v:textbox${inset}><w:txbxContent>${text}</w:txbxContent></v:textbox></v:shape></w:pict></w:r>`
);
};
const BOXES = [
["OB1a", 5, false],
["OB1b", 1, false],
["OB1c", 5, true],
["OB1d", 1, true],
] as const;
// The shape type of a text box, which Word writes once before the first shape of it
const SHAPE_TYPE =
`<v:shapetype id="_x0000_t202" coordsize="21600,21600" o:spt="202" path="m,l,21600r21600,l21600,xe">` +
`<v:stroke joinstyle="miter"/><v:path gradientshapeok="t" o:connecttype="rect"/></v:shapetype>`;
const children: Child[] = [
...splitRows("SR1", { bordered: false, marginBottom: 0 }),
...splitRows("SR2", { bordered: true, marginBottom: 0 }),
...splitRows("SR3", { bordered: false, marginBottom: 300 }),
...BOXES.flatMap(([name]) => probe(name, [new Paragraph({ children: [marker(name)] })])),
];
await write({
name: "word-split-rows-and-boxes",
children,
injections: [
...BOXES.map(([name, count, framed]) => replaceMarkerRun(name, box(name, count, framed))),
// The shape type goes before the first box in the document, whichever boxes ONLY leaves in it
replaceText(/<w:pict>(?=<v:shape id="OB1)/, `<w:pict>${SHAPE_TYPE}`),
],
});
+20 -17
View File
@@ -1013,12 +1013,22 @@ describe("paginate", () => {
expect(pagesOf(keptAtEnd)).to.include({ e: "1", f: "2" });
});
it("should stop where Word hasn't shown whether the spacing below a line goes past the bottom", () => {
// In a table row across pages, at 40 points down, where the third line of the cell ends at 85
it("should move a cell's line to the next page when only the spacing below its text fits at the end of a row's part, as Word does", () => {
// A row across pages at 40 points down, whose cell's third line ends at 85, its text at 80, the bottom: Word puts it
// on the next page, unlike in the body (`word-split-rows-and-boxes.docx` SR1 to SR3), so 2 lines are on the first
// and 4 on the next, with b below them
const rowAcross = document([paragraph("a", 3), table([row([[paragraph("cell", 6, spaced)]])]), paragraph("b", 1)]);
expect(paginate(rowAcross, { measurer: MEASURER }).stoppedAt).to.equal(
"a table row across pages whose line's multiple spacing goes below the page",
);
const { pages, stoppedAt } = paginate(rowAcross, { measurer: MEASURER });
expect(stoppedAt).to.equal(undefined);
expect(
pages.map(({ body }) =>
body.flatMap((block) => (block.type === "table" ? block.rows.map(({ y, height }) => [y, height]) : [])),
),
).to.deep.equal([[[40, 30]], [[10, 60]]]);
expect(pagesOf(rowAcross)).to.include({ a: "1", b: "2" });
});
it("should stop where Word hasn't shown whether the spacing below a line goes past the bottom", () => {
// Above a paragraph's border below: e's line ends at 70, and its border at 73, but at 68 without the spacing
const borders = { top: 0, bottom: 3, between: 0, betweenSpace: 0, box: "box", outline: "box" };
const bordered = document([paragraph("a", 3), ...lines("b"), paragraph("c", 1), { ...paragraph("e", 1, spaced), borders }]);
@@ -8260,7 +8270,7 @@ describe("paginate", () => {
).to.deep.equal([[[10, 26]], [[36, 10]]]);
});
it("should break a text box's lines in the room for its text, and make one Word doesn't size to its text as tall as it is (TX1, VM25a)", () => {
it("should break a text box's lines in the room for its text, and make one Word doesn't size to its text as tall as it is (TX1, VM25a, OB1)", () => {
// "ab ab" is 50 wide, so it fits the room of 50: one line of 10, and 6 (`word-stops-floats2.docx` TX1a to TX1k), and
// "ab abc" is two lines
const heightOf = (block: ParagraphBlock): number => (laidOut([block]).pages[0].body[0] as ParagraphLayout).lines[0].height;
@@ -8276,7 +8286,10 @@ describe("paginate", () => {
],
});
expect(heightOf(fixed("ab ab", 40, 30))).to.equal(40);
expect(stopOf([fixed("ab abc", 25, 15)])).to.equal("a text box whose text is taller than it");
// And when it doesn't: Word cuts off its text, and the box is as tall as it says (`word-split-rows-and-boxes.docx`
// OB1)
expect(heightOf(fixed("ab abc", 25, 15))).to.equal(25);
expect(stopOf([fixed("ab abc", 25, 15)])).to.equal(undefined);
});
});
@@ -8632,15 +8645,5 @@ describe("paginate with automatic hyphenation", () => {
});
expect(keptBefore({ ...rows, unsupported: "an imported document", noGuess: true })).to.deep.equal({ a: "1", b: "1" });
});
it("should still stop where it has no guess, such as at the multiple spacing of a line in a table row across pages", () => {
// Letting it go below the page, as in the text, would leave the row's lines below the page as it is cut for them
const spaced = { lineSpacing: { rule: "multiple", multiple: 1.5 } } as const;
const rowAcross = document([paragraph("a", 3), table([row([[paragraph("cell", 6, spaced)]])]), paragraph("b", 1)]);
expect(guessed(rowAcross)).to.deep.include({
stoppedAt: "a table row across pages whose line's multiple spacing goes below the page",
bookmarks: { a: "1" },
});
});
});
});
+10 -20
View File
@@ -1027,19 +1027,13 @@ export const paginate = (
/**
* How tall a text box in the line is: its paragraphs, broken in the room for its text, which is its width less its
* insets and its outline (`word-stops-floats2.docx` TX1a to TX1k), and the room above and below them; or its own
* height, when Word doesn't size it to its text, which its text must fit in (`word-stops-vml-text-boxes.docx` VM25a)
* height, when Word doesn't size it to its text (`word-stops-vml-text-boxes.docx` VM25a), whether its text fits in it
* or not: Word cuts off what doesn't, and the line below a box of 30 points with 5 lines in it is where it is below
* the same box with 1 (`word-split-rows-and-boxes.docx` OB1)
*/
const textBoxHeight = (box: Extract<LayoutItem, { readonly type: "textBox" }>): number => {
const { room, textWidth: inside, blocks: inBox, fixed } = box;
const ofText = stackHeight(inBox, inside, true);
if (fixed === undefined) {
return room + ofText;
}
if (ofText > fixed.inner + TOLERANCE) {
// Where its text goes past its bottom hasn't been seen
throw new Unsupported("a text box whose text is taller than it");
}
return fixed.height;
return fixed === undefined ? room + stackHeight(inBox, inside, true) : fixed.height;
};
/**
@@ -4667,16 +4661,12 @@ export const paginate = (
// Widow control and keepLines hold lines back in a row that breaks across pages, as in Word, where LibreOffice
// lets them go (`word-rules.docx` P8, `word-rules2.docx` Q3). A paragraph that ends in the cell's part on the
// page needs room for its space after there too, as in Word (`word-line-heights.docx` T2), and for its border.
// Whether a line's multiple spacing can go below the bottom of the page at the end of a row's part isn't known
const { fits, count: kept } = linesThatFit(
remaining,
room - used - space,
paragraph,
from === 0,
(upTo) => (upTo === remaining.length ? paragraph.borderBelow + paragraph.spaceAfter : 0),
() => {
throw new Unsupported("a table row across pages whose line's multiple spacing goes below the page");
},
// A line needs room for the space its multiple spacing adds below its text too, which Word doesn't let go below
// the page at the end of a row's part, as it does in the body: a line at 1.15 lines goes on to the next page
// unless all of it fits, with or without borders, and above a cell's margin below
// (`word-split-rows-and-boxes.docx` SR1 to SR3)
const { fits, count: kept } = linesThatFit(remaining, room - used - space, paragraph, from === 0, (upTo) =>
upTo === remaining.length ? paragraph.borderBelow + paragraph.spaceAfter : 0,
);
const upToLimit = limit - placed.length;
const count = fits <= upToLimit ? kept : upToLimit > 0 ? linesKept(remaining.length, upToLimit, paragraph, from === 0) : 0;
+28
View File
@@ -4426,6 +4426,34 @@ describe("readDocument", () => {
},
]).blocks[0].block as TableBlock;
expect(indented.unsupported).to.equal("a table row with table properties of its own");
// Unless they are the same as the table's own, as some templates write them on every row, which changes
// nothing; one that isn't, or that the table doesn't have, still stops
const tableProperties = [
{ "w:tblW": { _attr: { "w:w": 4000, "w:type": "dxa" } } },
{ "w:tblInd": { _attr: { "w:w": 100, "w:type": "dxa" } } },
{ "w:tblLayout": { _attr: { "w:type": "fixed" } } },
{ "w:tblLook": { _attr: { "w:val": "0000" } } },
];
const repeating = (rowExceptions: readonly object[]): TableBlock =>
readBody([
{
"w:tbl": [
{ "w:tblPr": tableProperties },
{ "w:tblGrid": [2000, 2000].map((width) => ({ "w:gridCol": { _attr: { "w:w": width } } })) },
{ "w:tr": [cell([], p()), cell([], p())] },
{ "w:tr": [{ "w:tblPrEx": rowExceptions }, cell([], p()), cell([], p())] },
],
},
]).blocks[0].block as TableBlock;
expect(repeating(tableProperties).unsupported).to.equal(undefined);
// With their attributes in another order, which XML gives no meaning
expect(repeating([{ "w:tblW": { _attr: { "w:type": "dxa", "w:w": 4000 } } }]).unsupported).to.equal(undefined);
expect(repeating([{ "w:tblW": { _attr: { "w:w": 5000, "w:type": "dxa" } } }]).unsupported).to.equal(
"a table row with table properties of its own",
);
expect(repeating([{ "w:tblCellSpacing": { _attr: { "w:w": 40, "w:type": "dxa" } } }]).unsupported).to.equal(
"a table row with table properties of its own",
);
// With space between its cells, the table's borders go around the space (word-stops-table-borders.docx TB5),
// and a row's own are its cells', as its margins are (word-stops-table-borders2.docx BT6b: an inside border of a
// double line of 0.75 points between them keeps the second cell's text 2.25 points further in)
+15 -3
View File
@@ -3205,6 +3205,12 @@ const FOLLOWED_STYLE_CELL_PROPERTIES = new Set(["w:tcMar"]);
// cells as the table's (TS4)
const FOLLOWED_ROW_TABLE_PROPERTIES = new Set(["w:tblBorders", "w:tblCellMar"]);
/** An element's content as text, with each element's attributes in one order, as XML gives their order no meaning */
const orderFree = (content: unknown): string =>
JSON.stringify(content, (_, value: unknown) =>
isObject(value) ? Object.fromEntries(Object.entries(value).sort(([one], [other]) => one.localeCompare(other))) : value,
);
/** The last of a property given among properties, each over those before: those of a table's styles, then its own */
const lastOf = (properties: readonly (readonly XmlObject[])[], name: string): unknown =>
properties.reduce<unknown>((found, given) => find(given, name) ?? found, undefined);
@@ -3474,6 +3480,11 @@ const readTable = (element: XmlObject, reader: Reader): TableBlock | undefined =
// The row's table properties of its own (`w:tblPrEx`): its borders and cell margins, which its cells have as the
// table's (TS4). Most rows have none, so nothing is read for them
const exceptions = childrenOf(find(rowChildren, "w:tblPrEx"));
// Those that are the same as the table's own, as some templates repeat them on each row, change nothing
const ownExceptions = exceptions.filter((exception) => {
const own = find(properties, nameOf(exception));
return own === undefined || orderFree(own) !== orderFree(exception[nameOf(exception)]);
});
const rowBorderSet = exceptions.length > 0 ? readBorderSet(find(exceptions, "w:tblBorders")) : {};
const rowMargins = exceptions.length > 0 ? readCellMargins(find(exceptions, "w:tblCellMar")) : {};
// A row is as tall as the parts of its table's style for it say, when it doesn't say itself (TS1a)
@@ -3640,11 +3651,12 @@ const readTable = (element: XmlObject, reader: Reader): TableBlock | undefined =
// A row of a division of a web page (`w:divId`) Word moves across by the division's left margin, as wide and
// as tall as it is without, with the division's borders beside it but not above or below
// (`word-stops-pages.docx` DV1b), so its lines are as they are. One with table properties of its own
// (`w:tblPrEx`) other than borders and cell margins, such as a width, isn't followed. Its own borders are its
// cells', with space between them too (word-stops-table-borders2.docx BT6a to BT6c)
// (`w:tblPrEx`) other than borders and cell margins, such as a width, isn't followed, unless they are the
// table's own. Its own borders are its cells', with space between them too (word-stops-table-borders2.docx
// BT6a to BT6c)
const rowUnsupported = rowParts.some((part) => "w:sdt" in part)
? BOUND_CONTROL
: changesLines(exceptions, FOLLOWED_ROW_TABLE_PROPERTIES)
: changesLines(ownExceptions, FOLLOWED_ROW_TABLE_PROPERTIES)
? "a table row with table properties of its own"
: rowReferences.some(hasOwnMark)
? DELETED_OWN_MARK