Fit native paragraph endings using preceding line glue

This commit is contained in:
gloamxun committed 2026-11-28 11:50:07 +08:00
1 parent e72104eab3
commit 11fd66713b
10 files changed
+247 -23

No files matched your search

+109 -14
View File
@@ -664,6 +664,36 @@ struct Break {
forced: bool,
}
#[derive(Clone)]
struct LineBreaks {
lines: Vec<(Break, i32)>,
final_fill: Option<Glue>,
}
#[derive(Clone, Copy, Default)]
struct FitWidths {
shortfall: i64,
glue: i64,
}
impl FitWidths {
// e-TeX computes the previous line's ratio in scaled points first,
// then applies lastlinefit in thousandths with a second rounding.
fn adjustment(self, available: i64, factor: i64) -> i64 {
if self.shortfall == 0 || self.glue <= 0 || available <= 0 {
return 0;
}
const MAX_DIMEN: i128 = (1 << 30) - 1;
let denominator = i128::from(self.glue);
let product = i128::from(available) * i128::from(self.shortfall.abs());
let scaled = (product + denominator / 2) / denominator;
let scaled = if scaled > MAX_DIMEN {
MAX_DIMEN
} else {
(scaled * i128::from(factor) + 500) / 1000
};
scaled as i64 * self.shortfall.signum()
}
}
#[derive(Clone)]
struct Active {
serial: usize,
previous: usize,
@@ -674,6 +704,7 @@ struct Active {
fitness: u8,
hyphen: bool,
cost: i64,
fit_widths: FitWidths,
path: Vec<(Break, i32)>,
}
fn geometry(
@@ -806,11 +837,27 @@ fn break_lines(
work: &mut usize,
previous_lines: usize,
trace: &mut super::paragraph_trace::Tracer,
) -> Result<Option<Vec<(Break, i32)>>, String> {
) -> Result<Option<LineBreaks>, String> {
let get = |q| p[&q].width() as i64;
let left = p[&Parameter::Leftskip].glue();
let right = p[&Parameter::Rightskip].glue();
let par_fill = p[&Parameter::Parfillskip].glue();
let fit_factor = get(Parameter::Lastlinefit).min(1000);
let mut infinite_fill = [0; 4];
let fit_last_line = fit_factor > 0
&& par_fill.stretch.amount > 0
&& par_fill.stretch.order > 0
&& (1..4).all(|order| {
[left.stretch, right.stretch]
.into_iter()
.filter(|stretch| stretch.order == order)
.map(|stretch| i64::from(stretch.amount))
.sum::<i64>()
== 0
});
if fit_last_line {
infinite_fill[usize::from(par_fill.stretch.order)] = i64::from(par_fill.stretch.amount);
}
let mut breaks = Vec::new();
let mut auto_breaking = true;
let mut replacement_end = 0;
@@ -923,6 +970,7 @@ fn break_lines(
fitness: 1,
hyphen: false,
cost: 0,
fit_widths: FitWidths::default(),
path: Vec::new(),
}];
let last_special_line = if !shape.is_empty() {
@@ -1007,7 +1055,22 @@ fn break_lines(
shortfall
};
let infinite = stretch[1..].iter().any(|n| *n != 0);
let bad = if delta >= 0 {
let fit_adjustment = if fit_last_line
&& keep_par_fill
&& delta > 0
&& stretch[1..] == infinite_fill[1..]
{
let available = if a.fit_widths.shortfall > 0 { stretch[0] } else { shrink };
a.fit_widths
.adjustment(available, fit_factor)
.clamp(-available.max(0), delta)
} else {
0
};
let bad = if fit_adjustment != 0 {
let available = if fit_adjustment > 0 { stretch[0] } else { shrink };
tex_badness(fit_adjustment.abs(), available)
} else if delta >= 0 {
if infinite {
0
} else {
@@ -1024,7 +1087,8 @@ fn break_lines(
&& index + 1 == total
&& added.is_empty();
if bad <= threshold as i32 || forced_artificial {
let fitness = if delta < 0 && bad > 12 {
let shrinking = delta < 0 || fit_adjustment < 0;
let fitness = if shrinking && bad > 12 {
0
} else if bad <= 12 {
1
@@ -1101,6 +1165,21 @@ fn break_lines(
fitness,
hyphen: b.hyphen,
cost: a.cost.saturating_add(demerits),
fit_widths: if fit_adjustment != 0 {
FitWidths {
shortfall: delta,
glue: fit_adjustment,
}
} else if !fit_last_line || final_break || delta > 0 && infinite {
FitWidths::default()
} else {
let glue = match delta.cmp(&0) {
std::cmp::Ordering::Greater => stretch[0],
std::cmp::Ordering::Less => shrink,
std::cmp::Ordering::Equal => 0,
};
FitWidths { shortfall: delta, glue }
},
path,
};
let key = (a.line.min(merged_class), 3 - fitness, b.hyphen);
@@ -1140,6 +1219,11 @@ fn break_lines(
hyphenated: a.hyphen,
demerits: a.cost,
previous: a.previous,
last_line_fit: fit_last_line.then_some(super::ParagraphLineFitTrace {
shortfall: a.fit_widths.shortfall,
glue: a.fit_widths.glue,
final_line: final_break,
}),
})?;
}
trace.after_break(nodes, b.end);
@@ -1191,13 +1275,25 @@ fn break_lines(
if !accepted {
return Ok(None);
}
Ok(Some(chosen.path.clone()))
let final_fill = if chosen.fit_widths.shortfall == 0 {
None
} else {
let width = i64::from(par_fill.width) + chosen.fit_widths.shortfall - chosen.fit_widths.glue;
let mut glue = par_fill;
glue.width = i32::try_from(width).map_err(|_| "native last line fill width overflow")?;
glue.stretch.amount = 0;
Some(glue)
};
Ok(Some(LineBreaks {
lines: chosen.path.clone(),
final_fill,
}))
}
fn pack(
nodes: &[TextNode],
p: &BTreeMap<Parameter, ParameterValue>,
(indent, target): (i64, i64),
keep_par_fill: bool,
par_fill: Option<Glue>,
terminal_marker: bool,
ends_in_pre_break: bool,
direction_stack: &[super::direction::Region],
@@ -1217,7 +1313,7 @@ fn pack(
}
let right_end = nodes.len() - usize::from(terminal_marker);
material.extend_from_slice(&nodes[..right_end]);
if keep_par_fill {
if par_fill.is_some() {
material.push(TextNode::Penalty(10000));
}
if enabled
@@ -1226,11 +1322,8 @@ fn pack(
material.push(kern);
}
material.extend_from_slice(&nodes[right_end..]);
if keep_par_fill {
material.push(TextNode::NamedGlue(
p[&Parameter::Parfillskip].glue(),
Parameter::Parfillskip,
));
if let Some(fill) = par_fill {
material.push(TextNode::NamedGlue(fill, Parameter::Parfillskip));
}
super::direction::close(&mut material, direction_stack);
material.push(TextNode::NamedGlue(
@@ -1412,7 +1505,8 @@ pub(super) fn finish(
Err(String::from("native paragraph has no legal break sequence"))
})();
*records = trace.into_records();
let (path, selected_pass) = search?;
let (breaks, selected_pass) = search?;
let path = &breaks.lines;
let mut start = 0;
let mut post = None;
let mut lines = Vec::new();
@@ -1447,7 +1541,8 @@ pub(super) fn finish(
let terminal_marker = point.zero_tail.is_some()
|| matches!(b.nodes.get(point.end), Some(TextNode::Penalty(_)))
|| (point.pre_break.is_some() && !ends_in_pre_break);
let keep_par_fill = i + 1 == path.len() && (i == 0 || !material.is_empty());
let par_fill = (i + 1 == path.len() && (i == 0 || !material.is_empty()))
.then(|| breaks.final_fill.unwrap_or_else(|| parameters[&Parameter::Parfillskip].glue()));
if directions {
// Keep a real breakpoint marker before the synthetic line closers.
super::direction::line(&mut material, &mut direction_stack);
@@ -1456,7 +1551,7 @@ pub(super) fn finish(
&material,
&parameters,
dimensions,
keep_par_fill,
par_fill,
terminal_marker,
ends_in_pre_break,
&direction_stack,