SPB Git

Repository Public

pagination.md 21.3 KB

# Pagination

Code: Packages/ORIXDocsKit/Sources/DocLayout/Paginator.swift (types in DocumentLayout.swift). Tests: Packages/ORIXDocsKit/Tests/DocLayoutTests/PaginationTests.swift; every rule below names the test that checks it, or says that none does. Typesetting of a single paragraph is in layout-engine.md.

Paginator.layout(_:citations:options:cache:previous:) runs one or more Pass objects. A pass walks DocumentModel.body once, in order, and appends fragments to pages. There is no backtracking: a decision, once emitted, is final for that pass.

# Flow state

A Pass is a small state machine:

State Meaning
pages, page Pages produced so far; the current one is the last.
section, setup Index and PageSetup of the section being flowed.
col, y Current column and the y where the next line goes.
bandTop, bandMaxY A band is one set of columns on a page. A page has several bands when continuous section breaks change the column count. bandTop is where the band's columns start, bandMaxY the lowest point reached in it.
atColumnTop Nothing has been placed in the column yet.
pendingNotes, noteHeight Footnotes referenced in the current column and the height they need at its foot.
pageNoteReserve Height at the page foot already taken by footnotes of columns or bands that were closed on this page.
exclusions Regions narrowed by floats in the current column, in page coordinates.
lastNumber, pendingRestart, sectionStartsPage Page numbering and first-page-of-section state.

Derived values: colBottom = contentRect.maxY − pageNoteReserve, remaining = colBottom − noteHeight − y, columnCapacity = colBottom − bandTop.

Transitions: newPage(blank:) closes the band and starts a page; nextColumn() closes the column and moves to the next one, or to a new page after the last; closeColumn() places the pending footnotes; closeBand() closes the column and adds column rules when the setup asks for them.

# Page geometry

newPage builds a PageLayout from the current PageSetup:

  • size = paper size, swapped for landscape (pageWidth, pageHeight);
  • the header and footer variant for the page are measured (measure, with placeholder field values, cached per section and variant);
  • content top = max(margins.top, headerDistance + headerHeight + 8) (the 8 pt only when there is a header); content bottom = pageHeight − max(margins.bottom, footerDistance + footerHeight + 8); the content rectangle is at least 40 pt high;
  • column width = (contentWidth − (columns − 1) × columnGap) / columns, never under 36 pt.

A tall header therefore pushes the body down instead of overlapping it.

Tests: everythingStaysInsideTheContentArea, landscapeAndMarginsAreHonoured, emptyDocumentHasOnePageAndACaret, noLineIsLostOrDuplicatedAcrossPages; header and footer placement relative to the content rectangle in headersAndFootersShowPageFieldsAndRunningHeads.

# Page numbers

A page's number is pendingRestart ?? lastNumber + 1; its text is the number in the section's pageNumberFormat. pendingRestart is loaded from pageNumberStart of the first section and of each section break, and consumed by the next page that starts. Test: sectionBreakChangesPageSetupAndNumbering (pages "i", "ii", "1").

# Breaks and sections

Block Behaviour
.pageBreak (kind .page) A marker fragment, then newPage().
.pageBreak (kind .column) A marker, then nextColumn() — a new page from the last column.
pageBreakBefore on a paragraph newPage() unless the paragraph is already at the top of the first column of the page's first band.
.sectionBreak .nextPage New setup, new page, which is the first page of the section.
.sectionBreak .continuous When paper, orientation and margins are unchanged: the band is closed, the new setup applies from bandMaxY + 7 pt on the same page, in column 0. If less than 30 pt remain, a new page starts instead. A continuous break that changes paper, orientation or margins behaves like .nextPage. A page-number restart on a continuous break applies to the next page.
.sectionBreak .oddPage / .evenPage Like .nextPage; if the next page number has the wrong parity, a blank page is inserted first. The blank page belongs to the section that ends, takes the next number in sequence, and gets no header or footer (isBlank).

Parity is that of the page number, not of the physical sheet index.

Tests: pageBreakBlockAndPageBreakBefore, columnBreakMovesToTheNextColumn, continuousSectionBreakStartsColumnsOnTheSamePage, oddPageSectionBreakInsertsABlankPage. No test covers .evenPage, the 30 pt rule, or a continuous break that changes page geometry.

# Placing one paragraph

Pass.place(_:story:path:generated:):

flowchart TD
    A[Typeset the paragraph for the column] --> B{"pageBreakBefore and not at page top"}
    B -- yes --> B1["New page, typeset again"]
    B -- no --> C
    B1 --> C{"Own float does not fit in the rest of the column but fits in a full one"}
    C -- yes --> C1["Next column, typeset again"]
    C -- no --> D
    C1 --> D["Count lines k that fit: line heights plus the footnotes they bring"]
    D --> E{All remaining lines fit}
    E -- yes --> H[Emit the fragment]
    E -- no --> F{"keepLinesTogether, at the first line, paragraph fits in a full column"}
    F -- yes --> G0["take becomes 0"]
    F -- no --> G["Widow and orphan control adjusts take"]
    G0 --> G1{take is 0}
    G --> G1
    G1 -- "yes, column not empty" --> N[Next column]
    N --> D
    G1 -- "yes, column empty" --> G2[Force at least one line]
    G2 --> H
    G1 -- no --> H
    H --> I[Register footnotes and floats]
    I --> J{Lines left}
    J -- yes --> N
    J -- no --> K[Add space after]

# Spacing

  • Space before is added in front of a paragraph's first line unless the paragraph starts at the top of a column (atColumnTop), where it is suppressed.
  • Space after is added after the last line, limited to what remains in the column.
  • Space after one paragraph and space before the next add up; they are not collapsed.
  • A table gets 4 pt above it (not at a column top) and up to 8 pt below.

No test checks these rules directly; KeepRuleTests.docLeaving sets both spacings to zero to make its arithmetic exact.

# Widow and orphan control

Applied when the paragraph cannot be finished in the column (take < rest), widowControl is on (the default) and more than one line remains. With k the number of lines that fit and first the index of the first line not yet placed:

  1. Orphan: if exactly one line fits and it is the paragraph's first line, take none.
  2. Widow: if taking the lines would leave exactly one for the next column, take one fewer.
  3. If step 2 leaves a single first line, take none.

When the result is zero lines, the paragraph moves to the next column; if the column is empty, at least one line is placed anyway so the flow always progresses. The consequences: a paragraph never starts with one line at a column foot nor ends with one at a column head, and a paragraph of two or three lines is never split.

Tests: orphanControlMovesALoneFirstLine, widowControlLeavesTwoLinesOnTheNextPage, withoutWidowControlTheParagraphSplitsAnywhere.

# Keep lines together

With keepLinesTogether, a paragraph that does not fit in what remains and whose line height total is at most a full column moves whole to the next column. A paragraph taller than a column flows normally. Tests: keepLinesTogetherMovesTheWholeParagraph, aParagraphTallerThanAPageStillFlows.

# Keep with next

Checked in run() before a paragraph is placed, when the column is not empty, the paragraph has keepWithNext, and the previous block is not itself a keep-with-next paragraph (it starts a chain). The engine adds up:

  • space before + full height + space after of the paragraph and of the keep-with-next paragraphs that follow it — the look-ahead is bounded to five following blocks (j − i < 6) and stops at the first block that is not a keep-with-next paragraph;
  • leadHeight of the block after the chain: for a paragraph, its space before plus its first two lines (all of them with keepLinesTogether); for a table, 4 pt plus its header rows and first body row; zero for other blocks.

If the sum exceeds what remains but fits in a full column, the chain starts in the next column. Test: keepWithNextKeepsAHeadingWithItsText.

# Footnotes

  • Cost model. When counting the lines that fit, each line brings the footnotes whose references it contains and that are not placed yet. Their cost is the height of their paragraphs (each paragraph's height plus its space after) plus a 10 pt separator for the first note of the column (noteCost). A line fits only with its notes, so a footnote is always in the column of its reference.
  • Placement. closeColumn() places the column's notes at its foot, at colBottom − noteHeight: a 0.5 pt rule at most 120 pt wide, then the notes in order of reference, as fragments of story .note(id). The first paragraph of a note hangs its number in a 13 pt indent.
  • Reserve. After closing a column, pageNoteReserve keeps the height its notes took, and colBottom is lowered by it for whatever follows on that page. This is what stops the columns of a band that starts after a continuous section break from running into footnotes already placed at the page foot. It also applies to the later columns of the same band.
  • A note's layout is computed once per pass (noteLayouts). Footnotes referenced in a table are gathered row by row (rowNotes).

Tests: footnotesSitAtTheFootOfThePageOfTheirReference (same page as the reference, below the body, inside the content area, one rule per page with notes), noteNumbersFollowDocumentOrder. No test covers the reserve.

# Endnotes

After the body, if the document has endnotes: a generated heading ("Notes", or "Notes de fin" when the document language starts with fr), then each endnote in order of reference with its lower-roman number followed by a period as a hanging label. Endnote lines are placed without widow/orphan control. Test: endnotesAreCollectedAfterTheBody.

# Tables

Pass.place(_:blockIndex:) flows a TableLayout (layout-engine.md) row by row:

  • a row that does not fit (its height plus the footnotes it brings) closes the current TableFragment and moves to the next column, unless it is the first row of a fragment in an empty column, in which case it is placed anyway;
  • at the top of a continuation fragment the header rows are repeated when the fragment starts at or after the first body row and header plus that row fit; the repeated cells are emitted as generated fragments (drawn, not editable) and counted in repeatedHeaderRows;
  • a row taller than a full column, or a table that had to be scaled to the column width, puts the table's id in overflowingTableIDs;
  • the table is aligned left, centre or right in the column; cell content is aligned top, centre or bottom within the cell's rows.

Tests: tablesSplitByRowsAndRepeatTheirHeader, cellTextStaysInsideItsCell, mergedCellsCoverTheirGrid, aTableWiderThanTheColumnIsScaledAndReported.

# Floats

A floating image or shape belongs to its anchor paragraph (layout-engine.md).

  • Moving with the paragraph. If the paragraph's lowest float (floatBottom) does not fit in what remains of a column that is not empty, but fits in a full column, the paragraph starts in the next column.
  • Registration. When the paragraph's first fragment is emitted, each float is added to page.floats at its page position, and .square and .topAndBottom floats add an exclusion to the pass.
  • Carried to the following paragraphs. Every later paragraph in the column is typeset with the exclusions that still lie below its top, translated to its own coordinates, so text continues to wrap until it has passed the float. Exclusions are cleared at each new column, page and band.
  • When exclusions exist, or after a break inside the paragraph, the paragraph is typeset again for the place its lines will really occupy; the new layout is adopted only if it has the same number of lines.

Tests: floatingObjectsNarrowTheLinesBesideThem checks the paragraph-level narrowing. No pagination test covers registration, carried exclusions or moving the paragraph.

# Generated blocks and convergence

  • Contents. One generated paragraph per outline entry up to maxLevel (style TOC1…), made of the heading number and text carrying an internal link to the heading, a tab, and the heading's page; a right tab stop with a dot leader sits at the column's right edge.
  • Lists of figures and tables. The same, from Numbering.captions whose sequence label starts with "fig" or "tab".
  • Bibliography. The paragraphs returned by the CitationFormatting implementation (references.md).
  • All three have an optional title paragraph and a placeholder sentence when empty. Their fragments are generated: the block is selected as a whole.

Page numbers shown in these blocks, in .page cross-references, in body pageNumber fields and in body pageCount fields depend on the layout being computed. The engine iterates:

  1. A pass receives pageRefs (block id → page number text) and a page count from the previous pass, or from the previous layout given by the caller; on a cold start both are empty, and references show "–", "?" or "#".
  2. Every lookup goes through pageRef(_:), which records the value it returned in usedRefs; using the page count sets usedPageCount.
  3. After the pass, the layout is stable when every value in usedRefs equals the page text the pass itself produced for that block, and the page count is unchanged or was not used.
  4. Otherwise the references are rebuilt from the pass and another pass runs. At most four passes; the fourth result is returned as it is, stable or not.

DocumentLayout.passes reports how many ran. While editing, DocumentSession.relayout() passes the previous layout, so one pass is the normal case.

Tests: contentsPageNumbersMatchWhereHeadingsLand (at least two passes on a cold start; every contents entry ends with the page of its heading), layoutIsStableWhenRunAgainFromItsOwnResult (one pass, identical result), crossReferenceToAPageResolves. The lists of figures and tables and the bibliography have no test in PaginationTests.swift.

# Headers and footers

Placed by placeHeadersAndFooters() once the flow is complete, so the total page count is known.

  • Variant. .first on the first page of a section when differentFirstPage is on; .even on even page numbers when differentOddEven is on; .default otherwise.
  • Fallback. An empty .even variant falls back to the default paragraphs (and the fragments then belong to the default story, so editing them edits the default). An empty .first variant means no header on that page.
  • Position. The header starts at headerDistance from the top edge; the footer ends at footerDistance from the bottom edge. Both use the full content width.
  • Fields. pageNumber is the page's number text, pageCount the total number of pages.
  • Running heads. headingText(level:) shows the first heading of that level that starts on the page; if there is none, the last one before the page; else nothing. A heading resets the remembered headings of deeper levels.
  • Blank parity pages get neither. The page's section is the one in force when the page started.

Tests: headersAndFootersShowPageFieldsAndRunningHeads (a page-number box exists, header and footer lie between the page edge distances and the content rectangle; it does not assert the running-head text), differentFirstPageAndOddEvenVariants.

# What DocumentLayout exposes

Member Content
pages: [PageLayout] Per page: size, section index, number and number text, content rectangle, header variant, isFirstOfSection, isBlank, and the fragments: texts, tables, floats, markers, footnoteRules, columnRules.
pageOfBlock, yOfBlock Block or paragraph id → page index and page y where it starts. Filled for body paragraphs (cell paragraphs and generated paragraphs included), tables, breaks and generated blocks.
pageText(ofBlock:) The formatted page number of a block.
overflowingTableIDs Tables scaled to fit or holding a row taller than a column.
passes Number of pagination passes.
numbering, options, pageCount The Numbering used, the layout options, the number of pages.
fragments(story:path:) and the queries of Geometry.swift See layout-engine.md.

# Summary

Rule Behaviour Test
Content area Margins, or header/footer height when larger everythingStaysInsideTheContentArea, landscapeAndMarginsAreHonoured
Line conservation Every line placed exactly once noLineIsLostOrDuplicatedAcrossPages
Page break, pageBreakBefore New page pageBreakBlockAndPageBreakBefore
Column break Next column, else next page columnBreakMovesToTheNextColumn
Section, numbering restart New setup and number format sectionBreakChangesPageSetupAndNumbering
Odd/even section Blank page for parity oddPageSectionBreakInsertsABlankPage (odd only)
Continuous section New band on the same page continuousSectionBreakStartsColumnsOnTheSamePage
Space before / after Suppressed at column top / added none
Orphan No single first line at a foot orphanControlMovesALoneFirstLine
Widow No single last line at a head widowControlLeavesTwoLinesOnTheNextPage, withoutWidowControlTheParagraphSplitsAnywhere
Keep lines Whole paragraph moves if it can fit keepLinesTogetherMovesTheWholeParagraph, aParagraphTallerThanAPageStillFlows
Keep with next Chain + lead of next block stay together keepWithNextKeepsAHeadingWithItsText
Footnotes At the foot of the reference's column footnotesSitAtTheFootOfThePageOfTheirReference, noteNumbersFollowDocumentOrder
Footnote reserve Later bands and columns stop above placed notes none
Endnotes After the body endnotesAreCollectedAfterTheBody
Tables Split by rows, header repeated, scaled if too wide tablesSplitByRowsAndRepeatTheirHeader, aTableWiderThanTheColumnIsScaledAndReported, mergedCellsCoverTheirGrid, cellTextStaysInsideItsCell
Floats Exclusions carried, paragraph moved floatingObjectsNarrowTheLinesBesideThem (paragraph level only)
Contents, page references Multi-pass until stable, at most four contentsPageNumbersMatchWhereHeadingsLand, layoutIsStableWhenRunAgainFromItsOwnResult, crossReferenceToAPageResolves
Headers, footers Variants, fields headersAndFootersShowPageFieldsAndRunningHeads, differentFirstPageAndOddEvenVariants
Screen = print Same pagination with and without markup decorations screenAndPrintLayoutsPaginateIdentically (PDFTests.swift)

# Measured cost

From docs/reports/benchmarks.json (release build, 18 cores, macOS "Version 27.0 (Build 26A5425a)"; generated document of 1,884 blocks, 177,162 words, 487 pages; what each figure means is in performance.md):

Metric Value
layout_cold_ms (empty cache) 436.577292
layout_passes 2
keystroke_relayout_ms median / p95 / max 14.027374999999999 / 18.708082999999998 / 22.288083
paragraph_break_at_start_relayout_ms 13.884333

# Limits

  • Rows do not split across pages. A row taller than a column is placed whole and overflows; it is only reported (overflowingTableIDs).
  • Vertical merges are not kept together. A page break can fall inside the rows of a merged cell; the cell's content is emitted with its first row.
  • Footnotes do not split between pages, and a line always travels with its notes. A note taller than a column overflows.
  • Continuation beside a float. A paragraph that continues in the next column after wrapping around a float of an earlier paragraph keeps its narrowed lines there, because the layout typeset without the float usually has a different number of lines and is then not adopted. A paragraph's own float narrows its lines relative to the paragraph, whichever page they land on.
  • No column balancing. Columns fill one after the other; the last band of a section is not evened out. Tables and floats do not span columns.
  • Tables ignore floats: a table is not narrowed by an exclusion.
  • Keep with next looks at most five blocks ahead and does nothing when the chain cannot fit in a full column.
  • Parity pages: with a page-number restart whose value has the wrong parity for an odd/even break, a blank page is inserted and the section still starts on the restarted number.
  • Convergence is bounded, not guaranteed: after four passes the result is returned even if a page reference still disagrees with the final page.
  • Whole-document passes. Every edit re-flows the body from the first block; what makes this fast is the paragraph cache, not partial pagination.
Files main
Menu

Theme