Support hang indentation and parshape measures

This commit is contained in:
gloamxun committed 2026-10-23 01:18:19 +08:00
1 parent 24a96d1c7c
commit 8993186005
7 files changed
+269 -88

No files matched your search

+171 -62
View File
@@ -74,6 +74,17 @@ pub struct ParagraphStyle {
pub left_skip: i64,
/// Right skip reserved at the end of every line (`\rightskip`).
pub right_skip: i64,
/// Extra indentation for hanging lines (`\hangindent`); negative values
/// indent the right margin instead.
#[serde(default)]
pub hang_indent: i64,
/// First hanging line (`\hangafter`): non-negative N applies from line
/// N+1 on, negative -N applies to the first N lines.
#[serde(default)]
pub hang_after: i32,
/// Explicit `(indent, width)` pairs for `\parshape`.
#[serde(default)]
pub par_shape: Vec<(i64, i64)>,
/// Center each line in the measure instead of justifying it.
#[serde(default)]
pub centered: bool,
@@ -124,12 +135,61 @@ pub struct ParagraphStyle {
pub space_shrink: i64,
}
impl ParagraphStyle {
/// `(indent, measure)` for a zero-based line number, honouring
/// `\parshape` and `\hangindent`/`\hangafter`.
pub fn line_geometry(&self, line: usize) -> (i64, i64) {
if !self.par_shape.is_empty() {
let (indent, width) = if line < self.par_shape.len() {
self.par_shape[line]
} else {
*self.par_shape.last().expect("parshape")
};
return (indent, width.max(1));
}
if self.hang_indent != 0 {
let hangs = if self.hang_after >= 0 {
line >= self.hang_after as usize
} else {
line < (-self.hang_after) as usize
};
if hangs {
return if self.hang_indent > 0 {
(
self.hang_indent,
(self.line_width - self.hang_indent).max(1),
)
} else {
(0, (self.line_width + self.hang_indent).max(1))
};
}
}
(0, self.line_width)
}
fn par_indent_for(&self, line: usize) -> i64 {
if line == 0 && self.par_shape.is_empty() {
self.par_indent
} else {
0
}
}
fn line_target(&self, line: usize) -> i64 {
let (_, width) = self.line_geometry(line);
(width - self.left_skip - self.right_skip).max(1) - self.par_indent_for(line)
}
}
impl Default for ParagraphStyle {
fn default() -> Self {
Self {
line_width: 400,
left_skip: 0,
right_skip: 0,
hang_indent: 0,
hang_after: 1,
par_shape: Vec::new(),
centered: false,
right_aligned: false,
par_indent: 0,
@@ -177,6 +237,9 @@ pub struct Paragraph {
pub font: ParagraphFont,
#[serde(default)]
pub left_skip: i64,
/// Left offset for each line, from `\hangindent`/`\parshape`.
#[serde(default)]
pub line_indents: Vec<i64>,
#[serde(default)]
pub centered: bool,
#[serde(default)]
@@ -240,6 +303,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
width: 0,
font: ParagraphFont::Roman,
left_skip: style.left_skip,
line_indents: Vec::new(),
centered: style.centered,
right_aligned: style.right_aligned,
};
@@ -271,6 +335,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
cost: i64,
previous: usize,
previous_state: usize,
line: usize,
}
let count = breakpoints.len();
let mut solution: Option<Vec<(usize, usize)>> = None;
@@ -286,11 +351,14 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
};
let extra_stretch = if pass == 2 { style.emergencystretch } else { 0 };
// State = fitness * 2 + whether the previous line was hyphenated.
// A candidate also records its zero-based line number so that
// \parshape and \hangindent can give each line its own measure.
let mut best: Vec<[Option<Candidate>; 8]> = vec![[None; 8]; count];
best[0][2] = Some(Candidate {
cost: 0,
previous: 0,
previous_state: 2,
line: 0,
});
for end_index in 1..count {
let end = breakpoints[end_index];
@@ -320,8 +388,6 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
stretch: stretch_amount,
shrink: shrink_amount,
} => {
// A break at glue discards that glue: the line ends
// before it, exactly as TeX's line breaker does.
if start + offset + 1 == end {
continue;
}
@@ -334,11 +400,11 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
pre_break_width,
no_break_width,
} => {
if start + offset + 1 == end {
natural += *pre_break_width;
natural += if start + offset + 1 == end {
*pre_break_width
} else {
natural += *no_break_width;
}
*no_break_width
};
}
}
}
@@ -360,58 +426,53 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
style.hyphen_penalty
};
}
let target = (style.line_width - style.left_skip - style.right_skip).max(1)
- if start_index == 0 {
style.par_indent
} else {
0
};
let stretch = stretch + extra_stretch;
let (ratio, badness) = if natural < target {
if stretch > 0 {
let ratio = (target - natural) as f64 / stretch as f64;
(ratio, (100.0 * ratio.powi(3)).round().min(10_000.0) as i64)
} else {
(1.0, 10_000)
}
} else if natural > target {
if shrink > 0 {
let ratio = (natural - target) as f64 / shrink as f64;
(ratio, (100.0 * ratio.powi(3)).round().min(10_000.0) as i64)
} else {
(1.0, 10_000)
}
} else {
(0.0, 0)
};
// TeX's final line has \parfillskip's infinite stretch.
let badness = if is_last && natural <= target {
0
} else {
badness
};
if badness > limit {
continue;
}
let fitness = if ratio < -0.5 {
0
} else if ratio <= 0.5 {
1
} else if ratio <= 1.0 {
2
} else {
3
};
let fitness = if natural < target && stretch == 0 {
3
} else {
fitness
};
let state = fitness * 2 + usize::from(hyphen_break);
for previous_state in 0..8 {
let Some(node) = best[start_index][previous_state] else {
continue;
};
let target = style.line_target(node.line);
let stretch = stretch + extra_stretch;
let (ratio, badness) = if natural < target {
if stretch > 0 {
let ratio = (target - natural) as f64 / stretch as f64;
(ratio, (100.0 * ratio.powi(3)).round().min(10_000.0) as i64)
} else {
(1.0, 10_000)
}
} else if natural > target {
if shrink > 0 {
let ratio = (natural - target) as f64 / shrink as f64;
(ratio, (100.0 * ratio.powi(3)).round().min(10_000.0) as i64)
} else {
(1.0, 10_000)
}
} else {
(0.0, 0)
};
// TeX's final line has \parfillskip's infinite stretch.
let badness = if is_last && natural <= target {
0
} else {
badness
};
if badness > limit {
continue;
}
let fitness = if ratio < -0.5 {
0
} else if ratio <= 0.5 {
1
} else if ratio <= 1.0 {
2
} else {
3
};
let fitness = if natural < target && stretch == 0 {
3
} else {
fitness
};
let state = fitness * 2 + usize::from(hyphen_break);
let previous_fitness = previous_state / 2;
let mut demerits = (style.line_penalty + badness).pow(2);
if trailing_penalty >= 0 {
@@ -431,12 +492,14 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
}
}
let cost = node.cost.saturating_add(demerits);
let line = node.line + 1;
let entry = &mut best[end_index][state];
if entry.map_or(true, |current| cost < current.cost) {
*entry = Some(Candidate {
cost,
previous: start_index,
previous_state,
line,
});
}
}
@@ -467,12 +530,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
let mut greedy = Vec::new();
let mut start_index = 0;
while start_index + 1 < count {
let target = (style.line_width - style.left_skip - style.right_skip).max(1)
- if start_index == 0 {
style.par_indent
} else {
0
};
let target = style.line_target(greedy.len());
let mut feasible = None;
let mut overflow = None;
for end_index in start_index + 1..count {
@@ -605,8 +663,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
// Bake the justification into the line: TeX distributes the
// difference between the natural width and the measure across the
// glue, so the shipped line (and therefore the PDF) is flush.
let target = (style.line_width - style.left_skip - style.right_skip).max(1)
- if line_index == 0 { style.par_indent } else { 0 };
let target = style.line_target(line_index);
let (mut natural, mut stretch, mut shrink) = (0_i64, 0_i64, 0_i64);
for item in &line {
match item {
@@ -695,12 +752,16 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
max_width = max_width.max(width + italic);
lines.push(line);
}
let line_indents: Vec<i64> = (0..lines.len())
.map(|line| style.line_geometry(line).0 + style.par_indent_for(line))
.collect();
Paragraph {
height: lines.len() as i64 * style.line_height,
width: max_width,
lines,
font: ParagraphFont::Roman,
left_skip: style.left_skip,
line_indents,
centered: style.centered,
right_aligned: style.right_aligned,
}
@@ -1145,6 +1206,54 @@ mod tests {
let full_lines = layout_paragraph(text, &full).lines.len();
assert!(narrow_lines > full_lines);
}
#[test]
fn hang_geometry_applies_after_hang_after() {
let positive = ParagraphStyle {
line_width: 100,
hang_indent: 20,
hang_after: 1,
..ParagraphStyle::default()
};
assert_eq!(positive.line_geometry(0), (0, 100));
assert_eq!(positive.line_geometry(1), (20, 80));
assert_eq!(positive.line_target(1), 80);
let negative = ParagraphStyle {
line_width: 100,
hang_indent: 20,
hang_after: -2,
..ParagraphStyle::default()
};
assert_eq!(negative.line_geometry(0), (20, 80));
assert_eq!(negative.line_geometry(1), (20, 80));
assert_eq!(negative.line_geometry(2), (0, 100));
}
#[test]
fn parshape_overrides_the_measure_and_repeats_the_last_pair() {
let style = ParagraphStyle {
line_width: 400,
par_shape: vec![(0, 100), (20, 80)],
..ParagraphStyle::default()
};
assert_eq!(style.line_geometry(0), (0, 100));
assert_eq!(style.line_geometry(1), (20, 80));
assert_eq!(style.line_geometry(2), (20, 80));
assert_eq!(style.line_target(1), 80);
}
#[test]
fn parshape_offsets_paragraph_lines() {
let style = ParagraphStyle {
line_width: 80,
par_shape: vec![(0, 80), (30, 80)],
..ParagraphStyle::default()
};
let paragraph = layout_paragraph("aa bb cc dd ee ff gg hh ii", &style);
assert_eq!(paragraph.line_count(), 3);
assert_eq!(paragraph.line_indents, vec![0, 30, 30]);
}
#[test]
fn empty_paragraph_has_no_lines() {
assert_eq!(layout_paragraph("", &ParagraphStyle::default()).height, 0);
+5 -4
View File
@@ -409,7 +409,8 @@ impl Page {
let lines = paragraph.lines.len().max(1) as i64;
let line_height = (paragraph.height / lines).max(1);
let size = 10 * 65_536;
for line in &paragraph.lines {
for (line_index, line) in paragraph.lines.iter().enumerate() {
let indent = paragraph.line_indents.get(line_index).copied().unwrap_or(0);
let baseline = y + ((line_height as f64) * 0.8) as i64;
let natural: i64 = line
.iter()
@@ -421,11 +422,11 @@ impl Page {
})
.sum();
let mut x = if paragraph.centered {
paragraph.left_skip + ((paragraph.width - natural) / 2).max(0)
paragraph.left_skip + indent + ((paragraph.width - natural) / 2).max(0)
} else if paragraph.right_aligned {
paragraph.left_skip + (paragraph.width - natural).max(0)
paragraph.left_skip + indent + (paragraph.width - natural).max(0)
} else {
paragraph.left_skip
paragraph.left_skip + indent
};
for item in line {
match item {