Prefer the later equal-cost page break

This commit is contained in:
gloamxun committed 2026-10-23 23:58:28 +08:00
1 parent 66b2ccf380
commit bf31936146
3 files changed
+53 -16

No files matched your search

+47 -11
View File
@@ -815,17 +815,23 @@ impl PageBuilder {
})
.cloned()
.collect();
let pool = if feasible.is_empty() {
candidates
} else {
feasible
};
pool.into_iter().min_by_key(|candidate| {
(
candidate.cost,
(candidate.height + candidate.reserved + candidate.bottom - self.page_goal).abs(),
)
})
if feasible.is_empty() {
// Nothing fits: TeX ships an overfull page, and the least overfull
// break keeps the damage minimal.
return candidates.into_iter().min_by_key(|candidate| {
(
candidate.cost,
(candidate.height + candidate.reserved + candidate.bottom - self.page_goal)
.abs(),
)
});
}
// TeX keeps the least-cost breakpoint and prefers the later one on a
// tie (`<=` in the page builder's scan), so ties resolve by document
// order rather than by distance to the page goal.
feasible
.into_iter()
.min_by_key(|candidate| (candidate.cost, std::cmp::Reverse(candidate.end)))
}
}
@@ -1054,6 +1060,36 @@ mod tests {
assert_eq!(pages[0].depth, 4);
}
#[test]
fn equal_cost_breaks_prefer_the_later_candidate() {
// Two legal breaks have cost zero: the earlier one is 5pt short of
// the goal with 100pt of stretch, the later one overfills by 10pt
// with 1000pt of shrink. TeX's page builder updates its best break
// with `<=`, so the later candidate wins even though it is farther
// from the goal.
let builder = PageBuilder::new(200);
let nodes = vec![
VerticalNode::Box {
height: 90,
depth: 0,
},
VerticalNode::Glue(VerticalGlue::new(0, 100, 1000)),
VerticalNode::Box {
height: 105,
depth: 0,
},
VerticalNode::Glue(VerticalGlue::new(0, 0, 0)),
VerticalNode::Box {
height: 15,
depth: 0,
},
VerticalNode::Glue(VerticalGlue::new(0, 0, 0)),
];
let pages = builder.build(&nodes);
assert_eq!(pages.len(), 1);
assert_eq!(pages[0].height, 210);
}
#[test]
fn overfull_pages_take_the_least_overfull_break() {
let builder = PageBuilder::new(50);