Compare commits

...
Author SHA1 Message Date
Martin Ball b01c9b4075 Merge branch 'main' into land/4134 2026-11-17 13:43:07 +01:00
216458edc6 Layout: a paragraph with a hidden mark is shown on one line with the next one (#3986) (#4134)
Lands #4134 rebased onto main; only docs conflicts were resolved (both sides kept).

Co-Authored-By: Menonro <25549525+Menonro@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FypgCXtSjB6e5jmy9Uq7u8
2026-11-17 07:38:10 +00:00
14 changed files with 800 additions and 25 deletions
+150 -6
View File
@@ -1,7 +1,8 @@
use super::ctx::{Ctx, page_anchored};
use super::ctx::{Ctx, Joining, page_anchored};
use super::floats::{
ObjFrame, ObjectPlacement, WrapArea, align_in, float_rect, floating, left_out_objects, place_objects, rel_exclusions, wrap_area,
};
use super::flow::again;
use super::page::PageFrame;
use super::placed::Placed;
use super::table_flow::below;
@@ -230,12 +231,24 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
let frames = !matches!(story, StoryRef::Part(id) if ctx.doc.parts.get(&id).is_some_and(|p| p.kind == wordcraft_doc::PartKind::TextBox));
// The bottom of the last paragraph's lines.
let mut prev_end = 0.0f32;
// Where the last paragraph, whose mark is hidden, ended: the next one goes on from there.
let mut joint: Option<Joint> = None;
let outer_joined = ctx.joined;
for (i, b) in blocks.iter().enumerate() {
last_top = y;
let mut path = prefix.to_vec();
path.push(i as u32);
match &**b {
Block::Para(p) => {
// A paragraph after one whose mark is hidden goes on from that one's last line
// (Word, #3986; see `Joint`); one that shows nothing passes the place on.
let chr = table.map(|t| &t.chr);
let mark_hidden = ctx.mark_hidden(p, chr);
let shows_nothing = mark_hidden && ctx.text_hidden(p, chr);
let came = joint.take().filter(|j| j.next == i);
joint = came.filter(|_| shows_nothing).map(|j| Joint { next: i + 1, ..j });
let taken = came.filter(|_| !shows_nothing).and_then(|j| j.take_up(ctx, p, width, table));
let p = taken.as_ref().map_or(p, |t| &t.para);
let label = ctx.next_label(p);
let listed = label.is_some();
let mut pl = ctx.para_labelled(p, width, table, &[], label.clone());
@@ -276,6 +289,10 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
// body path. Keep text and wrap exclusions relative to the text's actual top.
let para_top = y;
y += if i == 0 { before } else { before.max(0.0) };
if let Some(t) = &taken {
y = t.joint.top + t.gap;
excl.push(t.area.clone());
}
// Floating objects anchored here: place them, then wrap the text around them.
// One left out of the layout (hidden, or deleted in the final text) takes no room.
let mut floats = HashMap::new();
@@ -315,10 +332,11 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
if !rel.is_empty() {
pl = ctx.para_labelled(p, width, table, &rel, label);
}
TakenUp::clear(taken.as_ref(), &mut excl);
// Bordered paragraphs: room for their borders, those of a group joined in one box.
let cell = table.map(|t| &t.para);
let (above, below) = (joined(ctx.doc, blocks, i, i.checked_sub(1), cell), joined(ctx.doc, blocks, i, Some(i + 1), cell));
let mut edges = Edges::own(&pl, 0, pl.lines.len());
let mut edges = Edges::own(&pl, 0, pl.lines.len()).sharing(&pl);
if above {
edges.top = 0.0;
}
@@ -330,6 +348,9 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
edges.up = (y + lead - prev_end).max(0.0);
}
prev_end = push_para(&mut items, (story, &path), &pl, (0, pl.lines.len()), (0.0, y + lead), width, edges);
if mark_hidden && !shows_nothing {
joint = Joint::after(&pl, (0, pl.lines.len()), i, (0.0, y + lead), edges.bottom);
}
// Pictures, shapes and text boxes: drawn, their areas and text boxes' text.
if !p.objects.is_empty() {
let at = ObjFrame {
@@ -372,7 +393,9 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
let last = i + 1 == blocks.len();
let normal = || pl.rp.style == "Normal" || ctx.doc.styles.get(&pl.rp.style).is_none();
let after = if last && (pl.rp.after_auto || (in_cell && ctxl && normal())) { 0.0 } else { pl.rp.space_after };
y += edges.top + pl.height + edges.bottom + after;
y += edges.top + pl.height + edges.bottom;
// One going on from the line of the paragraph before ends below that line (#3986).
y = TakenUp::end(taken.as_ref(), ctx, (y, after), outer_joined);
prev_after = after;
prev_after_auto = pl.rp.after_auto;
prev_listed = listed;
@@ -404,6 +427,7 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
}
let floats_bottom = float_tables.iter().map(|r| r.bottom()).fold(float_objects_bottom, f32::max);
ctx.hide_deleted = outer_hide;
ctx.joined = outer_joined;
BoxLayout { items, height: y.max(0.0), floats_bottom, last_top: last_top.max(0.0), table_areas, page_table_wraps }
}
@@ -652,6 +676,117 @@ impl Edges {
let b = pl.rp.borders.unwrap_or_default();
Edges { top: if l0 == 0 { border_room(b.top) } else { 0.0 }, bottom: if l1 >= pl.lines.len() { border_room(b.bottom) } else { 0.0 }, up: 0.0 }
}
/// A paragraph going on from the line of the one before, whose mark is hidden (#3986), takes
/// no room for its borders on that line, nor below it when that line is all it has: the
/// shared line shows the first paragraph's shading and borders (Word).
pub(crate) fn sharing(mut self, pl: &ParaLayout) -> Edges {
if pl.shares_line() {
self.top = 0.0;
if pl.lines.len() <= 1 {
self.bottom = 0.0;
}
}
self
}
}
/// Where a paragraph whose mark is hidden ends (#3986). Word shows it on one line with the next
/// paragraph: that one's text goes on from where this one's ends, beside it on its last line.
/// Paragraphs that show nothing (an empty one with a hidden mark, say) pass the place on.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Joint {
/// The block that goes on from here.
pub(crate) next: usize,
/// The page (the count of pages) and column of the last line (body text only).
pub(crate) page: usize,
pub(crate) col: usize,
/// The last line's top, height and baseline (from its top), the left edge of its column and
/// the x its text ends at.
pub(crate) top: f32,
pub(crate) height: f32,
baseline: f32,
left: f32,
end: f32,
/// The room under the line for the paragraph's bottom border: what follows the shared line
/// starts below it.
room: f32,
}
impl Joint {
/// After lines `l0..l1` of paragraph layout `pl`, block `block`, the first of them at `y` in
/// a column whose left edge is at `x`, with `room` under them for its bottom border.
pub(crate) fn after(pl: &ParaLayout, (l0, l1): (usize, usize), block: usize, (x, y): (f32, f32), room: f32) -> Option<Joint> {
let li = l1.checked_sub(1)?;
let (first, last) = (pl.lines.get(l0)?, pl.lines.get(li)?);
// Right-to-left text runs the other way: its lines aren't joined.
if pl.rp.bidi || !last.vis.is_empty() {
return None;
}
let end = pl.x_of(li, pl.text_len)?;
let (top, height, baseline) = (y + last.top - first.top, last.height, last.baseline - last.top);
Some(Joint { next: block + 1, page: 0, col: 0, top, height, baseline, left: x, end: x + end, room })
}
/// The bottom of the shared line, with the room for the first paragraph's bottom border.
pub(crate) fn bottom(&self) -> f32 {
self.top + self.height + self.room
}
/// How the next paragraph `q`, laid out `width` wide, goes on from here: how far below the
/// shared line's top it starts (its first line's text sits on this paragraph's baseline, not
/// above it), and the area its first line keeps clear of, this paragraph's text, down to the
/// bottom of that line only.
pub(crate) fn fit(&self, ctx: &mut Ctx, q: &Paragraph, width: f32, table: Option<&para::CellText>) -> (f32, WrapArea) {
let eq = ctx.eq_count;
let probe = again(ctx, eq, |ctx| ctx.para_labelled(q, width, table, &[], None));
let (gap, height) = probe.lines.first().map_or((0.0, self.height), |l| ((self.baseline - (l.baseline - l.top)).max(0.0), l.height));
let rect = Rect::new(self.left, self.top, (self.end - self.left).max(0.0), (gap + height - 0.01).max(0.01));
(gap, (rect, false, None, WrapText::Right, false))
}
/// Paragraph `p` of a box `width` wide going on from here, unless a page break comes before
/// it or it runs right to left: without its space before, as [`Joint::fit`] lays it out.
fn take_up(self, ctx: &mut Ctx, p: &Paragraph, width: f32, table: Option<&para::CellText>) -> Option<TakenUp> {
let own = ctx.doc.styles.resolve_para(&p.props);
if own.page_break_before || own.bidi {
return None;
}
let mut para = p.clone();
para.props.space_before = Some(0.0);
para.props.space_before_auto = Some(false);
ctx.joined = Some(Joining::new(para.rev, 0.0));
let (gap, area) = self.fit(ctx, &para, width, table);
Some(TakenUp { joint: self, para, gap, area })
}
}
/// A paragraph of a box going on from a [`Joint`]: the paragraph without its space before, how
/// far below the shared line's top it starts and the area its first line keeps clear of.
struct TakenUp {
joint: Joint,
para: Paragraph,
gap: f32,
area: WrapArea,
}
impl TakenUp {
/// Its first line laid out: the area that line kept clear of comes out of `excl`.
fn clear(taken: Option<&TakenUp>, excl: &mut Vec<WrapArea>) {
let Some(t) = taken else { return };
if let Some(k) = excl.iter().position(|a| a.0 == t.area.0 && !a.1 && a.2.is_none() && a.3 == t.area.3) {
excl.remove(k);
}
}
/// Where what follows a paragraph ending at `y`, with `after` its space after, starts: below
/// the shared line at least, with the first paragraph's bottom border. With the copy laid
/// out, the paragraph's own layouts are its own again (`outer`).
fn end(taken: Option<&TakenUp>, ctx: &mut Ctx, (y, after): (f32, f32), outer: Option<Joining>) -> f32 {
let Some(t) = taken else { return y + after };
ctx.joined = outer;
y.max(t.joint.bottom()) + after
}
}
/// Paragraph lines plus their shading and borders; returns the bottom of the lines. The
@@ -669,12 +804,21 @@ pub(crate) fn push_para(
return y;
};
let h = last.top + last.height - first.top;
let lines = Placed::Lines { story, path: Path(path.to_vec()), para: pl.clone(), l0, l1, x, y, turn: TextDirection::Horizontal };
// The line a paragraph shares with the one before, whose mark is hidden, shows that one's
// shading and borders: this one's start on its own next line, without a top border (Word, #3986).
let shared = l0 == 0 && pl.shares_line();
let Some(own) = pl.lines.get(if shared { 1 } else { l0 }).filter(|_| !shared || l1 > 1) else {
items.push(lines);
return y + h;
};
let (y_own, e) = if shared { (y + own.top - first.top, Edges { top: 0.0, up: 0.0, ..e }) } else { (y, e) };
// Indents are logical: a right-to-left paragraph's start indent (and hanging indent) is on the right.
let start = pl.rp.indent_left.min(pl.rp.indent_left + pl.rp.indent_first);
let (li, ri) = if pl.rp.bidi { (pl.rp.indent_right, start) } else { (start, pl.rp.indent_right) };
let left = x + li;
let right = x + width - ri;
let (top, bottom) = (y - e.top - e.up, y + h + e.bottom);
let (top, bottom) = (y_own - e.top - e.up, y + h + e.bottom);
// The outer edges of the side borders.
let sides = pl.rp.borders.unwrap_or_default();
let (lx, rx) = (left - border_room(sides.left), right + border_room(sides.right));
@@ -683,11 +827,11 @@ pub(crate) fn push_para(
let (sl, sr) = (lx.min(left - pad), rx.max(right + pad));
items.push(Placed::Fill { rect: Rect::new(sl, top, sr - sl, bottom - top), color: c });
}
items.push(Placed::Lines { story, path: Path(path.to_vec()), para: pl.clone(), l0, l1, x, y, turn: TextDirection::Horizontal });
items.push(lines);
if let Some(b) = &pl.rp.borders {
// All four lines lie beyond their distance from the text; top and bottom reach the corners.
if let Some(t) = b.top.filter(|t| e.top > 0.0 && t.is_visible()) {
let ty = y - t.space - t.width / 2.0;
let ty = y_own - t.space - t.width / 2.0;
items.push(Placed::Rule { x0: lx, y0: ty, x1: rx, y1: ty, border: t });
}
if let Some(t) = b.bottom.filter(|t| e.bottom > 0.0 && t.is_visible()) {
+3
View File
@@ -27,6 +27,9 @@ pub(crate) struct Key {
pub(crate) sref: u64,
/// The word being typed in this paragraph, left without a spelling squiggle.
pub(crate) typing: Option<(usize, usize)>,
/// A copy of the paragraph going on from the line of the one before (`ctx::Joining`): its
/// space before and whether it shares that line ([`ParaEnv::joined`](crate::para::ParaEnv)).
pub(crate) joined: Option<(u32, bool)>,
}
/// Memoised paragraph layouts.
+82 -4
View File
@@ -51,6 +51,9 @@ pub(crate) struct Ctx<'a> {
/// Empty body paragraphs with hidden marks or continuous section breaks, in order:
/// they take no room (see [`place_para`]).
pub(crate) quiet_marks: Vec<usize>,
/// The paragraph being laid out as going on from the line of the one before, whose mark is
/// hidden: its list number is counted but not drawn (#3986).
pub(crate) joined: Option<Joining>,
/// Empty paragraphs closing a continuous section right after another section's mark, in
/// order: each takes its line while it fits, then stays at the page's bottom (#3907).
pub(crate) stacked_marks: Vec<usize>,
@@ -79,6 +82,31 @@ pub(crate) struct Ctx<'a> {
pub(crate) header_repeats: usize,
}
/// A paragraph going on from the line of the one before, whose mark is hidden (#3986): a copy of
/// the document's, which keeps its revision, given the space before that puts its text on that
/// line's baseline.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Joining {
/// The paragraph's revision.
pub(crate) rev: u64,
/// The space before the copy is given.
before: f32,
/// Whether it still shares that line: not once its first line has moved on to the next
/// column or page, where it is laid out as on its own (the copy's space before kept).
pub(crate) shares: bool,
}
impl Joining {
pub(crate) fn new(rev: u64, before: f32) -> Self {
Joining { rev, before, shares: true }
}
/// What tells the copy's layouts apart from each other and from the paragraph's own.
fn key(self) -> (u32, bool) {
(self.before.to_bits(), self.shares)
}
}
struct ParaEnvInput<'a> {
width: f32,
label: Option<(String, Level)>,
@@ -87,6 +115,7 @@ struct ParaEnvInput<'a> {
eq_number: u32,
typing_word: Option<(usize, usize)>,
fitted: &'a [(usize, f32)],
joined: bool,
}
/// A header or footer (`story`) laid out for page `number` of a section (`sect`, `mirror`): its
@@ -227,12 +256,31 @@ impl Ctx<'_> {
grid: para::Grid::default(),
fit_objects: false,
fitted: &[],
joined: false,
};
let pl = Arc::new(para::layout_para(&p, &env));
self.numbers.insert(n, pl.clone());
pl
}
/// Whether `p` is laid out going on from the line of the paragraph before, sharing it (#3986).
fn shares_line(&self, p: &Paragraph) -> bool {
self.joined.is_some_and(|j| j.rev == p.rev && j.shares)
}
/// Whether `p`'s paragraph mark is hidden, with hidden text not shown: Word then shows the
/// paragraph on one line with the next one (#3986). A section's closing mark never joins.
pub(crate) fn mark_hidden(&self, p: &Paragraph, table_chr: Option<&CharProps>) -> bool {
!self.opts.show_hidden && p.section.is_none() && self.doc.styles.resolve_char_in(p.props.style.as_deref(), table_chr, &p.mark).hidden
}
/// Whether `p` shows none of its text (it has none, or all of it is hidden and not shown).
pub(crate) fn text_hidden(&self, p: &Paragraph, table_chr: Option<&CharProps>) -> bool {
p.text.is_empty()
|| (!self.opts.show_hidden
&& p.runs.iter().all(|r| r.len == 0 || self.doc.styles.resolve_char_in(p.props.style.as_deref(), table_chr, &r.props).hidden))
}
/// The list label of `p`, advancing the list counters: call it once per paragraph, in
/// document order (only for paragraphs that will show).
/// Whether `p` gets a list label ([`Ctx::next_label`] is `Some`), without counting it.
@@ -269,7 +317,16 @@ impl Ctx<'_> {
let typing = key.typing;
let pl = Arc::new(para::layout_para(
p,
&self.para_env(ParaEnvInput { width, label, table, exclusions, eq_number, typing_word: typing, fitted: &fitted }),
&self.para_env(ParaEnvInput {
width,
label,
table,
exclusions,
eq_number,
typing_word: typing,
fitted: &fitted,
joined: self.shares_line(p),
}),
));
self.cache.paras.insert(key, pl.clone());
pl
@@ -302,7 +359,16 @@ impl Ctx<'_> {
self.cache.misses += 1;
let pl = Arc::new(para::layout_para(
p,
&self.para_env(ParaEnvInput { width, label, table: None, exclusions: &[], eq_number, typing_word: None, fitted: &[] }),
&self.para_env(ParaEnvInput {
width,
label,
table: None,
exclusions: &[],
eq_number,
typing_word: None,
fitted: &[],
joined: self.shares_line(p),
}),
));
self.cache.paras.insert(key, pl.clone());
Some(pl)
@@ -330,7 +396,16 @@ impl Ctx<'_> {
let typing = key.typing;
let m = measure(&para::layout_para(
p,
&self.para_env(ParaEnvInput { width, label, table, exclusions: &[], eq_number, typing_word: typing, fitted: &fitted }),
&self.para_env(ParaEnvInput {
width,
label,
table,
exclusions: &[],
eq_number,
typing_word: typing,
fitted: &fitted,
joined: self.shares_line(p),
}),
));
self.cache.measures.insert(key, m);
m
@@ -415,6 +490,7 @@ impl Ctx<'_> {
hide_deleted: self.hide_deleted,
sref: if self.fields.styleref.is_some() && styleref::has_styleref(p) { self.fields.styleref_key(p) } else { 0 },
typing: self.opts.typing_word.filter(|t| t.rev == p.rev).map(|t| (t.start, t.end)),
joined: self.joined.filter(|j| j.rev == p.rev).map(Joining::key),
};
(key, eq_number)
}
@@ -435,7 +511,7 @@ impl Ctx<'_> {
}
fn para_env<'b>(&'b self, input: ParaEnvInput<'b>) -> para::ParaEnv<'b> {
let ParaEnvInput { width, label, table, exclusions, eq_number, typing_word, fitted } = input;
let ParaEnvInput { width, label, table, exclusions, eq_number, typing_word, fitted, joined } = input;
para::ParaEnv {
doc: self.doc,
width,
@@ -454,6 +530,7 @@ impl Ctx<'_> {
grid: self.grid,
fit_objects: self.boxes.inside(),
fitted,
joined,
}
}
}
@@ -525,6 +602,7 @@ mod tests {
track_totals: false,
pct_base: None,
quiet_marks: Vec::new(),
joined: None,
stacked_marks: Vec::new(),
mirror: false,
table_keys: Vec::new(),
+94 -4
View File
@@ -1,6 +1,6 @@
use super::boxes::{BoxInput, BoxLayout, Edges, joined, layout_box, push_para};
use super::boxes::{BoxInput, BoxLayout, Edges, Joint, joined, layout_box, push_para};
use super::cache::has_page_number_fields;
use super::ctx::Ctx;
use super::ctx::{Ctx, Joining};
use super::floats::{
FloatAnchor, LateFloats, ObjFrame, ObjectPlacement, anchor_floats, body_wraps, continued_exclusions, fitting, late_floats, place_late,
place_objects,
@@ -15,9 +15,91 @@ use super::{
#[cfg(test)]
use crate::WRAP_RELAYS;
/// A body paragraph. One after a paragraph whose mark is hidden goes on from that one's last line,
/// as Word shows them, on one line (#3986): see [`Joint`].
pub(crate) fn place_para(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize, body_top: f32) {
let joint = pb.joint.take().filter(|j| !pb.web && j.next == block && j.page == pb.pages.len() && j.col == pb.col);
let mark_hidden = ctx.mark_hidden(p, None);
// Nothing of it is shown: the place passes on to the paragraph after it.
if mark_hidden && ctx.text_hidden(p, None) {
place_para_alone(ctx, pb, p, block, body_top);
pb.joint = joint.map(|mut j| {
j.next = block + 1;
j
});
return;
}
let goes_on = joint.filter(|_| {
p.section.is_none()
&& ctx.quiet_marks.binary_search(&block).is_err()
&& ctx.stacked_marks.binary_search(&block).is_err()
&& !ctx.doc.styles.resolve_para(&p.props).page_break_before
&& !ctx.doc.styles.resolve_para(&p.props).bidi
});
match goes_on {
Some(j) => place_para_joined(ctx, pb, p, (block, body_top), j),
None => place_para_alone(ctx, pb, p, block, body_top),
}
if mark_hidden {
let path = Path::top(block);
pb.joint = pb.page().and_then(|page| {
page.items.iter().rev().find_map(|it| match it {
Placed::Lines { story: StoryRef::Body, path: at, para, l0, l1, x, y, turn: TextDirection::Horizontal, .. } if *at == path => {
let room = if *l1 >= para.lines.len() { Rooms::of(ctx, block, para).bottom } else { 0.0 };
Joint::after(para, (*l0, *l1), block, (*x, *y), room)
}
_ => None,
})
});
if let Some(j) = pb.joint.as_mut() {
(j.page, j.col) = (pb.pages.len(), pb.col);
}
}
}
/// `p` going on from the last line of the paragraph before (`j`): its first line starts at that
/// line's top, beside that paragraph's text, with no space before and its list number counted
/// but not drawn; its space after and line spacing are its own (Word, #3986).
fn place_para_joined(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, (block, body_top): (usize, f32), j: Joint) {
// The copy keeps the paragraph's revision, so the word being typed in it is found and its
// layouts are reused from one pass to the next: the cache tells them apart by `Joining`.
let mut q = p.clone();
q.props.space_before = Some(0.0);
q.props.space_before_auto = Some(false);
let outer = ctx.joined.replace(Joining::new(q.rev, 0.0));
let (gap, area) = j.fit(ctx, &q, pb.col_w(), None);
if gap > 0.0 {
q.props.space_before = Some(gap);
ctx.joined = Some(Joining::new(q.rev, gap));
}
pb.y = j.top;
pb.prev = None;
pb.unmark_block();
pb.excl.push(area.clone());
place_para_alone(ctx, pb, &q, block, body_top);
ctx.joined = outer;
if let Some(k) = pb.excl.iter().position(|a| a.0 == area.0 && !a.1 && a.2.is_none() && a.3 == area.3) {
pb.excl.remove(k);
}
// The shared line is at least as tall as the first paragraph's, with its bottom border: what
// follows starts below it.
if (pb.pages.len(), pb.col) == (j.page, j.col) {
pb.y = pb.y.max(j.bottom() + ctx.doc.styles.resolve_para(&q.props).space_after);
}
}
/// A paragraph going on from the line of the one before (#3986) whose first line moves on to the
/// next column or page no longer shares that line: it is laid out as it is on its own there, its
/// list number drawn and its first-line indent and alignment its own.
fn unjoin(ctx: &mut Ctx, p: &Paragraph) {
if let Some(j) = ctx.joined.as_mut().filter(|j| j.rev == p.rev) {
j.shares = false;
}
}
/// A closing mark before a continuous section takes no room after content. An otherwise empty
/// section starting a new page retains its paragraph line.
pub(crate) fn place_para(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize, body_top: f32) {
fn place_para_alone(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: usize, body_top: f32) {
if !pb.web && ctx.quiet_marks.binary_search(&block).is_ok() {
let follows_section = block.checked_sub(1).and_then(|i| ctx.doc.body.get(i)).and_then(|b| b.as_para()).is_some_and(|p| p.section.is_some());
let section = pb.sect_idx;
@@ -126,7 +208,7 @@ impl Rooms {
fn of(ctx: &Ctx, block: usize, pl: &ParaLayout) -> Self {
let above = joined(ctx.doc, &ctx.doc.body, block, block.checked_sub(1), None);
let below = joined(ctx.doc, &ctx.doc.body, block, Some(block + 1), None);
let own = Edges::own(pl, 0, pl.lines.len());
let own = Edges::own(pl, 0, pl.lines.len()).sharing(pl);
Rooms { above, top: if above { 0.0 } else { own.top }, bottom: if below { 0.0 } else { own.bottom } }
}
}
@@ -350,6 +432,7 @@ impl<'a> Flow<'a> {
// 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) {
pb.advance(self.block, self.body_top);
unjoin(ctx, self.p);
pb.y += rp.space_before.min(0.0);
return rp.space_before.min(0.0);
}
@@ -502,6 +585,7 @@ impl<'a> Flow<'a> {
fn move_on(&mut self, ctx: &mut Ctx, pb: &mut PageBuilder) {
pb.advance(self.block, self.body_top);
if self.l0 == 0 {
unjoin(ctx, self.p);
let y0 = pb.y;
self.reanchor(ctx, pb, (y0, 0.0), &[]);
self.anchor_y = y0;
@@ -786,6 +870,11 @@ fn line_numbers(ctx: &mut Ctx, pb: &mut PageBuilder, pl: &ParaLayout, (l0, l1):
{
for li in l0..l1 {
let Some(line) = pl.lines.get(li).filter(|l| !l.beside) else { continue };
// The first line of a paragraph going on from the line of the one before (#3986)
// shares that line, numbered already, unless its first word went on the next one.
if li == 0 && pl.shares_line() {
continue;
}
pb.line_no = pb.line_no.saturating_add(1);
let n = pb.line_no.saturating_add(ln.start.saturating_sub(1));
if ln.count_by > 1 && !n.is_multiple_of(ln.count_by) {
@@ -1028,6 +1117,7 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, counte
grid: ctx.grid,
fit_objects: false,
fitted: &[],
joined: false,
};
Arc::new(para::layout_para(p, &env))
}
+8
View File
@@ -319,6 +319,14 @@ pub fn page_lines(page: &Page, story: StoryRef) -> Vec<LineHit<'_>> {
}
}
}
// A paragraph going on from the last line of one whose mark is hidden shares that line
// (#3986): the first one's part of it ends where the second one's text starts.
let joins: Vec<(f32, f32, f32)> = v.iter().filter(|l| l.para.joined && l.li == 0).map(|l| (l.top, l.bottom, l.left)).collect();
for (top, bottom, left) in joins {
for l in v.iter_mut().filter(|l| l.top < bottom && top < l.bottom && l.left < left && left < l.right) {
l.right = left;
}
}
v
}
+13 -1
View File
@@ -1,4 +1,4 @@
use super::boxes::{BoxInput, layout_box};
use super::boxes::{BoxInput, Joint, layout_box};
use super::ctx::{Ctx, with_pin};
use super::floats::{EarlyFloats, WrapArea};
use super::notes::{NOTE_SEP, NOTE_SEP_W, NoteBox, NoteSeps, v_span};
@@ -35,6 +35,8 @@ pub(crate) struct PageBuilder<'a> {
/// The previous paragraph ended with a page break (its mark stayed with the break): the next
/// paragraph, first on the new page, gets no space before (Word).
pub(crate) after_break_mark: bool,
/// Where the last paragraph, whose mark is hidden, ended: the next one goes on from there.
pub(crate) joint: Option<Joint>,
/// The next section starts on a new page: this section's closing mark, when empty, needs no
/// room (Word leaves it on a full page rather than starting a page for it).
pub(crate) next_starts_page: bool,
@@ -229,6 +231,16 @@ impl PageBuilder<'_> {
self.block_marks.push(pg.items.len().saturating_sub(behind));
}
}
/// Takes back the mark of a block that has placed nothing yet: it goes on from the line of
/// the block before (#3986), and justified vertical alignment keeps the two together.
pub(crate) fn unmark_block(&mut self) {
if let Some(pg) = self.pages.last() {
let behind = self.behind.last().copied().unwrap_or(0);
if self.block_marks.last() == Some(&pg.items.len().saturating_sub(behind)) {
self.block_marks.pop();
}
}
}
/// Justified vertical alignment: share the room left below the page's text out equally
/// between the gaps of its blocks, so the last line sits on the bottom margin (above the
/// footnotes). A page with one block, or several columns, stays at the top.
+10
View File
@@ -101,9 +101,18 @@ pub struct ParaLayout {
/// Room after a cluster between Asian text and Latin text or digits ([`auto_space`]), by
/// cluster index, sorted. It is part of the cluster's advance, but takes no room at a line's end.
pub auto_space: Vec<(usize, f32)>,
/// It goes on from the last line of the paragraph before, whose mark is hidden, and shares
/// that line ([`ParaEnv::joined`]).
pub joined: bool,
}
impl ParaLayout {
/// Whether its first line is the one it shares with the paragraph before, whose mark is
/// hidden (#3986), rather than a line of its own below it (its first word didn't fit there).
pub(crate) fn shares_line(&self) -> bool {
self.joined && self.lines.first().is_some_and(|l| l.top <= 0.01)
}
/// The room a horizontal rule at cluster `k` is placed in, from its left edge to the end of
/// what the line has left. A first-line indent moves that end along (Word, measured with
/// 50 % and fixed-width rules beside floats on either side and with first-line and hanging
@@ -359,6 +368,7 @@ mod label_spacing_tests {
read_line_spacing: None,
fit_objects: false,
fitted: &[],
joined: false,
};
let mut p = Paragraph::with_text(if wrap { "Alpha probe synthetic business text repeated" } else { "Alpha probe" }, Default::default());
p.props.line_spacing = Some(spacing);
+21 -6
View File
@@ -63,6 +63,9 @@ struct Breaker<'e> {
row_first: usize,
/// Spans skipped in a row because the next word didn't fit (see `Scan::skip`).
skipped: usize,
/// The paragraph goes on from the line of the one before (#3986): its first line starts right
/// after that one's text, and takes its place there whatever its own alignment.
joined: bool,
/// A left tab past the right indent that wrapped to start the next line.
wrapped_tab: Option<usize>,
}
@@ -188,7 +191,9 @@ impl<'e> Breaker<'e> {
n: pl.clusters.len(),
width,
base_right: (width - rp.indent_right).max(1.0),
first_left: rp.indent_left + rp.indent_first,
// On the line it shares with the paragraph before (#3986), kept clear of that one's
// text by an exclusion, a joined paragraph's own indents don't hold its text back.
first_left: if env.joined { (rp.indent_left + rp.indent_first).min(0.0) } else { rp.indent_left + rp.indent_first },
default_tab: settings.default_tab,
hanging_at: if rp.indent_first < 0.0 { Some(rp.indent_left) } else { None },
tab_origin: if settings.odf.is_some_and(|o| o.tabs_from_indent) { rp.indent_left } else { 0.0 },
@@ -222,13 +227,20 @@ impl<'e> Breaker<'e> {
row_rest: VecDeque::new(),
row_first: 0,
skipped: 0,
joined: env.joined,
wrapped_tab: None,
}
}
/// The first line's start: a joined paragraph's first line pushed below the shared line (its
/// first word didn't fit there) starts at the paragraph's left indent, as its other lines do.
fn first_indent(&self) -> f32 {
if self.joined && self.top > 0.0 { self.rp.indent_left } else { self.first_left }
}
/// The left edge of the row's first span: the indent, behind a drop cap on its lines.
fn row_left(&self, pl: &ParaLayout) -> f32 {
let lo = if self.first { self.first_left } else { self.rp.indent_left };
let lo = if self.first { self.first_indent() } else { self.rp.indent_left };
match pl.drop_cap {
Some((_, dl, dw)) if dw > 0.0 && self.lines.len() < dl as usize => self.first_left.max(self.rp.indent_left) + dw,
_ => lo,
@@ -271,7 +283,7 @@ impl<'e> Breaker<'e> {
/// The start of a line: its span, and the list label if it is the first.
fn begin_line(&mut self, pl: &mut ParaLayout) -> Scan {
let beside = !self.row_rest.is_empty() && self.lines.len() > self.row_first;
let row_lo = if self.first { self.first_left } else { self.rp.indent_left };
let row_lo = if self.first { self.first_indent() } else { self.rp.indent_left };
let (left, right_edge, narrowed) = self.next_span(pl);
let x = if self.first { self.place_label(pl, left) } else { left };
Scan {
@@ -563,7 +575,10 @@ impl<'e> Breaker<'e> {
let last_tab = (c0..c1).rev().find(|k| pl.clusters.get(*k).is_some_and(|c| c.kind == ClKind::Tab));
let align_from = last_tab.map(|k| k + 1).unwrap_or(c0);
let display = pl.displays.iter().find(|(ci, _)| *ci >= c0 && *ci < c1).map(|d| d.1);
let shift = match (display, rp.align) {
// The line a paragraph shares with the one before, whose mark is hidden, starts in that
// one, and takes its place right after that one's text (Word, #3986).
let align = if self.joined && self.lines.is_empty() { Align::Left } else { rp.align };
let shift = match (display, align) {
(Some(MathJc::Left), _) => 0.0,
(Some(MathJc::Right), _) => slack,
(Some(_), _) => slack / 2.0,
@@ -587,13 +602,13 @@ impl<'e> Breaker<'e> {
}
// A line ending in a manual line break is stretched too, unless `doNotExpandShiftReturn` says not to.
let stretch_end = sc.end == LineEnd::Wrap || (sc.end == LineEnd::LineBreak && self.expand_break);
let justify = display.is_none() && ((rp.align == Align::Justify && stretch_end) || rp.align == Align::Distribute);
let justify = display.is_none() && ((align == Align::Justify && stretch_end) || align == Align::Distribute);
// A line that only fits with shrunk spaces is shrunk, the last line of the paragraph too.
let shrink = display.is_none() && self.shrink_spaces && slack < 0.0 && last_tab.is_none();
if shrink {
shrink_line_spaces(pl, &mut sc.xs, c0, c1, content_end, slack);
} else if justify && slack > 0.0 {
justify_line(pl, &mut sc.xs, (c0, c1, align_from), (content_end, slack), rp.align == Align::Distribute);
justify_line(pl, &mut sc.xs, (c0, c1, align_from), (content_end, slack), align == Align::Distribute);
}
}
+3
View File
@@ -398,4 +398,7 @@ pub struct ParaEnv<'a> {
/// Heights of the paragraph's inline text boxes that resize to fit their text, by object
/// index: they take these instead of their saved heights.
pub fitted: &'a [(usize, f32)],
/// The paragraph goes on from the line of the one before, whose mark is hidden (#3986): its
/// list number is counted and sets its indents, but isn't drawn.
pub joined: bool,
}
+5 -3
View File
@@ -530,13 +530,14 @@ fn mark_break_opportunities(clusters: &mut [Cluster], bt: &BreakText, rp: &Resol
}
}
/// The list label, shaped; none on a paragraph containing only a page break: Word hides it there.
/// The list counter has already advanced, so the following item keeps its number.
/// The list label, shaped; none on a paragraph containing only a page break, nor on one that goes
/// on from the line of the paragraph before (#3986): Word hides it there. The list counter has
/// already advanced, so the following item keeps its number.
fn list_label(cx: &Cx, b: &mut Builder, mark_style: u32) -> Option<Label> {
let (p, rp) = (cx.p, cx.rp);
let break_only =
b.clusters.iter().any(|c| c.kind == ClKind::PageBreak) && b.clusters.iter().all(|c| matches!(c.kind, ClKind::PageBreak | ClKind::Marker));
let (text, lvl) = cx.env.label.as_ref().filter(|_| !break_only)?;
let (text, lvl) = cx.env.label.as_ref().filter(|_| !break_only && !cx.env.joined)?;
let rc = cx.res.char(&p.mark.clone().overlaid(&lvl.chr));
// A bullet no installed font can draw would come from whatever icon font has its
// private-use code (Font Awesome's Twitter logo at U+F081, #1683): it shows the level's
@@ -710,6 +711,7 @@ pub fn layout_para(p: &Paragraph, env: &ParaEnv) -> ParaLayout {
left_out: Vec::new(),
enclosures,
auto_space,
joined: env.joined,
};
let auto = env.doc.settings.auto_hyphenation && !pl.rp.suppress_hyphens;
pl.hyph_after = hyphenation_points(&bt.text, |i| bt.to_para(i), &pl, auto, env.doc.settings.hyphenate_caps, &runs);
+2
View File
@@ -101,6 +101,7 @@ fn new_ctx<'a>(
track_totals: true,
pct_base: None,
quiet_marks: Vec::new(),
joined: None,
stacked_marks: Vec::new(),
mirror: false,
table_keys: Vec::new(),
@@ -202,6 +203,7 @@ fn new_page_builder<'p>(
orig_bottom: 0.0,
prev: None,
after_break_mark: false,
joint: None,
next_starts_page: false,
restart_at: None,
excl: Vec::new(),
+1
View File
@@ -233,6 +233,7 @@ pub fn measure_table_columns(doc: &wordcraft_doc::Document, t: &Table) -> Vec<(f
grid: crate::para::Grid::default(),
fit_objects: false,
fitted: &[],
joined: false,
};
let (mut min, mut max) = (EMPTY_TEXT, EMPTY_TEXT);
if cell.props.vmerge != VMerge::Continue && !cell.props.text_direction.is_turned() {
+404
View File
@@ -2157,6 +2157,410 @@ fn empty_list_paragraph_with_a_hidden_mark_counts_but_shows_nothing() {
}
}
#[test]
fn a_paragraph_with_a_hidden_mark_goes_on_into_the_next_one() {
// Word (#3986): a paragraph whose mark is hidden is shown on one line with the next one. The
// next one's text goes on from where the first one's ends; its number is counted but not
// drawn ("1. AlphaOmega", then "3. Beta") and it takes no line of its own. A paragraph that
// shows nothing in between passes the joint on. In a table cell as in the body.
let doc = |paras: &[(&str, bool)], in_cell: bool| {
let text: Vec<&str> = paras.iter().map(|(t, _)| *t).collect();
let mut d = Document::from_text(&text.join("\n"));
let id = Arc::make_mut(&mut d.numbering).add_list(wordcraft_doc::ListKind::Numbered);
let last = d.body.len() - 1;
let end = paras.last().map_or(0, |(t, _)| t.len());
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(last, end), &|p| {
p.numbering = Some(wordcraft_doc::props::NumRef { num: id, level: 0 });
})
.unwrap();
for (i, (_, hidden)) in paras.iter().enumerate() {
if *hidden {
d.para_mut(StoryRef::Body, &Path::top(i)).unwrap().mark.hidden = Some(true);
}
}
if in_cell {
let mut table = Table::new(1, 1, 400.0);
table.rows[0].cells[0].blocks = std::mem::take(&mut d.body);
d.body = vec![std::sync::Arc::new(Block::Table(table))];
}
d
};
// Each paragraph's number, the top of its first line, and the x its text starts and ends at.
let laid = |d: &Document, show_hidden: bool| {
let l = layout(d, &mut LayoutCache::new(), &LayoutOptions { show_hidden, ..Default::default() });
let lines: Vec<(Option<String>, f32, f32, f32)> = l
.pages
.iter()
.flat_map(|p| &p.items)
.filter_map(|it| match it {
Placed::Lines { para, l0, l1, x, y, .. } => {
let last = l1.checked_sub(1)?;
Some((para.label.as_ref().map(|label| label.text.clone()), *y, x + para.x_of(*l0, 0)?, x + para.x_of(last, para.text_len)?))
}
_ => None,
})
.collect();
lines
};
for in_cell in [false, true] {
let plain = laid(&doc(&[("Alpha", false), ("Beta", false)], in_cell), false);
let beta_y = plain[1].1;
// Text: "Omega" on Alpha's line, after Alpha's text.
let joined = laid(&doc(&[("Alpha", true), ("Omega", false), ("Beta", false)], in_cell), false);
let labels: Vec<_> = joined.iter().map(|l| l.0.as_deref()).collect();
assert_eq!(labels, vec![Some("1."), None, Some("3.")], "in_cell={in_cell}");
assert!((joined[1].1 - joined[0].1).abs() < 0.01, "in_cell={in_cell}: Omega at {} not on Alpha's line {}", joined[1].1, joined[0].1);
assert!((joined[1].2 - joined[0].3).abs() < 0.5, "in_cell={in_cell}: Omega starts at {}, Alpha ends at {}", joined[1].2, joined[0].3);
assert!((joined[2].1 - beta_y).abs() < 0.01, "in_cell={in_cell}: Beta at {} instead of {beta_y}", joined[2].1);
// An empty paragraph: no line of its own, no number.
let empty = laid(&doc(&[("Alpha", true), ("", false), ("Beta", false)], in_cell), false);
let labels: Vec<_> = empty.iter().map(|l| l.0.as_deref()).collect();
assert_eq!(labels, vec![Some("1."), None, Some("3.")], "in_cell={in_cell}");
assert!((empty[2].1 - beta_y).abs() < 0.01, "in_cell={in_cell}: Beta at {} instead of {beta_y}", empty[2].1);
// Through an empty paragraph with a hidden mark (which shows nothing).
let chain = laid(&doc(&[("Alpha", true), ("", true), ("Omega", false), ("Beta", false)], in_cell), false);
let labels: Vec<_> = chain.iter().map(|l| l.0.as_deref()).collect();
assert_eq!(labels, vec![Some("1."), None, None, Some("4.")], "in_cell={in_cell}");
assert!((chain[2].1 - chain[0].1).abs() < 0.01, "in_cell={in_cell}: Omega not on Alpha's line");
// Hidden text shown: each paragraph on its own line, with its number.
let shown = laid(&doc(&[("Alpha", true), ("Omega", false), ("Beta", false)], in_cell), true);
let labels: Vec<_> = shown.iter().map(|l| l.0.as_deref()).collect();
assert_eq!(labels, vec![Some("1."), Some("2."), Some("3.")], "in_cell={in_cell}");
assert!(shown[1].1 > shown[0].1 + 5.0, "in_cell={in_cell}: shown hidden text keeps the paragraphs apart");
}
// A click on the joined text lands in the paragraph it belongs to.
let d = doc(&[("Alpha", true), ("Omega", false), ("Beta", false)], false);
let l = lay(&d);
let omega = l.caret(&Pos::body(1, 2)).unwrap();
let hit = l.hit(omega.page, omega.x + 0.5, omega.top + omega.height / 2.0, StoryRef::Body).unwrap();
assert_eq!(hit.path, Path::top(1));
}
#[test]
fn text_going_on_from_a_larger_heading_sits_on_its_baseline() {
// A heading with a hidden mark followed by body text (a style separator in Word, #3986): the
// body text's first line goes on beside the heading, on the heading's baseline; its next lines
// start at the margin, below both.
let body = "Body text that is long enough to wrap onto a second line in this column. ".repeat(3);
let mut d = Document::from_text(&format!("Heading\n{body}"));
d.format_range(&Pos::body(0, 0), &Pos::body(0, 7), &|c| c.size = Some(18.0)).unwrap();
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
let l = lay(&d);
let lines: Vec<(Path, f32, f32, f32)> = l.pages[0]
.items
.iter()
.filter_map(|it| match it {
Placed::Lines { path, para, l0, l1, x, y, .. } => {
let first = para.lines.get(*l0)?;
let (x, y) = (*x, *y);
Some((*l0..*l1).filter_map(move |li| {
let line = para.lines.get(li)?;
Some((path.clone(), y + line.baseline - first.top, x + para.x_of(li, line.start)?, y + line.top - first.top))
}))
}
_ => None,
})
.flatten()
.collect();
let heading = lines.iter().find(|l| l.0 == Path::top(0)).unwrap();
let body: Vec<_> = lines.iter().filter(|l| l.0 == Path::top(1)).collect();
assert!(body.len() >= 2, "{lines:?}");
assert!((body[0].1 - heading.1).abs() < 0.01, "body baseline {} vs heading {}", body[0].1, heading.1);
assert!(body[0].2 > 100.0, "the body text starts after the heading's, at {}", body[0].2);
assert!((body[1].2 - 72.0).abs() < 0.5, "the next line starts at the margin, not at {}", body[1].2);
assert!(body[1].3 > heading.1, "the next line is below the shared one");
}
#[test]
fn a_text_box_anchored_in_a_paragraph_with_a_hidden_mark_is_not_joined() {
// A text box anchored in the first paragraph lays its own story out, whose first line has
// the same path as that paragraph (#3986). The next paragraph goes on from the paragraph's
// text, not from the box's, which is drawn after it.
let mut d = Document::from_text("Alpha\nOmega");
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
let float = wordcraft_doc::para::Float {
wrap: wordcraft_doc::para::Wrap::InFrontOfText,
h_rel: wordcraft_doc::para::Anchor::Column,
v_rel: wordcraft_doc::para::Anchor::Paragraph,
x: 200.0,
y: 100.0,
dist: 0.0,
..Default::default()
};
text_box(&mut d, 0, "Box", 100.0, 40.0, float);
let l = lay(&d);
// The top of a story's line at a block, and the x its text starts and ends at.
let line = |story: StoryRef, block: usize| {
l.pages[0].items.iter().find_map(|it| match it {
Placed::Lines { story: s, path, para, l0, l1, x, y, .. } if *s == story && *path == Path::top(block) => {
Some((*y, x + para.x_of(*l0, 0)?, x + para.x_of(l1.checked_sub(1)?, para.text_len)?))
}
_ => None,
})
};
let (alpha, omega) = (line(StoryRef::Body, 0).unwrap(), line(StoryRef::Body, 1).unwrap());
assert!((omega.0 - alpha.0).abs() < 0.01, "Omega at {} not on Alpha's line {}", omega.0, alpha.0);
assert!((omega.1 - alpha.2).abs() < 0.5, "Omega starts at {}, Alpha ends at {}", omega.1, alpha.2);
}
#[test]
fn a_joined_paragraph_moved_to_the_next_page_has_its_own_number() {
// A paragraph going on from one with a hidden mark (#3986) that moves whole to the next page
// (its lines kept together) no longer shares that line: there its number is drawn and its
// text starts at its own indent.
let omega = "Omega ".repeat(60);
let build = |filler: usize| {
let mut text: Vec<String> = (0..filler).map(|i| format!("Filler {i}")).collect();
text.push("Alpha".into());
text.push(omega.clone());
let mut d = Document::from_text(&text.join("\n"));
let id = Arc::make_mut(&mut d.numbering).add_list(wordcraft_doc::ListKind::Numbered);
d.format_paragraphs(&Pos::body(filler, 0), &Pos::body(filler + 1, omega.len()), &|p| {
p.numbering = Some(wordcraft_doc::props::NumRef { num: id, level: 0 });
})
.unwrap();
d.para_mut(StoryRef::Body, &Path::top(filler)).unwrap().mark.hidden = Some(true);
d.para_mut(StoryRef::Body, &Path::top(filler + 1)).unwrap().props.keep_lines = Some(true);
d
};
// The page of a paragraph's first line, with its number there.
let first = |l: &DocLayout, block: usize| {
l.pages.iter().enumerate().find_map(|(pi, page)| {
page.items.iter().find_map(|it| match it {
Placed::Lines { path, para, l0: 0, .. } if *path == Path::top(block) => {
Some((pi, para.label.as_ref().map(|label| label.text.clone())))
}
_ => None,
})
})
};
for filler in 20..80 {
let d = build(filler);
let l = lay(&d);
let (Some((0, alpha)), Some((1, omega_label))) = (first(&l, filler), first(&l, filler + 1)) else { continue };
assert_eq!(alpha.as_deref(), Some("1."));
assert_eq!(omega_label.as_deref(), Some("2."), "the moved paragraph draws its number");
let (a, o) = (l.caret(&Pos::body(filler, 0)).unwrap(), l.caret(&Pos::body(filler + 1, 0)).unwrap());
assert_eq!(o.page, 1);
assert!((o.x - a.x).abs() < 0.5, "the moved paragraph's text starts at its own indent: {} vs {}", o.x, a.x);
return;
}
panic!("no filler put Alpha last on the first page with the joined paragraph moved on");
}
#[test]
fn a_joined_first_word_that_does_not_fit_goes_on_the_next_line_at_the_indent() {
// Word (#3986): when the next paragraph's first word doesn't fit after the first one's text,
// it goes on the next line, still joined (no number drawn), at the indent of the list's text.
let build = |n: usize| {
let alpha = vec!["aa"; n].join(" ");
let omega = "Omegaomegaomega tail";
let mut d = Document::from_text(&format!("{alpha}\n{omega}"));
let id = Arc::make_mut(&mut d.numbering).add_list(wordcraft_doc::ListKind::Numbered);
d.format_paragraphs(&Pos::body(0, 0), &Pos::body(1, omega.len()), &|p| {
p.numbering = Some(wordcraft_doc::props::NumRef { num: id, level: 0 });
})
.unwrap();
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
(d, alpha.len())
};
for n in 20..200 {
let (d, alpha_len) = build(n);
let l = lay(&d);
let (end, start) = (l.caret(&Pos::body(0, alpha_len)).unwrap(), l.caret(&Pos::body(1, 0)).unwrap());
if (start.top - end.top).abs() < 0.5 {
continue; // still on the shared line
}
let indent = l.caret(&Pos::body(0, 0)).unwrap().x;
assert!(start.top > end.top, "the first word goes below the shared line");
assert!((start.x - indent).abs() < 0.5, "at the list text's indent {indent}, not {}", start.x);
let label = l.pages.iter().flat_map(|p| &p.items).find_map(|it| match it {
Placed::Lines { path, para, .. } if *path == Path::top(1) => Some(para.label.as_ref().map(|label| label.text.clone())),
_ => None,
});
assert_eq!(label, Some(None), "still joined: no number drawn");
return;
}
panic!("no length of the first paragraph left its last line too full for the next one's first word");
}
#[test]
fn a_shared_line_is_one_line_for_line_numbers_and_vertical_alignment() {
// Word (#3986): the line two paragraphs share through a hidden mark is one line. Line
// numbering gives it one number ("Line one", the shared line, "After": 1, 2, 3), and justified
// vertical alignment keeps the two paragraphs together as one block.
let doc = |valign: wordcraft_doc::section::PageVAlign| {
let mut d = Document::from_text("Line one\nAlpha\nOmega\nAfter");
for b in d.body.iter_mut() {
if let Block::Para(p) = std::sync::Arc::make_mut(b) {
p.props.space_before = Some(0.0);
p.props.space_after = Some(0.0);
}
}
d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().mark.hidden = Some(true);
d.last_section.valign = valign;
d
};
let mut d = doc(wordcraft_doc::section::PageVAlign::Top);
d.last_section.line_numbers = Some(Default::default());
let l = lay(&d);
let numbers: Vec<f32> = l.pages[0]
.items
.iter()
.filter_map(|it| match it {
Placed::Lines { story, y, .. } if *story == DECOR_STORY => Some(*y),
_ => None,
})
.collect();
assert_eq!(numbers.len(), 3, "one number per shown line: {numbers:?}");
assert!(numbers.windows(2).all(|w| w[1] > w[0] + 5.0), "no two numbers on one line: {numbers:?}");
let l = lay(&doc(wordcraft_doc::section::PageVAlign::Justify));
let y = |off: (usize, usize)| l.caret(&Pos::body(off.0, off.1)).unwrap().top;
assert!((y((2, 0)) - y((1, 0))).abs() < 0.01, "Omega stays on Alpha's line: {} vs {}", y((2, 0)), y((1, 0)));
let (g1, g2) = (y((1, 0)) - y((0, 0)), y((3, 0)) - y((1, 0)));
assert!(g1 > 100.0 && (g1 - g2).abs() < 0.05, "equal gaps around the shared line: {g1} {g2}");
}
#[test]
fn a_joined_line_with_a_hanging_indent_still_starts_after_the_text_before() {
// The joined paragraph's first-line indent reaches left of the margin: its text still starts
// after the text of the paragraph before, never left of it (#3986).
let mut d = Document::from_text("Alpha\na b c");
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
let q = d.para_mut(StoryRef::Body, &Path::top(1)).unwrap();
q.props.indent_left = Some(0.0);
q.props.indent_first = Some(-36.0);
let l = lay(&d);
let (end, start) = (l.caret(&Pos::body(0, 5)).unwrap(), l.caret(&Pos::body(1, 0)).unwrap());
assert!((start.top - end.top).abs() < 0.01, "on the shared line");
assert!(start.x >= end.x - 0.01, "after Alpha: starts at {}, Alpha ends at {}", start.x, end.x);
}
#[test]
fn a_joined_paragraphs_shading_and_borders_start_below_the_shared_line() {
// Word (synthetic DOCX, 16.0.20625): the line a paragraph shares with the one before, whose
// mark is hidden, shows that one's shading and borders, not its own. Its own start on its next
// line (no top border there), and a paragraph that is all on the shared line shows neither and
// takes no room for its borders; what follows starts below the first one's bottom border.
let yellow = wordcraft_doc::props::Rgb(0xFF, 0xFF, 0);
let boxed = || Some(Borders::all(Border { space: 1.0, ..Border::single(1.5) }));
// "Alpha" (mark hidden) with `first`'s formatting, then `second` with its own, then "After".
let doc = |first: &dyn Fn(&mut ParaProps), second_text: &str, second: &dyn Fn(&mut ParaProps), in_cell: bool| {
let mut d = Document::from_text(&format!("Alpha\n{second_text}\nAfter"));
let a = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
a.mark.hidden = Some(true);
first(&mut a.props);
second(&mut d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().props);
if in_cell {
let mut table = Table::new(1, 1, 400.0);
table.props.borders = Some(Borders::all(Border { style: BorderStyle::None, width: 0.0, color: None, space: 0.0 }));
table.rows[0].cells[0].blocks = std::mem::take(&mut d.body);
d.body = vec![std::sync::Arc::new(Block::Table(table))];
}
d
};
let path = |i: u32, in_cell: bool| if in_cell { Path(vec![0, 0, 0, i]) } else { Path::top(i as usize) };
// The shared line (top, bottom), "After"'s top, fills and the paragraphs' horizontal rules.
let laid = |d: &Document, in_cell: bool| {
crate::test_fonts();
let l = lay(d);
let at = |i: u32| l.caret(&Pos { story: StoryRef::Body, path: path(i, in_cell), off: 0 }).unwrap();
let (alpha, after) = (at(0), at(2));
let fills: Vec<Rect> = l.pages[0]
.items
.iter()
.filter_map(|i| if let Placed::Fill { rect, color } = i { (*color == yellow).then_some(*rect) } else { None })
.collect();
let rules: Vec<(f32, f32, f32, f32)> = l.pages[0]
.items
.iter()
.filter_map(
|i| if let Placed::Rule { x0, y0, x1, y1, border } = i { (border.width == 1.5).then_some((*x0, *y0, *x1, *y1)) } else { None },
)
.collect();
(alpha.top, alpha.top + alpha.height, after.top, fills, rules)
};
let none = |_: &mut ParaProps| {};
let long = format!("Omega {}", "zeta ".repeat(30));
for in_cell in [false, true] {
let (top, bottom, after, ..) = laid(&doc(&none, "Omega", &none, in_cell), in_cell);
// The second one shaded, all of it on the shared line: no shading over "Alpha".
let (t, _, a, fills, _) = laid(&doc(&none, "Omega", &|p| p.shading = Some(yellow), in_cell), in_cell);
assert!(fills.is_empty(), "in_cell={in_cell}: {fills:?}");
assert!((t - top).abs() < 0.01 && (a - after).abs() < 0.01, "in_cell={in_cell}");
// Shaded and running on: the shading starts on its own next line.
let (_, b, _, fills, _) = laid(&doc(&none, &long, &|p| p.shading = Some(yellow), in_cell), in_cell);
assert_eq!(fills.len(), 1, "in_cell={in_cell}: {fills:?}");
assert!(fills[0].y >= b - 0.01, "in_cell={in_cell}: shading from {} over the shared line ending at {b}", fills[0].y);
// The first one shaded: the shared line is.
let (t, b, _, fills, _) = laid(&doc(&|p| p.shading = Some(yellow), "Omega", &none, in_cell), in_cell);
assert_eq!(fills.len(), 1, "in_cell={in_cell}: {fills:?}");
assert!(fills[0].y <= t + 0.01 && fills[0].bottom() >= b - 0.01, "in_cell={in_cell}: {fills:?}");
// The second one boxed, all of it on the shared line: no borders, no room for them.
let (t, _, a, _, rules) = laid(&doc(&none, "Omega", &|p| p.borders = boxed(), in_cell), in_cell);
assert!(rules.is_empty(), "in_cell={in_cell}: {rules:?}");
assert!((t - top).abs() < 0.01 && (a - after).abs() < 0.01, "in_cell={in_cell}: {t} {a}");
// Boxed and running on: its box is around its own lines, open at the top, with its bottom
// border's room under it; the shared line stays where it is.
let (t, b, _, _, rules) = laid(&doc(&none, &long, &|p| p.borders = boxed(), in_cell), in_cell);
assert!((t - top).abs() < 0.01, "in_cell={in_cell}: shared line moved to {t}");
assert_eq!(rules.iter().filter(|r| r.1 == r.3).count(), 1, "in_cell={in_cell}: only the bottom border: {rules:?}");
assert!(rules.iter().all(|r| r.1.min(r.3) >= b - 0.01), "in_cell={in_cell}: a border over the shared line: {rules:?}");
// The first one boxed: what follows starts below its bottom border.
let (_, _, a, _, rules) = laid(&doc(&|p| p.borders = boxed(), "Omega", &none, in_cell), in_cell);
let bottom_rule = rules.iter().filter(|r| r.1 == r.3).map(|r| r.1).fold(f32::MIN, f32::max);
assert!(bottom_rule > bottom, "in_cell={in_cell}: {rules:?}");
assert!(a >= bottom_rule + 0.75 - 0.01, "in_cell={in_cell}: After at {a}, over the border at {bottom_rule}");
}
}
#[test]
fn a_joined_paragraph_keeps_its_revision_for_the_cache_and_the_word_being_typed() {
// The joined paragraph is laid out as a copy without its space before (#3986). The copy keeps
// the document's revision: the word being typed in it gets no squiggle, and laying the
// document out again reuses its layouts.
crate::test_fonts();
let mut d = Document::from_text("Alpha\nhelo wrld\nAfter");
d.para_mut(StoryRef::Body, &Path::top(0)).unwrap().mark.hidden = Some(true);
let rev = d.para(StoryRef::Body, &Path::top(1)).unwrap().rev;
let marks = |l: &DocLayout| -> Vec<String> {
l.pages[0]
.items
.iter()
.filter_map(|i| match i {
Placed::Lines { para, path, .. } if *path == Path::top(1) => {
Some(para.issues.iter().filter(|i| !i.2).map(|i| "helo wrld"[i.0..i.1].to_string()).collect::<Vec<_>>())
}
_ => None,
})
.flatten()
.collect()
};
let mut c = LayoutCache::new();
let opts = LayoutOptions { proofing: true, ..LayoutOptions::default() };
let both = layout(&d, &mut c, &opts);
assert_eq!(marks(&both), ["helo", "wrld"]);
let (a, b) = (both.caret(&Pos::body(0, 5)).unwrap(), both.caret(&Pos::body(1, 0)).unwrap());
assert!((a.top - b.top).abs() < 0.01, "joined");
let misses = c.misses;
let again = layout(&d, &mut c, &opts);
assert_eq!(marks(&again), ["helo", "wrld"]);
assert_eq!(c.misses, misses, "nothing laid out again");
let typing = layout(&d, &mut c, &LayoutOptions { typing_word: Some(TypingWord { rev, start: 5, end: 9 }), ..opts.clone() });
assert_eq!(marks(&typing), ["helo"], "the word being typed is left alone");
}
#[test]
fn a_numbered_heading_opening_with_a_page_break_takes_its_number_along() {
crate::test_fonts();
File diff suppressed because one or more lines are too long