diff --git a/docs/usage/layout.md b/docs/usage/layout.md index 61e9f5cc41..7a0a932e68 100644 --- a/docs/usage/layout.md +++ b/docs/usage/layout.md @@ -217,7 +217,7 @@ The pages are laid out with the widths and heights of the characters of the font - tables, with their columns' widths (`columnWidths`, or their cells' widths), their rows' heights, cell margins and borders. The columns of a table given no widths are sized to their text, as Word sizes them: each as wide as its longest line, or narrower when they don't all fit, but never narrower than its longest word, and a column whose cells give it a width keeps it. A cell merged across columns (`columnSpan`) widens them where its longest line needs more room, each in proportion to how wide it is, and a table in a cell counts as wide as its columns. In a table whose cells all have widths, a column with a word longer than its cells give it is widened to fit the word, and the other columns are narrowed to make room, as Word does, unless the table's layout is fixed. A table with a width of its own in twips is fitted to it, as Word fits it: when its columns are narrower, they are widened in proportion, and when they are wider, they are narrowed toward their longest words, or, when its layout is fixed, whatever is in them, each by the same share of the room for its text. When a word is longer than the table, its column is as wide as the word, and the table goes past the margin. Without a width of its own in twips, or with all of the width, a table whose columns' longest words don't fit in the room has each column narrowed to a share of it in proportion to its longest word, whatever width its cells give it, and the words break across lines, as Word breaks them. A table of a share of less than the width (`WidthType.PERCENTAGE`) whose columns' longest words don't fit in its share is as wide as they are, up to the room, and past it is narrowed as one of all of the width. A table sized to its text, or of a share of the width, has half of each of its left and right borders inside the room it fills, outside its columns, as Word draws them, where one of a width in twips has them outside it. Where the rows of a table give a column different widths, each column is as wide as the widest a row gives it, and a cell merged across columns that is wider than they are widens the last of them, before they are fitted to the table's width, in twips or as a share of the width, or, without one, narrowed to the room, unless its layout is fixed. In [templates](#templates), a row that starts past the first column (`w:gridBefore`) gives it its width before it (`w:wBefore`), as a cell does. A word in a cell merged across columns that is longer than they are wide is shared among them in proportion to each column's longest word and its longest line, or its width, added together, as Word shares it, and those columns keep its width when the others are narrowed. A long word with more text beside it widens them as its line does. Rows break across pages between the lines of their cells, as Word breaks them, keeping to widow and orphan control and lines kept together, and with room on the page for the space after a cell's paragraph that ends there. They move to the next page whole when a cell would have none of its lines on the page, when they are kept whole (`cantSplit`), and when the page hasn't room for the height they are set to. A row kept whole, or whose paragraph is kept together, that is taller than a page moves to a new page and breaks there as other rows do, and a row set to a height taller than a page takes a page of its own, cut off at its bottom, as Word lays them out. The text of a cell merged down from such a row, or to it from a row above, goes in all of its set height, past the bottom of the page, and the rest goes on in the rows after it on the next page, keeping to widow control. The row's footnotes start at the bottom of the next page, one after the other. A header row set to a height taller than a page isn't repeated on the next page, and what comes after its table goes on the page after the one the table ends on, as Word lays it out. A row set to at least a height taller than a page, whose text is taller than a page too, breaks where its text does, and each part of it fills its page. In columns, a row kept whole, or whose paragraph is kept together, that is taller than a column goes down only the first column of each page, from the top of a new page unless it is at the top of this one, as a paragraph kept together does, and what comes after one set to a height taller than a column goes on the next page. Where a table breaks across pages, Word draws its bottom border below the last of it on the page, which takes room there too, or its cells' own bottom borders. Header rows are repeated at the top of each page and column a table is on, and they aren't left alone at the foot of a page: when none of the row after them goes there, as it is kept whole, kept with the next or set to a height, they go on to the next page with it, as Word moves them. The text of a cell merged down rows (`verticalMerge`) goes down from below the border above its first row across the others, to above the border below the last, and makes the last of them taller when it needs the room. Where one of its rows breaks across pages, its text breaks with the row, as far down the page as its lines go, keeping to widow control, as Word breaks it, and the rest of it goes on from the top of its rows on the next page, and on across the pages after. Where the page breaks between its rows, as the next is kept whole or set to a height, the text that doesn't fit in its rows on the page goes on in its rows on the next, all of it where widow control leaves none of it on the page. A table in a cell breaks with its row, between its own rows and in them between the lines of their cells, as Word breaks it: as a table in the text breaks, keeping to widow control, with its bottom border below the last of it on the page and its cells' margins around their lines on each page, and with its rows kept whole, or of a set height, moving to the next page whole. On the next page, Word draws its top border above the rest of it, and doesn't repeat its header rows. A table in a cell merged down rows breaks as one in a cell of a row, and so does one with cells merged down its rows whose text is in their first rows, or whose rows are all on the page. An empty paragraph that ends a cell after a table in it takes no room, as Word lays it out - table formatting, as Word lays it out. Borders come from the table's style and the table (`borders`), side by side, from its cells (`TableCell`'s `borders`), and from the parts of its style for some of its cells. Where two cells meet, Word draws the heavier of their borders, by its width and a weight for its style, but makes room for the wider, so each row is as much taller as the widest border above its cells and below those above it. Double, triple and the other styles of border take the room Word gives them, such as three times their width for a double border, and a border's `space` adds to it. In [templates](#templates), an art border takes as many points above and below a cell's text as its size. A cell's text is as far in from its left and right edges as its margin, or half the border there when that is more: its own, whichever of two borders that meet Word draws, but for the cell before them, whose text is kept from the border Word draws, as Word lays them out. A row of an exact height (`HeightRule.EXACT`) has the border above it inside that height, and one of at least a height has it outside, as Word lays them out; with space between cells, a row of an exact height has its own space and its cells' borders inside its height too, and only the table's edge, its border and the space inside it, outside. A row is as tall as its tallest cell's text, with the largest margins above and below of its cells, which needn't be the same cell's. Space between cells (`cellSpacing`) goes around each cell and inside the table's edges, and the table keeps its width, its columns narrowed for the space as Word narrows them, or widened to it in proportion, the space aside, and a column with a long word widened for it as in a table without the space. Where its rows give a column different widths, they are evened out as in a table without it, unless its layout is fixed. Each cell's own borders take room inside it, left and right of its text as well as above and below it, and the table's own go around the space. Where such a table breaks across pages, Word draws its bottom border below the last of it on the page, and its top border above the rest of it on the next, but for below its header rows repeated there, which have it above them. A row's own space between its cells (`TableRow`'s `cellSpacing`) goes around its cells in place of the table's, at the table's edges too, as do its own borders (`w:tblPrEx`, in [templates](#templates)), and the table's columns are as wide as they would be without it, where the table has a width of its own and its cells have widths. Space given as a share of the table's width, or of the type `auto`, is none, as Word lays them out. A row whose first cell's first paragraph is kept with the next (`keepNext`) is kept on the page with the next row, or, for the last row, with the paragraph after the table, and rows kept together that don't fit on a page of their own start a new page and break where it ends. Text that runs up or down a cell (`textDirection`) makes a row of only such cells as tall as a line of its last paragraph's mark, and a row with other cells no taller, as Word breaks it into lines as long as the row is tall, and a row with it breaks across pages as other rows do, the text on the page of its first part. In a table sized to its text, its column is as wide as a line of each of its paragraphs with text, however long, with the space before and after them, its lines as far apart as Word lays them out at their line spacing: a quarter of their size further than their size in Calibri, and as far as across the page in Times New Roman, Arial, Cambria and Courier New. A long word in it widens nothing, and the table's other columns are sized as they would be beside any other column. Text down with East Asian characters upright is laid out as text that runs down, and across with them on their side as text across. A table sized to its text that is indented (`indent`) is sized in the room the indent leaves, and one indented by a share of the width (`WidthType.PERCENTAGE`) is laid out as though it weren't indented, as Word lays it out. The parts of a table style for some cells, such as its first row, its last column or its bands of rows, apply where the table turns them on (`tableLook`), and where it doesn't say, as Word turns them on: its first row and column and its bands of rows. A header of several rows (`tableHeader`) is the table's first row, all of it, with the parts for its corner cells in each of its rows, and the bands of rows start below it, as Word applies them, but for a header of three rows or more with the first row turned off, whose bands start at its first row. A table style's own cell margins apply to its cells, its rows kept whole (`w:cantSplit`) are kept whole, and its own row height doesn't apply, as in Word, and a part of it for some rows gives them its height, and keeps them whole, and not its space between cells. In [templates](#templates), a row's own table borders and cell margins (`w:tblPrEx`) apply to its cells, cells merged across columns as old versions of Word wrote them (`w:hMerge`) are one cell across them, and a cell whose text Word is told not to wrap (`w:noWrap`) has it wrapped all the same, and text fitted to its cell (`w:tcFitText`) is on one line a paragraph, as Word lays them out. In a table sized to its text, the one makes its column as wide as its lines, as though they didn't wrap, and the other as wide as its column in the table's grid. In [templates](#templates), an empty last paragraph of a cell whose mark is hidden (`w:hideMark`) takes no room - sections, with their page sizes, margins, columns, headers and footers, how they start, and their page numbering. Page numbers are written in Word's number formats as Word writes them, such as roman numerals, letters, words ("twenty-one") and the numbers of other languages, but for those it leaves blank (see below), and with chapter numbers in front of them (`chapterHeadingLevel`), such as 2-5 for page 5 of chapter 2. Each column's lines are broken at its own width, so a paragraph that goes on into a column of another width is broken again there, as Word breaks it. Widow control counts the lines left for the next column as they are broken in the column before, as Word counts them, and a table sized to its text keeps the widths it was sized to in each column it goes on into, as Word keeps them, going past the edge of a narrower one. Columns before a continuous section break are evened out, as Word evens them out, unless a column break is in them or a section in them started in the next column, and the next section starts below the longest. A section that starts in the next column (`SectionType.NEXT_COLUMN`) starts in the next column of the page when the section before has as many columns and one is left, as Word starts it, and on a new page otherwise. When its own columns are of other widths, it is laid out in the page's, where they are and as wide as they are, as Word lays it out, and in its own on the pages after. Its footnotes are laid out in its own columns. A continuous section numbered afresh (`pageNumbers: { start }`) leaves the page it starts on its number, and numbers the next on from its own first number, as Word does: 8 after a section numbered from 7 starts on page 12. When none of it fits on the page before, the page it starts at the top of is its first, numbered 7. One that starts in the next column of a page numbers on through the document, as Word numbers it. A gutter is beside the page's text, or above it in a document that puts it at the top (`w:gutterAtTop`), as Word takes it from the page's height, on every page with mirrored margins too, and below a negative top margin, which the header doesn't push the text below. A paragraph kept together that is taller than a column goes down only the first column of each page, as Word lays it out, from the top of a new page unless it is at the top of this one, and what follows it goes on below it. In columns of different widths it does when it is taller than each of them. One taller than some of them but not others goes in the first column, from where it is, that it fits in, as Word moves it: from the top of a narrow first column to a wide second, and past a narrow second column to a new page, in 3 columns or more as in 2, and the paragraphs kept with the next before it go with it. Paragraphs kept with the next before one taller than each column go to the new page with it, unless they are at the top of the page already, and it moves on to the next page, as Word moves them, so they are alone on theirs. A section that ends with a table has a line below it for the empty paragraph that ends the section, as Word has it -- in [templates](#templates), the divisions of a web page that paragraphs are in (`w:divId`), as documents made from HTML have them, laid out as Word lays them out: a paragraph is indented by the margins left and right of its division and of the divisions that division is in, with the division's borders outside them as a paragraph's borders, and a division's paragraphs are in one box, with its margins above its first and below its last. And pages printed two to a sheet or folded as a booklet (`w:printTwoOnOne` and `w:bookFoldPrinting`), which Word lays out as the section's pages, as it does without +- in [templates](#templates), the divisions of a web page that paragraphs are in (`w:divId`), as documents made from HTML have them, laid out as Word lays them out: a paragraph is indented by the margins left and right of its division and of the divisions that division is in, with the division's borders outside them as a paragraph's borders, and a division's paragraphs are in one box, with its margins above its first and below its last, and at the top of a page below the border and its space, without the margin. Word draws the box once, round the first run of the division's paragraphs: its paragraphs after other paragraphs have its borders left and right but none above or below, its margins above the first and below the last, which stand in for less space before or after of the paragraph's own and give way to more, and the larger of a margin and the space of the paragraph or division next to it between them. And pages printed two to a sheet or folded as a booklet, either way round (`w:printTwoOnOne`, `w:bookFoldPrinting` and `w:bookFoldRevPrinting`), which Word lays out as the section's pages, as it does without - a section's document grid (`grid`), as Chinese and Japanese documents and Word's templates for them have it. On a grid of lines (`DocumentGridType.LINES`), each line takes as many of the grid's lines (`linePitch`) as its own height needs, with its text in the middle, as Word lays it out: at 360 twips, a line of Times New Roman of up to 15.5 points takes one, and from 16 points two. Multiple line spacing takes the grid's lines times the spacing when that is more, so 1.08 lines are 388.8 twips, at least a height takes that height when it is more, and exact spacing is as it is without the grid. The space before and after a paragraph isn't put on the grid's lines, a line of space before or after (in lines) is one of them, and the room below the last line's text can go below the bottom of the page. The lines of table cells, headers and footers aren't on the grid, nor the lines above footnotes and endnotes, but footnotes and endnotes are. A paragraph whose `snapToGrid` is off, in documents Word made, isn't on the grid's lines. A grid of lines and characters (`DocumentGridType.LINES_AND_CHARS`) also adds its `charSpace`, in 4096ths of a point, after each character, and a quarter of a character more between Chinese, Japanese or Korean characters and Latin letters, as Word does. One that snaps to characters (`DocumentGridType.SNAP_TO_CHARS`) puts each Chinese, Japanese or Korean character in as many cells as it needs, as many cells as fit across a column at the size of the Normal style's text and the `charSpace` more, spread evenly across it, and the other text between them on a line in as many cells as it needs together, with text spaced out by its run (`characterSpacing`) as wide as it is spaced. In columns of different widths each column has cells of its own. A left tab, and a line beside a drawing, start at the next cell, Chinese, Japanese or Korean text at a right or centred tab ends at the stop, or is centred on it, in its cells, a picture in the line takes as many cells as it needs after the text before it, a word longer than its line goes on to the next, a word with soft hyphens breaks at the last whose part fits in the cells left, and a justified or distributed line isn't squeezed. Characters of indents are the grid's characters, an indent of part of one is rounded up to the next cell, each line's on its own, as a first line indent of part of a cell beside a left indent of part of one, and an indent of part of a cell before the margin, are, a hanging indent's other lines go that many more cells in, and a tab goes to its stop and the text after it to the next cell, as Word lays them out. Footnotes are on the grid as the body is, and endnotes on the last section's grid. Kerned text is kerned on a grid of characters, and on one that snaps to characters takes as many cells as it needs kerned. On a grid of lines and characters, text in a font that isn't East Asian, such as digits in Calibri, has no quarter of a character beside Chinese, Japanese or Korean characters. Emphasis marks take their room in the line before it is put on the grid, with multiple line spacing and at least a height too. A run with `snapToGrid: false` isn't on a grid of characters, and headers and footers aren't. Sections whose text direction (`page: { textDirection }`) runs across the page are laid out as those without one - text that runs down the page (`page: { textDirection: PageTextDirectionType.TOP_TO_BOTTOM_RIGHT_TO_LEFT }`, and the other directions down it of documents Word made), as Chinese and Japanese documents have it, laid out as Word lays it out: each line runs from the top margin to the bottom one, and the lines go across the page from the right margin, or from the left for the directions that put them that way, each as far from the one before as it is tall, on the section's grid if it has one. Chinese, Japanese and Korean characters in fonts whose characters are all an em, such as MS Mincho and SimSun, are an em down the line, and Latin text is on its side, as wide as it is across a page. Indents are from the top and bottom margins, and the space before and after a paragraph is across the page. Half-width katakana are on their side, half an em each. A tab to a left stop, a border around text or around the paragraph, emphasis marks, superscript and subscript, and a justified line with spaces take the room they take across the page, and a footnote goes below the text, at the left of the page. Two digits set across the line (`w:eastAsianLayout w:vert`) take as much room along it as the line is tall. A gutter is beside the right margin, a negative top or bottom margin is as far from the edge as a positive one, and a grid that snaps to characters puts its cells along the lines. The header and footer stay across the top and bottom of the page, and a header doesn't push the lines down. A section whose text runs down the page starts a new page after one whose text runs across it, as a continuous section does too, and a continuous one goes on on the page after text that runs down it the same way. Endnotes referred to from text that runs down the page go at the end of the document, down the page too, and endnotes from a section followed by one whose text runs another way end with their own section, before it, as Word ends them @@ -271,9 +271,9 @@ It stops at the first thing it can't lay out yet, and the page numbers of the he - tracked changes Word hasn't been seen laying out: a field only part of which is deleted, a deleted paragraph mark at the end of a content control with no paragraph after it, or before one bound to custom XML, a deleted section break of a paragraph with text shown before a table, a deleted footnote or endnote reference with a mark of its own, whose note Word lays out after the others, a cell merged down from a deleted row with something in it, a deleted row whose borders above and below it take different room, or, at the top or bottom of the table, other room than the table's own top or bottom border would, and a deleted row in a header of several rows (`tableHeader`) whose table style formats some of its rows by where they are, such as its first row or its bands - a date or time (a `DATE` or `TIME` field, or a `DayLong`, `MonthLong`, `YearLong` and the like) in the text, a footnote or an endnote, as Word writes the date and time it opens the document, whose width changes with them. One in a header or footer is laid out as it is written - a page reference, number of pages or page number in a format other than those above, or with a picture Word's text isn't known for, as above, or past what its format writes, such as 781 in letters -- in a document in compatibility mode, which Word lays out as Word 2010, 2007 or 2003 did (one saved by those versions of Word, or by an application that writes their mode, or given `compatibility: { version: 14 }`, 12 or 11), what those versions lay out unlike Word 2013 and haven't been seen laying out: text after a tab past the end of the line that goes more than 941 points past the margin, a line beside a frame in a gap narrower than 100 points, or beside a picture or a table that text wraps around in one narrower than 50 points, or 94 for text not aligned left, which they may leave empty, a table that text wraps around sized to its text or lined up across the page, a table sized to its text as a share of the width, or in a table cell indented or as a share of its width, a table with no width of its own widened for a long word past the room for it or with its rows evened out, and any of the `compatibility` options, which Word 2013 leaves out in its own mode, but the older ones may follow; and in Word 2007's and 2003's modes, Chinese, Japanese and Korean text in an East Asian language, and VML drawings that take room other than a text box in the line. The rest is laid out as in Word 2013's mode, but that: justified and distributed lines, and lines justified for Thai or with a low kashida, aren't squeezed, so they break as lines aligned left do; a tab to a stop past the end of the line goes to that stop on the line, past the margin, and the rest of the paragraph's text stays on that line; a table sized to its text has its first and last cells' margins beside the room for it, the page's text or what its indent leaves of it, as Word 2010 and before line a table's text up with its indent rather than its borders, but in a table cell; a table that text wraps around is placed with its first cell's text where it is placed across the page; ligatures are drawn only with Word's `enableOpenTypeFeatures` on, as Word 2010 writes it; and in Word 2007's and 2003's modes, Chinese and Japanese text breaks only at its spaces, as Latin text does, and a text box's outline takes no room in its line. A mode Word doesn't have, such as 13, stops the layout -- a compatibility setting that changes how Word lays out lines in compatibility mode 15 in a way not yet followed: with `suppressTopSpacing`, a line at the top of a page or column at multiple spacing of less than a line or on a document grid, and a paragraph's later line there below a border above it; with `useFELayout`, Chinese, Japanese and Korean text beside other text, such as Latin letters and digits, which Word spaces apart unless the paragraph turns both of its automatic spacings off (`w:autoSpaceDE` and `w:autoSpaceDN`, in templates), and any text where another of the East Asian `compatibility` options is on too. `suppressTopSpacing` is followed otherwise: Word leaves out the space above the text of a line at the top of a page or column, a paragraph's first or a later one, and below the space before a section's first paragraph too, at exact spacing all but 9.6 points of the 80% of the line above its baseline, and at at-least spacing all but 9.6 points of that height, whether the line is taller or shorter than it, and leaves a line of single or multiple spacing as it is, as it does the first line of a paragraph with a border above it and the lines of a table's cells. `useFELayout` leaves the lines of other paragraphs as they are. The other `compatibility` options, which ask for an older Word's or another application's layout, Word lays out lines with as without them in its own mode, so they don't stop it, and `doNotUseHTMLParagraphAutoSpacing` is followed. In [templates](#templates), Word's own settings (`overrideTableStyleFontSizeAndJustification`, `enableOpenTypeFeatures`, `doNotFlipMirrorIndents`, `differentiateMultirowTableHeaders`, `useWord2013TrackBottomHyphenation`, `allowHyphenationAtTrackBottom` and `allowTextAfterFloatingTableBreak`) leave Word's lines as they are too, and those it doesn't know, such as ones a later Word may write, stop it whether they are on or off. Settings for other applications, whose `w:uri` isn't Word's, are left to them, as Word leaves them -- in [templates](#templates), what `docx` doesn't write and Word lays out in ways not yet followed: space between a row's cells as a share of the table's width, a table indent of a type other than twips or a share of the width, a row with table properties of its own other than borders and cell margins, a table style with formatting of its rows or cells other than its rows' height, its rows kept whole and its cells' margins, or a part of one for some cells with properties other than borders, margins, a height for its rows, its rows kept whole and space between cells, text with a phonetic guide, text fitted to a width with other than text in it, wider than its line or in runs of other sizes or fonts, two lines in one with brackets, of Chinese, Japanese or Korean text or at a size of a fraction of a point, and horizontal in vertical text, ink and other content parts, a subdocument, a paragraph in an HTML division with indents, borders or space before or after it of its own, at the top of a page or column, in a table cell, note, header, footer or text box, or in a division next to another, next to a paragraph with space between them, in another with borders or other margins above or below, or that is a quotation or a page's body, cells merged across columns as old versions of Word wrote them with text after the first, footnotes in more than 4 columns of their own, or in columns of their own in a section of several columns, of text that runs down the page, or whose columns are spaced otherwise than half an inch apart, endnotes numbered afresh on each page, footnotes numbered afresh on each page after a section on the page numbered otherwise, or in a format not yet written, footnotes anywhere but at the bottom of the page or just below the text, and below the text of columns, or after space below the last paragraph of a page whose text goes on, or of the document, a content control bound to custom XML or the document's properties that Word fills in with other text than is written in it when it opens the document (one whose text is already the XML's is laid out as it is), pages printed as a booklet folded the other way round, for text that runs right to left, styles Word updates from the document's template when it opens it, and an imported document (`w:altChunk`) in another format than `.docx`, such as HTML, RTF or plain text, which Word converts its own way, of more than one section, whose formatting is kept as it is (`w:matchSrc`), with a style of its own where its defaults leave out some of the template's, or with a page reference or number of pages, whose number `docx` can't write in it +- in a document in compatibility mode, which Word lays out as Word 2010, 2007 or 2003 did (one saved by those versions of Word, or by an application that writes their mode, or given `compatibility: { version: 14 }`, 12 or 11), what those versions lay out unlike Word 2013 and haven't been seen laying out: a line beside a frame in a gap between 62.5 and 75 points, or of text centred or aligned right in one narrower than 75, or beside a picture or a table that text wraps around in one narrower than 25 points for text aligned left, 50 for justified, 75 for centred and 94 for right-aligned, a line whose only room is a gap beside a frame that they leave empty, a table sized to its text in a table cell indented or as a share of its width, a table with space between its cells or a share of the width widened for a long word or with its rows evened out, and any of the `compatibility` options, which Word 2013 leaves out in its own mode, but the older ones may follow; and in Word 2007's and 2003's modes, VML shapes that text flows around other than a text box, embedded objects, and VML drawings in a header, footer or text box. The rest is laid out as in Word 2013's mode, but that: justified and distributed lines, and lines justified for Thai or with a low kashida, aren't squeezed, so they break as lines aligned left do; a tab to a stop past the end of the line goes to that stop on the line, past the margin, and the rest of the paragraph's text stays on that line as far as 22 inches from where the lines start, where it goes on to the next line; a gap of 62.5 points or less beside a frame is left empty, of text aligned left or justified, and the line goes in the room beside it; a table sized to its text has its first and last cells' margins beside the room for it, the page's text or what its indent leaves of it, as Word 2010 and before line a table's text up with its indent rather than its borders, but in a table cell, and one of a share of the width is that share of the room with the margins, whatever its indent; a table whose cells all have widths grows for a long word to the room with the margins beside it, its columns narrowed in proportion to their widest words, and has its rows evened out as Word 2013 does; a table that text wraps around is placed with its first cell's text where it is placed across the page, sized to its text too, and one lined up across the page as Word 2013 places it; ligatures are drawn only with Word's `enableOpenTypeFeatures` on, as Word 2010 writes it; and in Word 2007's and 2003's modes, Chinese and Japanese text breaks only at its spaces, as Latin text does, in an East Asian language too, and a text box's or a shape's outline takes no room in its line, nor beside a text box that text flows around. A mode Word doesn't have, such as 13, stops the layout +- a compatibility setting that changes how Word lays out lines in compatibility mode 15 in a way not yet followed: with `suppressTopSpacing`, a line at the top of a page or column on a document grid; with `useFELayout`, Chinese, Japanese and Korean text beside letters of another script than Latin, East Asian punctuation or full-width forms beside Latin letters or digits, or Chinese, Japanese and Korean text beside Latin letters or digits in a font whose average character width isn't known, such as Courier New, Yu Mincho or a bold East Asian font, and any text where another of the East Asian `compatibility` options is on too. `suppressTopSpacing` is followed otherwise: Word leaves out the space above the text of a line at the top of a page or column, a paragraph's first or a later one, and below the space before a section's first paragraph too, at exact spacing all but 9.6 points of the 80% of the line above its baseline, and at at-least spacing all but 9.6 points of that height, whether the line is taller or shorter than it, in a document of any default font and below a header too, and leaves a line of single or multiple spacing as it is, of less than a line too, as it does the lines of a paragraph with a border above it, its first and a later one at the top of a page, and the lines of a table's cells. `useFELayout` is followed too: Word puts half the average width of a character of the font before, at its size, between Chinese, Japanese or Korean text and a Latin letter beside it (`w:autoSpaceDE`, in templates), and between it and a digit (`w:autoSpaceDN`), as the paragraph has them on unless it turns them off: 52.5 twips after MS Mincho 10.5 and 54.7 after Calibri 10.5, and nothing beside a space or punctuation. It leaves the lines of other paragraphs as they are. The other `compatibility` options, which ask for an older Word's or another application's layout, Word lays out lines with as without them in its own mode, so they don't stop it, and `doNotUseHTMLParagraphAutoSpacing` is followed. In [templates](#templates), Word's own settings (`overrideTableStyleFontSizeAndJustification`, `enableOpenTypeFeatures`, `doNotFlipMirrorIndents`, `differentiateMultirowTableHeaders`, `useWord2013TrackBottomHyphenation`, `allowHyphenationAtTrackBottom` and `allowTextAfterFloatingTableBreak`) leave Word's lines as they are too, and those it doesn't know, such as ones a later Word may write, stop it whether they are on or off. Settings for other applications, whose `w:uri` isn't Word's, are left to them, as Word leaves them +- in [templates](#templates), what `docx` doesn't write and Word lays out in ways not yet followed: space between a row's cells as a share of the table's width, a table indent of a type other than twips or a share of the width, a row with table properties of its own other than borders and cell margins, a table style with formatting of its rows or cells other than its rows' height, its rows kept whole and its cells' margins, or a part of one for some cells with properties other than borders, margins, a height for its rows, its rows kept whole and space between cells, text with a phonetic guide, text fitted to a width with other than text in it, wider than its line or in runs of other sizes or fonts, two lines in one with brackets, of Chinese, Japanese or Korean text or at a size of a fraction of a point, and horizontal in vertical text, ink and other content parts, a subdocument, a paragraph in an HTML division with indents or borders of its own, with automatic space before or after it or space in lines, with space before or after it of its own below the division's border above it or above the one below it or between two of its paragraphs, without a border above it at the top of a page or column, in a table cell, note, header, footer or text box, or in a division next to another or to a paragraph with space between them where the division's border is, or in a document that adds the space after a paragraph to the space before the next, in another with borders or other margins above or below, or that is a quotation or a page's body, cells merged across columns as old versions of Word wrote them with text after the first, footnotes in more than 4 columns of their own, or in columns of their own in a section of several columns, of text that runs down the page, or whose columns are spaced otherwise than half an inch apart, endnotes numbered afresh on each page, footnotes numbered afresh on each page after a section on the page numbered otherwise, or in a format not yet written, footnotes anywhere but at the bottom of the page or just below the text, and below the text of columns, or after space below the last paragraph of a page whose text goes on, or of the document, a content control bound to custom XML or the document's properties that Word fills in with other text than is written in it when it opens the document (one whose text is already the XML's is laid out as it is), styles Word updates from the document's template when it opens it, and an imported document (`w:altChunk`) in another format than `.docx`, such as HTML, RTF or plain text, which Word converts its own way, of more than one section, whose formatting is kept as it is (`w:matchSrc`), with a style of its own where its defaults leave out some of the template's, or with a page reference or number of pages, whose number `docx` can't write in it When laying out the pages again with the page numbers it worked out still changes them after three passes, as when a table of contents wraps one way with a number and the other way without it, all of them are left blank, and `layoutDocument` lays out the pages without them. diff --git a/scripts/layout-probes/stops2/README.md b/scripts/layout-probes/stops2/README.md index 0aed6e5ac0..5dad7e7ad7 100644 --- a/scripts/layout-probes/stops2/README.md +++ b/scripts/layout-probes/stops2/README.md @@ -33,7 +33,8 @@ committed here are the ones a change to docx/layout has followed, with Word's PD | `word-stops-marks.ts` | HD1 to HD10, TR1 to TR11 | HD1 to HD10 (`word-stops-hidden`, `-hidden-edges`): paragraphs joined by a hidden mark in the first one's indents, tabs and borders, spaced line by line, across a control's end, sized as one; hidden notes laid out and counted. TR1 to TR11 (`word-stops-tracked`, `-tracked-edges`, `-moves`, in balloons, the page scaled 0.7422): deleted room counts in columns' widths, deleted endnotes and moves are counted, deleted section breaks leave theirs to the next | | `word-stops-compat-mode.ts` | CM1 to CM22, in modes 15 to 11 | Word 2010 and before laid out all but a few alike: justified lines not squeezed (CM1), a table's text at its indent, one sized to its text with its cells' margins beside the room (CM4) | | `word-stops-pages.ts` | CO1, CO2, GT1, DV1, TB10, BK1, TO1 | CO1, CO2: kept paragraphs in 3 columns as in 2; GT1: a gutter at the top below a negative margin; DV1b: a row in a division as tall; TO1: two pages to a sheet as the section's | -| `word-stops-compat2.ts` | CN, ST6 to ST12, BK2, DV2, FE2 | CN: modes 14 and 12 as 15 but tabs past the end at their stops, the line past the margin (CN5), no ligatures (CN2b), tables in a cell as in 15 (CN8d), floating ones' text at their place (CN9), in 12 East Asian text broken only at spaces (CN10), a text box's outline no room (CN11); ST6 to ST12: at least X leaves out X less 9.6 points, multiple spacing, cells and a border as they are; BK2: a booklet's pages as the section's; DV2: divisions' margins and borders as paragraphs'; FE2: useFELayout as without it but East Asian text beside Latin | +| `word-stops-compat2.ts` | CN, ST6 to ST15, BK2, BK3, DV2, FE2 | CN: modes 14 and 12 as 15 but tabs past the end at their stops, the line past the margin (CN5), no ligatures (CN2b), tables in a cell as in 15 (CN8d), floating ones' text at their place (CN9), in 12 East Asian text broken only at spaces (CN10), a text box's outline no room (CN11); ST6 to ST15: at least X leaves out X less 9.6 points, in Calibri 20 below a header too, other spacing, cells, borders as they are; BK2, BK3: a booklet's pages as the section's, folded either way; DV2: divisions' margins and borders as paragraphs'; FE2: useFELayout spaces East Asian from Latin | +| `word-stops-compat3.ts` | CN12 to CN18, ST16, DV3, FE3 | CN12: a share of the width is of the text and two margins; CN13: gaps of 1250 or less beside a frame empty, pictures' as in 15; CN14: text after a tab on the line to 22 inches; CN15: floating tables sized to text shifted as CN9, centred as in 15; CN16: widened to the room and margins, rows evened; CN17: in 12 East Asian text in its language as in none; CN18: in 12 a shape's outline no room; ST16: 0.8 lines and a bordered later line as they are; DV3: a division's box drawn once, later paragraphs with margins and side borders; FE3: half the font's average character width | | `word-stops-east-asian.ts` | GR1 to GR13, VD1 to VD13, EA1 to EA3 | GR1 to GR12: notes, spaced and kerned text, marks, tabs, pictures, long words and columns on grids; VD1 to VD13: text down the page with tabs, borders, notes, gutters, grids; EA1 to EA3: no change in text of no language | | `word-stops-east-asian2.ts` | GR14 to GR16, EA4 | GR14a to GR14f: indents of part of a cell rounded up to the next, a hanging indent's other lines that many cells more; GR16a to GR16f: soft hyphens, distributed lines, right and centred tabs, emphasis marks at least a height, kerning and pictures on grids; GR15a, GR15c: endnotes on the last section's grid; EA4a to EA4c: the strict rules keep small kana from the start of a line, and compressed punctuation is left as it is aligned left | | `word-stops-imported.ts` | IM1 to IM3 | IM2a to IM2d: kept formatting keeps its own paragraph and character styles but takes the document's table styles and theme, its last paragraph without space after; IM3: no font or size in its defaults is Times New Roman 10 | @@ -89,8 +90,12 @@ is a line of its own above its base in `word-stops.py`, so the base's line is "n it are where they are; Word fitted one more "m" of TA12h's 110 on the number's line than docx/layout's widths do, 44 ending at 9022 twips where the 44th ends 1.4 past 9026 in them, with three lines either way. `word-stops-compat2.ts`'s `word-stops-top-spacing3` (ST13 to ST15) and `word-stops-booklet3` (BK3), which round 25 -left out, and `word-stops-compat3.ts`, which has what the compatibility modes, `suppressTopSpacing`, `useFELayout` and -HTML divisions still leave stopping (CN12 to CN18, ST16, DV3 and FE3), are for the next batch. +left out, and `word-stops-compat3.ts`'s probes of what the compatibility modes, `suppressTopSpacing`, `useFELayout` and +HTML divisions left stopping (CN12 to CN18, ST16, DV3 and FE3) were saved in round 26 too and are followed as the table +says. `word-stops-divisions2`'s paragraphs are all in the division of `word-stops-divisions`' DV2a, so DV3b to DV3f showed +how Word lays out a division's paragraphs after its first run, with its margins and side borders but no box, and not the +box's own edges beside spacing, which still stop. `word-stops-compat4.ts` has those, and what else the round left open +(DV4, DV5, CN19 to CN21, FE4), for a later batch; it has no PDF from Word yet. `word-stops-equations.py` reads the equations' widths and heights from Word's PDFs, and `word-equation-characters.py` EQ27's width of each character, which Cambria Math's own widths in `src/layout/cambria-math.ts`, generated by diff --git a/scripts/layout-probes/stops2/word-stops-booklet3.docx b/scripts/layout-probes/stops2/word-stops-booklet3.docx new file mode 100644 index 0000000000..db8f73a4ec Binary files /dev/null and b/scripts/layout-probes/stops2/word-stops-booklet3.docx differ diff --git a/scripts/layout-probes/stops2/word-stops-booklet3.pdf b/scripts/layout-probes/stops2/word-stops-booklet3.pdf new file mode 100644 index 0000000000..e9e6d7dd7d Binary files /dev/null and b/scripts/layout-probes/stops2/word-stops-booklet3.pdf differ diff --git a/scripts/layout-probes/stops2/word-stops-compat2.ts b/scripts/layout-probes/stops2/word-stops-compat2.ts index 29790fa95e..aac3232202 100644 --- a/scripts/layout-probes/stops2/word-stops-compat2.ts +++ b/scripts/layout-probes/stops2/word-stops-compat2.ts @@ -58,8 +58,8 @@ * a paragraph with a right indent of 1000 (FE2b), Chinese (FE2c), and FE1's Japanese with Latin words with both * autoSpaceDE and autoSpaceDN off (FE2d; FE1b had only autoSpaceDN off), whose lines Word breaks otherwise than without it * - * What Word showed, in the PDFs saved from Word 16 for Mac in round 25 (word-stops-top-spacing3 and word-stops-booklet3 - * weren't saved): + * What Word showed, in the PDFs saved from Word 16 for Mac in round 25, and in round 26 for word-stops-top-spacing3 and + * word-stops-booklet3: * * - Modes 14 and 12 laid out CN1a, CN1b, CN2a, CN3, CN6a to CN6d, CN7a, CN7b and CN8c as mode 15 does: the paragraph after a * page break at the top of the next page, gaps of 1000 to 2500 twips beside a picture and 2000 beside a frame filled @@ -84,7 +84,11 @@ * ST7: multiple spacing as it is; ST8: a paragraph's later line at the top of the next page cut as its first; ST9a to * ST9c: a table's cells as they are; ST10: cut below the space before a section's first paragraph; ST11: below a border * above, as it is; ST12: after a page break in the paragraph before, cut - * - BK2: each page laid out as the section's A4 page, two to a sheet in the booklet's order + * - ST13, ST14a, ST14b: in a document of Calibri 20 below a header of 869 twips, exactly 30 and 40 and at least 40 cut as + * in Calibri 11, their baselines 16.3 points down the page, from the header's end; ST15: the header's own first line at + * exactly 30 as it is + * - BK2: each page laid out as the section's A4 page, two to a sheet in the booklet's order; BK3: folded the other way + * round, the same pages, each sheet's two the other way round: 1 and 4, then 3 and 2 * - DV2a, DV2b, DV2d: text indented by the margins, added up for a division in another, with the margin, border and its space * above the division and below it once; DV2c: with space before and after of its own, 240 twips above and below it, and * no border drawn above or below diff --git a/scripts/layout-probes/stops2/word-stops-compat3-12.docx b/scripts/layout-probes/stops2/word-stops-compat3-12.docx new file mode 100644 index 0000000000..549011a2c3 Binary files /dev/null and b/scripts/layout-probes/stops2/word-stops-compat3-12.docx differ diff --git a/scripts/layout-probes/stops2/word-stops-compat3-12.pdf b/scripts/layout-probes/stops2/word-stops-compat3-12.pdf new file mode 100644 index 0000000000..4c3ef8fb61 Binary files /dev/null and b/scripts/layout-probes/stops2/word-stops-compat3-12.pdf differ diff --git a/scripts/layout-probes/stops2/word-stops-compat3-14.docx b/scripts/layout-probes/stops2/word-stops-compat3-14.docx new file mode 100644 index 0000000000..b73b46c1b9 Binary files /dev/null and b/scripts/layout-probes/stops2/word-stops-compat3-14.docx differ diff --git a/scripts/layout-probes/stops2/word-stops-compat3-14.pdf b/scripts/layout-probes/stops2/word-stops-compat3-14.pdf new file mode 100644 index 0000000000..d008fec7bf Binary files /dev/null and b/scripts/layout-probes/stops2/word-stops-compat3-14.pdf differ diff --git a/scripts/layout-probes/stops2/word-stops-compat3-15.docx b/scripts/layout-probes/stops2/word-stops-compat3-15.docx new file mode 100644 index 0000000000..1866898f65 Binary files /dev/null and b/scripts/layout-probes/stops2/word-stops-compat3-15.docx differ diff --git a/scripts/layout-probes/stops2/word-stops-compat3-15.pdf b/scripts/layout-probes/stops2/word-stops-compat3-15.pdf new file mode 100644 index 0000000000..4f348fe80d Binary files /dev/null and b/scripts/layout-probes/stops2/word-stops-compat3-15.pdf differ diff --git a/scripts/layout-probes/stops2/word-stops-compat3.ts b/scripts/layout-probes/stops2/word-stops-compat3.ts index fec5def4bc..25ef7e600e 100644 --- a/scripts/layout-probes/stops2/word-stops-compat3.ts +++ b/scripts/layout-probes/stops2/word-stops-compat3.ts @@ -53,6 +53,39 @@ * FE3b: with autoSpaceDE off and autoSpaceDN on, numbers among the ideographs * FE3c: with autoSpaceDE on and autoSpaceDN off, Latin words among them (FE1b, with a full stop at the start of a line) * + * What Word showed, in the PDFs saved from Word 16 for Mac in round 26, read with `word-stops.py`, `whole-lines.py` and the + * PDFs' content streams (Word draws text at sizes rounded to 1/300 inch, and each run's start is exact): + * + * - CN12a to CN12c: in modes 14 and 12 a table of a share of the width is that share of the page's text and its first and + * last cells' margins, whatever its indent: 4611 twips between the borders of 50% indented 720 and 6926 of 75%, where + * mode 15's are 4501 and 6754, its text at its indent, and 25% widened for its words as in mode 15, 115 to the left + * - CN13: beside a picture, text aligned left in gaps of 500 and 750 (CN13f, CN13g), justified in 1000 (CN13a) and centred + * in 1500 (CN13h), as in mode 15; beside a frame, gaps of 1000 and 1250 left empty (CN13b, CN13c), the lines in the room + * right of it, and text in 1500 and 1750 (CN13d, CN13e) + * - CN14: the text after the tab on the line to 31580 twips, 22 inches from the margin, and the word after it starting the + * next line, which breaks as the paragraph's lines do + * - CN15a: a floating table sized to its text 115 to the left of mode 15's, its text at 1997 and the text beside it at 3269, + * as CN9's with a width; CN15b: one centred as in mode 15; CN15c, CN15d: as mode 15 with the shift, as the layout had them + * - CN16a: the table widened to 9242, the page's text and two margins, its columns 7943, 642 and 647 where mode 15's are + * 7737, 632 and 633 of 9002: narrowed in proportion as in mode 15; CN16b: rows evened out as in mode 15, the text at 0 + * - CN17a, CN17b: in mode 12, Japanese and Chinese in their languages broken as in no language: after the last character + * that fits, a comma at the start of a line too, and in mode 14 as in 15 + * - CN18a: in mode 12 the rectangle's line 1062 twips from its top rather than 1081 and "after" at 3266 rather than 3285: + * no room for its outline of a point, as the text box's (CN11); CN18b: the floating text box sized to its text (height + * auto) in every mode, the text beside it at 5200 in 15 and 14 and 5179 in 12 + * - ST16a: 0.8 lines as it is, its text 42 twips above the top as a 0.8 line's is; ST16b: the bordered paragraph's later + * line at the top of the next page as it is, its baseline 480 down the line + * - DV3a: at the top of a page, the text 110 twips down, below the border and its space without the margin, the borders + * drawn; DV3b to DV3f, whose paragraphs are in division 1001 after DV3a's: no border above or below, its left and right + * borders beside each line, and 120 above the first and below the last, the larger of 120 and the paragraph's own 60 or + * 240 (DV3c, DV3d), of 120 and the 60 after the paragraph before (DV3e), and of 1001's and 1002's margins (DV3b). Word + * draws a division's box once, round the first run of its paragraphs, as in word-stops-divisions.docx (DV2a boxed, DV2c + * not). DV3c's first line fit "lighthouse" and not "of", which the layout fits by 0.6 twips + * - FE3a: 52.5 twips after the Japanese before "Latin words" in Calibri 14 and 73.4 after it, and after Calibri 10.5 + * (word-stops-fe-layout.docx FE1a) 55.0 after "words" and 54.6 after "123": half the font's average character width + * (OS/2 xAvgCharWidth: 1067 of 2048 for Calibri, 128 of 256 for MS Mincho) at the size of the character before; FE3b: the + * digits spaced and the letters not; FE3c: the letters spaced and the digits not + * * Usage: npm run run-ts -- scripts/layout-probes/stops2/word-stops-compat3.ts [folder] */ import { diff --git a/scripts/layout-probes/stops2/word-stops-compat4.ts b/scripts/layout-probes/stops2/word-stops-compat4.ts new file mode 100644 index 0000000000..97a87df08d --- /dev/null +++ b/scripts/layout-probes/stops2/word-stops-compat4.ts @@ -0,0 +1,356 @@ +/** + * Probes of what `word-stops-compat3.ts` left open, where docx/layout still stops after following what Word's PDFs of it + * showed in round 26. Each probe starts a page, between a line above and a line below it, in Calibri 11 on A4 with inch + * margins, unless it says. `word-stops.py` reads them all, and `whole-layout.ts` with `whole-lines.py` the divisions, whose + * paragraphs Word lays out by the order of their divisions in the document. + * + * word-stops-divisions3.docx: paragraphs in HTML divisions, each probe in divisions of its own, as documents made from HTML + * have them, so each is the first run of its division's paragraphs, whose box Word draws (`word-stops-divisions2.docx` + * DV3b to DV3f were in the division of DV3a, after it, and showed no box). Each bordered division has margins of 720 left + * and right and 120 above and below, and borders of 1.5 points 4 points away; those without borders the margins alone + * DV4a: a paragraph with 12 points before and after it in a bordered division ("a paragraph in an HTML division with space + * before or after it, where the division has a border there") + * DV4b: a bordered division after a paragraph with 12 points after it, and before one with 12 points before it ("an HTML + * division with a border above or below it next to a paragraph with space between them") + * DV4c: a bordered division next to one without borders, and one without borders next to a bordered one ("... or next to + * another division") + * DV4d: a division without borders at the top of a page, after a page break ("a paragraph in an HTML division without a + * border above it at the top of a page or column") + * DV4e: three paragraphs in a bordered division, the middle one with 6 points before and after it ("a paragraph in an HTML + * division with space before or after it ... or another paragraph of it") + * DV4f: a bordered division of 3 paragraphs of 12 lines going on to the next page, as DV3f did after its first run + * + * word-stops-divisions4.docx: the same divisions in a document that adds the space after a paragraph to the space before + * the next (`w:doNotUseHTMLParagraphAutoSpacing`), where a division's margins beside spacing haven't been seen + * DV5a: a division without borders after a paragraph with 12 points after it ("an HTML division next to a paragraph with + * space between them ... in a document that adds the space after a paragraph to the space before the next") + * DV5b: two divisions without borders next to each other ("... or to another division") + * + * word-stops-compat4-15.docx, -14 and -12: the same pages in compatibility modes 15 (the control), 14 and 12 + * CN19: prose beside frames and pictures, with no distance from the text: frames 1300 and 1400 twips from the margin of + * prose aligned left (CN19a, CN19b), between the 1250 Word 2010 left empty and the 1500 it filled; a frame 1000 from it of + * centred (CN19c) and right-aligned prose (CN19d); a picture 1000 from it of right-aligned prose (CN19e) and 500 of + * centred (CN19f) ("a line beside a drawing or frame in a gap narrower than Word was seen putting text in") + * CN20: a VML rectangle 100 by 50 points with an outline of a point placed 100 points from the margin with square wrapping + * (CN20a), and docx's text box in the line of a header (CN20b, in the header of CN20's pages) ("a VML shape that text + * flows around ... or a VML drawing in a header, footer or text box, in a document in compatibility mode 12 or 11") + * CN21: tables whose cells all have widths of 2000 with a word of 2400, of half the width (CN21a) and with space of 30 + * twips between the cells (CN21b) ("a table with space between its cells or a share of the width widened for a long word, + * or with its rows evened out, in a document in compatibility mode") + * + * word-stops-fe-layout4.docx, with useFELayout on, Japanese in MS Mincho 10.5 with Latin words: + * FE4a: the Latin words in Arial, Times New Roman and Cambria 12, whose average character widths are 441, 401 and 615 + * thousandths of an em, to check the half of it Word puts after them: 26.5, 24.1 and 36.9 twips + * FE4b: the Latin words in Calibri bold 10.5 (536 thousandths: 56.3 twips) and Calibri 8 (521: 41.7) + * FE4c: the Japanese in Yu Mincho 10.5, whose average is 969 thousandths (101.7 twips, or 52.5 for a quarter of its em) + * FE4d: Japanese beside Greek letters and full-width Latin letters ("East Asian text beside letters of another script than + * Latin, or East Asian punctuation or full-width forms beside Latin letters or digits"), and beside Latin punctuation, + * which Word left as it is in FE2c, as a check + * FE4e: 42 ideographs filling a line of 8850 twips (a right indent of 176) and then Latin words, to show whether the space + * after the last ideograph counts against the line, which would send the ideograph to the next line + * FE4f: a right-aligned paragraph of Japanese ending in Latin words, and one ending in Japanese after Latin words, to show + * whether a space at the end of the line moves the text + * + * Usage: npm run run-ts -- scripts/layout-probes/stops2/word-stops-compat4.ts [folder] + */ +import { AlignmentType, FrameAnchorType, Header, PageBreak, Paragraph, Table, TableRow, TextRun, Textbox, WidthType } from "docx"; + +import { + ALL_BORDERS, + type Child, + type Injection, + PAGE, + cell, + injectIntoParagraph, + line, + marker, + para, + picture, + probe, + prose, + replaceMarkerRun, + write, +} from "./kit"; + +// The divisions: each probe's own, 2001 and on, bordered or not +const BORDER = 'w:val="single" w:sz="12" w:space="4" w:color="000000"'; +const MARGINS = ''; +const division = (id: number, bordered: boolean): string => + `${MARGINS}${ + bordered ? `` : "" + }`; +const webSettings = + (divisions: readonly string[]): Injection => + (parts) => { + parts.set( + "word/webSettings.xml", + '' + + `${divisions.join("")}`, + ); + const rels = parts.get("word/_rels/document.xml.rels")!; + parts.set( + "word/_rels/document.xml.rels", + rels.replace( + "", + '', + ), + ); + const types = parts.get("[Content_Types].xml")!; + parts.set( + "[Content_Types].xml", + types.replace( + "", + '', + ), + ); + }; + +// The document adds the space after a paragraph to the space before the next (`w:doNotUseHTMLParagraphAutoSpacing`, in +// the compatibility settings) +const addsParagraphSpacing: Injection = (parts) => { + const text = parts.get("word/settings.xml")!; + const at = text.indexOf(""); + if (at < 0) { + throw new Error("No compatibility settings in word/settings.xml"); + } + parts.set("word/settings.xml", text.replace("", "")); +}; + +const divisionDocument = async ( + name: string, + probes: (inDivision: (text: string, id: number, options?: object) => Paragraph) => Child[], + extra: readonly Injection[] = [], +) => { + const injections: Injection[] = []; + const divisions: string[] = []; + const inDivision = (text: string, id: number, options: object = {}): Paragraph => { + const markerName = `DIV${injections.length + 1}`; + injections.push(injectIntoParagraph(markerName, { pPr: `` })); + return new Paragraph({ ...options, children: [new TextRun(text), marker(markerName)] }); + }; + const declare = (id: number, bordered: boolean): number => { + divisions.push(division(id, bordered)); + return id; + }; + const children = probes((text, id, options) => inDivision(text, declare(id, id % 2 === 1), options)); + await write({ name, sections: [{ properties: PAGE, children }], injections: [...injections, webSettings(divisions), ...extra] }); +}; + +// Odd ids are bordered, even ones have margins alone +await divisionDocument("word-stops-divisions3", (inDivision) => [ + ...probe("DV4a", [inDivision(`DV4a ${prose(60)}`, 2001, { spacing: { before: 240, after: 240 } })]), + ...probe("DV4b", [ + para("DV4b before", 20, { spacing: { after: 240 } }), + inDivision(`DV4b ${prose(60)}`, 2003), + para("DV4b after", 20, { spacing: { before: 240 } }), + ]), + ...probe("DV4c", [ + inDivision(`DV4c first ${prose(60)}`, 2005), + inDivision(`DV4c second ${prose(60)}`, 2006), + line("DV4c between"), + inDivision(`DV4c third ${prose(60)}`, 2008), + inDivision(`DV4c fourth ${prose(60)}`, 2009), + ]), + line("DV4d above"), + new Paragraph({ children: [new TextRun("DV4d break"), new PageBreak()] }), + inDivision(`DV4d ${prose(60)}`, 2010), + line("DV4d below"), + ...probe("DV4e", [ + inDivision(`DV4e p1 ${prose(60)}`, 2011), + inDivision(`DV4e p2 ${prose(60)}`, 2011, { spacing: { before: 120, after: 120 } }), + inDivision(`DV4e p3 ${prose(60)}`, 2011), + ]), + ...probe("DV4f", [ + ...Array.from({ length: 36 }, (_, index) => line(`DV4f fill ${index + 1}`)), + ...[1, 2, 3].map((index) => inDivision(`DV4f p${index} ${prose(150)}`, 2013)), + ]), +]); + +await divisionDocument( + "word-stops-divisions4", + (inDivision) => [ + ...probe("DV5a", [para("DV5a before", 20, { spacing: { after: 240 } }), inDivision(`DV5a ${prose(60)}`, 2102)]), + ...probe("DV5b", [inDivision(`DV5b first ${prose(60)}`, 2104), inDivision(`DV5b second ${prose(60)}`, 2106)]), + ], + [addsParagraphSpacing], +); + +// A picture placed on the page with square wrapping, at a distance from the margin in twips, with no distance from the text +const floatPicture = + (name: string, offset: number): Injection => + (parts) => { + const text = parts.get("word/document.xml")!; + const at = text.indexOf(`${name} anchor `); + const start = at < 0 ? -1 : text.indexOf("", start) + "".length; + const inline = text.slice(start, end); + const extent = inline.match(/]*\/>/)![0]; + const inner = inline.slice(inline.indexOf("")); + const anchor = + `` + + `${offset * 635}` + + `0${extent}` + + `${inner.replace(/]*\/>/, "")}`; + parts.set("word/document.xml", text.slice(0, start) + anchor + text.slice(end)); + }; + +const beside = (name: string, alignment: (typeof AlignmentType)[keyof typeof AlignmentType]): Child[] => + probe(name, [new Paragraph({ alignment, children: [new TextRun(`${name} anchor ${prose(150)}`), picture(72)] })]); + +const framed = (name: string, x: number, alignment: (typeof AlignmentType)[keyof typeof AlignmentType] = AlignmentType.LEFT): Child[] => + probe(name, [ + new Paragraph({ + frame: { + type: "absolute", + position: { x, y: 600 }, + width: 3000, + height: 1000, + anchor: { horizontal: FrameAnchorType.MARGIN, vertical: FrameAnchorType.TEXT }, + }, + children: [new TextRun(`${name} frame`)], + }), + para(`${name} beside`, 200, { alignment }), + ]); + +// The pictures beside CN19e and CN19f, by their distances from the margin +const PICTURES = { CN19e: 1000, CN19f: 500 } as const; +const RECTANGLE = + ''; +// Space of 30 twips between the cells of CN21b's table +const cellSpacing: Injection = (parts) => { + const text = parts.get("word/document.xml")!; + const at = text.indexOf("CN21b"); + const table = at < 0 ? -1 : text.lastIndexOf("", at); + const width = table < 0 ? -1 : text.indexOf("/>", text.indexOf("${text.slice(width)}`); +}; + +const widened = (name: string, options: object): Table => + new Table({ + borders: ALL_BORDERS, + columnWidths: [2000, 2000, 2000], + ...options, + rows: [ + new TableRow({ + children: [ + cell(`${name} ${"lighthouse".repeat(4)}`, { width: { size: 2000, type: WidthType.DXA } }), + cell(`${name} ${prose(20)}`, { width: { size: 2000, type: WidthType.DXA } }), + cell(`${name} ${prose(20)}`, { width: { size: 2000, type: WidthType.DXA } }), + ], + }), + ], + }); + +const compatPages = (): Child[] => [ + ...framed("CN19a", 1300), + ...framed("CN19b", 1400), + ...framed("CN19c", 1000, AlignmentType.CENTER), + ...framed("CN19d", 1000, AlignmentType.RIGHT), + ...beside("CN19e", AlignmentType.RIGHT), + ...beside("CN19f", AlignmentType.CENTER), + ...probe("CN20a", [new Paragraph({ children: [new TextRun("CN20a anchor "), marker("CN20a"), new TextRun(prose(150))] })]), + ...probe("CN21a", [widened("CN21a", { width: { size: 50, type: WidthType.PERCENTAGE } })]), + ...probe("CN21b", [widened("CN21b", {})]), +]; + +for (const mode of [15, 14, 12]) { + await write({ + name: `word-stops-compat4-${mode}`, + options: { compatibility: { version: mode } }, + sections: [ + { + properties: PAGE, + headers: { + default: new Header({ + children: [ + new Paragraph({ + children: [ + new TextRun("CN20b header "), + new Textbox({ style: { width: "150pt", height: "auto" }, children: [line("CN20b in the box")] }), + new TextRun(" after"), + ], + }), + ], + }), + }, + children: [line(`CN mode ${mode}`), ...compatPages()], + }, + ], + injections: [ + ...Object.entries(PICTURES).map(([name, offset]) => floatPicture(name, offset)), + replaceMarkerRun("CN20a", RECTANGLE), + cellSpacing, + ], + }); +} + +const MINCHO = { font: { eastAsia: "MS Mincho", ascii: "MS Mincho" }, size: 21 }; +const JAPANESE = "日本語の文章に"; +const AFTER = "と数字を含む。測量は夏に行われた。"; +const mixed = (latin: object, times = 6): Paragraph[] => [ + new Paragraph({ + children: Array.from({ length: times }, () => [ + new TextRun({ text: JAPANESE, ...MINCHO }), + new TextRun({ text: "Latin words", ...latin }), + new TextRun({ text: AFTER, ...MINCHO }), + ]).flat(), + }), +]; +await write({ + name: "word-stops-fe-layout4", + options: { compatibility: { useFELayout: true } }, + sections: [ + { + properties: PAGE, + children: [ + ...probe("FE4a", [ + ...mixed({ font: "Arial", size: 24 }, 3), + ...mixed({ font: "Times New Roman", size: 24 }, 3), + ...mixed({ font: "Cambria", size: 24 }, 3), + ]), + ...probe("FE4b", [...mixed({ font: "Calibri", size: 21, bold: true }, 3), ...mixed({ font: "Calibri", size: 16 }, 3)]), + ...probe("FE4c", [ + new Paragraph({ + children: Array.from({ length: 6 }, () => [ + new TextRun({ text: JAPANESE, font: { eastAsia: "Yu Mincho", ascii: "Yu Mincho" }, size: 21 }), + new TextRun({ text: "Latin words", font: "Calibri", size: 21 }), + new TextRun({ text: AFTER, font: { eastAsia: "Yu Mincho", ascii: "Yu Mincho" }, size: 21 }), + ]).flat(), + }), + ]), + ...probe("FE4d", [line(`FE4d ${"日本語(にほんご)の文章, Word, と数字。αβγの文字Aaと".repeat(5)}`, {}, MINCHO)]), + ...probe("FE4e", [ + new Paragraph({ + indent: { right: 176 }, + children: [ + new TextRun({ text: "日本語の文章に".repeat(6), ...MINCHO }), + new TextRun({ text: "Latin words", font: "Calibri", size: 21 }), + ], + }), + ]), + ...probe("FE4f", [ + new Paragraph({ + alignment: AlignmentType.RIGHT, + children: [ + new TextRun({ text: JAPANESE, ...MINCHO }), + new TextRun({ text: "Latin words", font: "Calibri", size: 21 }), + ], + }), + new Paragraph({ + alignment: AlignmentType.RIGHT, + children: [ + new TextRun({ text: "Latin words", font: "Calibri", size: 21 }), + new TextRun({ text: JAPANESE, ...MINCHO }), + ], + }), + ]), + ], + }, + ], +}); diff --git a/scripts/layout-probes/stops2/word-stops-divisions2.docx b/scripts/layout-probes/stops2/word-stops-divisions2.docx new file mode 100644 index 0000000000..cd68eba381 Binary files /dev/null and b/scripts/layout-probes/stops2/word-stops-divisions2.docx differ diff --git a/scripts/layout-probes/stops2/word-stops-divisions2.pdf b/scripts/layout-probes/stops2/word-stops-divisions2.pdf new file mode 100644 index 0000000000..67835a70f0 Binary files /dev/null and b/scripts/layout-probes/stops2/word-stops-divisions2.pdf differ diff --git a/scripts/layout-probes/stops2/word-stops-fe-layout3.docx b/scripts/layout-probes/stops2/word-stops-fe-layout3.docx new file mode 100644 index 0000000000..8b585b7461 Binary files /dev/null and b/scripts/layout-probes/stops2/word-stops-fe-layout3.docx differ diff --git a/scripts/layout-probes/stops2/word-stops-fe-layout3.pdf b/scripts/layout-probes/stops2/word-stops-fe-layout3.pdf new file mode 100644 index 0000000000..9d15735d86 Binary files /dev/null and b/scripts/layout-probes/stops2/word-stops-fe-layout3.pdf differ diff --git a/scripts/layout-probes/stops2/word-stops-top-spacing3.docx b/scripts/layout-probes/stops2/word-stops-top-spacing3.docx new file mode 100644 index 0000000000..d4aed52cb8 Binary files /dev/null and b/scripts/layout-probes/stops2/word-stops-top-spacing3.docx differ diff --git a/scripts/layout-probes/stops2/word-stops-top-spacing3.pdf b/scripts/layout-probes/stops2/word-stops-top-spacing3.pdf new file mode 100644 index 0000000000..0c018262cb Binary files /dev/null and b/scripts/layout-probes/stops2/word-stops-top-spacing3.pdf differ diff --git a/scripts/layout-probes/stops2/word-stops-top-spacing4.docx b/scripts/layout-probes/stops2/word-stops-top-spacing4.docx new file mode 100644 index 0000000000..1a95973a9d Binary files /dev/null and b/scripts/layout-probes/stops2/word-stops-top-spacing4.docx differ diff --git a/scripts/layout-probes/stops2/word-stops-top-spacing4.pdf b/scripts/layout-probes/stops2/word-stops-top-spacing4.pdf new file mode 100644 index 0000000000..466754412d Binary files /dev/null and b/scripts/layout-probes/stops2/word-stops-top-spacing4.pdf differ diff --git a/src/layout/column-widths.spec.ts b/src/layout/column-widths.spec.ts index 64304b4b56..ec0532f66d 100644 --- a/src/layout/column-widths.spec.ts +++ b/src/layout/column-widths.spec.ts @@ -232,19 +232,37 @@ describe("fitColumns", () => { const older = { ...table([[cell(0, "a"), cell(1, LONG), cell(2, `${LONG} ${LONG}`)]]), marginsBeside: true }; expect(widthsOf(fitColumns(older, 200, measure))).to.deep.equal([10, 68.1, 101.9]); // A table whose cells all have widths Word 2010 widens for a long word as Word 2013 does, when it fits in the room - // (word-stops-compat2-14.docx CN8e). How far it lets one grow past the room, with its margins beside it, and how it - // evens out its rows, haven't been seen + // (word-stops-compat2-14.docx CN8e), and past it to the room with its margins beside it, its columns narrowed in + // proportion to their widest words (word-stops-compat3-14.docx CN16a): here to 210 of 200 and two margins of 5 const widened = { ...table([[cell(0, "aaaaaa", 30), cell(1, LONG, 150)]]), fit: undefined, widen: {}, marginsBeside: true }; - const reason = - "a table widened for a long word past the room for it, or with its rows evened out, in a document in compatibility mode"; const current = { ...widened, marginsBeside: undefined }; expect(fitColumns(widened, 300, measure)).to.deep.equal({ ...fitColumns(current, 300, measure), marginsBeside: true }); expect(widthsOf(fitColumns(widened, 300, measure))).to.deep.equal([60, 140]); - expect(fitColumns(widened, 200, measure).unsupported).to.equal(reason); - expect(fitColumns({ ...widened, widen: { uneven: true } }, 300, measure).unsupported).to.equal(reason); + expect(fitColumns(widened, 200, measure).unsupported).to.equal(undefined); + expect(widthsOf(fitColumns(widened, 200, measure))).to.deep.equal([60, 130]); + // And evens out its rows as Word 2013 does (CN16b) + const uneven = { ...widened, widen: { uneven: true as const } }; + expect(fitColumns(uneven, 300, measure)).to.deep.equal({ + ...fitColumns({ ...uneven, marginsBeside: undefined }, 300, measure), + marginsBeside: true, + }); + // With space between its cells or a share of the width, how it widens one hasn't been seen + const reason = + "a table with space between its cells or a share of the width widened for a long word, or with its rows evened out, in a document in compatibility mode"; + expect(fitColumns({ ...widened, widen: { share: 0.5 } }, 300, measure).unsupported).to.equal(reason); + expect(fitColumns({ ...widened, cellSpacing: 5 }, 300, measure).unsupported).to.equal(reason); // Without one, it keeps its cells' widths const kept = { ...table([[cell(0, "aa", 30), cell(1, "bb", 150)]]), fit: undefined, widen: {}, marginsBeside: true }; expect(fitColumns(kept, 300, measure)).to.equal(kept); + // A table sized to its text as a share of the width is a share of the room with the margins, whatever its indent + // (word-stops-compat2-14.docx CN8b, word-stops-compat3-14.docx CN12b, CN12c): half of 200 and two margins of 5 is 105, + // where Word 2013's mode makes it 100 + const half = { ...table([[cell(0, "a"), cell(1, "bb")]], { share: 0.5 }), marginsBeside: true }; + expect(widthsOf(fitColumns(half, 200, measure)).map((width) => width + 10)).to.deep.equal([42, 63]); + expect(widthsOf(fitColumns({ ...half, indent: 30 }, 200, measure)).map((width) => width + 10)).to.deep.equal([42, 63]); + expect(widthsOf(fitColumns({ ...half, marginsBeside: undefined }, 200, measure)).map((width) => width + 10)).to.deep.equal([ + 40, 60, + ]); }); it("should widen a column for a long word in an indented table in the room the indent leaves", () => { diff --git a/src/layout/column-widths.ts b/src/layout/column-widths.ts index 1b86ddc82f..afe18b8c8a 100644 --- a/src/layout/column-widths.ts +++ b/src/layout/column-widths.ts @@ -491,18 +491,16 @@ const fitTo = (table: TableBlock, available: number, content: ReadonlyMap width)); // Word 2010 and before widen a table for a long word as Word 2013 does, when it fits in the room for it - // (`word-stops-compat2-14.docx`, `-12` CN8e). How far they let one grow past it, with its cells' margins beside the - // room, and how they even out its rows, or widen one with space between its cells or a share of the width, hasn't - // been seen - if ( - widen && - table.marginsBeside === true && - (widen.uneven || spaced || widen.share !== undefined || total > available - indent + SAME) - ) { + // (`word-stops-compat2-14.docx`, `-12` CN8e), and past it to the room with its cells' margins beside it, its columns + // narrowed in proportion to their widest words as in Word 2013's mode: to 9242 twips of 9026, the long word's column + // 7943 of them where Word 2013's is 7737 of 9002 (`word-stops-compat3-14.docx`, `-12` CN16a), and they even out its + // rows as Word 2013 does, with its text at its indent (CN16b). How they widen one with space between its cells or a + // share of the width hasn't been seen + if (widen && table.marginsBeside === true && (spaced || widen.share !== undefined)) { return { ...table, unsupported: - "a table widened for a long word past the room for it, or with its rows evened out, in a document in compatibility mode", + "a table with space between its cells or a share of the width widened for a long word, or with its rows evened out, in a document in compatibility mode", }; } const tableWidth = fit ?? widen!; @@ -511,10 +509,12 @@ const fitTo = (table: TableBlock, available: number, content: ReadonlyMap { }); it("should stop at a paragraph Word hasn't been seen to lay out at the top of a page or column, such as one in an HTML division", () => { - // word-stops-divisions.docx DV2a: a division's paragraphs below the text above them - const reason = "a paragraph in an HTML division at the top of a page or column"; + // word-stops-divisions.docx DV2a: a division's paragraphs below the text above them, and word-stops-divisions2.docx + // DV3f: a paragraph's later lines at the top of the next page are as they are + const reason = "a paragraph in an HTML division without a border above it at the top of a page or column"; const divided = (name: string, lines: number): ParagraphBlock => ({ ...paragraph(name, lines), unknownAtTop: reason }); expect( [ [paragraph("x", 1), divided("a", 2)], [divided("a", 1)], [paragraph("x", 7), divided("a", 1)], - // Its lines going on to the next page too - [paragraph("x", 5), divided("a", 3)], + [paragraph("x", 4), divided("a", 4)], ].map((blocks) => numbersOf(document(blocks)).stoppedAt), - ).to.deep.equal([undefined, reason, reason, reason]); + ).to.deep.equal([undefined, reason, reason, undefined]); }); it("should give the borders of the paragraphs in a table cell room in its row, and in a row that breaks across pages", () => { @@ -912,8 +912,7 @@ describe("paginate", () => { body.flatMap((block) => (block.type === "paragraph" ? block.lines.map(({ y }) => Math.round(y * 10) / 10) : [])), ); const stoppedAt = (content: DocumentContent): string | undefined => paginate(content, { measurer: MEASURER }).stoppedAt; - const reason = - "the first line of a page or column, at line spacing Word hasn't shown, in a document that suppresses the space above it"; + const reason = "the first line of a page or column, on a document grid, in a document that suppresses the space above it"; it("should leave out the space above the text of a page's first line of exact or at-least spacing, as Word does", () => { // word-stops-top-spacing.docx ST1: at exactly 40 points, its baseline 9.6 points down rather than 32, so it goes @@ -952,14 +951,15 @@ describe("paginate", () => { expect(topsOf(suppressed([{ ...paragraph("a", 1, exact(40)), borders }]))).to.deep.equal([[13]]); }); - it("should stop at the first line of a page at spacing Word hasn't shown with suppressTopSpacing", () => { - // Multiple spacing of less than a line, a line on a document grid, and a paragraph's later line below a border above - // it - expect(stoppedAt(suppressed([paragraph("a", 1, { lineSpacing: { rule: "multiple", multiple: 0.8 } })]))).to.equal(reason); - expect(stoppedAt(suppressed([{ ...paragraph("a", 1, exact(40)), grid: { linePitch: 15 } }]))).to.equal(reason); + it("should leave a page's first line at multiple spacing of less than a line, or below a border, as it is, and stop on a grid", () => { + // word-stops-top-spacing4.docx ST16a: 0.8 lines as they are, and ST16b: a paragraph's later line at the top of the + // next page below a border above the paragraph as it is too, as its first is (ST11) + expect(topsOf(suppressed([paragraph("a", 1, { lineSpacing: { rule: "multiple", multiple: 0.8 } })]))).to.deep.equal([[10]]); const borders = { top: 3, bottom: 0, between: 0, betweenSpace: 0, box: "box", outline: "box" }; - expect(stoppedAt(suppressed([{ ...paragraph("a", 2, exact(40)), borders }]))).to.equal(reason); - // Below the top of the page, a line of any spacing is as it is + expect(topsOf(suppressed([{ ...paragraph("a", 2, exact(40)), borders }]))).to.deep.equal([[13], [10]]); + expect(stoppedAt(suppressed([{ ...paragraph("a", 2, exact(40)), borders }]))).to.equal(undefined); + // A line on a document grid hasn't been seen + expect(stoppedAt(suppressed([{ ...paragraph("a", 1, exact(40)), grid: { linePitch: 15 } }]))).to.equal(reason); expect( stoppedAt(suppressed([paragraph("a", 1), paragraph("b", 1, { lineSpacing: { rule: "multiple", multiple: 0.8 } })])), ).to.equal(undefined); @@ -6950,55 +6950,81 @@ describe("paginate", () => { changes: Partial = {}, ): string | undefined => laidOut(blocks, changes).stoppedAt; - it("should stop at a line beside a drawing in a gap narrower than Word 2010 was seen putting text in, in compatibility mode", () => { - // word-stops-compat2-14.docx CN6a to CN6d: text aligned left in gaps of 50 points and more beside a picture, CN9: 94 - // beside a table, CN7a: 100 beside a frame; word-stops-compat-14.docx CM10: justified text in 94 beside a table, and - // CM14: a gap of 50 beside a frame, of justified text, Word 2010 leaves empty and Word 2013 doesn't. Here a page 180 - // wide, with a drawing at its right + it("should lay out a line beside a drawing in compatibility mode as Word 2010 does, leaving a narrow gap beside a frame empty", () => { + // word-stops-compat2-14.docx CN6a to CN6d, word-stops-compat3-14.docx CN13f, CN13g: text aligned left in gaps of 25 + // points and more beside a picture, CN9: 94 beside a table, CN13a: justified text in 50 beside a picture, CN13h: + // centred text in 75; word-stops-compat-14.docx CM10: justified text in 94 beside a table. Beside a frame, Word + // 2010 leaves a gap of 62.5 or less empty, of text aligned left (CN13b, CN13c) or justified (CM14), where Word 2013 + // puts words, and puts text in one of 75 or more (CN13d, CN13e, CN7a, CN7b). Here a page 180 wide, with a drawing at + // its right const older = { compatibilityMode: 14 }; const reason = "a line beside a drawing or frame in a gap narrower than Word was seen putting text in, in a document in compatibility mode"; const gapped = (drawing: Partial, format: ParagraphFormat = {}): ParagraphBlock => prose("a", 12, [floating(drawing)], format); const justified: ParagraphFormat = { alignment: "justified" }; + const centred: ParagraphFormat = { alignment: "center" }; const framed = { frame: { blocks: [], heightRule: "exact" as const, fitsWidth: false } }; expect(stopOf([gapped({})], older)).to.equal(undefined); - expect(stopOf([gapped({ width: 140 })], older)).to.equal(reason); - expect(stopOf([gapped({ width: 140 })])).to.equal(undefined); - expect(stopOf([gapped({ width: 100 })], older)).to.equal(undefined); - expect(stopOf([gapped({ width: 100 }, justified)], older)).to.equal(reason); - expect(stopOf([gapped({ width: 80 }, justified)], older)).to.equal(undefined); - expect(stopOf([gapped({ width: 100, ...framed })], older)).to.equal(reason); - expect(stopOf([gapped({ width: 70, ...framed })], older)).to.equal(undefined); - // Only the room the paragraph's indents leave counts: a gap of 40 inside a left indent of 60 takes no text, and - // one of 80 that an indent of 40 narrows to 40 is as narrow as that - expect(stopOf([gapped({ width: 140 }, { indentLeft: 60 })], older)).to.equal(undefined); - expect(stopOf([gapped({ width: 100 }, { indentLeft: 40 })], older)).to.equal(reason); + expect(stopOf([gapped({ width: 160 })], older)).to.equal(reason); + expect(stopOf([gapped({ width: 160 })])).to.equal(undefined); + expect(stopOf([gapped({ width: 150 })], older)).to.equal(undefined); + expect(stopOf([gapped({ width: 140 }, justified)], older)).to.equal(reason); + expect(stopOf([gapped({ width: 130 }, justified)], older)).to.equal(undefined); + expect(stopOf([gapped({ width: 110 }, centred)], older)).to.equal(reason); + expect(stopOf([gapped({ width: 100 }, centred)], older)).to.equal(undefined); + expect(stopOf([gapped({ width: 90 }, { alignment: "right" })], older)).to.equal(reason); + // Beside a frame, a gap of 70 hasn't been seen, and one of 75 takes text + expect(stopOf([gapped({ width: 110, ...framed })], older)).to.equal(reason); + expect(stopOf([gapped({ width: 105, ...framed })], older)).to.equal(undefined); + // One of 60 left of a frame 40 wide is left empty, and the lines go in the 80 right of it, where Word 2013 puts words + // in both; of centred text it hasn't been seen + const inMiddle = { width: 40, height: 30, horizontal: { from: "margin" as const, offset: 60 }, ...framed }; + expect(stopOf([gapped(inMiddle)], older)).to.equal(undefined); + expect(roomsOf([gapped(inMiddle)], older)[0].slice(0, 3)).to.deep.equal([ + [110, 10, 80], + [110, 20, 80], + [110, 30, 80], + ]); + expect(roomsOf([gapped(inMiddle)])[0].slice(0, 2)).to.deep.equal([ + [10, 10, 60], + [110, 10, 80], + ]); + expect(stopOf([gapped(inMiddle, centred)], older)).to.equal(reason); + // Where the empty gap is all the room a line has, where Word 2010 puts the line hasn't been seen + expect(stopOf([gapped({ width: 120, ...framed })], older)).to.equal( + "a line whose only room is a gap beside a frame that Word 2010 and before leave empty, in a document in compatibility mode", + ); + // Only the room the paragraph's indents leave counts: a gap of 20 inside a left indent of 60 takes no text, and + // one of 60 that an indent of 40 narrows to 20 is as narrow as that + expect(stopOf([gapped({ width: 160 }, { indentLeft: 60 })], older)).to.equal(undefined); + expect(stopOf([gapped({ width: 120 }, { indentLeft: 40 })], older)).to.equal(reason); // A first line indent of 25 leaves a gap of 20 left of a drawing a line tall no room, and the first line may go in the - // gap of 60 right of it, where the indent would leave 35, which Word hasn't been seen putting text in; in one of 90, 65 + // gap of 40 right of it, where the indent would leave 15, which Word hasn't been seen putting text in; in one of 70, 45 const besideFirst = (width: number): ParagraphBlock => gapped({ width, height: 10, horizontal: { from: "margin", offset: 20 } }, { firstLineIndent: 25 }); - expect(stopOf([besideFirst(100)], older)).to.equal(reason); - expect(stopOf([besideFirst(70)], older)).to.equal(undefined); - // When the first gap takes the first line, a gap of 60 after it takes the second, with all of its room - const firstTaken = gapped({ width: 40, height: 10, horizontal: { from: "margin", offset: 80 } }, { firstLineIndent: 25 }); + expect(stopOf([besideFirst(120)], older)).to.equal(reason); + expect(stopOf([besideFirst(90)], older)).to.equal(undefined); + // When the first gap takes the first line, a gap of 40 after it takes the second, with all of its room + const firstTaken = gapped({ width: 40, height: 10, horizontal: { from: "margin", offset: 100 } }, { firstLineIndent: 25 }); expect(stopOf([firstTaken], older)).to.equal(undefined); - // A hanging indent widens no gap: one of 80 right of a drawing, of centred text, is narrower than 94 however far + // A hanging indent widens no gap: one of 70 right of a drawing, of centred text, is narrower than 75 however far // the first line hangs const hanging = gapped( - { width: 100, height: 10, horizontal: { from: "margin", offset: 0 } }, + { width: 110, height: 10, horizontal: { from: "margin", offset: 0 } }, { firstLineIndent: -25, alignment: "center" }, ); expect(stopOf([hanging], older)).to.equal(reason); - // A frame lower on the page whose edge is where a picture's is leaves the gap beside the picture one of 80 - const picture = floating({ width: 100, height: 10 }); - const frameBelow = floating({ width: 100, height: 10, vertical: { from: "paragraph", offset: 100 }, ...framed }); + // A frame lower on the page whose edge is where a picture's is leaves the gap beside the picture one of 70, which + // text aligned left goes in + const picture = floating({ width: 110, height: 10 }); + const frameBelow = floating({ width: 110, height: 10, vertical: { from: "paragraph", offset: 100 }, ...framed }); expect(stopOf([prose("a", 12, [picture, frameBelow])], older)).to.equal(undefined); // And one above it, with no text beside it const frameAbove = floating({ width: 100, height: 10, wrap: "topAndBottom", ...framed }); expect(stopOf([prose("b", 3, [frameAbove]), prose("a", 12, [picture])], older)).to.equal(undefined); - // A frame left of a gap of 80 makes it one beside a frame too - const frameLeft = floating({ width: 100, height: 10, horizontal: { from: "margin", offset: 0 }, ...framed }); + // A frame left of a gap of 70 makes it one beside a frame too + const frameLeft = floating({ width: 110, height: 10, horizontal: { from: "margin", offset: 0 }, ...framed }); expect(stopOf([prose("a", 12, [frameLeft])], older)).to.equal(reason); }); diff --git a/src/layout/paginate.ts b/src/layout/paginate.ts index 3b439fd787..a4942fab05 100644 --- a/src/layout/paginate.ts +++ b/src/layout/paginate.ts @@ -168,32 +168,42 @@ const EXACT_ABOVE_BASELINE = 0.8; // its text is left out (`suppressTopSpacing`), in points, in each font alike (`word-stops-top-spacing.docx` ST1 to ST3) const TOP_SPACE_KEPT = 9.6; // Why the layout stops where Word's way with the space above the first line of a page or column isn't known -const TOP_SPACING_UNKNOWN = - "the first line of a page or column, at line spacing Word hasn't shown, in a document that suppresses the space above it"; +const TOP_SPACING_UNKNOWN = "the first line of a page or column, on a document grid, in a document that suppresses the space above it"; -// The narrowest gaps beside drawings Word 2010 and before were seen putting text in, in points. They put text aligned left -// in gaps of 1000 to 2500 twips beside a picture (`word-stops-compat2-14.docx`, `-12` CN6a to CN6d), of 1882 beside a -// table that text flows around (CN9), and of 2000 and 3000 beside a frame (CN7a, CN7b), and justified text in gaps of 1882 -// beside a table (`word-stops-compat-14.docx` CM10) and 2880 beside a picture (CM9), but left one of 1000 beside a frame -// empty, of justified text (CM14), where Word 2013 puts words. Whether the frame or the justification left it empty isn't -// known, so narrower gaps beside a frame, or of text aligned otherwise than left, haven't been seen -const OLDER_LEAST_GAP = 50; +// The gaps beside drawings Word 2010 and before put text in, or leave empty, in points. Beside a picture or a table that +// text flows around they put text in gaps as Word 2013 does, as far as seen: text aligned left in gaps of 500 to 2500 +// twips beside a picture (`word-stops-compat2-14.docx`, `-12` CN6a to CN6d, `word-stops-compat3-14.docx`, `-12` CN13f, +// CN13g) and of 1882 beside a table (CN9), justified text in gaps of 1000 beside a picture (CN13a), 1882 beside a table +// (`word-stops-compat-14.docx` CM10) and 2880 beside a picture (CM9), and centred text in one of 1500 (CN13h). Beside a +// frame they leave a gap of 1250 twips or less empty, of text aligned left (CN13b, CN13c) or justified (CM14), where Word +// 2013 puts words, and put text in one of 1500 or more (CN13d, CN13e, CN7a, CN7b). Narrower gaps beside a picture or a +// table, gaps between 1250 and 1500 beside a frame, and text aligned right beside a drawing, or centred or right beside a +// frame, haven't been seen +const OLDER_LEAST_GAP = 25; +const OLDER_LEAST_GAP_JUSTIFIED = 50; +const OLDER_LEAST_GAP_CENTERED = 75; const OLDER_LEAST_GAP_ALIGNED = 94; -const OLDER_LEAST_GAP_BESIDE_FRAME = 100; +const OLDER_EMPTY_GAP_BESIDE_FRAME = 62.5; +const OLDER_LEAST_GAP_BESIDE_FRAME = 75; /** - * Whether a line's room beside drawings is a gap they cut narrower than Word 2010 and before were seen putting text in, of - * text aligned as it is: `width` of it, the room the paragraph's indents leave in it, in the line's row from `top` to - * `bottom`, where a frame beside the row makes the gap one beside a frame + * How Word 2010 and before lay out a line's room beside drawings when it is a gap they cut, of text aligned as it is: + * `width` of it, the room the paragraph's indents leave in it, in the line's row from `top` to `bottom`, where a frame + * beside the row makes the gap one beside a frame. They leave a narrow gap beside a frame empty (`"empty"`), and haven't + * been seen with gaps narrower than those they put text in (`"unknown"`). Undefined for a gap they put text in as Word + * 2013 does */ -const narrowGap = ( +const olderGap = ( span: Span, width: number, within: Span, row: { readonly top: number; readonly bottom: number }, around: readonly PlacedDrawing[], alignment: ParagraphFormat["alignment"], -): boolean => { +): "empty" | "unknown" | undefined => { + if (span.start <= within.start + TOLERANCE && span.end >= within.end - TOLERANCE) { + return undefined; + } const beside = (edge: number, at: number): boolean => Math.abs(edge - at) <= TOLERANCE; const framed = around.some( ({ drawing, keepOut }) => @@ -202,12 +212,22 @@ const narrowGap = ( row.top < keepOut.bottom && (beside(keepOut.left, span.end) || beside(keepOut.right, span.start)), ); - const least = framed - ? OLDER_LEAST_GAP_BESIDE_FRAME - : alignment === undefined || alignment === "left" - ? OLDER_LEAST_GAP - : OLDER_LEAST_GAP_ALIGNED; - return width < least && (span.start > within.start + TOLERANCE || span.end < within.end - TOLERANCE); + const left = alignment === undefined || alignment === "left"; + if (framed) { + return width >= OLDER_LEAST_GAP_BESIDE_FRAME + ? undefined + : width <= OLDER_EMPTY_GAP_BESIDE_FRAME && (left || alignment === "justified") + ? "empty" + : "unknown"; + } + const least = left + ? OLDER_LEAST_GAP + : alignment === "justified" + ? OLDER_LEAST_GAP_JUSTIFIED + : alignment === "center" + ? OLDER_LEAST_GAP_CENTERED + : OLDER_LEAST_GAP_ALIGNED; + return width < least ? "unknown" : undefined; }; // Word's automatic space before and after a paragraph, in points (`word-watertight-text.docx` TX6a, TX6b) @@ -834,6 +854,7 @@ export const paginate = ( endnoteNumbers, compatibilityMode, suppressesTopSpacing, + feLayout, } = content; // The section at whose end each of the endnotes' blocks goes: the last, or each's where the settings say so const endnoteEnds = endnotes.map((_, index) => content.endnotesAfter?.[index] ?? sections.length - 1); @@ -1077,6 +1098,7 @@ export const paginate = ( hyphenation, grid: paragraph.grid, compatibilityMode, + ...(feLayout ? { feLayout } : {}), }); // The lines are kept with the guess they are, so a pass that lays them out again notes it too return guessed === undefined @@ -4021,28 +4043,40 @@ export const paginate = ( end: Math.min(span.end - left, within.end - left - indentRight), }, })); - // Word 2010 and before leave a gap beside a frame 1000 twips wide empty, of justified text, where Word 2013 puts - // words, and put text in wider ones as it does (see `OLDER_LEAST_GAP`). How narrow a gap they leave empty isn't - // known. One the paragraph's indents leave no room in takes no text anyway, and one they narrow is as narrow as - // the room they leave. The paragraph's first line goes in the first gap of its row its first line indent leaves - // room in, which is measured with the indent, and a hanging indent widens no gap: where Word starts a first line - // that hangs past a drawing's edge hasn't been seen + // Word 2010 and before leave a gap beside a frame of 1250 twips or less empty, where Word 2013 puts words, and put + // text in wider ones, and in those beside pictures and tables, as it does (see `olderGap`). One the paragraph's + // indents leave no room in takes no text anyway, and one they narrow is as narrow as the room they leave. The + // paragraph's first line goes in the first gap of its row its first line indent leaves room in, which is + // measured with the indent, and a hanging indent widens no gap: where Word starts a first line that hangs past a + // drawing's edge hasn't been seen const indentOf = (offset: number): number => (offset > 0 ? Math.max(0, firstLineIndent) : 0); const firstLine = line === 0 ? rooms.findIndex(({ inIndents: { start, end } }, offset) => end - start - indentOf(offset) > TOLERANCE) : -1; - const narrow = ({ span, inIndents: { start, end } }: (typeof rooms)[number], offset: number): boolean => { + const gapOf = ( + { span, inIndents: { start, end } }: (typeof rooms)[number], + offset: number, + ): "empty" | "unknown" | undefined => { const width = end - Math.max(start, span.start - left) - (offset === firstLine ? indentOf(offset) : 0); - return ( - end > start + TOLERANCE && - narrowGap(span, width, within, { top: y, bottom: y + height }, around, block.format.alignment) - ); + return end > start + TOLERANCE && compatibilityMode !== undefined + ? olderGap(span, width, within, { top: y, bottom: y + height }, around, block.format.alignment) + : undefined; }; - if (compatibilityMode !== undefined && rooms.some(narrow)) { + const gaps = rooms.map(gapOf); + if (gaps.includes("unknown")) { stopAt( "a line beside a drawing or frame in a gap narrower than Word was seen putting text in, in a document in compatibility mode", ); } - const spans = rooms.map(({ inIndents }) => inIndents).filter((span) => span.end > span.start + TOLERANCE); + // Where a narrow gap beside a frame is all the room a line has, where Word 2010 puts the line hasn't been seen + if (gaps.includes("empty") && gaps.every((gap) => gap !== undefined)) { + stopAt( + "a line whose only room is a gap beside a frame that Word 2010 and before leave empty, in a document in compatibility mode", + ); + } + const spans = rooms + .filter((_, offset) => gaps[offset] !== "empty") + .map(({ inIndents }) => inIndents) + .filter((span) => span.end > span.start + TOLERANCE); const ownRoom = within.end - left - indentRight - (indentLeft + (line === 0 ? firstLineIndent : 0)) > TOLERANCE; if (spans.length === 0 && ownRoom) { // The room beside the drawings is outside the paragraph's indents, so the line goes below them, as it does @@ -4207,22 +4241,21 @@ export const paginate = ( * a page break, with the space before the paragraph, which is left out there, at the top of a column, and of a section * on a new page, below the space before its first paragraph there (`word-stops-top-spacing.docx` ST1 to ST5, * `word-stops-top-spacing2.docx` ST6, ST10, ST12), and for a paragraph's later line at the top of the next page too - * (ST8). It leaves a line of single or multiple spacing as it is (ST4b, ST7), and the first line of a paragraph with a - * border above it (ST11). Multiple spacing of less than a line, a line on a document grid, and a later line of a - * paragraph with a border above it haven't been seen. Guessing, nothing is left out + * (ST8), in a document whose text is Calibri 20 and below a header too (`word-stops-top-spacing3.docx` ST13, ST14). It + * leaves a line of single or multiple spacing as it is, of less than a line too (ST4b, ST7, `word-stops-top-spacing4.docx` + * ST16a), and the lines of a paragraph with a border above it, its first (ST11) and a later one at the top of the next + * page (ST16b). A line on a document grid hasn't been seen. Guessing, nothing is left out */ - const cutAbove = (block: ParagraphBlock, isFirstLine: boolean, borderAbove: number): number => { + const cutAbove = (block: ParagraphBlock, borderAbove: number): number => { const spacing = block.format.lineSpacing; - if (spacing === undefined || (spacing.rule === "multiple" && spacing.multiple >= 1) || (isFirstLine && borderAbove > 0)) { + if (spacing === undefined || spacing.rule === "multiple" || borderAbove > 0) { return 0; } const cut = spacing.rule === "exact" ? Math.max(0, EXACT_ABOVE_BASELINE * spacing.height - TOP_SPACE_KEPT) - : spacing.rule === "atLeast" - ? Math.max(0, spacing.height - TOP_SPACE_KEPT) - : undefined; - if (cut === undefined || (cut > 0 && (borderAbove > 0 || block.grid?.linePitch !== undefined))) { + : Math.max(0, spacing.height - TOP_SPACE_KEPT); + if (cut > 0 && block.grid?.linePitch !== undefined) { stopAt(TOP_SPACING_UNKNOWN); return 0; } @@ -4317,12 +4350,12 @@ export const paginate = ( if (isFirstLine && !placedInColumn && paragraph.joinedUnlike === true) { stopAt("a paragraph at the top of a page in one box with the one before, whose between border is another"); } - if (!placedInColumn && block.unknownAtTop !== undefined) { + if (isFirstLine && !placedInColumn && block.unknownAtTop !== undefined) { stopAt(block.unknownAtTop); } const above = isFirstLine ? spaceAbove() + paragraph.borderAbove : 0; const atTop = suppressesTopSpacing === true && !placedInColumn; - const space = above - (atTop ? cutAbove(block, isFirstLine, paragraph.borderAbove) : 0); + const space = above - (atTop ? cutAbove(block, paragraph.borderAbove) : 0); // Its lines in rows down the column, beside the drawings on the page and its own, placed against its top. The space // after the paragraph before is that paragraph's, so its top is below it, and only the rest of the space above it // is its own (`word-floats2.docx` G7 to G10) diff --git a/src/layout/read-document.spec.ts b/src/layout/read-document.spec.ts index 059e6e123d..d5c3ff67b4 100644 --- a/src/layout/read-document.spec.ts +++ b/src/layout/read-document.spec.ts @@ -5685,12 +5685,11 @@ describe("readDocument", () => { ).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", () => { - // A folded booklet's pages Word lays out as the section's (word-stops-booklet2.docx BK2) + it("should lay out a document printed as a booklet as the section's pages, and mark one whose styles Word updates from its template as unsupported", () => { + // A folded booklet's pages Word lays out as the section's (word-stops-booklet2.docx BK2), folded the other way + // round too (word-stops-booklet3.docx BK3) expect(readSettings({ "w:bookFoldPrinting": {} }).unsupported).to.equal(undefined); - expect(readSettings({ "w:bookFoldRevPrinting": {} }).unsupported).to.equal( - "pages printed as a booklet folded the other way round, for text that runs right to left", - ); + expect(readSettings({ "w:bookFoldRevPrinting": {} }).unsupported).to.equal(undefined); // word-stops-two-on-one.docx TO1: Word lays out the section's pages as without it, two to each sheet it prints expect(readSettings({ "w:printTwoOnOne": {} }).unsupported).to.equal(undefined); expect(readSettings({ "w:linkStyles": {} }).unsupported).to.equal( @@ -5867,25 +5866,30 @@ describe("readDocument", () => { expect(reasonOf(readBody([japanese], in2007))).to.equal(undefined); expect(readBody([japanese], in2007).breakRules).to.deep.equal({ ideographs: false }); expect(readBody([japanese], in2010).breakRules).to.equal(undefined); - // In an East Asian language it hasn't been seen; beside curly quotes, in the run's high ANSI font, it has (CN10c) - const older = "East Asian text in an East Asian language, in a document in compatibility mode 12 or 11"; + // In an East Asian language too, as that of none (word-stops-compat3-12.docx CN17a, CN17b), and beside curly + // quotes, in the run's high ANSI font (CN10c) const inJapanese = p(r(rPr({ "w:lang": { _attr: { "w:eastAsia": "ja-JP" } } }), t("日本語の文章"))); - expect(reasonOf(readBody([inJapanese], in2007))).to.equal(older); + expect(reasonOf(readBody([inJapanese], in2007))).to.equal(undefined); + expect(readBody([inJapanese], in2007).breakRules).to.deep.equal({ ideographs: false }); expect(reasonOf(readBody([p(r(t("\u201c日本語\u201d")))], in2007))).to.equal(undefined); expect(reasonOf(readBody([japanese], in2010))).to.equal(undefined); // Word 2003's East Asian layout spaces East Asian text apart from Latin letters and digits beside it, with the - // paragraph's automatic spacing of them on (word-stops-fe-layout2.docx FE2b), and lays it out as without it - // otherwise (FE2a, FE2c, FE2d) + // paragraph's automatic spacing of them on (word-stops-fe-layout2.docx FE2b, word-stops-fe-layout3.docx FE3a to + // FE3c), which the lines are laid out with (see line-breaking.spec.ts): the document says it does, and each + // paragraph which of its spacings are off const feLayout = { compatibility: { useFELayout: true } }; - const spaced = - "East Asian text beside other text, which Word spaces apart, in a document that lays it out as Word 2003 did (useFELayout)"; - expect(reasonOf(readBody([japanese], feLayout))).to.equal(undefined); - expect(reasonOf(readBody([p(r(t("Latin 日本語 123")))], feLayout))).to.equal(undefined); - expect(reasonOf(readBody([p(r(t("Latin日本語")))], feLayout))).to.equal(spaced); - expect(reasonOf(readBody([p(r(t("日本語")), r(t("123")))], feLayout))).to.equal(spaced); + expect(readBody([japanese], feLayout).feLayout).to.equal(true); + expect(readBody([japanese], in2007).feLayout).to.equal(undefined); + expect(reasonOf(readBody([p(r(t("Latin日本語")), r(t("123")))], feLayout))).to.equal(undefined); const off = pPr(value("w:autoSpaceDE", 0), value("w:autoSpaceDN", 0)); - expect(reasonOf(readBody([p(off, r(t("Latin日本語123")))], feLayout))).to.equal(undefined); - expect(reasonOf(readBody([p(pPr(value("w:autoSpaceDE", 0)), r(t("Latin日本語")))], feLayout))).to.equal(spaced); + expect(paragraphOf(readBody([p(off, r(t("Latin日本語123")))], feLayout)).format).to.deep.include({ + autoSpaceDE: false, + autoSpaceDN: false, + }); + const { autoSpaceDE, autoSpaceDN } = paragraphOf( + readBody([p(pPr(value("w:autoSpaceDN", 0)), r(t("Latin日本語")))], feLayout), + ).format; + expect([autoSpaceDE, autoSpaceDN]).to.deep.equal([undefined, false]); // And Latin text as it is (FE1c to FE1f), past ASCII too expect(reasonOf(readBody([p(r(t("Latin \u201cquoted\u201d")))], in2007))).to.equal(undefined); expect(reasonOf(readBody([p(r(t("Latin")))], { compatibility: { useFELayout: true } }))).to.equal(undefined); @@ -5913,15 +5917,21 @@ describe("readDocument", () => { expect(fontOf(readBody([ligatures]))).to.deep.include({ ligatures: "standard" }); }); - it("should lay out a text box in the line in Word 2007's and 2003's modes, its outline taking no room, and stop at other VML drawings", () => { + it("should lay out VML text boxes and shapes in Word 2007's and 2003's modes, their outlines taking no room, and stop at other VML drawings", () => { // word-stops-compat-12.docx CM14, word-stops-compat2-12.docx CN11a, CN11b: docx's text box 14 twips higher than in Word - // 2010's mode and 2013's, as large, and its line as much narrower + // 2010's mode and 2013's, as large, and its line as much narrower; word-stops-compat3-12.docx CN18a: a rectangle in + // the line with an outline of a point, its line 19 twips shorter and the text after it 19 nearer const shape = (style: string, ...children: readonly object[]): object => p(r({ "w:pict": [{ "v:rect": [{ _attr: { style, stroked: "f" } }, ...children] }] })); const inLine = shape("width:100pt;height:50pt"); + const outlined = p(r({ "w:pict": [{ "v:rect": [{ _attr: { style: "width:100pt;height:50pt", strokeweight: "1pt" } }] }] })); const floating = shape("position:absolute;width:100pt;height:50pt", { "w10:wrap": { _attr: { type: "square" } } }); - const reason = "a VML drawing other than a text box in the line, in a document in compatibility mode 12 or 11"; - expect(paragraphOf(readBody([inLine], in2007)).unsupported).to.equal(reason); + const reason = + "a VML shape that text flows around, an embedded object, or a VML drawing in a header, footer or text box, in a document in compatibility mode 12 or 11"; + expect(paragraphOf(readBody([inLine], in2007)).unsupported).to.equal(undefined); + expect(itemsOf(readBody([inLine], in2007))).to.deep.equal([{ type: "box", width: 100, height: 50, font: {} }]); + expect(itemsOf(readBody([outlined], in2007))).to.deep.equal([{ type: "box", width: 100, height: 50, font: {} }]); + expect(itemsOf(readBody([outlined], in2010))).to.deep.equal([{ type: "box", width: 101, height: 51, font: {} }]); expect(paragraphOf(readBody([floating], in2007)).unsupported).to.equal(reason); const object = r({ "w:object": [{ "v:shape": [{ _attr: { style: "width:72pt;height:36pt" } }] }] }); expect(paragraphOf(readBody([p(object)], in2007)).unsupported).to.equal(reason); @@ -5947,6 +5957,42 @@ describe("readDocument", () => { expect(sizeOf(readBody([textBox], in2007))).to.deep.equal([100, 7.92]); expect(sizeOf(readBody([textBox], in2010))).to.deep.equal([100.72, 8.64]); expect(paragraphOf(readBody([textBox], in2007)).unsupported).to.equal(undefined); + // One in a text box hasn't been seen in those modes + const nested = p( + r({ + "w:pict": [ + { + "v:shape": [ + { _attr: { style: "width:200pt;height:auto" } }, + { "v:textbox": [{ _attr: { style: "mso-fit-shape-to-text:t" } }, { "w:txbxContent": [textBox] }] }, + ], + }, + ], + }), + ); + expect(paragraphOf(readBody([nested], in2007)).unsupported).to.equal(reason); + expect(paragraphOf(readBody([nested], in2010)).unsupported).to.equal("a VML drawing in the line of a text box"); + // A text box placed on the page that text flows around is sized to its text whatever height it gives, or none + // (word-stops-compat3-15.docx CN18b: height:auto), in every mode, its outline taking no room in Word 2007's + const placed = p( + r({ + "w:pict": [ + { + "v:shape": [ + { _attr: { style: "position:absolute;width:150pt;height:auto", strokeweight: "1pt" } }, + { "v:textbox": [{ _attr: { style: "mso-fit-shape-to-text:t" } }, { "w:txbxContent": [p(r(t("in")))] }] }, + { "w10:wrap": { _attr: { type: "square" } } }, + ], + }, + ], + }), + ); + const effectsOf = (content: DocumentContent): readonly unknown[] => + itemsOf(content).map((item) => (item as { readonly drawing?: { readonly effects: unknown } }).drawing?.effects); + expect(paragraphOf(readBody([placed])).unsupported).to.equal(undefined); + expect(effectsOf(readBody([placed]))).to.deep.equal([{ top: 0.5, bottom: 0.5, left: 0, right: 1 }]); + expect(paragraphOf(readBody([placed], in2007)).unsupported).to.equal(undefined); + expect(effectsOf(readBody([placed], in2007))).to.deep.equal([{ top: 0, bottom: 0, left: 0, right: 0 }]); }); it("should give a table sized to its text its cells' margins beside the room, and stop where Word hasn't shown its size", () => { @@ -5964,11 +6010,11 @@ describe("readDocument", () => { const indented = { "w:tblInd": { _attr: { "w:w": 200, "w:type": "dxa" } } }; expect(tableOf(readBody([tableWith(indented)], in2010))).to.deep.include({ indent: 10, marginsBeside: true }); expect(tableOf(readBody([tableWith(indented)], in2010)).unsupported).to.equal(undefined); - // As a share of the width it is wider than its share (CN8b), by how much hasn't been seen + // As a share of the width it is a share of the room with the margins (CN8b, word-stops-compat3-14.docx CN12a to + // CN12c; see column-widths.spec.ts) const share = { "w:tblW": { _attr: { "w:w": 2500, "w:type": "pct" } } }; - expect(tableOf(readBody([tableWith(share)], in2010)).unsupported).to.equal( - "a table sized to its text as a share of the width, in a document in compatibility mode", - ); + expect(tableOf(readBody([tableWith(share)], in2010))).to.deep.include({ fit: { share: 0.5 }, marginsBeside: true }); + expect(tableOf(readBody([tableWith(share)], in2010)).unsupported).to.equal(undefined); // In a table cell, as Word 2013 sizes it (CN8d), but indented or as a share of the width const nestedIn = (inner: object): DocumentContent => readBody([{ "w:tbl": [{ "w:tr": [tableCell(inner, p())] }] }], in2010); const innerOf = (content: DocumentContent): TableBlock => tableOf(content).rows[0].cells[0].blocks[0] as TableBlock; @@ -5979,8 +6025,8 @@ describe("readDocument", () => { expect(tableOf(nestedIn(tableWith(indented))).unsupported).to.equal(inCell); expect(tableOf(nestedIn(tableWith(share))).unsupported).to.equal(inCell); // One that text flows around Word places with its first cell's text where it is placed (CM10, CN9), the text - // half a point from it with no distance given, as in Word 2013's mode (CN9), but for one sized to its text or - // lined up across the page + // half a point from it with no distance given, as in Word 2013's mode (CN9), one sized to its text too + // (word-stops-compat3-14.docx CN15a), and one lined up across the page as Word 2013 does (CN15b) const distant = { "w:leftFromText": 180, "w:rightFromText": 180 }; const floating = { "w:tblpPr": { _attr: { "w:horzAnchor": "margin", "w:vertAnchor": "text", "w:tblpX": 2000, ...distant } }, @@ -5994,9 +6040,15 @@ describe("readDocument", () => { from: "margin", offset: 100, }); - const floatReason = - "a table that text flows around, sized to its text or lined up across the page, in a document in compatibility mode"; - expect(tableOf(readBody([tableWith(floating), p()], in2010)).unsupported).to.equal(floatReason); + const sizedFloat = tableOf(readBody([tableWith(floating, borders, margins), p()], in2010)); + expect([sizedFloat.unsupported, sizedFloat.marginsBeside, sizedFloat.float!.horizontal]).to.deep.equal([ + undefined, + true, + { from: "margin", offset: 100 - 5.4 - 0.25 }, + ]); + const centredFloat = { "w:tblpPr": { _attr: { "w:horzAnchor": "margin", "w:tblpXSpec": "center", "w:vertAnchor": "text" } } }; + const linedUp = tableOf(readBody([tableWith(own, centredFloat), p()], in2010)); + expect([linedUp.unsupported, linedUp.float!.horizontal]).to.deep.equal([undefined, { from: "margin", align: "center" }]); const touching = { "w:tblpPr": { _attr: { "w:horzAnchor": "margin", "w:vertAnchor": "text", "w:tblpX": 2000 } } }; const touched = tableOf(readBody([tableWith(own, touching), p()], in2010)); expect([touched.unsupported, touched.float!.distances]).to.deep.equal([ @@ -6020,7 +6072,7 @@ describe("readDocument", () => { "w:tblpPr": { _attr: { "w:horzAnchor": "margin", "w:vertAnchor": "text", "w:tblpXSpec": "center", ...distant } }, }; const lined = tableOf(readBody([tableWith(own, centred), p()], in2010)); - expect([lined.unsupported, lined.float!.horizontal]).to.deep.equal([floatReason, { from: "margin", align: "center" }]); + expect([lined.unsupported, lined.float!.horizontal]).to.deep.equal([undefined, { from: "margin", align: "center" }]); }); }); diff --git a/src/layout/read-document.ts b/src/layout/read-document.ts index 9e33f5447b..5aee4c817c 100644 --- a/src/layout/read-document.ts +++ b/src/layout/read-document.ts @@ -554,6 +554,11 @@ export type DocumentContent = { readonly compatibilityMode?: number; /** Whether the space above the text of the first line of a page or column is left out (`suppressTopSpacing`) */ readonly suppressesTopSpacing?: boolean; + /** + * Whether the document lays out East Asian text as Word 2003 did (`useFELayout`), spacing it apart from the Latin letters + * and digits beside it (see `layoutLines`) + */ + readonly feLayout?: boolean; /** The number each footnote shows, by the name of its marker: empty for those numbered on each page, or with a mark of their own */ readonly footnoteNumbers: ReadonlyMap; /** @@ -1156,9 +1161,13 @@ const readDrawing = (element: XmlObject, font: TextFont, reader: Reader): readon // Word 2007 and 2003 put the line of docx's text box (VML) 14 twips higher than Word 2010 and 2013 do // (`word-stops-compat-12.docx` CM14): they give its outline no room of its own beside the box, across or down, though -// they draw the box as large, and in the same place (`word-stops-compat2-12.docx` CN11a, CN11b). The layout stops at -// other VML drawings that take room in a document in their compatibility modes, which haven't been seen there -const OLDER_VML = "a VML drawing other than a text box in the line, in a document in compatibility mode 12 or 11"; +// they draw the box as large, and in the same place (`word-stops-compat2-12.docx` CN11a, CN11b). So they do a rectangle in +// the line, whose line is 19 twips shorter and the text after it 19 nearer with an outline of a point +// (`word-stops-compat3-12.docx` CN18a), and a text box placed on the page that text flows around, the text beside it 21 +// nearer (CN18b). The layout stops at other VML drawings that take room in a document in their compatibility modes, which +// haven't been seen there +const OLDER_VML = + "a VML shape that text flows around, an embedded object, or a VML drawing in a header, footer or text box, in a document in compatibility mode 12 or 11"; // A VML shape with neither a width nor a height is 50 points square (`word-stops-vml-shapes.docx` VM29d) const DEFAULT_VML_SIZE = 50; // Word draws a VML picture (`v:imagedata`) at its shape's size: pictures of 100 by 50 pixels in shapes of 20 to 150 points @@ -1259,22 +1268,25 @@ const readVml = (pict: unknown, font: TextFont, reader: Reader): readonly Layout if (wrap === undefined || attributesOf(wrap).type === "none") { return []; } - const reason = olderVml(reader) - ? OLDER_VML - : reader.inCell || reader.inNote || reader.inTextBox - ? IN_CELL_OR_NOTE - : group - ? "a VML group of shapes that text flows around" - : picture - ? VML_PICTURE_FLOATING - : typeof width !== "number" || typeof height !== "number" - ? unsized() - : undefined; + const reason = + olderVml(reader) && shape.text === undefined + ? OLDER_VML + : reader.inCell || reader.inNote || reader.inTextBox + ? IN_CELL_OR_NOTE + : group + ? "a VML group of shapes that text flows around" + : picture + ? VML_PICTURE_FLOATING + : typeof width !== "number" || (typeof height !== "number" && !(shape.text !== undefined && fitsText(shape))) + ? unsized() + : undefined; if (reason !== undefined) { return reason; } if (shape.text !== undefined) { - return readFloatingTextBox(shape, wrap as XmlObject, width as number, height as number, outline, reader); + // A text box sized to its text is as tall as its text, whatever height it gives, or none (`word-vml.docx` VM3, + // `word-stops-compat3-15.docx` CN18b: `height:auto`) + return readFloatingTextBox(shape, wrap as XmlObject, width as number, typeof height === "number" ? height : 0, outline, reader); } const floating = readVmlFloating(shape, wrap as XmlObject, width as number, height as number, outline.drawn ? outline.weight : 0); return typeof floating === "string" ? floating : floatingItem(floating, reader); @@ -1284,7 +1296,7 @@ const readVml = (pict: unknown, font: TextFont, reader: Reader): readonly Layout typeof width === "number" && typeof height === "number" ? guessedOr(reader, reason, () => [{ type: "box", width, height, font }]) : reason; - if (olderVml(reader) && (shape.text === undefined || reader.inHeader || reader.inTextBox)) { + if (olderVml(reader) && (reader.inHeader || reader.inTextBox)) { return OLDER_VML; } if (reader.inTextBox) { @@ -1296,7 +1308,8 @@ const readVml = (pict: unknown, font: TextFont, reader: Reader): readonly Layout if (typeof width !== "number" || typeof height !== "number") { return unsized(); } - const room = outline.drawn ? outline.weight : 0; + // Word 2007 and 2003 give its outline no room (see `OLDER_VML`) + const room = outline.drawn && !olderVml(reader) ? outline.weight : 0; const drawn = picture ? pictureSizeOf(imagedata, width, height, reader) : { width, height }; return typeof drawn === "string" ? sized(drawn) : [{ type: "box", width: drawn.width + room, height: drawn.height + room, font }]; }; @@ -1358,6 +1371,9 @@ const textBoxBlocks = (shape: VmlShape, reader: Reader): readonly Block[] | stri * fields in it are where it is, in the paragraph it is in, and a footnote referred to in it is left out, reference and * note, as Word leaves it (`word-stops-vml-note.docx` VM26a). Or why it can't be laid out */ +/** Whether a text box is sized to its text (`mso-fit-shape-to-text`), as docx writes its text boxes to be */ +const fitsText = (shape: VmlShape): boolean => shape.textStyle?.get("mso-fit-shape-to-text") === "t"; + const readTextBox = ( shape: VmlShape, width: number | string | undefined, @@ -1368,7 +1384,7 @@ const readTextBox = ( ): readonly LayoutItem[] | string => { const textbox = find(childrenOf(shape.element[nameOf(shape.element)]), "v:textbox"); const insets = textBoxInsets(textbox); - const fits = shape.textStyle?.get("mso-fit-shape-to-text") === "t"; + const fits = fitsText(shape); if (typeof width !== "number") { return width ?? "a VML drawing with no size"; } @@ -1421,7 +1437,7 @@ const readFloatingTextBox = ( if (typeof insets === "string") { return insets; } - if (shape.textStyle?.get("mso-fit-shape-to-text") !== "t") { + if (!fitsText(shape)) { return "a text box that text flows around not sized to its text"; } const blocks = textBoxBlocks(shape, reader); @@ -1432,7 +1448,8 @@ const readFloatingTextBox = ( if (paragraphs.length !== blocks.length) { return "a table in a text box that text flows around"; } - const floating = readVmlFloating(shape, wrap, width, height, outline.drawn ? outline.weight : 0); + // Word 2007 and 2003 give its outline no room beside it (see `OLDER_VML`) + const floating = readVmlFloating(shape, wrap, width, height, outline.drawn && !olderVml(reader) ? outline.weight : 0); if (typeof floating === "string") { return floating; } @@ -2431,48 +2448,6 @@ const withFeaturesOf = (format: RunFormat, { compatibilityMode, openTypeFeatures ? { ...format, ligatures: undefined } : format; -/** - * Why a paragraph can't be laid out as Word lays it out in the document's compatibility mode, or with Word 2003's layout - * of East Asian text (`useFELayout`), when it can't. Word 2010 and before don't squeeze the spaces of a justified line, - * nor of a distributed one, or one justified for Thai or with a low kashida (`word-stops-compat-14.docx` CM1, - * `word-stops-compat2-14.docx` CN4a to CN4c), which the lines are broken for (see `line-breaking.ts`). Word 2007 and 2003 - * break East Asian text otherwise than Word 2010 and 2013 (CM18, CN10a to CN10c), and Word 2003's East Asian layout - * spaces it apart from the text beside it (`word-stops-fe-layout.docx` FE1a, FE1b): see below. Paragraphs without East - * Asian text it lays out as they are without it (FE1c to FE1f). - */ -const unknownInOlderLayout = (items: readonly LayoutItem[], reader: Reader, autoSpaced: boolean): string | undefined => { - const { compatibilityMode } = reader; - // Its East Asian text is looked for only where it is laid out otherwise, as the text of every paragraph is long. Word 2007 - // and 2003 break that of no East Asian language only at its spaces (see `ideographs` in `LineBreakRules`), beside - // characters past ASCII that aren't East Asian too, such as curly quotes, in the run's font for them (`w:hAnsi`; - // `word-stops-compat2-12.docx` CN10c). That of an East Asian language, whose characters that can't start or end a line - // Word knows, hasn't been seen - const older = compatibilityMode !== undefined && compatibilityMode < WORD_2010_MODE; - const texts = items.filter((item) => item.type === "text"); - const eastAsian = texts.some((item) => [...item.text].some(isEastAsian)); - if (!eastAsian || (!older && reader.feLayout !== true)) { - return undefined; - } - // Word 2003's layout of East Asian text puts a quarter of an em between East Asian text and Latin letters and digits - // beside it, with the paragraph's automatic spacing of them on (`w:autoSpaceDE`, `w:autoSpaceDN`), as it is unless the - // paragraph turns it off: 52.5 twips at 10.5 points (`word-stops-fe-layout2.docx` FE2b, `word-stops-fe-layout.docx` FE1a, - // FE1b), which isn't followed yet. Otherwise it lays out its lines as without it: Japanese and Chinese after a space, - // and Japanese with Latin words with both turned off (FE2a, FE2c, FE2d) - if (!older) { - const characters = [...texts.map(({ text }) => text).join("")]; - const beside = characters.some( - (character, at) => - at > 0 && isEastAsian(character) !== isEastAsian(characters[at - 1]) && !/\s/u.test(character + characters[at - 1]), - ); - return autoSpaced && beside - ? "East Asian text beside other text, which Word spaces apart, in a document that lays it out as Word 2003 did (useFELayout)" - : undefined; - } - return texts.some((item) => kinsokuLanguageOf(item.language) !== undefined) - ? "East Asian text in an East Asian language, in a document in compatibility mode 12 or 11" - : undefined; -}; - // A line of space before or after a paragraph, in `w:beforeLines` and `w:afterLines`, is 12 points whatever the font: 100 // is 240 twips in Calibri 11, whose lines are 268.55 (`word-watertight-text.docx` TX7d) const POINTS_PER_LINE = 12; @@ -2869,13 +2844,7 @@ const readParagraph = (element: XmlObject, reader: Reader, tableFormats: TableFo ? "a paragraph justified for Arabic with a medium or high kashida" : forThaiOrArabic && typeof items !== "string" && items.some((item) => item.type === "text" && ARABIC.test(item.text)) ? "Arabic text justified for Thai or with a kashida" - : (unknownInOlderLayout( - content, - reader, - onOff(properties, "w:autoSpaceDE") !== false || onOff(properties, "w:autoSpaceDN") !== false, - ) ?? - (typeof format === "string" ? format : undefined) ?? - (typeof borders === "string" ? borders : undefined))); + : ((typeof format === "string" ? format : undefined) ?? (typeof borders === "string" ? borders : undefined))); return { type: "paragraph", items: content, @@ -2895,9 +2864,7 @@ const readParagraph = (element: XmlObject, reader: Reader, tableFormats: TableFo ...(typeof borders === "object" ? { borders } : {}), ...(paragraphGrid !== undefined && Object.keys(paragraphGrid).length > 0 ? { grid: paragraphGrid } : {}), ...(typeof frame === "object" ? { frame } : {}), - ...(division?.division === undefined - ? {} - : { division: division.division, unknownAtTop: "a paragraph in an HTML division at the top of a page or column" }), + ...(division?.division === undefined ? {} : { division: division.division }), style, // Word's chapter numbers are the numbers headings' styles give them, and it passes over headings numbered on their // own, or not at all @@ -2940,10 +2907,9 @@ const divisionsIn = ( * one box, with its margin above the box and below it as the space before its first paragraph and after its last: 720 * twips in on each side, and 230 above and below three paragraphs, a margin of 120, a border of 30 and its space of 80 * (`word-stops-divisions.docx` DV2a, DV2b, `word-stops-pages.docx` DV1a). A division in another with the same margins - * above and below has them once (DV2d). With the paragraph's own space before or after it, the division's borders and - * margins above and below aren't laid out that way (DV2c), and its own indents or borders, a division in another with - * borders or other margins, a quotation or a page's body, and a division in a table cell, a note, a header, a footer or a - * text box, haven't been seen. + * above and below has them once (DV2d). Its paragraphs after other paragraphs, and its margins beside their own space, + * are as `withDivisions` says. Its own indents or borders, a division in another with borders or other margins, a + * quotation or a page's body, and a division in a table cell, a note, a header, a footer or a text box, haven't been seen. */ const readDivision = ( properties: readonly XmlObject[], @@ -2971,7 +2937,6 @@ const readDivision = ( const border = find(division, "w:divBdr"); return border === undefined ? [] : [border]; }); - const spaced = [own.spaceBefore, own.spaceAfter, own.spaceBeforeLines, own.spaceAfterLines].some((space) => (space ?? 0) !== 0); const indented = [own.indentLeft, own.indentRight, own.firstLineIndent, own.indentLeftChars, own.indentRightChars, own.firstLineChars]; const bordered = [own.borderTop, own.borderBottom, own.borderLeft, own.borderRight, own.borderBetween, own.borderBar]; const unsupported = @@ -2981,11 +2946,9 @@ const readDivision = ( ? "an HTML division that is a quotation or a page's body" : above.size > 1 || below.size > 1 || (chain.length > 1 && borders.length > 0) ? "an HTML division in another, with borders, or other margins above or below" - : spaced || own.autoSpaceBefore === true || own.autoSpaceAfter === true - ? "a paragraph in an HTML division with space before or after it" - : indented.some((indent) => (indent ?? 0) !== 0) || bordered.some((border) => border !== undefined) - ? "a paragraph in an HTML division with indents or borders of its own" - : undefined; + : indented.some((indent) => (indent ?? 0) !== 0) || bordered.some((border) => border !== undefined) + ? "a paragraph in an HTML division with indents or borders of its own" + : undefined; const sum = (name: string): number => margin(name).reduce((total, length) => total + length, 0); return { format: readParagraphFormat([ @@ -2999,42 +2962,109 @@ const readDivision = ( /** * The body's blocks with the margins of the divisions of a web page their paragraphs are in as space before the first - * paragraph of each division and after its last (see `readDivision`). Space after the paragraph before a division, or - * before the one after it, or a division next to another, haven't been seen + * paragraph of each run of them and after its last (see `readDivision`), and the division's borders above and below its + * first run only. Word draws a division's box once, round the first run of its paragraphs in the document: three + * paragraphs in one with margins of 120 twips and borders of 30 with 80 of space are in one box, 230 above the first and + * below the last (`word-stops-divisions.docx` DV2a), and so is one at the top of a page, below the border and its space + * without the margin (`word-stops-divisions2.docx` DV3a). Its paragraphs after other paragraphs have its left and right + * borders beside their lines, and its margins above their first and below their last, but no border above or below (DV3b + * to DV3f), and so a margin is beside the paragraph's own space before or after, where the larger of the two is taken, + * 120 with 60 of its own and 240 with 240 (DV3c, DV3d, DV2c), as the larger of a paragraph's space after and the next + * one's space before is between them, 120 after a paragraph with 60 after it (DV3e) and between two divisions (DV3b). + * Where the box's border is above or below, a paragraph with space of its own, or next to one with space between them, + * or another division, hasn't been seen, nor has a division without a border above at the top of a page or column, a + * paragraph with automatic space or space in lines, or a division next to a paragraph with space between them, or to + * another division, in a document that adds the space after a paragraph to the space before the next + * (`w:doNotUseHTMLParagraphAutoSpacing`) */ const withDivisions = ( blocks: readonly { readonly block: Block; readonly section: number }[], + addsParagraphSpacing: boolean, ): readonly { readonly block: Block; readonly section: number }[] => { const divisionOf = (at: number): ParagraphBlock["division"] => { const block = blocks[at]?.block; return block?.type === "paragraph" ? block.division : undefined; }; + // Whether each block is in a run of its division's paragraphs after the first + const seen = new Set(); + let inLaterRun = false; + const laterRun = blocks.map((_, at) => { + const division = divisionOf(at); + if (division === undefined) { + return false; + } + if (divisionOf(at - 1)?.id !== division.id) { + inLaterRun = seen.has(division.id); + // eslint-disable-next-line functional/immutable-data + seen.add(division.id); + } + return inLaterRun; + }); + /** + * Whether the division's box has a border above the paragraph at `at`, the first of its run, or below it, the last. Only + * asked of a paragraph in a division + */ + const boxed = (at: number, side: "borderTop" | "borderBottom"): boolean => + laterRun[at] === false && (blocks[at].block as ParagraphBlock).format[side] !== undefined; return blocks.map((placed, at) => { const { block } = placed; if (block.type !== "paragraph" || block.division === undefined) { return placed; } const { id, above, below } = block.division; + const { format } = block; const [before, after] = [at - 1, at + 1].map(divisionOf); const [previous, next] = [blocks[at - 1]?.block, blocks[at + 1]?.block]; const first = before?.id !== id; const last = after?.id !== id; + const boxedAbove = first && boxed(at, "borderTop"); + const boxedBelow = last && boxed(at, "borderBottom"); + const own = { before: format.spaceBefore ?? 0, after: format.spaceAfter ?? 0 }; const spacedBefore = previous?.type === "paragraph" && ((previous.format.spaceAfter ?? 0) > 0 || previous.format.autoSpaceAfter === true); const spacedAfter = next?.type === "paragraph" && ((next.format.spaceBefore ?? 0) > 0 || next.format.autoSpaceBefore === true); + // Whether the division before this one's run ends with its box's border, or the one after starts with its + const boxedBefore = first && before !== undefined && boxed(at - 1, "borderBottom"); + const boxedAfter = last && after !== undefined && boxed(at + 1, "borderTop"); const unsupported = - (first && before !== undefined) || (last && after !== undefined) - ? "an HTML division next to another" - : (first && spacedBefore) || (last && spacedAfter) - ? "an HTML division next to a paragraph with space before or after it" - : undefined; + format.autoSpaceBefore === true || + format.autoSpaceAfter === true || + (format.spaceBeforeLines ?? 0) !== 0 || + (format.spaceAfterLines ?? 0) !== 0 + ? "a paragraph in an HTML division with automatic space before or after it, or space in lines" + : (own.before > 0 && (!first || boxedAbove)) || (own.after > 0 && (!last || boxedBelow)) + ? "a paragraph in an HTML division with space before or after it, where the division has a border there or another paragraph of it" + : (first && spacedBefore && boxedAbove) || + (last && spacedAfter && boxedBelow) || + (first && before !== undefined && (boxedAbove || boxedBefore)) || + (last && after !== undefined && (boxedBelow || boxedAfter)) + ? "an HTML division with a border above or below it next to a paragraph with space between them, or next to another division" + : addsParagraphSpacing && + ((first && (spacedBefore || before !== undefined)) || (last && (spacedAfter || after !== undefined))) + ? "an HTML division next to a paragraph with space between them, or to another division, in a document that adds the space after a paragraph to the space before the next" + : undefined; + // After the division's first run, the box has no border above or below its paragraphs, so no room above or below + // for them, which `readBorders` could only fail to read + const withoutBox: ParagraphFormat = laterRun[at] + ? withoutUndefined({ ...format, borderTop: undefined, borderBottom: undefined }) + : format; + const borders = laterRun[at] ? readBorders(withoutBox) : block.borders; return { ...placed, - block: { + block: withoutUndefined({ ...block, - format: { ...block.format, spaceBefore: first ? above : 0, spaceAfter: last ? below : 0 }, - ...(block.unsupported === undefined && unsupported !== undefined ? { unsupported } : {}), - }, + format: { + ...withoutBox, + spaceBefore: first ? (boxedAbove ? above : Math.max(above, own.before)) : own.before, + spaceAfter: last ? (boxedBelow ? below : Math.max(below, own.after)) : own.after, + }, + borders: typeof borders === "object" ? borders : undefined, + unknownAtTop: + first && !boxedAbove + ? "a paragraph in an HTML division without a border above it at the top of a page or column" + : undefined, + unsupported: block.unsupported ?? unsupported, + }), }; }); }; @@ -3814,13 +3844,13 @@ const readTable = (element: XmlObject, reader: Reader): TableBlock | undefined = const float = floatElement === undefined ? undefined : readTableFloat(floatElement, find(properties, "w:tblOverlap")); // In compatibility mode, Word 2010 and before put a table's text, rather than its borders, at its indent, and give one // sized to its text its cells' margins beside the room for it, the page's text or what its indent leaves of it - // (`word-stops-compat-14.docx` CM4, CM5, CM11, CM16, `word-stops-compat2-14.docx`, `-12` CN8a). One in a table cell - // they size as Word 2013 does, its borders at the cell's text (CN8d). How they size one as a share of the width hasn't - // been seen: wider than the share, by its first cell's margin, at least (CN8b), nor one indented or as a share of the - // width in a table cell. One that text flows around they place with its text where Word 2013 puts its border, its - // first cell's margin and half its left border to the left (CM10, CN9), the text beside it half a point from it with - // no distance given, as in Word 2013's mode (CN9; see `readTableFloat`). One lined up across the page, or sized to its - // text, which haven't been seen, stop the layout + // (`word-stops-compat-14.docx` CM4, CM5, CM11, CM16, `word-stops-compat2-14.docx`, `-12` CN8a), or a share of the room + // with the margins (CN8b, `word-stops-compat3-14.docx`, `-12` CN12a to CN12c; see `fitTo`). One in a table cell they + // size as Word 2013 does, its borders at the cell's text (CN8d), but one indented or as a share of the width in a table + // cell hasn't been seen. One that text flows around they place with its text where Word 2013 puts its border, its + // first cell's margin and half its left border to the left (CM10, CN9), one sized to its text too (CN15a), the text + // beside it half a point from it with no distance given, as in Word 2013's mode (CN9; see `readTableFloat`), and one + // lined up across the page as Word 2013 does (CN15b) const older = reader.compatibilityMode !== undefined; const marginsBeside = older && sized && givenWidth.width === undefined && reader.inCell !== true; // How wide Word makes a column of text that runs up or down isn't known in every font, so how wide a table sized to its @@ -3838,12 +3868,6 @@ const readTable = (element: XmlObject, reader: Reader): TableBlock | undefined = (float !== undefined && (reader.inCell || reader.inHeader) ? "a table that text flows around in a table cell, header or footer" : undefined) ?? - (typeof float === "object" && older && (marginsBeside || float.horizontal.align !== undefined) - ? "a table that text flows around, sized to its text or lined up across the page, in a document in compatibility mode" - : undefined) ?? - (marginsBeside && fits && givenWidth.share !== undefined - ? "a table sized to its text as a share of the width, in a document in compatibility mode" - : undefined) ?? (older && sized && fits && @@ -5736,6 +5760,7 @@ const readSettings = ( | "hyphenation" | "compatibilityMode" | "suppressesTopSpacing" + | "feLayout" | "unsupported" > => { const settings = childrenOf(xml?.["w:settings"]); @@ -5752,11 +5777,11 @@ const readSettings = ( const ideographsUnbroken = olderMode !== undefined && olderMode < WORD_2010_MODE; const rules: LineBreakRules = ideographsUnbroken ? { ...breakRules, ideographs: false } : breakRules; // Pages printed folded as a booklet Word lays out as the section's pages, as it does without, and prints two to a sheet - // in the booklet's order: 50 lines of A4 to the first, as wide as without (`word-stops-booklet2.docx` BK2). Those - // folded the other way round (`w:bookFoldRevPrinting`), for text that runs right to left, haven't been seen, and Word - // updates a document's styles from its template when it opens it, with `w:linkStyles`. Pages printed two to a sheet - // (`w:printTwoOnOne`) Word lays out as the section's pages too: 51 lines on the first of 62 - // (`word-stops-two-on-one.docx` TO1) + // in the booklet's order: 50 lines of A4 to the first, as wide as without (`word-stops-booklet2.docx` BK2), and so it + // does those folded the other way round (`w:bookFoldRevPrinting`), for text that runs right to left, with the two + // pages of each sheet the other way round (`word-stops-booklet3.docx` BK3). Word updates a document's styles from its + // template when it opens it, with `w:linkStyles`. Pages printed two to a sheet (`w:printTwoOnOne`) Word lays out as + // the section's pages too: 51 lines on the first of 62 (`word-stops-two-on-one.docx` TO1) const unsupported = ( [ [ @@ -5764,10 +5789,6 @@ const readSettings = ( "a document in a compatibility mode Word hasn't been seen laying out", ], [asksForUnfollowedCompatibility(compatibility, olderMode !== undefined), "a compatibility setting not yet followed"], - [ - onOff(settings, "w:bookFoldRevPrinting"), - "pages printed as a booklet folded the other way round, for text that runs right to left", - ], [onOff(settings, "w:linkStyles"), "styles updated from the document's template when Word opens it"], ] as const ).find(([applies]) => applies === true)?.[1]; @@ -5779,6 +5800,7 @@ const readSettings = ( ...(onOff(settings, "w:autoHyphenation") === true ? { hyphenation: readHyphenation(settings) } : {}), ...(olderMode === undefined ? {} : { compatibilityMode: olderMode }), ...(onOff(compatibility, "w:suppressTopSpacing") === true ? { suppressesTopSpacing: true } : {}), + ...(onOff(compatibility, "w:useFELayout") === true ? { feLayout: true } : {}), ...(unsupported ? { unsupported } : {}), }; }; @@ -6478,8 +6500,9 @@ export const readContent = (writtenBody: XmlObject, writtenParts: DocumentParts, }; }; + const documentSettings = readSettings(parts.settings); const documentContent: DocumentContent = { - blocks: withDivisions(blocks), + blocks: withDivisions(blocks, documentSettings.addsParagraphSpacing), sections, footnotes, footnoteSeparator: footnotes.size > 0 ? readNoteContent("footnote", "separator") : [], @@ -6492,7 +6515,7 @@ export const readContent = (writtenBody: XmlObject, writtenParts: DocumentParts, relativeReferences: markers.relative, endnoteReferences, ...(parts.fonts !== undefined && parts.fonts.length > 0 ? { fonts: parts.fonts } : {}), - ...readSettings(parts.settings), + ...documentSettings, }; // Notes numbered or placed in a way not yet followed stop the layout before anything, as any paragraph may refer to // them diff --git a/src/layout/read-docx.spec.ts b/src/layout/read-docx.spec.ts index 5fb983f77c..7d3a4ad94e 100644 --- a/src/layout/read-docx.spec.ts +++ b/src/layout/read-docx.spec.ts @@ -602,40 +602,105 @@ describe("readDocx", () => { [5.5, 5.5], ]); expect(new Set(boxed.map(({ borders }) => borders?.box)).size).to.equal(1); - expect(boxed.map(({ unsupported, division, unknownAtTop }) => [unsupported, division, unknownAtTop])).to.deep.include([ - undefined, - { id: "1001", above: 6, below: 6 }, - "a paragraph in an HTML division at the top of a page or column", + // At the top of a page, below the border without the margin (word-stops-divisions2.docx DV3a): nothing to stop at + expect(boxed.map(({ unsupported, division, unknownAtTop }) => [unsupported, division, unknownAtTop])).to.deep.equal([ + [undefined, { id: "1001", above: 6, below: 6 }, undefined], + [undefined, { id: "1001", above: 6, below: 6 }, undefined], + [undefined, { id: "1001", above: 6, below: 6 }, undefined], ]); // DV2b, DV2d: one without borders, and one in another, its margins left and right added up and those above and - // below once + // below once; without a border above, how Word lays it out at the top of a page hasn't been seen + const atTop = "a paragraph in an HTML division without a border above it at the top of a page or column"; const [, , nested] = paragraphs(read(plain + inDivision(1002) + plain + inDivision(1003) + plain)).slice(1); expect(paragraphs(read(plain + inDivision(1002) + plain))[1].format).to.deep.include({ indentLeft: 36, spaceBefore: 6, spaceAfter: 6, }); + expect(paragraphs(read(plain + inDivision(1002) + plain))[1].unknownAtTop).to.equal(atTop); expect(nested.format).to.deep.include({ indentLeft: 72, indentRight: 72, spaceBefore: 6, spaceAfter: 6 }); expect(nested.borders).to.equal(undefined); const reasonOf = (body: string, index = 1): string | undefined => read(body).blocks[index].block.unsupported; - // DV2c: with space of its own before or after it, or next to one with space after it or before it - expect(reasonOf(plain + inDivision(1001, '') + plain)).to.equal( - "a paragraph in an HTML division with space before or after it", - ); + // A division's paragraphs after other paragraphs have its borders left and right, but none above or below, and its + // margins above the first and below the last (DV3b to DV3f) + const again = plain + inDivision(1001) + plain + inDivision(1001) + inDivision(1001) + plain; + const later = paragraphs(read(again)).slice(3, 5); + expect( + later.map(({ format: { spaceBefore, spaceAfter, borderTop, borderLeft }, unsupported }) => [ + spaceBefore, + spaceAfter, + borderTop, + borderLeft?.size, + unsupported, + ]), + ).to.deep.equal([ + [6, 0, undefined, 12, undefined], + [0, 6, undefined, 12, undefined], + ]); + // Borders left and right take no room above or below, so there is no box to join (see `readBorders`) + expect(later.map(({ borders }) => borders)).to.deep.equal([undefined, undefined]); + expect(later[0].unknownAtTop).to.equal(atTop); + expect(later[1].unknownAtTop).to.equal(undefined); + // There the margins stand in for less space before or after of the paragraph's own, and give way to more (DV3c, + // DV3d, DV2c), and the larger of a margin and the space of the paragraph next to it is between them (DV3e), as of two + // divisions' margins (DV3b) + const spaced = (before: number, after: number): string => inDivision(1001, ``); const spacedAfter = ''; const spacedBefore = ''; - expect(reasonOf(`${spacedAfter}${inDivision(1001)}${plain}`)).to.equal( - "an HTML division next to a paragraph with space before or after it", + const ownSpace = paragraphs(read(plain + inDivision(1001) + plain + spaced(60, 240) + plain))[3]; + expect([ownSpace.format, ownSpace.unsupported]).to.deep.equal([{ ...later[0].format, spaceBefore: 6, spaceAfter: 12 }, undefined]); + const between = paragraphs(read(plain + inDivision(1001) + spacedAfter + inDivision(1001) + spacedBefore))[3]; + expect([between.format, between.unsupported]).to.deep.equal([{ ...later[0].format, spaceBefore: 6, spaceAfter: 6 }, undefined]); + const nextTo = paragraphs(read(plain + inDivision(1001) + plain + inDivision(1001) + inDivision(1002) + plain)).slice(3, 5); + expect(nextTo.map(({ format: { spaceBefore, spaceAfter }, unsupported }) => [spaceBefore, spaceAfter, unsupported])).to.deep.equal([ + [6, 6, undefined], + [6, 6, undefined], + ]); + // Where the box's border is above or below, a paragraph's own space, a paragraph with space between them, and another + // division haven't been seen (DV2c's and word-stops-divisions.docx DV2a's borders were drawn once) + const own = + "a paragraph in an HTML division with space before or after it, where the division has a border there or another paragraph of it"; + expect(reasonOf(plain + spaced(240, 0) + plain)).to.equal(own); + expect(reasonOf(plain + inDivision(1001) + spaced(0, 240) + inDivision(1001) + plain, 2)).to.equal(own); + expect(reasonOf(plain + inDivision(1001) + plain + inDivision(1001) + spaced(60, 0) + plain, 4)).to.equal(own); + const bordered = + "an HTML division with a border above or below it next to a paragraph with space between them, or next to another division"; + expect(reasonOf(`${spacedAfter}${inDivision(1001)}${plain}`)).to.equal(bordered); + expect(reasonOf(`${plain}${inDivision(1001)}${spacedBefore}`)).to.equal(bordered); + expect(reasonOf(plain + inDivision(1001) + inDivision(1002) + plain)).to.equal(bordered); + expect(reasonOf(plain + inDivision(1002) + inDivision(1001) + plain, 2)).to.equal(bordered); + // Nor, in a document that adds the space after a paragraph to the space before the next, a division next to either + const adding = (body: string): DocumentContent => + readDocx( + new Map([ + [ + "word/_rels/document.xml.rels", + relationships( + `` + + ``, + ), + ], + ["word/settings.xml", parse(COMPATIBLE.replace("", ""))], + ["word/webSettings.xml", parse(web)], + ["word/document.xml", documentOf(body)], + ]), + ); + const adds = + "an HTML division next to a paragraph with space between them, or to another division, in a document that adds the space after a paragraph to the space before the next"; + expect(adding(plain + inDivision(1001) + spacedAfter + inDivision(1001) + plain).blocks[3].block.unsupported).to.equal(adds); + expect(adding(plain + inDivision(1001) + plain + inDivision(1001) + inDivision(1002) + plain).blocks[3].block.unsupported).to.equal( + adds, ); - expect(reasonOf(`${plain}${inDivision(1001)}${spacedBefore}`)).to.equal( - "an HTML division next to a paragraph with space before or after it", + expect(adding(plain + inDivision(1001) + plain + inDivision(1001) + plain).blocks[3].block.unsupported).to.equal(undefined); + // Automatic space, and space in lines, haven't been seen in a division + expect(reasonOf(plain + inDivision(1001, '') + plain)).to.equal( + "a paragraph in an HTML division with automatic space before or after it, or space in lines", ); - // And with indents or borders of its own, next to another division, in another with other margins or borders, the - // page's body, or not in the web settings at all + // And with indents or borders of its own, in another with other margins or borders, the page's body, or not in the + // web settings at all expect(reasonOf(plain + inDivision(1001, '') + plain)).to.equal( "a paragraph in an HTML division with indents or borders of its own", ); - expect(reasonOf(plain + inDivision(1001) + inDivision(1002) + plain)).to.equal("an HTML division next to another"); // A table next to one is as it is const table = `${plain}`; expect(paragraphs(read(table + inDivision(1001) + table))[1].format).to.deep.include({ spaceBefore: 6, spaceAfter: 6 }); diff --git a/src/text-layout/line-breaking.spec.ts b/src/text-layout/line-breaking.spec.ts index 4282860e79..e91818f5f0 100644 --- a/src/text-layout/line-breaking.spec.ts +++ b/src/text-layout/line-breaking.spec.ts @@ -3402,14 +3402,16 @@ describe("layoutLines in compatibility mode, as Word lays it out (scripts/layout ({ textWidth }) => textWidth, ), ).to.deep.equal([140]); - // Past where Word was seen keeping it on the line, 941.4 points from the margin, how it breaks it hasn't been seen: text - // to 930 is laid out, and to 950 isn't - expect(linesOf([text("a"), tab, text("b".repeat(78))], left(150))).to.deep.equal([ - { text: `a\t${"b".repeat(78)}`, textWidth: 930 }, + // The line goes on to 22 inches from where the lines start, 1584 points, and the word that would go past that starts + // the next line, which breaks as the paragraph's lines do (word-stops-compat3-14.docx CN14): 48 words of 30 fit after + // the stop at 150, to 1580, and the 49th and the rest go on the next lines + expect(linesOf([text("a"), tab, text("b".repeat(80))], left(150))).to.deep.equal([ + { text: `a\t${"b".repeat(80)}`, textWidth: 950 }, ]); - expect(linesOf([text("a"), tab, text("b".repeat(80))], left(150))[0].unsupported).to.equal( - "text after a tab past the end of the line that goes further past the margin than Word was seen keeping it on the line, in a document in compatibility mode", - ); + const long = linesOf([text("a"), tab, text(Array.from({ length: 52 }, () => "bb").join(" "))], left(150)); + expect(long.map(({ textWidth }) => textWidth)).to.deep.equal([1580, 80, 20]); + expect(long[1].text).to.equal("bb bb bb "); + expect(long.map(({ unsupported }) => unsupported)).to.deep.equal([undefined, undefined, undefined]); // One to a stop on the line is as it is, and the text after it breaks as it does without expect(linesOf([text("a"), tab, text("bb cc dd ee ff")], left(50))).to.deep.equal([ { text: "a\tbb cc ", textWidth: 100 }, @@ -3428,3 +3430,73 @@ describe("layoutLines in compatibility mode, as Word lays it out (scripts/layout expect(lines(older)).to.have.length(2); }); }); + +describe("layoutLines with Word 2003's East Asian layout (useFELayout; scripts/layout-probes/stops2/word-stops-compat3.ts FE3)", () => { + const run = (value: string, font: string, size: number): InlineItem => ({ type: "text", text: value, font: { font, size } }); + /** The width of each line, in twips, laid out with the setting unless told otherwise */ + const widthsOf = (items: readonly InlineItem[], options: Partial = {}): readonly number[] => + layoutLines(items, { width: 1000, feLayout: true, ...options }).map(({ textWidth }) => Math.round(textWidth * 20 * 100) / 100); + const reasonOf = (items: readonly InlineItem[], options: Partial = {}): string | undefined => + layoutLines(items, { width: 1000, feLayout: true, ...options })[0].unsupported; + const japanese = run("日本語の文章に", "MS Mincho", 10.5); + const latin = run("Latin words", "Calibri", 14); + + it("should put half the average width of the font before between East Asian text and the Latin letters or digits beside it, as Word does", () => { + // word-stops-fe-layout3.docx FE3a: 52.5 twips after MS Mincho 10.5, a quarter of its em, and 72.94 after Calibri 14, + // half of 521 thousandths of an em; word-stops-fe-layout.docx FE1a: 54.7 after Calibri 10.5 + const [plain] = widthsOf([japanese, latin, japanese], { feLayout: false }); + expect(widthsOf([japanese, latin, japanese])[0] - plain).to.be.closeTo(52.5 + 72.94, 0.05); + const small = run("Latin words", "Calibri", 10.5); + expect(widthsOf([japanese, small, japanese])[0] - widthsOf([japanese, small, japanese], { feLayout: false })[0]).to.be.closeTo( + 52.5 + 54.7, + 0.05, + ); + // word-stops-fe-layout2.docx FE2b: in one run of MS Mincho, whose Latin letters and digits are half an em, 52.5 either + // side of them: 4 gaps round "Latin words" and "123" + const mixed = run("日本語にLatin wordsと数字123を", "MS Mincho", 10.5); + expect(widthsOf([mixed])).to.deep.equal([3150 + 4 * 52.5]); + expect(widthsOf([mixed], { feLayout: false })).to.deep.equal([3150]); + // Nothing beside a space (FE2a), nor between East Asian punctuation and East Asian letters + expect(widthsOf([run("日本語に Latin words と数字123を", "MS Mincho", 10.5)])).to.deep.equal([3360 + 52.5 + 52.5]); + expect(widthsOf([run("日本語。文章にLatin", "MS Mincho", 10.5)])).to.deep.equal([7 * 210 + 5 * 105 + 52.5]); + // Nor without the setting, as in Word 2013's mode + expect(widthsOf([japanese, latin, japanese], {})).to.deep.equal(widthsOf([japanese, latin, japanese])); + // A bookmark's marker, or a character that takes no room, such as a zero-width space, between them leaves the space + // as it is, and a tab or a picture between them is no boundary + const [spaced] = widthsOf([japanese, latin]); + expect(widthsOf([japanese, { type: "marker", name: "m" }, latin])).to.deep.equal([spaced]); + expect(widthsOf([run("日本語の文章に\u200b", "MS Mincho", 10.5), latin])).to.deep.equal([spaced]); + expect(widthsOf([run("\u200b日本語の文章に", "MS Mincho", 10.5), latin])).to.deep.equal([spaced]); + const box: InlineItem = { type: "box", width: 10, height: 10 }; + expect(widthsOf([japanese, box, latin])).to.deep.equal([spaced - 52.5 + 200]); + }); + + it("should leave out the space the paragraph turns off, and lay out its lines as they are with both off, as Word does", () => { + // FE3b: with autoSpaceDE off, the digits spaced and the letters not; FE3c: the other way round; FE2d: both off + const mixed = run("日本語にLatin wordsと数字123を", "MS Mincho", 10.5); + expect(widthsOf([mixed], { format: { autoSpaceDE: false } })).to.deep.equal([3150 + 2 * 52.5]); + expect(widthsOf([mixed], { format: { autoSpaceDN: false } })).to.deep.equal([3150 + 2 * 52.5]); + expect(widthsOf([mixed], { format: { autoSpaceDE: false, autoSpaceDN: false } })).to.deep.equal([3150]); + expect(reasonOf([run("日本語。abc", "MS Mincho", 10.5)], { format: { autoSpaceDE: false, autoSpaceDN: false } })).to.equal( + undefined, + ); + }); + + it("should stop beside letters of another script, East Asian punctuation or full-width forms beside Latin, and a font whose average width isn't known", () => { + // cspell:ignore Aabc + // Punctuation beside East Asian text is as it is: FE2c's curly quotes in Calibri between Chinese characters + const [plain] = widthsOf([run("日本語(abc)", "MS Mincho", 10.5)], { feLayout: false }); + expect(widthsOf([run("日本語(abc)", "MS Mincho", 10.5)])).to.deep.equal([plain]); + expect(reasonOf([run("日本語(abc)", "MS Mincho", 10.5)])).to.equal(undefined); + expect(reasonOf([run("中文\u201c引号\u201d和", "SimSun", 10.5)])).to.equal(undefined); + const unknown = + "East Asian text beside letters of another script than Latin, or East Asian punctuation or full-width forms beside Latin letters or digits, in a document that lays it out as Word 2003 did (useFELayout)"; + expect(reasonOf([run("日本語αβγ", "MS Mincho", 10.5)])).to.equal(unknown); + expect(reasonOf([run("日本語。abc", "MS Mincho", 10.5)])).to.equal(unknown); + expect(reasonOf([run("日本語Aabc", "MS Mincho", 10.5)])).to.equal(unknown); + expect(reasonOf([japanese, run("abc", "Courier New", 10.5), japanese])).to.equal( + "East Asian text beside Latin letters or digits in a font whose average character width isn't known, in a document that lays it out as Word 2003 did (useFELayout)", + ); + expect(reasonOf([japanese, run("abc", "Calibri", 10.5), japanese])).to.equal(undefined); + }); +}); diff --git a/src/text-layout/line-breaking.ts b/src/text-layout/line-breaking.ts index 13f820f798..1c1931c16a 100644 --- a/src/text-layout/line-breaking.ts +++ b/src/text-layout/line-breaking.ts @@ -12,7 +12,7 @@ */ // cspell:ignore Aptos Donaudampf schifffahrtsgesellschaftkapitän import { hasLigatures } from "./kerning"; -import { type LineBreakRules, extendsCharacter, findLineBreaks, joinsNext } from "./line-break-rules"; +import { type LineBreakRules, extendsCharacter, findLineBreaks, isEastAsian, joinsNext } from "./line-break-rules"; import { DEFAULT_FONT, DEFAULT_FONT_SIZE, @@ -20,6 +20,7 @@ import { type ParagraphFormat, type TextBorder, type TextFont, + averageCharacterWidth, isEastAsianFont, isGridCharacter, isKerned, @@ -250,6 +251,12 @@ export type LineLayoutOptions = { * or 2003 (11). None for Word 2013 and later */ readonly compatibilityMode?: number; + /** + * Whether the document lays out East Asian text as Word 2003 did (`useFELayout`), which puts half the average width of + * a character between a Chinese, Japanese or Korean character and the Latin letter or digit beside it (see + * `spacedBesideEastAsian`) + */ + readonly feLayout?: boolean; }; /** @@ -330,10 +337,12 @@ type Segment = { const DEFAULT_TAB_STOP = 36; // How far past its end a line may go before it wraps, for the rounding of the widths const TOLERANCE = 0.01; -// How far from where its lines start, at the margin, Word 2010 and before were seen keeping the text after a tab past the -// end of a line on it, in points: to 18827 twips, past the margin's 9026 (`word-stops-compat2-14.docx` CN5a). Whether they -// break a longer line hasn't been seen. A line's positions are from where the paragraph's lines start, as its tab stops are -const OLDER_TAB_REACH = 941.4; +// How far from where its lines start, at the margin, Word 2010 and before keep the text after a tab past the end of a +// line on it, in points: 22 inches, Word's widest page. 250 words after a tab to a stop at 9500 twips went on to 31580 +// twips, and the word after went to the start of the next line, which breaks as a line of the paragraph does +// (`word-stops-compat3-14.docx`, `-12` CN14; `word-stops-compat2-14.docx` CN5a's went to 18827). A line's positions are +// from where the paragraph's lines start, as its tab stops are +const OLDER_LINE_LIMIT = 1584; // Word squeezes one more word onto a justified line when its spaces would otherwise stretch by a share of their width // more than twice as large as the share they're squeezed by: 2.022 times as large, and not 2.008 (`word-justify.docx` J01 @@ -1356,6 +1365,111 @@ const spacedOnGrid = ( }; }; +/** + * What a character is next to another for the space Word 2003's East Asian layout puts between them: a Chinese, Japanese + * or Korean letter, East Asian punctuation, symbols or full-width forms, a Latin letter, a letter of another script, a + * digit, a space, or other text, such as punctuation + */ +const kindBesideEastAsian = ( + character: string, +): "eastAsian" | "eastAsianOther" | "latin" | "otherLetter" | "digit" | "space" | "other" | undefined => + takesNoRoom(character) + ? undefined + : /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u.test(character) + ? "eastAsian" + : isEastAsian(character) + ? "eastAsianOther" + : /\p{Script=Latin}/u.test(character) + ? "latin" + : /\p{L}/u.test(character) + ? "otherLetter" + : /[0-9]/.test(character) + ? "digit" + : /\s/u.test(character) + ? "space" + : "other"; + +// Why a paragraph's text can't be spaced as Word 2003's East Asian layout spaces it, where it can't +const UNKNOWN_FE_SPACING = + "East Asian text beside letters of another script than Latin, or East Asian punctuation or full-width forms beside Latin letters or digits, in a document that lays it out as Word 2003 did (useFELayout)"; +const UNKNOWN_FE_FONT = + "East Asian text beside Latin letters or digits in a font whose average character width isn't known, in a document that lays it out as Word 2003 did (useFELayout)"; + +/** + * A paragraph's content in a document that lays out East Asian text as Word 2003 did (`useFELayout`), which puts half the + * average width of a character of the font of the character before, at its size, between a Chinese, Japanese or Korean + * character and a Latin letter beside it, either way, with the paragraph's automatic spacing of them on (`w:autoSpaceDE`), + * and between one and a digit with the other on (`w:autoSpaceDN`), as they are unless the paragraph turns them off: 52.5 + * twips after MS Mincho 10.5, whose Latin letters and digits are half an em too, 54.7 after Calibri 10.5 and 72.9 after + * Calibri 14 (scripts/layout-probes/stops2/word-stops-fe-layout.ts FE1a, FE1b, word-stops-fe-layout2.ts FE2b, + * word-stops-compat3.ts FE3a to FE3c), and nothing beside a space (FE2a) or punctuation, such as curly quotes in Calibri + * between Chinese characters (FE2c). Beside letters of another script, East Asian punctuation or full-width forms beside + * Latin letters or digits, and a font whose average isn't known, haven't been seen + */ +const spacedBesideEastAsian = ( + items: readonly InlineItem[], + spacing: { readonly letters: boolean; readonly digits: boolean }, +): { readonly items: readonly InlineItem[]; readonly unsupported?: string } => { + // eslint-disable-next-line functional/prefer-readonly-type + const spaced: InlineItem[] = []; + let unsupported: string | undefined; + // The last character, its item in what is laid out and its kind + let last: { readonly index: number; readonly kind: NonNullable> } | undefined; + for (const item of items) { + if (item.type !== "text") { + // eslint-disable-next-line functional/immutable-data + spaced.push(item); + last = item.type === "marker" ? last : undefined; + continue; + } + for (const character of item.text) { + const kind = kindBesideEastAsian(character); + const lastKind = last?.kind; + const beside = (one: string, other: string): boolean => + kind !== undefined && + lastKind !== undefined && + ((lastKind === one && kind === other) || (lastKind === other && kind === one)); + const spacedApart = (spacing.letters && beside("eastAsian", "latin")) || (spacing.digits && beside("eastAsian", "digit")); + if (beside("eastAsian", "otherLetter") || beside("eastAsianOther", "latin") || beside("eastAsianOther", "digit")) { + unsupported ??= UNKNOWN_FE_SPACING; + } + if (spacedApart) { + // The space goes after the character before, the last of its item, which it is split from + const before = spaced[last!.index] as Extract; + const characters = [...before.text]; + const average = averageCharacterWidth(before.font); + if (average === undefined) { + unsupported ??= UNKNOWN_FE_FONT; + } + // eslint-disable-next-line functional/immutable-data + spaced.splice( + last!.index, + 1, + { ...before, text: characters.slice(0, -1).join("") }, + { + ...before, + text: characters[characters.length - 1], + font: { ...before.font, characterSpacing: (before.font.characterSpacing ?? 0) + (average ?? 0) / 2 }, + }, + ); + } + const current = spaced[spaced.length - 1]; + if (!spacedApart && current?.type === "text" && current.font === item.font) { + // eslint-disable-next-line functional/immutable-data + spaced[spaced.length - 1] = { ...current, text: current.text + character }; + } else { + // eslint-disable-next-line functional/immutable-data + spaced.push({ ...item, text: character }); + } + last = kind === undefined ? last && { ...last, index: spaced.length - 1 } : { index: spaced.length - 1, kind }; + } + } + return { + items: spaced.filter((item) => item.type !== "text" || item.text.length > 0), + ...(unsupported === undefined ? {} : { unsupported }), + }; +}; + // Why a tab on a grid that snaps to characters can't be laid out as Word does, where it can't const GRID_TAB = "a tab on a grid that snaps to characters, but for a left one before text, or a right or centred one before Chinese, Japanese or Korean text"; @@ -1512,6 +1626,7 @@ export const layoutLines = ( hyphenation, grid = {}, compatibilityMode, + feLayout, }: LineLayoutOptions, ): readonly LaidOutLine[] => { const items = withAcross(paragraphItems, measurer); @@ -1542,7 +1657,15 @@ export const layoutLines = ( // that doesn't snap to the grid is as it is without it (scripts/layout-probes/word-grid.ts CA1 to CA5, CA9, CB1 to // CB5) const spaced = characterSpace === undefined ? undefined : spacedOnGrid(items, characterSpace); - const content = spaced?.items ?? items; + // Word 2003's East Asian layout spaces East Asian text from the Latin letters and digits beside it (see + // `spacedBesideEastAsian`), unless the paragraph turns both of its automatic spacings off, which leaves its lines as + // they are without it (`word-stops-fe-layout2.docx` FE2d) + const eastAsianSpacing = { letters: format.autoSpaceDE !== false, digits: format.autoSpaceDN !== false }; + const spacedApart = + feLayout === true && (eastAsianSpacing.letters || eastAsianSpacing.digits) + ? spacedBesideEastAsian(spaced?.items ?? items, eastAsianSpacing) + : undefined; + const content = spacedApart?.items ?? spaced?.items ?? items; /** The width of the cells a width of text takes on a grid that snaps to characters */ const cellsOf = (textWidth: number): number => { const cell = cellOn(lines.length)!; @@ -1616,7 +1739,7 @@ export const layoutLines = ( ) ? "ligatures on a document grid of characters" : undefined; - const unknownOnGrid = onCells.unsupported ?? spaced?.unsupported ?? shapedOnGrid; + const unknownOnGrid = onCells.unsupported ?? spaced?.unsupported ?? spacedApart?.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; @@ -1760,10 +1883,10 @@ export const layoutLines = ( }; /** * Where the line being filled ends: the margin after a tab to one of the paragraph's stops past its right indent, which - * Word lines text up with on the line (scripts/layout-probes/word-breaks-and-tabs.ts TP6, TP9), and nowhere after a tab - * past its end in a document in compatibility mode + * Word lines text up with on the line (scripts/layout-probes/word-breaks-and-tabs.ts TP6, TP9), and 22 inches from where + * the lines start after a tab past its end in a document in compatibility mode */ - const endOf = (state: LineState): number => (state.unbroken ? Infinity : state.pastIndent ? marginOf() : limitOf()); + const endOf = (state: LineState): number => (state.unbroken ? OLDER_LINE_LIMIT : state.pastIndent ? marginOf() : limitOf()); /** * Whether Word squeezes a word or picture this wide onto a justified or distributed line it goes past the end of, * rather than move it to the next line. It squeezes the line's spaces in proportion to their widths, and does when that @@ -1905,9 +2028,6 @@ export const layoutLines = ( const unsupported = state.unknown ? "a justified line that only fits squeezed at a four-per-em space" : (state.unsupported ?? - (state.unbroken && state.end > OLDER_TAB_REACH + TOLERANCE - ? "text after a tab past the end of the line that goes further past the margin than Word was seen keeping it on the line, in a document in compatibility mode" - : undefined) ?? (markMatters(withNumber(heights)) ? "a picture alone in a line of a paragraph whose mark is larger, with multiple line spacing" : typeof marked === "string" diff --git a/src/text-layout/text-styles.ts b/src/text-layout/text-styles.ts index f14d345b8a..1985123f9d 100644 --- a/src/text-layout/text-styles.ts +++ b/src/text-layout/text-styles.ts @@ -480,6 +480,8 @@ export const readParagraphFormat = (element: unknown): ParagraphFormat => { widowControl: onOff(children, "w:widowControl"), tabs: readTabs(find(children, "w:tabs")), kinsoku: onOff(children, "w:kinsoku"), + autoSpaceDE: onOff(children, "w:autoSpaceDE"), + autoSpaceDN: onOff(children, "w:autoSpaceDN"), rightToLeft: onOff(children, "w:bidi"), wordWrap: onOff(children, "w:wordWrap"), suppressAutoHyphens: onOff(children, "w:suppressAutoHyphens"), diff --git a/src/text-layout/text-width.spec.ts b/src/text-layout/text-width.spec.ts index 5e7ecf678d..db0ba5308e 100644 --- a/src/text-layout/text-width.spec.ts +++ b/src/text-layout/text-width.spec.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"; import { + averageCharacterWidth, isGridCharacter, isMonospacedEastAsianFont, measureDescent, @@ -564,6 +565,29 @@ describe("isMonospacedEastAsianFont", () => { }); }); +describe("averageCharacterWidth", () => { + it("should give half the average width of each face from the font's own metrics, and none for faces or fonts not known", () => { + // Calibri's xAvgCharWidth is 1067 of 2048 regular and italic, 1098 bold and 1099 bold italic; MS Mincho's 128 of 256 + expect(averageCharacterWidth({ font: "Calibri", size: 10 })).to.be.closeTo(5.21, 0.001); + expect(averageCharacterWidth({ font: "Calibri", size: 10, bold: true })).to.be.closeTo(5.361, 0.001); + expect(averageCharacterWidth({ font: "calibri", size: 20, italic: true })).to.be.closeTo(10.42, 0.001); + expect(averageCharacterWidth({ font: "Calibri", size: 10, bold: true, italic: true })).to.be.closeTo(5.366, 0.001); + expect(averageCharacterWidth({ font: "MS Mincho", size: 10.5 })).to.equal(5.25); + expect(averageCharacterWidth({ font: "MS 明朝", size: 10.5 })).to.equal(5.25); + expect(averageCharacterWidth({ font: "SimSun", size: 12 })).to.equal(6); + // Times New Roman, which a document without a font has, at 10 points + expect(averageCharacterWidth({})).to.be.closeTo(4.009, 0.001); + // Tahoma has no italics, the East Asian fonts here no bold or italics of their own, and Yu Mincho, Courier New and + // fonts measured as others aren't known + expect(averageCharacterWidth({ font: "Tahoma", size: 10, italic: true })).to.equal(undefined); + expect(averageCharacterWidth({ font: "Tahoma", size: 10, bold: true })).to.be.closeTo(5.059, 0.001); + expect(averageCharacterWidth({ font: "MS Mincho", size: 10, bold: true })).to.equal(undefined); + expect(averageCharacterWidth({ font: "Yu Mincho", size: 10 })).to.equal(undefined); + expect(averageCharacterWidth({ font: "Courier New", size: 10 })).to.equal(undefined); + expect(averageCharacterWidth({ font: "Aptos", size: 10 })).to.equal(undefined); + }); +}); + describe("isGridCharacter", () => { it("should say which characters a grid that snaps to characters puts in cells of their own", () => { expect([..."永あア한,ア"].map(isGridCharacter)).to.deep.equal([true, true, true, true, true, true]); diff --git a/src/text-layout/text-width.ts b/src/text-layout/text-width.ts index 3342f801b8..14a43f5ef5 100644 --- a/src/text-layout/text-width.ts +++ b/src/text-layout/text-width.ts @@ -206,6 +206,12 @@ export type ParagraphFormat = { readonly tabs?: readonly TabStopSetting[]; /** Whether Word's East Asian rules keep characters from starting or ending its lines (`w:kinsoku`). Default is on */ readonly kinsoku?: boolean; + /** + * Whether Word's East Asian layout (`useFELayout`) spaces its Chinese, Japanese and Korean text apart from the Latin + * letters (`w:autoSpaceDE`) and the digits (`w:autoSpaceDN`) beside it. Default is on + */ + readonly autoSpaceDE?: boolean; + readonly autoSpaceDN?: boolean; /** Whether the paragraph is right to left (`w:bidi`) */ readonly rightToLeft?: boolean; /** Whether its lines break between words (`w:wordWrap`), or, when off, anywhere in the words of East Asian runs */ @@ -491,6 +497,56 @@ const eastAsianFontOf = (font: string): EastAsianFont | undefined => { /** Whether a font is one for Chinese, Japanese or Korean text */ export const isEastAsianFont = (font: string | undefined): boolean => font !== undefined && eastAsianFontOf(font) !== undefined; +/* cspell:disable */ +// The average width of the characters of each face of the fonts in the tables, in thousandths of an em, from the fonts' +// own OS/2 tables (`xAvgCharWidth`): regular, bold, italic and bold italic. Word 2003's East Asian layout (`useFELayout`) +// puts half of it between a character and the Latin letter, digit or East Asian character beside it, at the size of the +// character before: 52.5 twips after MS Mincho 10.5, 54.7 after Calibri 10.5 and 72.9 after Calibri 14 (stops2/ +// word-stops-fe-layout.ts FE1a, word-stops-fe-layout2.ts FE2b, word-stops-compat3.ts FE3a). The East Asian fonts whose +// average is half an em, so the half is a quarter of an em, are here; those whose average is otherwise, such as Yu Mincho's +// 969 thousandths, haven't been seen spaced +const AVERAGE_CHARACTER_WIDTHS: ReadonlyMap = new Map< + string, + readonly [number, number, number, number] +>([ + ["calibri", [521.0, 536.1, 521.0, 536.6]], + ["arial", [441.4, 478.5, 441.4, 478.5]], + ["cambria", [615.2, 599.6, 542.5, 585.0]], + ["tahoma", [444.3, 505.9, 444.3, 505.9]], + ["times new roman", [400.9, 426.8, 401.9, 412.1]], + ...[ + "ms mincho", + "ms gothic", + "simsun", + "nsimsun", + "simhei", + "kaiti", + "fangsong", + "pmingliu", + "mingliu", + "batang", + "gulim", + "dotum", + ].map((name): readonly [string, readonly [number, number, number, number]] => [name, [500, 500, 500, 500]]), +]); +/* cspell:enable */ + +/** + * The average width of the characters of a font's face, in points at its size, from the font's own metrics, for the space + * Word 2003's East Asian layout puts beside a character of it. Undefined for a font, or a face of it, whose average isn't + * known, such as a bold Tahoma, which Tahoma doesn't have, or a font measured as another + */ +export const averageCharacterWidth = ({ font = DEFAULT_FONT, size = DEFAULT_FONT_SIZE, bold, italic }: TextFont): number | undefined => { + const name = font.toLowerCase(); + const known = knownEastAsianFontOf(font); + const widths = AVERAGE_CHARACTER_WIDTHS.get(known === undefined ? name : known.name.toLowerCase()); + const face = widths?.[(bold ? 1 : 0) + (italic ? 2 : 0)]; + // Tahoma has no italics, which Word slants, and the East Asian fonts here no bold or italics of their own + return face === undefined || (name === "tahoma" && italic) || (known !== undefined && (bold || italic)) + ? undefined + : (face * size) / 1000; +}; + const named = (name: string): FontWidths | undefined => FONT_WIDTHS.find((known) => known.name.toLowerCase() === name.toLowerCase()); /** The widths of a font in the table, or of a font with the same widths as one. Undefined for other fonts */