Skip to content

feat(layout): keep with next, keep together, minimum lines at a break - #680

Merged
Tim81 merged 5 commits into
mainfrom
feat/keep-rules
Nov 22, 2026
Merged

Tim81 merged 5 commits into
mainfrom
feat/keep-rules

Conversation

@Tim81

@Tim81 Tim81 commented Nov 22, 2026 •

Copy link
Copy Markdown
Owner

Closes #306

What changes

Layout gains opt-in control over where a page break may fall:

  • KeepWithNext on Paragraph, Heading, TableElement, ListElement and LayoutImage.
  • KeepTogether on the same types except the image, which does not split.
  • Paragraph.MinLinesBeforeBreak and MinLinesAfterBreak (default 1). A value below 1 throws
    ArgumentOutOfRangeException from the init accessor. There is no upper bound.
  • Three warnings, LayoutDiagnosticCode.KeepWithNextRelaxed (801), KeepTogetherRelaxed (802) and
    MinLinesRelaxed (803). StrictDiagnostics still saves.

The rules live in the one placement loop that both passes run. A run of consecutive KeepWithNext
elements and the element after it form a group. The group is first placed on a copy of the cursor,
using the same loop, so the next element's own keep-together and line counts decide where its first
piece lands. The group holds when each element starts on the page the one before it ends on, which
for an element that splits is the page of its last piece. When it does not hold, the run moves to
the next page. A PageBreak, or an element with BreakBefore, ends the group. A request that
cannot be honoured is dropped and reported: keep-with-next first, then keep-together, then the line
counts. A run that already starts a page is never moved, so no page is left empty.

A run taller than a page is not dropped for that alone. A paragraph that splits keeps only its last
piece with the element after it, and the pieces before that fall where the pages end. Measured on a
page of 11 lines: 3 filler lines, a 20-line KeepWithNext paragraph and one more paragraph give
8 + 11 + 1 lines, the last line on the page of the next paragraph, with no report. The request is
reported when the next element cannot share the page the last piece ends on, as when that piece
ends exactly at a page foot and the run is already at the top of a page.

The line counts are read for a paragraph the document places, as a Paragraph or as a
ParagraphRenderer added to it. A custom IRenderer that wraps a ParagraphRenderer, a direct
ParagraphRenderer.Layout call and a context made with LayoutContext.WithArea ignore them and
place as many lines as fit, so setting them there cannot make a save throw.

A KeepTogether element is checked until it has split once, wherever the split comes from: the
first call that splits it below a page top, or the first call at the top of the page a Nothing
sent it to (a line count that refused the first page, for one). Either way it is reported once.
The empty-page probe offers the box a page top is offered, which differs from the content height by
a rounding step on some geometries.

Nothing is placed or reported while the group is tried, so anchors, outline entries, page-label
ranges and mirrored margins follow the page an element finally lands on. Everything is decided in
both passes, so {pages} is the number of pages drawn.

Compatibility

All members are opt-in, so a document that sets none of them saves to the same bytes.

Check Result
2,000 random documents (every element kind, bands, mirrored margins, tagging, recto breaks, labels, anchors), origin/main build against this build, every new member set explicitly to its default 2,000 of 2,000 equal: 1,821 byte-identical files, 179 the same exception type
12,000 random documents with random keep flags and counts (page counts against the same documents without them) no document with fewer pages (11,029 compared), 1,952 with more

The two builds were told apart by the loaded assembly's version and SHA-256 (2.3.3+2316dee,
2D2B4E44C030FE40 on origin/main; 2.3.3+fd8f9f0, F75BF0587A4EF5E6 on this branch), which
the probe printed with each run, and by the keep types being absent from one.

No deliberate output change. No document that saves today starts to throw.

One deviation from the planned "same page count or more" property. RandomKeepFlags_... compares the
pages that hold something, not all pages, because a recto break adds a blank page only when the page
it would start on is left-hand, and moving content can change that. The sweep above found no
document where the total fell, but the test does not assert that for the total.

Tests

KeepRulesTests (75 tests with the theory rows), KeepRulesByteIdentityTests (3) and
KeepRulesOracleTests (2: qpdf --check, pdftotext per page, veraPDF PDF/A-2u on a twelve-chapter
document with every heading kept; a missing qpdf now skips through the oracle gate). The acceptance
rows are read back as the words on each page.

Layout test project, Release, oracles required: 2,009 passed on net10.0 and on net11.0, 2 skipped on each (named-pipe tests). The three keep classes are 80 tests together.

Mutations

Each mutant was built in a separate worktree and run against the three keep test classes.

Mutant Failing tests
The retry no longer counts as a page top MinLinesBeforeBreak_moreThanAPage_afterAShortFiller_saves_andReportsTheSplits, RandomKeepFlags_..., the LargestLineCounts_... rows
The placement loop never says "page top" 7 tests, among them MinLines_aboveTheLineCount_... and MinLines_relaxedOnEveryPageOfALongParagraph_...
A paragraph never relaxes at a page top 7 tests, among them MinLines_aboveTheLineCount_...
WithArea copies the page-top flag, or the line-count flag WithArea_carriesTheFreshPageArea_andNeitherTheTopOfPageNorTheLineCountFlag
Every paragraph renderer reads the line counts ARendererThatWrapsAParagraphRenderer_inAFreshContext_ignoresTheLineCounts, ..._withWithArea_...
No paragraph renderer reads the line counts 13 tests, among them AParagraphRendererAddedToTheDocument_readsTheLineCounts
Keep-together is checked on every piece, not until the first split KeepTogetherParagraphOfThreePages_isReportedOnce_notOnceForEachPiece, KeepTogetherTable_afterAFullPage_...
Keep-together is checked on the first call only (the earlier code) 5 tests, among them KeepTogetherParagraph_afterAFullPage_splitsAtThePageTop_andIsReportedOnce, KeepTogetherList_afterAFullPage_...
The empty-page probe offers the content height, not the page-top box KeepTogetherParagraph_thatFitsOnlyWhenOfferedThePageTopBox_movesWhole
kept >= MinLinesBeforeBreak becomes > MinLinesBeforeBreak_ofExactlyTheLinesThatFit_keepsThemOnThePage
Off by one in the lines carried over FiveLineParagraph_whereFourFit_..., MinLinesBeforeAndAfterTogether_...
The line-count gate reads only MinLinesBeforeBreak FiveLineParagraph_whereFourFit_..., MinLines_aboveTheLineCount_...
Drop the keep-together report 8 tests, among them KeepTogetherParagraphOfThreePages_...
Drop the line-count report 6 tests, among them MinLinesBeforeBreak_moreThanAPage_...
Drop the keep-with-next report 6 tests, among them ChainTallerThanAPage_isPlacedAsWithoutTheFlag_andReportedOnce
The keep-with-next report is made when the run is decided, before its first element is placed KeepWithNextRelaxed_isReportedOnThePageTheFirstElementMovedTo
A run at a page top is moved to the next page when the group holds there ARunAtAPageTop_thatHoldsOnlyOnTheNextPage_isNotMovedOffIt
The simulation places the element after the run in full, not only its first piece TheGroupSimulation_placesTheElementAfterTheRunOnlyAsFarAsItsFirstPiece
The empty-page probe runs for a keep-together element at a page top AKeepTogetherParagraphAtThePageTop_isLaidOutOncePerPage_withNoProbeForAnEmptyPage

One mutant survives and is equivalent in output: naming the page before the right one as the page a
Nothing from the probe is retried on. The only reader of that box is the table renderer, for a row
taller than a page, and it uses the box's y and height, which are the same on every page; only x
differs, and only under mirrored margins.

The mutants of the first round (keep-with-next decided in the drawing pass only, keep-together
dropped before keep-with-next, a run moved off a page top, placements reported while a group is
tried, a look past a PageBreak, a break not moved up for MinLinesAfterBreak, keep-together never
testing an empty page, the run not advancing the page) were not rerun after this change. Their tests
are unchanged and pass.

Cost

On 1,000 paragraphs of about 32 words on A4, 63 pages, where no paragraph straddles a page foot:
1,124 Layout calls unflagged. With KeepWithNext on every paragraph the document is one run, and
the walk stops at the first element that starts on a later page than the one before it ended on, so
it costs 19 calls more: 1,143, 1.0003 times the allocation. With it on every second paragraph:
2,248 calls (2.25 per flag) and 1.0137 times the allocation. Every tenth: 1,348 calls, 1.0027 times.
KeepTogether alone adds no calls on this document because no paragraph is split. IRenderer.Layout
says the document may lay a renderer out ahead of the elements before it.

Not done

  • Splitting a KeepWithNext paragraph so that more than its last piece stays with the next
    element.
  • A document-wide default for headings, and turning any of this on by default.

A heading could end a page with its section starting overleaf, a
paragraph could leave one line at the foot of a page, and a figure could
be parted from its caption. Add opt-in KeepWithNext, KeepTogether and
Paragraph.MinLinesBeforeBreak/MinLinesAfterBreak, decided in the one
placement loop that both passes run, so the page count of the measuring
pass is the page count of the drawing pass.

A group is laid out on a copy of the cursor first. A request that cannot
be honoured, because the run already starts a page or the group does not
fit one, is dropped in a fixed order and listed as a warning (801-803),
so no page is left empty and no document that saved now throws.

Closes #306
A keep-together element whose first call answered Nothing moved to the next
page and split there without a report. The check now runs until the element
has split once, and the empty-page probe offers the box a page top gets and
names the page after it as the retry page.

The line counts are read only for a paragraph renderer the document places;
a wrapper, a direct Layout call and WithArea contexts ignore them, so they
cannot make a save throw. WithArea no longer copies the page-top flag.

The keep-with-next, keep-together and line-count remarks state the rule that
was measured, not a group-taller-than-a-page rule. The oracle tests route
qpdf through the gate.
The keep-with-next report was made when the run was decided, so an element
that then moved to the next page by its own keep-together or line count was
reported on the page it had left. It is now made once the element's first
piece is placed.

The paragraph docs no longer compare a line count above the paragraph's
length with KeepTogether, which differs for a paragraph taller than a page,
and say that the second walk and the empty-page probe are skipped at a page
top. New tests pin the report page, both tall-paragraph rows, the page-top
guard under mirrored margins and the layout-call counts.
@Tim81
Tim81 merged commit fc2b248 into main Nov 22, 2026
6 checks passed
@Tim81
Tim81 deleted the feat/keep-rules branch November 26, 2026 20:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Layout: widow and orphan control, keep-together and keep-with-next

1 participant