Newspaper columns keep a paragraph's last lines together, as Word does (#6828)

* Layout: balanced columns keep a continued paragraph's last lines together from Word 2013's layout

When the columns of a section's last page are balanced before a continuous
break, Word (compatibility mode 15) does not leave one line of a paragraph
alone in a column: the last two or three lines of a paragraph that began on the
page before, and a two- or three-line paragraph that begins the page, stay in
the first column that can hold them. settled_end only guarded a paragraph's
start, and skipped even that at the top of a column, so the balancing tries
split such lines one per column and the section came out a line short.

In mode 15, while balancing, widow/orphan control also applies at the top of a
column, a one-line fragment of a continued paragraph with more after it moves
on whole, and lines it moved go to the next column instead of overflowing.
Mode 14 and unbalanced flow are unchanged. Part of #6821 fix, measured in Word
with synthetic documents (see layout::tests::balanced_tail).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* Layout: balanced columns also keep kept paragraphs whole, and the lines are pinned beside notes and floats (#6821)

Measured in Word for Windows (synthetic documents, exact 14 pt lines, two and
three columns, compatibility mode 15): a paragraph with keep lines together, or
keep with next and the paragraph after it, stays whole in the first balanced
column; the tails and short paragraphs behave as before beside a footnote and a
square-wrapped picture; a section that starts and ends on one page, and plain
page flow with a footnote, widow control on and off, already matched.

keep_together now also applies at the top of a column while balancing in mode 15.
The move-on after widow/orphan control is taken only when that control, not a row
beside a floating object, moved the lines back (review of the first commit).
Tests added for notes, floats, a mid-page section, keep lines/next, unbalanced
columns and mode 14.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* Layout: balanced columns fall back to the old layout when the strict rules cannot fit, and keep paragraphs ask again at a column top (#6821)

Second review: pass(full) can now fail (a page whose columns are a couple of
lines high), so balance_columns lays the page out once more without the strict
rules of Word 2013's layout (PageBuilder::relaxed, kept across the snapshot
restore) instead of leaving a spilled pass. A paragraph moved to a column top
by the lines before it asks keep lines / keep with next again there, and keeps
going on to a column that holds it. Tests: the columns' left edges come from the
first page, a page too short for the rules keeps every line, docs reworded.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* Layout tests: classify columns by the declared column edges

The balanced-tail test helper took column edges from observed caret positions, so an empty middle column could be mistaken for the last one. The edges now come from the section geometry and keep every declared column.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* Layout: release floats when balancing moves their anchors (#6821)

Use the same overflow decision for line emission and for retaining late floats. Cover the strict widow control case and qualify the balancing evidence.

---------

Co-authored-by: vangel76 <[email protected]>
Co-authored-by: Claude Sonnet 5.5 <[email protected]>
Co-authored-by: Martin Ball <[email protected]>
This commit is contained in:
Valentin Klein
2026-11-21 17:00:25 +00:00
committed by GitHub
co-authored by Claude Sonnet 5.5 vangel76 Martin Ball
parent e15a3f9861
commit 8b73226375
8 changed files with 575 additions and 21 deletions
+6 -1
View File
@@ -1,6 +1,6 @@
# WordCraft roadmap
> **Last reviewed:** 2026-10-31 · **Last updated:** 2026-11-21 · **Change:** trivial (table rows split across pages: a cell's first paragraph on the page can split even when only one line fits, if the row starts at the top, with or without its own headers, or continues from the previous page (#6823)); previously trivial (progress log: TIFF picture chooser, drop and pasted-path routing, #6704); previously minor (added layout.fitOnePage and its Layout › Page Setup ribbon button to condense a multi-page document by one page while preserving typography hierarchy); previously minor (#3398: persistent screen paper colors; parity estimates unchanged); previously minor (#3693: additional Delete Previous Sentence command and shortcut; Word-parity estimates unchanged)
> **Last reviewed:** 2026-10-31 · **Last updated:** 2026-11-21 · **Change:** trivial (table rows split across pages: a cell's first paragraph on the page can split even when only one line fits, if the row starts at the top, with or without its own headers, or continues from the previous page (#6823)); previously trivial (release wrap areas when strict column balancing moves the anchor line, #6821); previously trivial (balanced columns keep lines together from Word 2013's layout, #6821); previously trivial (progress log: TIFF picture chooser, drop and pasted-path routing, #6704); previously minor (added layout.fitOnePage and its Layout › Page Setup ribbon button to condense a multi-page document by one page while preserving typography hierarchy); previously minor (#3398: persistent screen paper colors; parity estimates unchanged); previously minor (#3693: additional Delete Previous Sentence command and shortcut; Word-parity estimates unchanged)
> **CLI path update:** 2026-11-04 · Options before a non-Unicode input filename no longer make the CLI reject that filename; text option values still require Unicode; `run --file` and `run --script` retain native paths. No ranked gap or readiness estimate changes.
> **Floating anchor row segments:** 2026-11-07 · A floating anchor after a manual page/column break counts visible content on the far side of the same wrapped row. Marker-only cover anchors retain their previous-page rule. Synthetic picture spacing, placement and history controls; no new native Word measurement. Readiness estimates unchanged.
@@ -151,7 +151,11 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
## Progress log
- 2026-11-21: Layout: strict column balancing measures a kept paragraph again in each candidate column, so a float in one column does not make the paragraph skip another where it fits (#6821). Readiness estimates unchanged.
- 2026-11-20: `wordcraft-cli mcp` starts only with both `--automation-read-root` and `--automation-write-root` (shared rule 18, #7124); without them it stops with an error naming the two flags, where it used to serve with access to every file the user can reach. `mcp --connect` is refused until the desktop app confines its control channel to the same roots (#3695, #5819). The help, `docs/mcp.md`, the README and `AGENTS.md` pass both roots in every example.
- 2026-11-19: Layout: when strict column balancing moves an anchor line to the next column, it releases the floating object's wrap area from the abandoned column (#6821). Readiness estimates unchanged.
- 2026-11-16: Layout: a row of hyphens after a gap wraps at any hyphen, as in Word (it fills the line and its rest goes on the next), where the whole row moved to the next line.
- 2026-11-15: Native, built-in and web Insert/Change Picture choosers offer both TIFF extensions (`.tif`, `.tiff`) alongside other supported pictures; native drops, picked-file inbox dispatch and pasted picture paths recognize the same suffixes (#6704). TIFF decoding remains limited to supported compression.
- 2026-10-31: Screen readers hear what the dialogs and their drawn controls are: a dialog is a dialog, where it was only a window, so NVDA says so and reads the text in it (Word Count's figures); a dialog's tabs (Paragraph, Find and Replace, About) are tabs, the one shown selected, as in Word, where they were buttons read as pressed toggles; a colour field says its label and colour ("Font color: #104861"), where its text alone was the colour's hex digits; and each swatch of the colour grid says its colour, where it had no name. Readiness estimates unchanged.
@@ -166,6 +170,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
fix/6146-touchpad-scroll-speed
- 2026-11-09: Touchpad and mouse-wheel scroll speed settings (#6146): scales Wayland touchpad point input by default (4×) so two-finger scrolling matches desktop speed rather than crawling 1:1, and scales mouse wheel line distance; File › Options › Advanced › Scrolling; commands ui.scrollSpeed and ui.touchpadScrollSpeed.
- 2026-11-15: Layout: from Word 2013's layout (compatibility mode 15), balancing the columns before a continuous break keeps the last two, three or five lines of a paragraph that began on the page before together, keeps a two- or three-line paragraph that begins the last page whole, and holds a paragraph with keep lines together (or keep with next) whole in the first column when the strict rules fit. Synthetic tests also cover a footnote and a float (#6821); mode 14 splits them as before. Readiness estimates unchanged.
- 2026-11-14: Save As and Export (also the formats on the Print page) offer Browse in WordCraft… on Linux and the BSDs, as File › Open does, for when the system file dialog doesn't appear (#3535, from VoiceLessQ's #3801). Exporting in the built-in browser lists Export's formats as the types; the chosen type is the format and its extension, which replaces a known document extension on a typed name (`notes.docx` as plain text is `notes.txt`). An export the system dialog's name makes impossible (Word XML over an existing `.xml`) is refused on the Export page itself, not only the hidden status bar. Readiness estimates unchanged.
- 2026-11-14: Review › Language: "Apply to the whole document" sets the proofing language or Do not check spelling for every story (body, headers, footers, notes, comments, text boxes, table cells, glossary) in one undo step, selection unchanged; `review.language` takes `scope: "document"`, default `selection` (#3518). Readiness estimates unchanged.
- 2026-11-12: DOCX: `w:lnNumType` without a positive `w:countBy` leaves line numbering off, as Word does, instead of numbering every line on screen, in PDF export and on re-save (#6209). Readiness estimates unchanged.
+148 -16
View File
@@ -351,13 +351,14 @@ impl<'a> Flow<'a> {
let closes_page = pb.next_starts_page && self.p.section.is_some();
let need = height
+ if rp.keep_next && !closes_page {
next_first_line(ctx, self.block, self.width, 0, pb.next_starts_page, &mut ctx.counters.clone())
next_first_line(ctx, self.block, self.laid_width, 0, pb.next_starts_page, &mut ctx.counters.clone())
} else {
0.0
};
// (Against the whole column: balanced columns grow to hold it.)
// With the 0.01 pt of slack the other fit checks take.
if pb.y + need > pb.bottom + 0.01 && !pb.fresh() && need <= pb.next_room(self.body_top) {
// With the 0.01 pt of slack the other fit checks take. Balancing from Word 2013's layout
// keeps the lines and the next paragraph together at the top of a column too (#6821).
if pb.y + need > pb.bottom + 0.01 && (!pb.fresh() || Self::strict_widow_control(ctx, pb)) && need <= pb.next_room(self.body_top) {
pb.advance(self.block, self.body_top);
pb.y += rp.space_before.min(0.0);
return rp.space_before.min(0.0);
@@ -365,6 +366,25 @@ impl<'a> Flow<'a> {
before
}
/// Balancing from Word 2013's layout, a paragraph that was moved to the top of a column by
/// the lines before it (not by `keep_together`) keeps its lines, or itself with the next
/// paragraph, together there too: asks again, and places the paragraph's floats again where it
/// ends up (#6821).
fn keep_again(&mut self, ctx: &mut Ctx, pb: &mut PageBuilder, rooms: Rooms) {
while self.l0 == 0 && (self.pl.rp.keep_lines || self.pl.rp.keep_next) && pb.fresh() && Self::strict_widow_control(ctx, pb) {
let (col, pages) = (pb.col, pb.pages.len());
let before = self.keep_together(ctx, pb, rooms, 0.0);
if (pb.col, pb.pages.len()) == (col, pages) {
break;
}
// Reflow before testing the new column: wraps can change the paragraph's height.
let y0 = pb.y;
self.reanchor(ctx, pb, (y0, before), &[]);
self.anchor_y = y0 - before;
(self.rechecked, self.forced) = (false, Vec::new());
}
}
/// The lines going into a new column (or page) were broken around the wrap areas where the
/// paragraph started: break them again around this column's (the lines before stay as they
/// were, and so do the paragraph's own floating objects), when they differ (#1374).
@@ -490,25 +510,46 @@ impl<'a> Flow<'a> {
/// The end of the lines on this page after widow/orphan control, and keeping the rows beside
/// floating objects together.
fn settled_end(&self, pb: &PageBuilder, fit: &Fit) -> usize {
/// Also says whether, balancing from Word 2013's layout, widow/orphan control alone moved every
/// line back (the next column has them, #6821).
fn settled_end(&self, ctx: &Ctx, pb: &PageBuilder, fit: &Fit) -> (usize, bool) {
let (n, l0, mut l1) = (self.n(), self.l0, fit.l1);
// Widow/orphan control (2-line minimum at either end).
// Widow/orphan control (2-line minimum at either end). Balancing the columns of a
// section's last page from Word 2013's layout (compatibility mode 15) applies it at the
// top of a column too, where moving on is no loss, and never leaves one line of a
// paragraph that goes on in the next column, even when the paragraph began in an earlier
// one (#6821).
let strict = Self::strict_widow_control(ctx, pb);
if fit.forced.is_none() && l1 < n && self.pl.rp.widow_control && n >= 2 {
if l1 - l0 == 1 && l0 == 0 && !pb.fresh() {
if l1 - l0 == 1 && l0 == 0 && (!pb.fresh() || strict) {
l1 = l0; // orphan: move the first line to the next page
} else if n - l1 == 1 && (l1 - l0 >= 3 || (l0 > 0 && l1 - l0 >= 2)) {
l1 -= 1; // widow: take one more line along
} else if n - l1 == 1 && l0 == 0 && l1 - l0 == 2 && !pb.fresh() {
} else if n - l1 == 1 && l0 == 0 && l1 - l0 == 2 && (!pb.fresh() || strict) {
// Neither split of a three-line paragraph is allowed (two and a widow, or an
// orphan and two): it moves whole, as in Word.
l1 = l0;
}
// One line of a continued paragraph, with more after it (what was left of two lines
// after the widow line went along included): the rest moves with it.
if strict && l0 > 0 && l1 - l0 == 1 && l1 < n {
l1 = l0;
}
}
let moved_on = strict && fit.l1 > l0 && l1 == l0;
// A row (text both sides of a floating object) stays together.
while l1 > l0 && l1 < n && self.pl.lines.get(l1).is_some_and(|l| l.beside) {
l1 -= 1;
}
l1
(l1, moved_on)
}
/// Whether the columns of this page are being balanced (`balance_columns`) and the document
/// has Word 2013's layout: Word then keeps the lines of a paragraph together that widow or
/// orphan control would split, at the top of a column as anywhere (#6821). Before compatibility
/// mode 15 it splits them.
fn strict_widow_control(ctx: &Ctx, pb: &PageBuilder) -> bool {
ctx.doc.settings.compat_mode >= 15 && !pb.relaxed && pb.balance.is_some_and(|(page, _)| page + 1 == pb.pages.len())
}
/// Nothing fits on this page: move to the next column or page, and place the floats again
@@ -669,16 +710,16 @@ impl<'a> Flow<'a> {
}
}
/// Late floats placed for lines that went on after all (past `l1`) wait for the next piece;
/// one whose own wrap pushed its line on stays, as before. Whether the lines from `l0` are to
/// be broken again without them. Does nothing once the wrap relays are used up
/// Late floats placed for lines past `l1` wait for the next piece. An overflow line keeps
/// its floats because it is still emitted here. Whether the lines from `l0` are to be broken
/// again without the released floats. Does nothing once the wrap relays are used up
/// ([`MAX_WRAP_RELAYS`]).
fn settle_late(&mut self, pb: &mut PageBuilder, l1: usize) -> bool {
fn settle_late(&mut self, pb: &mut PageBuilder, l1: usize, overflow: bool) -> bool {
let l0 = self.l0;
if l0 == 0 || pb.web || self.late.placed.is_empty() || self.wrap_relays >= MAX_WRAP_RELAYS {
return false;
}
let end = if l1 == l0 && pb.fresh() { l0 + 1 } else { l1 }; // what the overflow keeps
let end = l1 + usize::from(overflow);
let moved = self.late.release(self.p, &self.pl, end, &mut pb.excl) || self.late.keep_back(self.p, &self.pl, l0..end);
moved && l1 > l0
}
@@ -863,6 +904,7 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
f.anchor_y = y0 - applied_before;
}
while f.l0 < f.n() {
f.keep_again(ctx, pb, rooms);
f.place_due_late(ctx, pb);
f.relay_wrap(ctx, pb);
f.relay_pages(ctx, pb);
@@ -873,12 +915,20 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
let lead = if f.l0 == 0 { first.top.max(0.0) + rooms.top } else { 0.0 };
let notes = para_notes(ctx.doc, p, &f.pl);
let mut fit = f.fit_lines(ctx, pb, &notes, lead);
fit.l1 = f.settled_end(pb, &fit);
if f.settle_late(pb, fit.l1) {
let (end, widowed) = f.settled_end(ctx, pb, &fit);
fit.l1 = end;
// On a fresh column an unfitting line can overflow. Strict widow control instead moves
// the lines on without emitting anything and must release their late floats as well.
let overflow = end == f.l0 && pb.fresh() && !widowed;
if f.settle_late(pb, end, overflow) {
continue;
}
if fit.l1 == f.l0 {
if !pb.fresh() {
// Balancing: widow/orphan control moved all the lines that fit on to the next column
// (or, short of room, the page after, which fails the try), where the lines of a
// column's first paragraph would otherwise overflow it. Lines pushed back for a row
// beside a floating object keep the overflow as before.
if !overflow {
f.move_on(ctx, pb);
continue;
}
@@ -1088,3 +1138,85 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_pa
None => 0.0,
}
}
#[cfg(test)]
mod tests {
use super::*;
use wordcraft_doc::Pos;
use wordcraft_doc::para::{Anchor, Float, LINE_BREAK, Wrap, WrapText};
use wordcraft_doc::props::LineSpacing;
#[test]
fn strict_balancing_remeasures_kept_lines_in_the_next_column() {
crate::test_fonts();
let mut doc = Document::new();
doc.settings.compat_mode = 15;
doc.last_section.columns.count = 2;
let mut p = Paragraph::with_text("One two three four five six", Default::default());
p.props.line_spacing = Some(LineSpacing::Exactly(14.0));
p.props.keep_lines = Some(true);
doc.body = vec![wordcraft_doc::para_block(p)];
let p = doc.body[0].as_para().unwrap();
crate::pass::with_flow_page(&doc, |ctx, pb| {
let top = pb.top;
pb.balance = Some((0, 28.1));
pb.cap_columns();
// A preceding floating object leaves a narrow strip of the first column, but does
// not occupy the second column. The same kept paragraph fits there in one line.
pb.excl.push((Rect::new(pb.col_x(), top, pb.col_w() - 26.0, 100.0), false, None, WrapText::BothSides, false));
place_para_in_flow(ctx, pb, p, 0, top);
assert_eq!(pb.pages.len(), 1, "a fitting candidate kept the balance attempt on its page");
assert_eq!(pb.col, 1);
assert!(
pb.pages[0]
.items
.iter()
.any(|item| { matches!(item, Placed::Lines { x, l0: 0, l1: 1, story: StoryRef::Body, .. } if (*x - pb.col_x()).abs() < 0.01) })
);
});
}
#[test]
fn strict_widow_control_releases_a_late_float_when_no_line_is_emitted() {
crate::test_fonts();
let mut doc = Document::new();
doc.settings.compat_mode = 15;
doc.last_section.columns.count = 2;
let mut p = Paragraph::with_text(&format!("First{LINE_BREAK}Second{LINE_BREAK}Third"), Default::default());
p.props.line_spacing = Some(LineSpacing::Exactly(14.0));
p.props.widow_control = Some(true);
doc.body = vec![wordcraft_doc::para_block(p)];
let anchor = Pos::body(0, "First".len() + LINE_BREAK.len_utf8());
let float = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, ..Default::default() };
doc.insert_object(&anchor, crate::tests::rect_shape(20.0, 20.0, float), &Default::default()).unwrap();
let p = doc.body[0].as_para().unwrap();
crate::pass::with_flow_page(&doc, |ctx, pb| {
let top = pb.top;
let height = 14.1;
pb.advance(0, top); // start in the last column of the previous page
pb.bottom = top + height;
pb.balance = Some((1, height));
let mut flow = Flow::new(ctx, pb, p, (0, top));
assert!(pb.excl.is_empty(), "the float waits for its anchor line");
// Continue after the first line. The balance attempt can fit only one of the two lines left.
flow.l0 = 1;
pb.advance(0, top);
assert!(pb.fresh());
assert!((pb.bottom - pb.top - height).abs() < 0.01);
flow.place_due_late(ctx, pb);
assert_eq!(pb.excl.len(), 1, "the anchor line fits before widow control");
let fit = flow.fit_lines(ctx, pb, &[], 0.0);
assert_eq!(fit.l1, 2);
let (end, widowed) = flow.settled_end(ctx, pb, &fit);
assert_eq!((end, widowed), (1, true));
let overflow = end == flow.l0 && pb.fresh() && !widowed;
assert!(!flow.settle_late(pb, end, overflow));
assert!(pb.excl.is_empty(), "no text is emitted here, so no wrap area may remain here");
});
}
}
+3
View File
@@ -71,6 +71,9 @@ pub(crate) struct PageBuilder<'a> {
/// Balancing columns: (page index, column height) — that page's columns end `height` below
/// the top of the section on it.
pub(crate) balance: Option<(usize, f32)>,
/// Balancing without the strict widow/orphan and keep rules of Word 2013's layout (#6821): the
/// last try when even the full column height does not hold the text with them.
pub(crate) relaxed: bool,
/// The page with the last explicit column break.
pub(crate) col_break_page: Option<usize>,
/// The section's footnotes go right below its text, not at the page bottom ...
+30 -2
View File
@@ -225,6 +225,7 @@ fn new_page_builder<'p>(
max_y: 0.0,
content_bottom: 0.0,
balance: None,
relaxed: false,
col_break_page: None,
sect_beneath: false,
beneath: false,
@@ -236,6 +237,18 @@ fn new_page_builder<'p>(
}
}
#[cfg(test)]
pub(super) fn with_flow_page(doc: &Document, test: impl FnOnce(&mut Ctx<'_>, &mut PageBuilder<'_>)) {
let mut cache = LayoutCache::new();
let opts = LayoutOptions::default();
let mut ctx = new_ctx(doc, &mut cache, &opts, (&HashMap::new(), None, &Totals::first_guess(1)));
let sect = &doc.last_section;
let early = EarlyFloats::new();
let mut page = new_page_builder(sect, sect.page_num_format, &early, false, false);
page.new_page(0, sect.margin_top);
test(&mut ctx, &mut page);
}
/// Endnotes in document order, with the section of their reference; placed at the end of a
/// section that keeps them there, else at the end of the document.
fn endnote_queue(ctx: &Ctx) -> VecDeque<(u32, usize)> {
@@ -694,7 +707,9 @@ fn balance_pass<'a>(
(page, top, h): (usize, f32, f32),
body_top: f32,
) -> bool {
let relaxed = pb.relaxed;
snap.restore(pb, ctx);
pb.relaxed = relaxed;
pb.balance = Some((page, h));
pb.cap_columns();
for block in first..end {
@@ -773,13 +788,26 @@ fn balance_columns<'a>(ctx: &mut Ctx, pb: &mut PageBuilder<'a>, blocks: (usize,
last = Some((mid, ok));
}
// End on the best height (the full column, as laid out first, when none was shorter).
let mut fits = true;
if last != Some((hi, true)) {
thrown = discard(ctx);
if !pass(ctx, pb, hi) && hi < full {
fits = pass(ctx, pb, hi);
if !fits && hi < full {
thrown = discard(ctx);
pass(ctx, pb, full);
fits = pass(ctx, pb, full);
}
}
// From Word 2013's layout the strict widow/orphan and keep rules (`Flow::strict_widow_control`)
// can push text past even the full column (on a page whose columns are only a couple of lines
// high, where moving a line on to the next column never helps). The layout first made, without
// them, always fit it, so lay the page out as it was then rather than leave the pass that
// spilled to a new page.
if !fits {
thrown = discard(ctx);
pb.relaxed = true;
pass(ctx, pb, full);
pb.relaxed = false;
}
thrown
}
+1
View File
@@ -5,6 +5,7 @@ use wordcraft_doc::props::{Align, Border, BorderStyle, Borders, ParaProps, TextD
use wordcraft_doc::{Pos, Table};
mod autospace;
mod balanced_tail;
mod bidi;
mod budget;
mod cell_floats;
+376
View File
@@ -0,0 +1,376 @@
//! The last page of a section whose columns are balanced before a continuous break, when it holds
//! only the end of a paragraph that began on the page before, or a whole paragraph of two or three
//! lines (#6821). Measured in Word for Windows with exact 14 pt lines and no spacing, in three and
//! in two columns, one case per document, saved as compatibility mode 15 and as 14: from mode 15
//! Word keeps such lines together in the first column that can hold them (the later columns may be
//! left short or empty), keeps a paragraph with "keep lines together" or "keep with next" whole
//! there when those rules fit, including in a section that starts and ends on one page. In mode
//! 14 Word splits two lines one per column. Synthetic tests also cover a footnote and a floating
//! picture. Mode 14's other layouts (a three-line tail, two and one; the text after the section)
//! and keep with next on the last lines of a paragraph that began on the page before remain open.
use crate::*;
use wordcraft_doc::para::{Anchor, Float, InlineObject, NoteKind, ShapeKind, Wrap};
use wordcraft_doc::props::{LineSpacing, ParaProps};
use wordcraft_doc::section::{SectionProps, SectionStart};
use wordcraft_doc::{PartKind, Pos, para_block};
const LINE: f32 = 14.0;
fn lay(doc: &Document) -> DocLayout {
let mut c = LayoutCache::new();
layout(doc, &mut c, &LayoutOptions::default())
}
fn para_with(text: &str, keep_lines: bool, keep_next: bool) -> Arc<Block> {
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
let mut p = Paragraph::with_text(text, chr);
p.props = ParaProps {
space_before: Some(0.0),
space_after: Some(0.0),
line_spacing: Some(LineSpacing::Exactly(LINE)),
keep_lines: keep_lines.then_some(true),
keep_next: keep_next.then_some(true),
..Default::default()
};
para_block(p)
}
fn para(text: &str) -> Arc<Block> {
para_with(text, false, false)
}
/// A paragraph of `k` lines, each ended by a line break: "P1", "P2"…
fn lines_text(k: usize) -> String {
(1..=k).map(|i| format!("P{i}")).collect::<Vec<_>>().join(&wordcraft_doc::para::LINE_BREAK.to_string())
}
#[derive(Clone, Copy, PartialEq)]
enum Keep {
No,
Lines,
Next,
}
/// What follows the filler paragraphs: a paragraph of `k` lines ("P1"…), then optionally one more
/// line ("Q1"), all in `cols` columns, then "After" in one column.
#[derive(Clone, Copy)]
struct Case {
cols: u32,
/// How many one-line paragraphs come first, relative to the lines on a page: `-3` leaves room
/// for three lines of the paragraph, `0` starts the paragraph on the next page, `1` puts one
/// more line before it there. With `intro` it is the plain number of them.
from_page_end: i32,
k: usize,
q: bool,
compat: u32,
/// A footnote referenced at the end of the paragraph.
note: bool,
/// A floating 28 pt tall picture-sized shape anchored in "Q1" (needs `q`).
float: Option<Wrap>,
/// This many lines of text and a one-column section break before the columns: the section
/// starts mid-page and ends on the same page.
intro: usize,
/// Columns closed by a continuous break (balanced) or running to the end of the document.
balanced: bool,
keep: Keep,
/// A page of this many lines of text (for a page too short for the rules).
page_lines: Option<i32>,
}
impl Case {
fn new(cols: u32, from_page_end: i32, k: usize) -> Case {
Case { cols, from_page_end, k, q: false, compat: 15, note: false, float: None, intro: 0, balanced: true, keep: Keep::No, page_lines: None }
}
}
/// The document of a case, the index of the `k`-line paragraph and of "Q1", and the offsets of the
/// paragraph's lines.
fn build(c: &Case) -> (Document, usize, Option<usize>, Vec<usize>) {
crate::test_fonts();
let mut d = Document::new();
d.settings.compat_mode = c.compat;
let mut s = SectionProps { start: SectionStart::Continuous, ..Default::default() };
s.columns.count = c.cols;
if let Some(n) = c.page_lines {
s.page_h = s.margin_top + s.margin_bottom + n as f32 * LINE + 0.5;
d.last_section.page_h = s.page_h;
}
let per_col = ((s.page_h - s.margin_top - s.margin_bottom) / LINE).floor() as i32;
let fillers = if c.intro > 0 { c.from_page_end.max(0) } else { (per_col * c.cols as i32 + c.from_page_end).max(0) } as usize;
let mut body: Vec<Arc<Block>> = (0..c.intro).map(|i| para(&format!("i{i}"))).collect();
if c.intro > 0 {
let mut one = SectionProps { start: SectionStart::Continuous, ..Default::default() };
one.columns.count = 1;
let mut mark = para("");
if let Block::Para(p) = Arc::make_mut(&mut mark) {
p.section = Some(Box::new(one));
}
body.push(mark);
}
body.extend((0..fillers).map(|i| para(&format!("r{i}"))));
let first = body.len();
let text = lines_text(c.k);
body.push(para_with(&text, c.keep == Keep::Lines, c.keep == Keep::Next));
let q = c.q.then_some(body.len());
if c.q {
body.push(para("Q1"));
}
let mark = body.len();
if c.balanced {
body.push(para(""));
body.push(para("After"));
}
d.body = body;
if c.balanced {
if let Some(Block::Para(p)) = d.body.get_mut(mark).map(Arc::make_mut) {
p.section = Some(Box::new(s));
}
d.last_section.start = SectionStart::Continuous;
} else {
d.last_section.columns.count = c.cols;
}
if let (Some(w), Some(qi)) = (c.float, q) {
let float = Float { wrap: w, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 0.0, y: 0.0, ..Default::default() };
let shape = InlineObject::Shape {
kind: ShapeKind::Rectangle,
w: if w == Wrap::TopAndBottom { 100.0 } else { 60.0 },
h: 28.0,
fill: None,
stroke: None,
stroke_width: 1.0,
float,
story: None,
freeform: None,
effects: Default::default(),
extra: Default::default(),
};
d.insert_object(&Pos::body(qi, 0), shape, &Default::default()).unwrap();
}
let breaks = text.char_indices().filter(|(_, ch)| *ch == wordcraft_doc::para::LINE_BREAK);
let starts: Vec<usize> = std::iter::once(0).chain(breaks.map(|(i, ch)| i + ch.len_utf8())).collect();
if c.note {
let id = d.add_part(PartKind::Footnote, vec![para("Note")]);
let end = text.len();
d.insert_object(&Pos::body(first, end), InlineObject::NoteRef { kind: NoteKind::Footnote, id, custom: String::new() }, &Default::default())
.unwrap();
}
(d, first, q, starts)
}
/// The columns of the lines of the `k`-line paragraph (counted from the left, 0 to `cols - 1`),
/// of "Q1" if there is one, and the number of pages.
fn columns(c: &Case) -> (Vec<usize>, Option<usize>, usize) {
let (d, first, q, starts) = build(c);
let l = lay(&d);
let carets: Vec<_> = starts.iter().map(|&o| l.caret(&Pos::body(first, o)).unwrap()).collect();
let q_caret = q.map(|qi| l.caret(&Pos::body(qi, 0)).unwrap());
// The columns' left edges, from the section's declared geometry so that an empty column keeps
// its place. A line beside a float starts right of its column's edge, so a position is in the
// last edge at or left of it.
let sp = SectionProps::default();
let n = c.cols.max(1);
let width = (sp.page_w - sp.margin_left - sp.margin_right - sp.gutter - sp.columns.space * (n - 1) as f32) / n as f32;
let xs: Vec<f32> = (0..n).map(|i| sp.margin_left + i as f32 * (width + sp.columns.space)).collect();
let col = |x: f32| xs.iter().rposition(|e| *e <= x + 1.0).unwrap_or(usize::MAX);
(carets.iter().map(|c| col(c.x)).collect(), q_caret.map(|c| col(c.x)), l.pages.len())
}
fn of(c: &Case) -> Vec<usize> {
columns(c).0
}
// A: the last two lines of a paragraph whose first three lines closed the page before.
#[test]
fn the_last_two_lines_of_a_continued_paragraph_stay_in_the_first_column() {
for cols in [3, 2] {
let (v, _, pages) = columns(&Case::new(cols, -3, 5));
assert_eq!(pages, 2, "{cols} columns");
assert_eq!(v[3..], [0, 0], "{cols} columns: lines 4 and 5 together");
}
}
// B: three lines stay together too: not two and one, nor one and two.
#[test]
fn the_last_three_lines_of_a_continued_paragraph_stay_in_the_first_column() {
for cols in [3, 2] {
assert_eq!(of(&Case::new(cols, -3, 6))[3..], [0, 0, 0], "{cols} columns");
}
}
// L: five lines are three and two (not two, one and two).
#[test]
fn the_last_five_lines_of_a_continued_paragraph_are_three_and_two() {
for cols in [3, 2] {
assert_eq!(of(&Case::new(cols, -3, 8))[3..], [0, 0, 0, 1, 1], "{cols} columns");
}
}
// N: a one-line paragraph after the two lines goes to the second column.
#[test]
fn a_line_after_the_continued_two_lines_goes_to_the_next_column() {
for cols in [3, 2] {
let (v, q, _) = columns(&Case { q: true, ..Case::new(cols, -3, 5) });
assert_eq!((v[3..].to_vec(), q), (vec![0, 0], Some(1)), "{cols} columns");
}
}
// K, E: a paragraph of three lines (or two) that begins the last page stays together.
#[test]
fn a_whole_paragraph_of_two_or_three_lines_at_the_top_of_the_last_page_stays_together() {
for cols in [3, 2] {
assert_eq!(of(&Case::new(cols, 0, 3)), [0, 0, 0], "{cols} columns, three lines");
assert_eq!(of(&Case::new(cols, 0, 2)), [0, 0], "{cols} columns, two lines");
}
}
// K2: the same after one line of another paragraph in the first column: it starts the second.
#[test]
fn a_three_line_paragraph_after_one_line_on_the_last_page_stays_together() {
for cols in [3, 2] {
let (v, _, pages) = columns(&Case::new(cols, 1, 3));
assert_eq!((v, pages), (vec![1, 1, 1], 2), "{cols} columns");
}
}
// F: with a footnote on the last page, referenced at the end of the paragraph.
#[test]
fn a_footnote_on_the_last_page_leaves_the_tail_together() {
for cols in [3, 2] {
let n = |off, k| of(&Case { note: true, ..Case::new(cols, off, k) });
assert_eq!(n(-3, 5)[3..], [0, 0], "{cols} columns, two lines");
assert_eq!(n(-3, 6)[3..], [0, 0, 0], "{cols} columns, three lines");
assert_eq!(n(0, 2), [0, 0], "{cols} columns, whole paragraph of two lines");
assert_eq!(n(0, 3), [0, 0, 0], "{cols} columns, whole paragraph of three lines");
}
}
// L2: beside a square-wrapped float in the next paragraph; a top-and-bottom one is the guard.
#[test]
fn a_square_wrapped_float_after_the_tail_leaves_it_together() {
for cols in [3, 2] {
let sq = |off, k| columns(&Case { q: true, float: Some(Wrap::Square), ..Case::new(cols, off, k) });
let (v, q, _) = sq(-3, 5);
assert_eq!((v[3..].to_vec(), q), (vec![0, 0], Some(1)), "{cols} columns, two lines");
let (v, q, _) = sq(0, 3);
assert_eq!((v, q), (vec![0, 0, 0], Some(1)), "{cols} columns, whole paragraph of three lines");
}
}
#[test]
fn a_top_and_bottom_float_after_the_tail_is_laid_out_as_before() {
for cols in [3, 2] {
let tb = |off, k| columns(&Case { q: true, float: Some(Wrap::TopAndBottom), ..Case::new(cols, off, k) });
let (v, q, _) = tb(-3, 5);
assert_eq!((v[3..].to_vec(), q), (vec![0, 0], Some(1)), "{cols} columns, two lines");
let (v, q, _) = tb(0, 3);
assert_eq!((v, q), (vec![0, 0, 0], Some(1)), "{cols} columns, whole paragraph of three lines");
}
}
// M: a section that starts and ends on one page (after two lines of text in one column).
#[test]
fn a_five_line_paragraph_balanced_mid_page_is_three_and_two() {
assert_eq!(of(&Case { intro: 2, ..Case::new(3, 0, 5) }), [0, 0, 0, 1, 1]);
}
#[test]
fn a_section_balanced_mid_page_is_laid_out_as_before() {
let mid = |cols, filler, k| of(&Case { intro: 2, ..Case::new(cols, filler, k) });
assert_eq!(mid(3, 0, 2), [0, 0]);
assert_eq!(mid(3, 0, 3), [0, 0, 0]);
assert_eq!(mid(3, 0, 4), [0, 0, 1, 1]);
assert_eq!(mid(3, 0, 6), [0, 0, 1, 1, 2, 2]);
assert_eq!(mid(2, 0, 3), [0, 0, 0]);
assert_eq!(mid(2, 0, 5), [0, 0, 0, 1, 1]);
assert_eq!(mid(2, 0, 6), [0, 0, 0, 1, 1, 1]);
// After one more line.
assert_eq!(mid(3, 1, 3), [1, 1, 1]);
assert_eq!(mid(3, 1, 4), [1, 1, 2, 2]);
assert_eq!(mid(3, 1, 5), [0, 0, 1, 1, 1]);
assert_eq!(mid(2, 1, 4), [0, 0, 1, 1]);
assert_eq!(mid(2, 1, 6), [0, 0, 0, 1, 1, 1]);
}
// X: keep lines together, and keep with next, hold the paragraph whole in the first column.
#[test]
fn a_paragraph_kept_together_stays_whole_in_the_first_balanced_column() {
for cols in [3, 2] {
let kept = |off, k| of(&Case { keep: Keep::Lines, ..Case::new(cols, off, k) });
assert_eq!(kept(0, 3), [0, 0, 0], "{cols} columns, three lines at the top");
// Keep lines together moved it whole onto the last page.
assert_eq!(kept(-3, 5), [0, 0, 0, 0, 0], "{cols} columns, five lines");
assert_eq!(kept(-3, 6), [0, 0, 0, 0, 0, 0], "{cols} columns, six lines");
}
}
#[test]
fn a_paragraph_kept_with_the_next_stays_with_it_in_the_first_balanced_column() {
for cols in [3, 2] {
let (v, q, _) = columns(&Case { keep: Keep::Next, q: true, ..Case::new(cols, 0, 3) });
assert_eq!((v, q), (vec![0, 0, 0], Some(0)), "{cols} columns");
}
}
// Guards, the same in Word and before the change.
// C, M: four lines are two and two, six are two, two and two.
#[test]
fn longer_tails_are_balanced_as_before() {
for cols in [3, 2] {
assert_eq!(of(&Case::new(cols, -3, 7))[3..], [0, 0, 1, 1], "{cols} columns, four lines");
}
assert_eq!(of(&Case::new(3, -3, 9))[3..], [0, 0, 1, 1, 2, 2], "three columns, six lines");
}
// O: a four-line paragraph that begins the last page is two and two.
#[test]
fn a_four_line_paragraph_at_the_top_of_the_last_page_is_two_and_two() {
for cols in [3, 2] {
assert_eq!(of(&Case::new(cols, 0, 4)), [0, 0, 1, 1], "{cols} columns");
}
}
// Columns not balanced (nothing follows them): the lines are not split without need.
#[test]
fn unbalanced_columns_keep_the_tail_in_the_first_column() {
for cols in [3, 2] {
let c = Case { balanced: false, ..Case::new(cols, -3, 5) };
assert_eq!(of(&c)[3..], [0, 0], "{cols} columns");
}
}
// Before Word 2013's layout (mode 14) the two lines are split one per column, as Word does.
#[test]
fn mode_14_still_splits_the_last_two_lines_of_a_continued_paragraph() {
for cols in [3, 2] {
let c = Case { compat: 14, ..Case::new(cols, -3, 5) };
assert_eq!(of(&c)[3..], [0, 1], "{cols} columns");
}
}
/// How many lines of body text are laid out, and on how many pages.
fn shape(c: &Case) -> (usize, usize) {
let (d, ..) = build(c);
let l = lay(&d);
let lines = l
.pages
.iter()
.flat_map(|p| p.items.iter())
.map(|it| match it {
Placed::Lines { story: StoryRef::Body, l0, l1, .. } => l1 - l0,
_ => 0,
})
.sum();
(l.pages.len(), lines)
}
// A page whose columns hold two lines is too short for the rules that keep three lines together:
// not even the full column holds the paragraph with them, so the columns are laid out as before
// (mode 14), with every line placed and no more pages.
#[test]
fn a_page_too_short_for_the_strict_rules_is_laid_out_as_in_mode_14() {
let tiny = |compat| Case { compat, page_lines: Some(2), ..Case::new(2, 0, 3) };
let (pages, lines) = shape(&tiny(14));
assert!(lines >= 4, "the paragraph's three lines and After: {lines}");
assert_eq!(shape(&tiny(15)), (pages, lines));
}
+4 -1
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long