diff --git a/crates/layout/src/boxes.rs b/crates/layout/src/boxes.rs index fa45039803..14bac54f3e 100644 --- a/crates/layout/src/boxes.rs +++ b/crates/layout/src/boxes.rs @@ -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; @@ -262,12 +263,19 @@ 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 = 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 (mark_hidden, shows_nothing, taken) = Joint::arrive(ctx, &mut joint, (i, p), (width, frames), 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()); @@ -306,8 +314,10 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout { }); // Paragraph-relative floats start above the effective space before, as in the // body path. Keep text and wrap exclusions relative to the text's actual top. - let para_top = y; + // A paragraph going on from a shared line has its origin at that line's top. + let para_top = taken.as_ref().map_or(y, |t| t.joint.top); y += if i == 0 { before } else { before.max(0.0) }; + TakenUp::start(taken.as_ref(), &mut y, &mut excl); // 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(); @@ -354,10 +364,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; } @@ -370,6 +381,7 @@ 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); + joint = Joint::after(&pl, (0, pl.lines.len()), i, (0.0, y + lead), edges.bottom).filter(|_| mark_hidden && !shows_nothing).or(joint); // Pictures, shapes and text boxes: drawn, their areas and text boxes' text. if !p.objects.is_empty() { let at = ObjFrame { @@ -412,7 +424,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; @@ -445,6 +459,7 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout { y = y.max(legacy_header_reach(y, &legacy_reach)); 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 } } @@ -700,6 +715,162 @@ impl Edges { joined: [false; 2], } } + + /// 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 { + 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 }) + } + + /// Paragraph `p`, block `i`, arriving at `joint`: whether its mark is hidden, whether it shows + /// nothing, and how it goes on from the place the one before left (if that one's mark was hidden). + fn arrive( + ctx: &mut Ctx, + joint: &mut Option, + (i, p): (usize, &Paragraph), + (width, frames): (f32, bool), + table: Option<¶::CellText>, + ) -> (bool, bool, Option) { + 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, frames), table)); + (mark_hidden, shows_nothing, taken) + } + + /// 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 areas it keeps clear of: its first line, this paragraph's text, down to + /// the bottom of that line only; its later lines, the rest of the shared line (a heading's, + /// taller than the text going on from it), with the room for its bottom border (Word). + pub(crate) fn fit(&self, ctx: &mut Ctx, q: &Paragraph, width: f32, table: Option<¶::CellText>) -> (f32, Vec) { + 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)); + let mut areas = vec![(rect, false, None, WrapText::Right, false)]; + // Just below the first row as the line breaker tests it: the breaker tests every row at + // its estimate (`row_est`), not at the line's height, so the first row never meets this + // area and every later row, starting lower, does and moves below it. The probe's own first + // line can be taller than the real one (a large word that wraps off the narrower shared + // line), so its height can't be used here. + let below = self.top + gap + probe.row_est + 0.01; + if self.bottom() > below { + areas.push((Rect::new(self.left, below, width.max(0.01), self.bottom() - below), true, None, WrapText::BothSides, false)); + } + (gap, areas) + } + + /// The areas [`Joint::fit`] gave taken out of `excl` again, the paragraph laid out. + pub(crate) fn unfit(areas: &[WrapArea], excl: &mut Vec) { + for area in areas { + if let Some(k) = excl.iter().position(|a| a.0 == area.0 && a.1 == area.1 && a.2.is_none() && a.3 == area.3) { + excl.remove(k); + } + } + } + + /// Paragraph `p` of a box `width` wide going on from here, unless a page break comes before + /// it, it runs right to left or it is a text frame (`frames`: placed apart, sharing no line): + /// without its space before, as [`Joint::fit`] lays it out. + fn take_up(self, ctx: &mut Ctx, p: &Paragraph, (width, frames): (f32, bool), table: Option<¶::CellText>) -> Option { + let own = ctx.doc.styles.resolve_para_in(&p.props, table.map(|t| &t.para)); + if own.page_break_before || own.bidi || (frames && own.frame.is_some()) { + 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, areas) = self.fit(ctx, ¶, width, table); + Some(TakenUp { joint: self, para, gap, areas }) + } +} + +/// 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 areas its lines keep clear of. +struct TakenUp { + joint: Joint, + para: Paragraph, + gap: f32, + areas: Vec, +} + +impl TakenUp { + /// Where it starts: `y` below the shared line's top, its lines keeping clear of that line. + fn start(taken: Option<&TakenUp>, y: &mut f32, excl: &mut Vec) { + let Some(t) = taken else { return }; + *y = t.joint.top + t.gap; + excl.extend(t.areas.iter().cloned()); + } + + /// Its lines laid out: the areas they kept clear of come out of `excl`. + fn clear(taken: Option<&TakenUp>, excl: &mut Vec) { + if let Some(t) = taken { + Joint::unfit(&t.areas, excl); + } + } + + /// 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) -> 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 @@ -717,12 +888,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)); @@ -731,7 +911,7 @@ 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 (`lx`, `rx`: the side lines' // outer edges); `box_rules` runs the top and bottom over the side lines to those edges. @@ -739,9 +919,10 @@ pub(crate) fn push_para( let (cl, cr) = (lx + half(b.left), rx - half(b.right)); let tb = b.top.filter(|t| e.top > 0.0 && t.is_visible()); let bb = b.bottom.filter(|t| e.bottom > 0.0 && t.is_visible()); - let ty = tb.map_or(top, |t| y - t.space - t.width / 2.0); + let ty = tb.map_or(top, |t| y_own - t.space - t.width / 2.0); let by = bb.map_or(bottom, |t| y + h + t.space + t.width / 2.0); - box_rules(items, (cl, ty, cr, by), [tb, bb, b.left, b.right], e.joined); + // Open at the top where it goes on over the shared line. + box_rules(items, (cl, ty, cr, by), [tb, bb, b.left, b.right], [e.joined[0] || shared, e.joined[1]]); } y + h } diff --git a/crates/layout/src/cache.rs b/crates/layout/src/cache.rs index d0fb9cd5a5..637c2115b5 100644 --- a/crates/layout/src/cache.rs +++ b/crates/layout/src/cache.rs @@ -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. diff --git a/crates/layout/src/ctx.rs b/crates/layout/src/ctx.rs index a53584a0ab..7e7baf3e8c 100644 --- a/crates/layout/src/ctx.rs +++ b/crates/layout/src/ctx.rs @@ -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, + /// 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, /// 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, @@ -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(¶::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(), diff --git a/crates/layout/src/flow.rs b/crates/layout/src/flow.rs index 2c7cc5da12..fc2ba1ff32 100644 --- a/crates/layout/src/flow.rs +++ b/crates/layout/src/flow.rs @@ -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,89 @@ 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, areas) = 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.extend(areas.iter().cloned()); + place_para_alone(ctx, pb, &q, block, body_top); + ctx.joined = outer; + Joint::unfit(&areas, &mut pb.excl); + // 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; @@ -127,7 +207,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, below, top: if above { 0.0 } else { own.top }, bottom: if below { 0.0 } else { own.bottom } } } } @@ -360,6 +440,7 @@ impl<'a> Flow<'a> { // 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); + unjoin(ctx, self.p); pb.y += rp.space_before.min(0.0); return rp.space_before.min(0.0); } @@ -557,6 +638,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; @@ -846,6 +928,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) { @@ -895,7 +982,7 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block: } let before = f.gap_before(ctx, pb, broke_before); pb.y += before; - let rooms = Rooms::of(ctx, block, &f.pl); + let mut rooms = Rooms::of(ctx, block, &f.pl); let applied_before = f.keep_together(ctx, pb, rooms, before); // A different top only matters when there is something to wrap around. if spot(pb) != placed_at || ((pb.y - f.guess).abs() > 0.01 && !pb.excl.is_empty()) { @@ -904,7 +991,10 @@ 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() { + // A paragraph moved on from the shared line (`unjoin`) is laid out again with borders of its own. + rooms = Rooms::of(ctx, block, &f.pl); f.keep_again(ctx, pb, rooms); + rooms = Rooms::of(ctx, block, &f.pl); f.place_due_late(ctx, pb); f.relay_wrap(ctx, pb); f.relay_pages(ctx, pb); @@ -1098,6 +1188,7 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_pa grid: ctx.grid, fit_objects: false, fitted: &[], + joined: false, }; Arc::new(para::layout_para(p, &env)) } diff --git a/crates/layout/src/hit.rs b/crates/layout/src/hit.rs index 3926b37e4c..0f0531bcda 100644 --- a/crates/layout/src/hit.rs +++ b/crates/layout/src/hit.rs @@ -319,6 +319,14 @@ pub fn page_lines(page: &Page, story: StoryRef) -> Vec> { } } } + // 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.shares_line() && 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 } diff --git a/crates/layout/src/page.rs b/crates/layout/src/page.rs index 565f00773e..7640f960de 100644 --- a/crates/layout/src/page.rs +++ b/crates/layout/src/page.rs @@ -1,4 +1,4 @@ -use super::boxes::{BoxInput, box_rules, layout_box}; +use super::boxes::{BoxInput, Joint, box_rules, 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, /// 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, @@ -228,6 +230,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. diff --git a/crates/layout/src/para.rs b/crates/layout/src/para.rs index 44bc2f6f97..4f1b65e6d3 100644 --- a/crates/layout/src/para.rs +++ b/crates/layout/src/para.rs @@ -101,9 +101,20 @@ 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, + /// How tall the line breaker takes a row to be when it checks it against wrap areas. + pub(crate) row_est: f32, } 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 +370,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); diff --git a/crates/layout/src/para/lines.rs b/crates/layout/src/para/lines.rs index f3f08f2328..7edd8f537f 100644 --- a/crates/layout/src/para/lines.rs +++ b/crates/layout/src/para/lines.rs @@ -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, } @@ -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); } } @@ -692,6 +707,7 @@ impl<'e> Breaker<'e> { fn finish(mut self, pl: &mut ParaLayout) { self.hang_drop_cap(pl); pl.height = self.top; + pl.row_est = self.est_h; pl.lines = std::mem::take(&mut self.lines); let label_shift = self.label_shifts.get(pl.label_line()).copied().unwrap_or(0.0); if let Some(lab) = pl.label.as_mut() { diff --git a/crates/layout/src/para/model.rs b/crates/layout/src/para/model.rs index 4372ddb35f..b46672909c 100644 --- a/crates/layout/src/para/model.rs +++ b/crates/layout/src/para/model.rs @@ -401,4 +401,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, } diff --git a/crates/layout/src/para/paragraph.rs b/crates/layout/src/para/paragraph.rs index c43db5a656..9687e73137 100644 --- a/crates/layout/src/para/paragraph.rs +++ b/crates/layout/src/para/paragraph.rs @@ -533,13 +533,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