Files
texrra-engine/crates/texrra-tex-core/src/paragraph.rs
T

2062 lines
75 KiB
Rust
Executable File

use serde::{Deserialize, Serialize};
/// A horizontal box in scaled points (1/65536 pt).
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct HorizontalBox {
pub width: i64,
pub height: i64,
pub depth: i64,
/// The source character when this box came from text, for display lists.
pub character: Option<char>,
/// TeX italic correction in scaled points.
#[serde(default)]
pub italic: i64,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum HorizontalItem {
Box(HorizontalBox),
Glue {
width: i64,
stretch: i64,
shrink: i64,
/// TeX glue order: 0 normal, 1 fil, 2 fill, 3 filll.
#[serde(default)]
order: u8,
},
Penalty {
width: i64,
penalty: i64,
flagged: bool,
},
/// A possible hyphenation point. `pre_break_width` is the hyphen width
/// added when the line breaks here; `no_break_width` is the material kept
/// when it does not break.
Discretionary {
pre_break_width: i64,
no_break_width: i64,
},
}
fn default_pretolerance() -> i64 {
100
}
fn default_tolerance() -> i64 {
200
}
fn default_hyphen_penalty() -> i64 {
50
}
fn default_ex_hyphen_penalty() -> i64 {
50
}
fn default_double_hyphen_demerits() -> i64 {
10_000
}
fn default_final_hyphen_demerits() -> i64 {
5_000
}
fn default_line_penalty() -> i64 {
10
}
fn default_adj_demerits() -> i64 {
10_000
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ParagraphStyle {
pub line_width: i64,
/// Left skip inserted before every line (`\leftskip`).
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)>,
/// `\parfillskip` width, inserted before the paragraph's final break.
#[serde(default)]
pub par_fillskip: i64,
/// Finite stretch of `\parfillskip`.
#[serde(default)]
pub par_fillskip_stretch: i64,
/// Whether `\parfillskip` ends in `fil` glue (the TeX default).
#[serde(default = "default_par_fillskip_fil")]
pub par_fillskip_fil: bool,
/// `\frenchspacing`: every character gets space factor 1000, so
/// punctuation adds no sentence spacing.
#[serde(default)]
pub frenchspacing: bool,
/// Per-character `\sfcode` overrides (the last matching assignment wins).
/// A code of zero leaves the previous space factor unchanged, as in TeX.
#[serde(default)]
pub space_factor_codes: Vec<(char, i64)>,
/// TeX `\baselineskip` (12pt for 10pt text).
#[serde(default = "default_baselineskip")]
pub baselineskip: i64,
/// TeX `\lineskip`, used when `\baselineskip` would be too tight.
#[serde(default = "default_lineskip")]
pub lineskip: i64,
/// TeX `\lineskiplimit`: below this interline distance use `\lineskip`.
#[serde(default)]
pub lineskiplimit: i64,
/// Center each line in the measure instead of justifying it.
#[serde(default)]
pub centered: bool,
#[serde(default)]
pub right_aligned: bool,
/// Ragged-right setting (`\raggedright`): lines keep their natural width
/// and the missing space is absorbed by an infinite `\rightskip`.
#[serde(default)]
pub ragged_right: bool,
pub par_indent: i64,
/// Extra stretch added to every line when TeX's emergency pass runs
/// (`\emergencystretch`).
#[serde(default)]
pub emergencystretch: i64,
/// Badness bound for the first pass, which never hyphenates
/// (`\pretolerance`).
#[serde(default = "default_pretolerance")]
pub pretolerance: i64,
/// Badness bound for the second pass (`\tolerance`).
#[serde(default = "default_tolerance")]
pub tolerance: i64,
/// Demerits charged when a line breaks at a hyphenation point
/// (`\hyphenpenalty`); values of 10000 or more disable hyphenation.
#[serde(default = "default_hyphen_penalty")]
pub hyphen_penalty: i64,
/// Demerits charged when a line breaks after an explicit hyphen
/// (`\exhyphenpenalty`).
#[serde(default = "default_ex_hyphen_penalty")]
pub ex_hyphen_penalty: i64,
/// Additional demerits when two consecutive lines are hyphenated
/// (`\doublehyphendemerits`).
#[serde(default = "default_double_hyphen_demerits")]
pub double_hyphen_demerits: i64,
/// Additional demerits when the second-to-last line is hyphenated
/// (`\finalhyphendemerits`).
#[serde(default = "default_final_hyphen_demerits")]
pub final_hyphen_demerits: i64,
/// Base demerits charged for every line (`\linepenalty`).
#[serde(default = "default_line_penalty")]
pub line_penalty: i64,
/// Extra demerits when adjacent lines' fitness classes differ by more
/// than one (`\adjdemerits`).
#[serde(default = "default_adj_demerits")]
pub adj_demerits: i64,
/// Hyphenation exceptions in TeX syntax (`\hyphenation{hy-phen-a-tion}`).
#[serde(default)]
pub hyphenation_exceptions: Vec<String>,
pub line_height: i64,
pub char_width: i64,
pub space_width: i64,
pub space_stretch: i64,
pub space_shrink: i64,
/// TeX `\spaceskip`: explicit interword glue `(width, stretch, shrink)`
/// that replaces the font glue when set.
#[serde(default)]
pub space_skip: Option<(i64, i64, i64)>,
/// TeX `\xspaceskip`: glue used instead of `\spaceskip` once the space
/// factor reaches 2000.
#[serde(default)]
pub xspace_skip: Option<(i64, i64, i64)>,
}
fn default_par_fillskip_fil() -> bool {
true
}
fn default_baselineskip() -> i64 {
12 * 65_536
}
fn default_lineskip() -> i64 {
65_536
}
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(),
par_fillskip: 0,
par_fillskip_stretch: 0,
par_fillskip_fil: true,
frenchspacing: false,
space_factor_codes: Vec::new(),
baselineskip: 12 * 65_536,
lineskip: 65_536,
lineskiplimit: 0,
centered: false,
right_aligned: false,
ragged_right: false,
par_indent: 0,
emergencystretch: 0,
pretolerance: 100,
tolerance: 200,
hyphen_penalty: 50,
ex_hyphen_penalty: 50,
double_hyphen_demerits: 10_000,
final_hyphen_demerits: 5_000,
line_penalty: 10,
adj_demerits: 10_000,
hyphenation_exceptions: Vec::new(),
line_height: 12,
char_width: 10,
space_width: 4,
space_stretch: 6,
space_shrink: 2,
space_skip: None,
xspace_skip: None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ParagraphFont {
Roman,
Bold,
Italic,
Mono,
Sans,
}
impl Default for ParagraphFont {
fn default() -> Self {
Self::Roman
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct Paragraph {
pub lines: Vec<Vec<HorizontalItem>>,
pub height: i64,
pub width: i64,
#[serde(default)]
pub font: ParagraphFont,
#[serde(default)]
pub left_skip: i64,
/// Left offset for each line, from `\hangindent`/`\parshape`.
#[serde(default)]
pub line_indents: Vec<i64>,
/// Baseline of each line relative to the top of the paragraph box.
#[serde(default)]
pub line_baselines: Vec<i64>,
#[serde(default)]
pub centered: bool,
#[serde(default)]
pub right_aligned: bool,
}
impl Paragraph {
pub fn line_count(&self) -> usize {
self.lines.len()
}
/// Move every line after `lines` into a new paragraph that starts at the
/// remaining baselines. Used to continue a paragraph on the next page.
pub fn split_at(&mut self, lines: usize) -> Paragraph {
let lines = lines.min(self.lines.len().saturating_sub(1));
let total = self.lines.len().max(1) as i64;
let line_height = (self.height / total).max(1);
let head_height = line_height * lines as i64;
let tail_lines = self.lines.split_off(lines);
let tail_indents = if self.line_indents.len() > lines {
self.line_indents.split_off(lines)
} else {
Vec::new()
};
let tail_baselines = if self.line_baselines.len() > lines {
self.line_baselines
.split_off(lines)
.into_iter()
.map(|baseline| baseline - head_height)
.collect()
} else {
Vec::new()
};
let tail_height = (self.height - head_height).max(1);
self.height = head_height;
Paragraph {
lines: tail_lines,
height: tail_height,
width: self.width,
font: self.font,
left_skip: self.left_skip,
line_indents: tail_indents,
line_baselines: tail_baselines,
centered: self.centered,
right_aligned: self.right_aligned,
}
}
}
/// Convert text into a horizontal item stream: one box per character, one
/// glue per space, and a final penalty.
pub fn text_items(text: &str, style: &ParagraphStyle) -> Vec<HorizontalItem> {
let mut items = Vec::new();
for character in text.chars() {
if character.is_whitespace() {
if !matches!(items.last(), Some(HorizontalItem::Glue { .. })) {
items.push(HorizontalItem::Glue {
width: style.space_width,
stretch: style.space_stretch,
shrink: style.space_shrink,
order: 0,
});
}
} else {
items.push(HorizontalItem::Box(HorizontalBox {
width: style.char_width,
height: style.line_height,
depth: 0,
character: Some(character),
italic: 0,
}));
}
}
while matches!(items.last(), Some(HorizontalItem::Glue { .. })) {
items.pop();
}
items.push(HorizontalItem::Penalty {
width: 0,
penalty: 10_000,
flagged: false,
});
items
}
/// M1 paragraph builder over a horizontal item stream.
///
/// Breakpoints are the ends of glue/penalty items. The cost model uses the
/// available glue stretch/shrink; overfull lines are allowed with an explicit
/// penalty so a single long word still produces output.
pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragraph {
if items.is_empty()
|| !items
.iter()
.any(|item| matches!(item, HorizontalItem::Box(_)))
{
return Paragraph {
lines: Vec::new(),
height: 0,
width: 0,
font: ParagraphFont::Roman,
left_skip: style.left_skip,
line_indents: Vec::new(),
line_baselines: Vec::new(),
centered: style.centered,
right_aligned: style.right_aligned,
};
}
let mut breakpoints = vec![0_usize];
for (index, item) in items.iter().enumerate() {
match item {
HorizontalItem::Glue { .. } => breakpoints.push(index + 1),
HorizontalItem::Penalty { penalty, .. } if *penalty < 10_000 => {
breakpoints.push(index + 1)
}
HorizontalItem::Discretionary { .. } => breakpoints.push(index + 1),
_ => {}
}
}
if breakpoints.last().copied() != Some(items.len()) {
breakpoints.push(items.len());
}
breakpoints.dedup();
// TeX's line breaker: demerits over badness, break penalties and fitness
// changes. Pass 0 uses \pretolerance without hyphenation, pass 1 uses
// \tolerance, and the emergency pass only exists when \emergencystretch is
// positive. With zero emergencystretch TeX gives up and falls back to
// filling each line up to the first break at or past the measure, which is
// what produces the familiar overfull boxes.
#[derive(Clone, Copy)]
struct Candidate {
cost: i64,
previous: usize,
previous_state: usize,
line: usize,
}
let count = breakpoints.len();
let mut solution: Option<Vec<(usize, usize)>> = None;
// TeX's emergency pass only exists when \emergencystretch is positive.
// With zero emergencystretch TeX gives up and falls back to a first-fit
// scan, which is what produces the familiar overfull boxes.
let passes = if style.emergencystretch > 0 { 3 } else { 2 };
for pass in 0..passes {
let limit = match pass {
0 => style.pretolerance,
1 => style.tolerance,
_ => 10_000,
};
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];
let is_last = end == items.len();
let hyphen_break = matches!(items[end - 1], HorizontalItem::Discretionary { .. });
if hyphen_break && (pass == 0 || style.hyphen_penalty >= 10_000) {
continue;
}
for start_index in 0..end_index {
let start = breakpoints[start_index];
if start >= end {
continue;
}
let mut natural = 0_i64;
let mut stretch = 0_i64;
let mut shrink = 0_i64;
let mut stretch_by_order = [0_i64; 4];
let mut has_box = false;
let mut trailing_penalty = 0_i64;
for (offset, item) in items[start..end].iter().enumerate() {
match item {
HorizontalItem::Box(box_item) => {
natural += box_item.width;
has_box = true;
}
HorizontalItem::Glue {
width,
stretch: stretch_amount,
shrink: shrink_amount,
order,
..
} => {
if start + offset + 1 == end {
continue;
}
natural += *width;
shrink += *shrink_amount;
match *order {
0 => stretch += *stretch_amount,
order => stretch_by_order[order as usize] += *stretch_amount,
}
}
HorizontalItem::Penalty { penalty, .. } => trailing_penalty = *penalty,
HorizontalItem::Discretionary {
pre_break_width,
no_break_width,
} => {
natural += if start + offset + 1 == end {
*pre_break_width
} else {
*no_break_width
};
}
}
}
if !has_box {
continue;
}
if is_last {
trailing_penalty = 0;
if !style.par_fillskip_fil {
natural += style.par_fillskip;
stretch += style.par_fillskip_stretch;
}
} else if hyphen_break {
// TeX charges \exhyphenpenalty after an explicit hyphen
// and \hyphenpenalty at an inserted hyphenation point.
trailing_penalty = if end >= 2
&& matches!(
&items[end - 2],
HorizontalItem::Box(box_item) if box_item.character == Some('-')
) {
style.ex_hyphen_penalty
} else {
style.hyphen_penalty
};
}
for previous_state in 0..8 {
let Some(node) = best[start_index][previous_state] else {
continue;
};
let target = style.line_target(node.line);
let infinite_order = (1..4).rev().find(|order| stretch_by_order[*order] > 0);
let stretch = stretch + extra_stretch;
let (mut ratio, mut badness) = if natural < target {
if infinite_order.is_some() {
(0.0, 0)
} else 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)
};
// \raggedright puts an infinite `fil` in \rightskip, so
// any line that fits has zero badness and natural glue.
if style.ragged_right && natural <= target {
ratio = 0.0;
badness = 0;
}
// TeX's default final line has \parfillskip's infinite
// stretch; without fil the last line is set like any other.
let badness = if is_last && style.par_fillskip_fil && natural <= target {
0
} else {
badness
};
// A line that cannot fit even after shrinking its glue is
// overfull. TeX only admits such lines in the emergency
// pass, no matter how large \tolerance is.
let overfull = natural > target && natural - target > shrink;
if overfull && pass != 2 {
continue;
}
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 && infinite_order.is_none() {
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 {
demerits = demerits.saturating_add(trailing_penalty.pow(2));
} else {
demerits = demerits.saturating_sub(trailing_penalty.pow(2));
}
if (fitness as i64 - previous_fitness as i64).abs() > 1 {
demerits = demerits.saturating_add(style.adj_demerits);
}
if hyphen_break {
if previous_state % 2 == 1 {
demerits = demerits.saturating_add(style.double_hyphen_demerits);
}
if end_index + 1 == count - 1 {
demerits = demerits.saturating_add(style.final_hyphen_demerits);
}
}
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,
});
}
}
}
}
let final_index = count - 1;
let winner = (0..8)
.filter_map(|state| best[final_index][state].map(|node| (node.cost, state)))
.min();
if let Some((_, mut state)) = winner {
let mut ranges = Vec::new();
let mut end_index = final_index;
while end_index > 0 {
let node = best[end_index][state].expect("chosen line");
ranges.push((breakpoints[node.previous], breakpoints[end_index]));
end_index = node.previous;
state = node.previous_state;
}
solution = Some(ranges);
break;
}
}
// With an infinite `fil` in `\rightskip` every line that fits has zero
// badness, so TeX fills each line greedily; the demerits search would
// instead pick the shortest first line among the equal-cost solutions.
if style.ragged_right {
solution = None;
}
let mut ranges = solution.unwrap_or_else(|| {
// TeX's final pass forces an overfull break only as a last resort.
// Emulate that choice: take the longest prefix that still satisfies
// \tolerance, and fall back to the first prefix that overflows the
// measure when no feasible line exists.
let mut greedy = Vec::new();
let mut start_index = 0;
while start_index + 1 < count {
let target = style.line_target(greedy.len());
let mut feasible = None;
let mut overflow = None;
for end_index in start_index + 1..count {
let start = breakpoints[start_index];
let end = breakpoints[end_index];
if start >= end {
continue;
}
if style.hyphen_penalty >= 10_000
&& matches!(items[end - 1], HorizontalItem::Discretionary { .. })
{
continue;
}
let mut natural = 0_i64;
let mut stretch = 0_i64;
let mut shrink = 0_i64;
let mut stretch_by_order = [0_i64; 4];
let mut has_box = false;
for (offset, item) in items[start..end].iter().enumerate() {
let last_item = start + offset + 1 == end;
match item {
HorizontalItem::Box(box_item) => {
natural += box_item.width;
has_box = true;
}
HorizontalItem::Glue {
width,
stretch: stretch_amount,
shrink: shrink_amount,
order,
..
} => {
if last_item {
continue;
}
natural += *width;
shrink += *shrink_amount;
match *order {
0 => stretch += *stretch_amount,
order => stretch_by_order[order as usize] += *stretch_amount,
}
}
HorizontalItem::Penalty { .. } => {}
HorizontalItem::Discretionary {
pre_break_width,
no_break_width,
} => {
natural += if last_item {
*pre_break_width
} else {
*no_break_width
};
}
}
}
if !has_box {
continue;
}
let final_line = end == items.len();
if final_line && !style.par_fillskip_fil {
natural += style.par_fillskip;
stretch += style.par_fillskip_stretch;
}
if overflow.is_none() && natural >= target {
overflow = Some(end_index);
}
let infinite_order = (1..4).rev().find(|order| stretch_by_order[*order] > 0);
let mut badness = if final_line && style.par_fillskip_fil && natural <= target {
0
} else if natural < target {
if infinite_order.is_some() {
0
} else if stretch > 0 {
(100.0 * ((target - natural) as f64 / stretch as f64).powi(3))
.round()
.min(10_000.0) as i64
} else {
10_000
}
} else if shrink > 0 {
(100.0 * ((natural - target) as f64 / shrink as f64).powi(3))
.round()
.min(10_000.0) as i64
} else {
10_000
};
if style.ragged_right && natural <= target {
badness = 0;
}
if badness <= style.tolerance {
feasible = Some(end_index);
}
}
// When hyphenation is forbidden TeX's fallback keeps filling to
// the first break at or past the measure instead of stopping at a
// loose-but-feasible line.
let chosen = if style.hyphen_penalty >= 10_000 {
overflow.or(feasible).unwrap_or(count - 1)
} else {
feasible.or(overflow).unwrap_or(count - 1)
};
greedy.push((breakpoints[start_index], breakpoints[chosen]));
start_index = chosen;
}
greedy.reverse();
greedy
});
ranges.reverse();
let mut lines = Vec::with_capacity(ranges.len());
let mut max_width = 0;
let line_count = ranges.len();
for (line_index, (start, end)) in ranges.into_iter().enumerate() {
let mut line: Vec<HorizontalItem> = Vec::new();
for (index, item) in items[start..end].iter().enumerate() {
match item {
HorizontalItem::Discretionary {
pre_break_width,
no_break_width,
} => {
if start + index + 1 == end {
line.push(HorizontalItem::Box(HorizontalBox {
width: *pre_break_width,
height: style.line_height,
depth: 0,
character: Some('-'),
italic: 0,
}));
} else if *no_break_width > 0 {
line.push(HorizontalItem::Box(HorizontalBox {
width: *no_break_width,
height: style.line_height,
depth: 0,
character: None,
italic: 0,
}));
}
}
_ => line.push(item.clone()),
}
}
while matches!(
line.last(),
Some(HorizontalItem::Glue { .. } | HorizontalItem::Penalty { .. })
) {
line.pop();
}
// 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_target(line_index);
let (mut natural, mut stretch, mut shrink) = (0_i64, 0_i64, 0_i64);
let mut stretch_by_order = [0_i64; 4];
for item in &line {
match item {
HorizontalItem::Box(box_item) => natural += box_item.width,
HorizontalItem::Glue {
width,
stretch: stretch_amount,
shrink: shrink_amount,
order,
..
} => {
natural += *width;
shrink += *shrink_amount;
match *order {
0 => stretch += *stretch_amount,
order => stretch_by_order[order as usize] += *stretch_amount,
}
}
HorizontalItem::Penalty { width, .. } => natural += *width,
HorizontalItem::Discretionary { .. } => {}
}
}
let is_last = line_index + 1 == line_count;
let fillskip = if is_last && !style.par_fillskip_fil {
style.par_fillskip
} else {
0
};
let fillskip_stretch = if is_last && !style.par_fillskip_fil {
style.par_fillskip_stretch
} else {
0
};
natural += fillskip;
stretch += fillskip_stretch;
// TeX can stretch normal glue past its nominal stretch (badness
// simply exceeds 100), but it never shrinks past the declared
// shrink: an overfull line keeps its overflow instead of pulling
// glue beyond its limits. A final line with a `fil` parfillskip only
// shrinks: the infinite stretch absorbs any shortfall, so only a
// line wider than the measure adjusts its finite glue.
let delta = if style.ragged_right {
(target - natural).min(0).max(-shrink)
} else {
(target - natural).max(-shrink)
};
let infinite_order = (1..4).rev().find(|order| stretch_by_order[*order] > 0);
let chosen_order = infinite_order.unwrap_or(0);
let chosen_stretch = if chosen_order == 0 {
stretch
} else {
stretch_by_order[chosen_order as usize]
};
if delta > 0 {
if !is_last || !style.par_fillskip_fil || infinite_order.is_some() {
let mut remaining = delta;
for item in &mut line {
if let HorizontalItem::Glue {
width,
stretch: stretch_amount,
order,
..
} = item
&& *order == chosen_order as u8
&& *stretch_amount > 0
&& chosen_stretch > 0
{
let share = delta * *stretch_amount / chosen_stretch;
*width += share;
remaining -= share;
}
}
if remaining != 0
&& let Some(HorizontalItem::Glue { width, .. }) = line
.iter_mut()
.rev()
.find(|item| matches!(item, HorizontalItem::Glue { .. }))
{
*width += remaining;
}
}
} else if delta < 0 {
let mut remaining = delta;
for item in &mut line {
if let HorizontalItem::Glue {
width,
shrink: shrink_amount,
..
} = item
&& *shrink_amount > 0
{
let share = delta * *shrink_amount / shrink;
*width += share;
remaining -= share;
}
}
if remaining != 0
&& let Some(HorizontalItem::Glue { width, .. }) = line
.iter_mut()
.rev()
.find(|item| matches!(item, HorizontalItem::Glue { .. }))
{
*width += remaining;
}
}
let width: i64 = line
.iter()
.map(|item| match item {
HorizontalItem::Box(box_item) => box_item.width,
HorizontalItem::Glue { width, .. } => *width,
HorizontalItem::Penalty { width, .. } => *width,
HorizontalItem::Discretionary { .. } => 0,
})
.sum();
let italic = match line.last() {
Some(HorizontalItem::Box(box_item)) => box_item.italic,
_ => 0,
};
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();
let extents: Vec<(i64, i64)> = lines.iter().map(|line| line_extent(line)).collect();
let mut line_baselines = Vec::with_capacity(extents.len());
if let Some((first_ascent, _)) = extents.first().copied() {
let mut baseline = first_ascent;
line_baselines.push(baseline);
for index in 1..extents.len() {
let (ascent, _) = extents[index];
let (_, previous_descent) = extents[index - 1];
let natural = style.baselineskip - previous_descent - ascent;
let distance = if natural >= style.lineskiplimit {
style.baselineskip
} else {
previous_descent + ascent + style.lineskip
};
baseline += distance;
line_baselines.push(baseline);
}
}
Paragraph {
// The page builder still budgets paragraphs on the line grid; the
// baseline table below carries TeX's interline glue for painting.
height: lines.len() as i64 * style.line_height,
width: max_width,
lines,
font: ParagraphFont::Roman,
left_skip: style.left_skip,
line_indents,
line_baselines,
centered: style.centered,
right_aligned: style.right_aligned,
}
}
/// `(ascent, descent)` of the tallest box on a line.
fn line_extent(line: &[HorizontalItem]) -> (i64, i64) {
let mut ascent = 0;
let mut descent = 0;
for item in line {
if let HorizontalItem::Box(box_) = item {
ascent = ascent.max(box_.height);
descent = descent.max(box_.depth);
}
}
(ascent, descent)
}
/// TeX Live's American English hyphenation patterns (`hyph-en-us`, 2005),
/// which are what pdfLaTeX loads for `\language` 0 with the `english` option.
/// The vendored plain-TeX patterns differ (for example `kappa`), so route-D
/// uses the same data as the reference implementation.
const HYPHENATION_PATTERNS: &str = include_str!("../assets/hyph-en-us-patterns.txt");
const HYPHENATION_EXCEPTIONS: &str = include_str!("../assets/hyph-en-us-exceptions.txt");
/// Convert text using TFM character widths and fontdimen glue parameters.
pub fn text_items_with_font(
text: &str,
style: &ParagraphStyle,
font: &crate::cmr10::Cmr10Metrics,
) -> Vec<HorizontalItem> {
let mut items = Vec::new();
let mut hyphenator = hyphenate::Hyphenator::default();
hyphenator.load_patterns(HYPHENATION_PATTERNS);
let mut exceptions = String::from(HYPHENATION_EXCEPTIONS);
for exception in &style.hyphenation_exceptions {
exceptions.push('\n');
exceptions.push_str(exception);
}
hyphenator.insert_exceptions(&exceptions);
let caser = hyphenate::AsciiLowerCaser::default();
// TeX's text fonts turn runs of hyphens into en/em dashes. cmr10's TFM
// does not carry these ligatures, so apply the same mapping before
// shaping the paragraph.
let text = text.replace("---", "\u{2014}").replace("--", "\u{2013}");
let words: Vec<&str> = text.split_whitespace().collect();
let mut previous_box: Option<usize> = None;
let mut previous_character: Option<char> = None;
// TeX's space factor starts at 1000 and is updated by each character's
// `\sfcode`; it scales the next interword glue (and adds `\fontdimen7`
// once it reaches 2000).
let mut space_factor = 1000_i64;
let mut after_control_word = false;
for (word_index, word) in words.iter().enumerate() {
if word_index > 0 && !after_control_word {
let factor = space_factor.max(1000);
// TeX's `\spaceskip`/`\xspaceskip` replace the font's interword
// glue; the space factor still scales stretch and shrink, and
// `\fontdimen7` is still added from factor 2000 on.
// TeX uses `\xspaceskip` verbatim once the space factor reaches
// 2000 (pdfTeX dumps it as 8.0 plus 4.0 minus 2.0 even at 3000).
// `\spaceskip` keeps its width but its stretch/shrink are scaled
// by the space factor like normal font glue; fontdimen7 is never
// added when an explicit skip is in force.
let (width, stretch, shrink) = if factor >= 2000
&& let Some((width, stretch, shrink)) = style.xspace_skip
{
(width, stretch, shrink)
} else if let Some((width, stretch, shrink)) = style.space_skip {
(width, stretch * factor / 1000, shrink * 1000 / factor)
} else {
(
font.space()
+ if factor >= 2000 {
font.extra_space()
} else {
0
},
font.stretch() * factor / 1000,
font.shrink() * 1000 / factor,
)
};
items.push(HorizontalItem::Glue {
width,
stretch,
shrink,
order: 0,
});
// TeX never kerns across interword glue.
previous_box = None;
previous_character = None;
}
if matches!(*word, "\\hfill" | "\\hfil") {
items.push(HorizontalItem::Glue {
width: 0,
stretch: 1,
shrink: 0,
order: if *word == "\\hfill" { 2 } else { 1 },
});
previous_box = None;
previous_character = None;
after_control_word = true;
continue;
}
after_control_word = false;
let original: Vec<char> = word.chars().collect();
// TeX hyphenates the letter run of a word: leading or trailing
// punctuation stays on the word and does not suppress the pattern
// lookup (for example `epsilon:` can still break as `ep-`).
let lead = original
.iter()
.take_while(|character| !character.is_ascii_alphabetic())
.count();
let trail = original
.iter()
.rev()
.take_while(|character| !character.is_ascii_alphabetic())
.count();
let core_len = original.len().saturating_sub(lead + trail);
let points: std::collections::HashSet<usize> = if core_len >= 5
&& original[lead..lead + core_len]
.iter()
.all(|character| character.is_ascii_alphabetic())
{
let core: String = original[lead..lead + core_len].iter().collect();
hyphenator
.calculate_indices(&caser, &core)
.map(|boundary| boundary + lead)
.collect()
} else {
std::collections::HashSet::new()
};
let mut resolved: Vec<(char, char)> = Vec::new();
let mut cursor = 0;
while cursor < original.len() {
if cursor + 1 < original.len() {
if let Some((unicode, slot)) = font.ligature(original[cursor], original[cursor + 1])
{
resolved.push((unicode, slot));
cursor += 2;
continue;
}
}
let character = original[cursor];
resolved.push((character, character));
cursor += 1;
}
let ligated = resolved.len() != original.len();
for (character_index, (character, slot)) in resolved.into_iter().enumerate() {
if let (Some(index), Some(left)) = (previous_box, previous_character) {
let kern = font.kern(left, character);
if kern != 0 {
if let Some(HorizontalItem::Box(previous)) = items.get_mut(index) {
previous.width += kern;
}
}
}
previous_box = Some(items.len());
previous_character = Some(character);
items.push(HorizontalItem::Box(HorizontalBox {
width: font.width(slot),
height: font.height(character),
depth: font.depth(character),
character: Some(character),
italic: font.italic(character),
}));
let boundary = character_index + 1;
// TeX's defaults for American English are \lefthyphenmin=2 and
// \righthyphenmin=3.
if !ligated
&& points.contains(&boundary)
&& boundary >= 2
&& boundary + 3 <= lead + core_len
{
items.push(HorizontalItem::Discretionary {
pre_break_width: font.width('-'),
no_break_width: 0,
});
}
}
space_factor = space_factor_after(
word,
space_factor,
style.frenchspacing,
&style.space_factor_codes,
);
}
while matches!(items.last(), Some(HorizontalItem::Glue { .. })) {
items.pop();
}
items.push(HorizontalItem::Penalty {
width: 0,
penalty: 10_000,
flagged: false,
});
items
}
/// TeX's default `\sfcode` values for sentence punctuation (`plain.tex`'s
/// `\nonfrenchspacing`); every other character is 1000. Explicit
/// `\sfcode` assignments in `space_factor_codes` override the defaults, and a
/// zero code leaves the running factor unchanged.
fn space_factor_after(
word: &str,
previous: i64,
frenchspacing: bool,
codes: &[(char, i64)],
) -> i64 {
if frenchspacing {
return 1000;
}
let Some(last) = word.chars().last() else {
return previous;
};
if let Some((_, code)) = codes.iter().rev().find(|(character, _)| *character == last) {
return if *code == 0 { previous } else { *code };
}
match last {
'.' | '?' | '!' => 3000,
':' => 2000,
';' => 1500,
',' => 1250,
_ => 1000,
}
}
/// Paragraph builder driven by a real TFM font instead of fixed widths.
pub fn layout_paragraph_with_font(
text: &str,
style: &ParagraphStyle,
font: &crate::cmr10::Cmr10Metrics,
) -> Paragraph {
let items = text_items_with_font(text, style, font);
layout_items(&items, style)
}
pub fn layout_paragraph(text: &str, style: &ParagraphStyle) -> Paragraph {
let items = text_items(text, style);
layout_items(&items, style)
}
#[cfg(test)]
mod tests {
use super::*;
fn boxes(line: &[HorizontalItem]) -> usize {
line.iter()
.filter(|item| matches!(item, HorizontalItem::Box(_)))
.count()
}
fn glues(line: &[HorizontalItem]) -> usize {
line.iter()
.filter(|item| matches!(item, HorizontalItem::Glue { .. }))
.count()
}
#[test]
fn overfull_lines_do_not_exceed_the_declared_shrink() {
let font = crate::cmr10::Cmr10Metrics::Roman;
let style = ParagraphStyle {
line_width: 150 * 65_536,
par_indent: 0,
emergencystretch: 0,
line_height: 12 * 65_536,
..ParagraphStyle::default()
};
let paragraph = layout_paragraph_with_font(
"alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu",
&style,
&font,
);
let first = &paragraph.lines[0];
let mut total = 0_i64;
for item in first {
match item {
HorizontalItem::Box(box_) => total += box_.width,
HorizontalItem::Glue { width, shrink, .. } => {
total += *width;
assert!(
*width >= font.space() - *shrink,
"glue shrank past its declared shrink"
);
}
HorizontalItem::Penalty { width, .. } => total += *width,
HorizontalItem::Discretionary { .. } => {}
}
}
assert!(
total > style.line_width,
"an overfull line must stay overfull instead of shrinking glue past its limits"
);
}
#[test]
fn overfull_final_line_shrinks_its_glue() {
let font = crate::cmr10::Cmr10Metrics::Roman;
let style = ParagraphStyle {
line_width: 23 * 65_536,
par_indent: 0,
emergencystretch: 0,
line_height: 12 * 65_536,
..ParagraphStyle::default()
};
let paragraph = layout_paragraph_with_font("aa bb", &style, &font);
assert_eq!(paragraph.line_count(), 1);
let glue = paragraph.lines[0].iter().find_map(|item| match item {
HorizontalItem::Glue { width, .. } => Some(*width),
_ => None,
});
let glue = glue.expect("the final line must keep its interword glue");
assert!(
glue < font.space(),
"an overfull final line must shrink its glue"
);
assert!(
glue >= font.space() - font.shrink(),
"the final line must not shrink past the declared shrink"
);
}
#[test]
fn ragged_right_leaves_lines_at_their_natural_width() {
let width = |line: &[HorizontalItem]| -> i64 {
line.iter()
.map(|item| match item {
HorizontalItem::Box(box_item) => box_item.width,
HorizontalItem::Glue { width, .. } => *width,
HorizontalItem::Penalty { width, .. } => *width,
HorizontalItem::Discretionary { .. } => 0,
})
.sum()
};
let style = |ragged_right: bool| ParagraphStyle {
line_width: 200,
par_fillskip_fil: false,
ragged_right,
..ParagraphStyle::default()
};
let justified = layout_paragraph("alpha beta", &style(false));
let ragged = layout_paragraph("alpha beta", &style(true));
assert_eq!(justified.lines.len(), 1);
assert_eq!(
width(&justified.lines[0]),
200,
"justified line fills the measure"
);
assert_eq!(
width(&ragged.lines[0]),
94,
"ragged line keeps its natural width"
);
}
#[test]
fn words_break_at_glue_and_lines_are_justified() {
let style = ParagraphStyle {
line_width: 110,
..ParagraphStyle::default()
};
let paragraph = layout_paragraph("alpha beta gamma delta", &style);
assert_eq!(paragraph.line_count(), 2);
assert!(glues(&paragraph.lines[0]) > 0);
assert!(boxes(&paragraph.lines[0]) >= 4);
}
#[test]
fn first_line_respects_par_indent() {
let style = ParagraphStyle {
line_width: 100,
par_indent: 20,
..ParagraphStyle::default()
};
let paragraph = layout_paragraph("alpha beta gamma delta", &style);
assert!(paragraph.line_count() >= 2);
}
#[test]
fn cmr10_boxes_carry_glyph_height_and_depth() {
let font = crate::cmr10::Cmr10Metrics::new();
let style = ParagraphStyle {
line_width: 400 * 65_536,
..ParagraphStyle::default()
};
let paragraph = layout_paragraph_with_font("Ag", &style, &font);
let boxes: Vec<&HorizontalBox> = paragraph.lines[0]
.iter()
.filter_map(|item| match item {
HorizontalItem::Box(box_) => Some(box_),
_ => None,
})
.collect();
assert_eq!(boxes.len(), 2);
assert_eq!(boxes[0].height, font.height('A'));
assert_eq!(boxes[0].depth, font.depth('A'));
assert_eq!(boxes[1].height, font.height('g'));
assert_eq!(boxes[1].depth, font.depth('g'));
assert_ne!(boxes[0].depth, boxes[1].depth);
}
#[test]
fn cmr10_italic_correction_extends_the_line_width() {
let font = crate::cmr10::Cmr10Metrics::default();
let style = ParagraphStyle {
line_width: 400 * 65_536,
..ParagraphStyle::default()
};
let paragraph = layout_paragraph_with_font("f", &style, &font);
assert!(paragraph.width > font.width('f'));
assert_eq!(paragraph.width - font.width('f'), font.italic('f'));
}
#[test]
fn cmr10_breaks_match_pdftex_at_180pt() {
let font = crate::cmr10::Cmr10Metrics::new();
let style = ParagraphStyle {
line_width: 180 * 65_536,
par_indent: 0,
..ParagraphStyle::default()
};
let paragraph = layout_paragraph_with_font(
"alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega",
&style,
&font,
);
// TeX produces four lines at this measure: 7, 8, 9 and 1 words.
let words: Vec<usize> = paragraph
.lines
.iter()
.map(|line| {
line.iter()
.filter(|item| matches!(item, HorizontalItem::Glue { .. }))
.count()
+ 1
})
.collect();
assert_eq!(words, vec![7, 8, 9, 1]);
}
#[test]
fn cmr10_breaks_match_a_pdftex_fixture() {
let font = crate::cmr10::Cmr10Metrics::new();
let style = ParagraphStyle {
line_width: 150 * 65_536,
par_indent: 0,
..ParagraphStyle::default()
};
let paragraph = layout_paragraph_with_font(
"alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu",
&style,
&font,
);
let counts: Vec<usize> = paragraph
.lines
.iter()
.map(|line| {
line.iter()
.filter(|item| matches!(item, HorizontalItem::Box(_)))
.count()
})
.collect();
assert_eq!(counts, vec![30, 25]);
}
#[test]
fn emergencystretch_enables_the_emergency_pass() {
let font = crate::cmr10::Cmr10Metrics::new();
let style = ParagraphStyle {
line_width: 150 * 65_536,
par_indent: 0,
..ParagraphStyle::default()
};
let text = "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu";
let plain = layout_paragraph_with_font(text, &style, &font);
assert_eq!(plain.line_count(), 2);
let emergency = ParagraphStyle {
emergencystretch: 10 * 65_536,
..style
};
let paragraph = layout_paragraph_with_font(text, &emergency, &font);
assert_eq!(paragraph.line_count(), 3);
}
fn line_ends_with_hyphen(line: &[HorizontalItem]) -> bool {
matches!(line.last(), Some(HorizontalItem::Box(item)) if item.character == Some('-'))
}
#[test]
fn final_hyphen_demerits_suppress_a_penultimate_hyphen() {
let font = crate::cmr10::Cmr10Metrics::Roman;
let text = "hyphenation demonstration algorithm parameter memory hyphenation \
demonstration algorithm parameter memory";
let mut observed = false;
let mut suppressed = false;
// An emergency pass keeps a dynamic-programming solution alive; without
// it the greedy fallback decides and ignores demerits entirely.
for width in (30..=90).step_by(2) {
let base = ParagraphStyle {
line_width: width * 65_536,
line_height: 12 * 65_536,
emergencystretch: 10 * 65_536,
..ParagraphStyle::default()
};
let penalised = ParagraphStyle {
final_hyphen_demerits: 1_000_000_000_000_000,
..base.clone()
};
let base_lines = layout_paragraph_with_font(text, &base, &font);
let strict_lines = layout_paragraph_with_font(text, &penalised, &font);
let base_hyphens: Vec<bool> = base_lines
.lines
.iter()
.map(|line| line_ends_with_hyphen(line))
.collect();
let strict_hyphens: Vec<bool> = strict_lines
.lines
.iter()
.map(|line| line_ends_with_hyphen(line))
.collect();
let base_penultimate = base_hyphens.iter().rev().nth(1).copied().unwrap_or(false);
let strict_penultimate = strict_hyphens.iter().rev().nth(1).copied().unwrap_or(false);
if base_penultimate {
observed = true;
if !strict_penultimate {
suppressed = true;
}
}
}
assert!(observed, "fixture never hyphenated the penultimate line");
assert!(
suppressed,
"final_hyphen_demerits never suppressed a penultimate hyphen"
);
}
#[test]
fn double_hyphen_demerits_suppress_consecutive_hyphenated_lines() {
let font = crate::cmr10::Cmr10Metrics::Roman;
let text = "hyphenation demonstration algorithm parameter memory hyphenation \
demonstration algorithm parameter memory";
let mut observed = false;
let mut avoided = false;
// An emergency pass keeps a dynamic-programming solution alive; without
// it the greedy fallback decides and ignores demerits entirely.
for width in (30..=90).step_by(2) {
let base = ParagraphStyle {
line_width: width * 65_536,
line_height: 12 * 65_536,
emergencystretch: 10 * 65_536,
..ParagraphStyle::default()
};
let penalised = ParagraphStyle {
double_hyphen_demerits: 1_000_000_000_000_000,
..base.clone()
};
let base_lines = layout_paragraph_with_font(text, &base, &font);
let strict_lines = layout_paragraph_with_font(text, &penalised, &font);
let base_hyphens: Vec<bool> = base_lines
.lines
.iter()
.map(|line| line_ends_with_hyphen(line))
.collect();
let strict_hyphens: Vec<bool> = strict_lines
.lines
.iter()
.map(|line| line_ends_with_hyphen(line))
.collect();
let consecutive = |flags: &[bool]| flags.windows(2).any(|pair| pair[0] && pair[1]);
if consecutive(&base_hyphens) {
observed = true;
if !consecutive(&strict_hyphens) {
avoided = true;
}
}
}
assert!(observed, "fixture never hyphenated two consecutive lines");
assert!(
avoided,
"double_hyphen_demerits never removed consecutive hyphenated lines"
);
}
#[test]
fn hyphenation_inserts_discretionary_breaks() {
let font = crate::cmr10::Cmr10Metrics::default();
let style = ParagraphStyle {
line_width: 2_000_000,
..ParagraphStyle::default()
};
let items = text_items_with_font("hyphenation", &style, &font);
assert!(
items
.iter()
.any(|item| matches!(item, HorizontalItem::Discretionary { .. }))
);
let paragraph = layout_items(&items, &style);
assert!(paragraph.lines.len() > 1);
}
#[test]
fn tolerance_does_not_admit_overfull_lines() {
let font = crate::cmr10::Cmr10Metrics::default();
let style = ParagraphStyle {
line_width: 75 * 65_536,
par_indent: 0,
tolerance: 10_000,
..ParagraphStyle::default()
};
let paragraph = layout_paragraph_with_font(
"hyphenation hyphenation hyphenation hyphenation hyphenation",
&style,
&font,
);
assert!(
paragraph.lines.len() > 1,
"an overfull single line must not satisfy \\tolerance"
);
}
#[test]
fn double_hyphen_becomes_one_en_dash_box() {
let font = crate::cmr10::Cmr10Metrics::new();
let style = ParagraphStyle::default();
let items = text_items_with_font("--", &style, &font);
let boxes: Vec<_> = items
.iter()
.filter_map(|item| match item {
HorizontalItem::Box(horizontal) => horizontal.character,
_ => None,
})
.collect();
assert_eq!(boxes, vec!['\u{2013}']);
}
#[test]
fn triple_hyphen_becomes_one_em_dash_box() {
let font = crate::cmr10::Cmr10Metrics::new();
let style = ParagraphStyle::default();
let items = text_items_with_font("---", &style, &font);
let boxes: Vec<_> = items
.iter()
.filter_map(|item| match item {
HorizontalItem::Box(horizontal) => horizontal.character,
_ => None,
})
.collect();
assert_eq!(boxes, vec!['\u{2014}']);
}
#[test]
fn fi_ligature_reduces_character_boxes() {
let font = crate::cmr10::Cmr10Metrics::new();
let style = ParagraphStyle::default();
let items = text_items_with_font("fi", &style, &font);
let boxes: Vec<_> = items
.iter()
.filter_map(|item| match item {
HorizontalItem::Box(box_) => Some(box_),
_ => None,
})
.collect();
assert_eq!(boxes.len(), 1);
assert_eq!(boxes[0].character, Some('\u{FB01}'));
}
#[test]
fn cmr10_font_drives_character_widths() {
let font = crate::cmr10::Cmr10Metrics::new();
let style = ParagraphStyle {
line_width: 150 * 65_536,
..ParagraphStyle::default()
};
let paragraph = layout_paragraph_with_font(
"The quick brown fox jumps over the lazy dog",
&style,
&font,
);
assert!(paragraph.line_count() >= 2);
assert!(paragraph.height > 0);
}
#[test]
fn cmr10_kerning_reduces_adjacent_character_width() {
let font = crate::cmr10::Cmr10Metrics::new();
assert!(font.kern('A', 'V') < 0);
let style = ParagraphStyle::default();
let items = text_items_with_font("AV", &style, &font);
let total: i64 = items
.iter()
.map(|item| match item {
HorizontalItem::Box(box_) => box_.width,
HorizontalItem::Glue { width, .. } => *width,
_ => 0,
})
.sum();
assert_eq!(
total,
font.width('A') + font.width('V') + font.kern('A', 'V')
);
}
#[test]
fn left_skip_narrows_the_measure_and_offsets_the_paragraph() {
let narrow = ParagraphStyle {
line_width: 150,
left_skip: 50,
..ParagraphStyle::default()
};
let full = ParagraphStyle {
line_width: 150,
..ParagraphStyle::default()
};
let text = "alpha beta gamma delta epsilon zeta eta theta";
let narrow_paragraph = layout_paragraph(text, &narrow);
assert_eq!(narrow_paragraph.left_skip, 50);
assert!(narrow_paragraph.lines.len() > layout_paragraph(text, &full).lines.len());
}
#[test]
fn right_skip_narrows_the_measure() {
let narrow = ParagraphStyle {
line_width: 150,
right_skip: 50,
..ParagraphStyle::default()
};
let full = ParagraphStyle {
line_width: 150,
..ParagraphStyle::default()
};
let text = "alpha beta gamma delta epsilon zeta eta theta";
let narrow_lines = layout_paragraph(text, &narrow).lines.len();
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);
}
#[test]
fn hyphenation_exceptions_add_breakpoints() {
let font = crate::cmr10::Cmr10Metrics::default();
let style = ParagraphStyle {
line_width: 20 * 65_536,
line_height: 12 * 65_536,
..ParagraphStyle::default()
};
let breaks = |style: &ParagraphStyle| {
text_items_with_font("zzzzzz", style, &font)
.iter()
.filter(|item| matches!(item, HorizontalItem::Discretionary { .. }))
.count()
};
assert_eq!(breaks(&style), 0, "no TeX pattern breaks this word");
let with_exception = ParagraphStyle {
hyphenation_exceptions: vec!["zzz-zzz".to_string()],
..style
};
assert_eq!(
breaks(&with_exception),
1,
"exceptions insert a discretionary point"
);
}
#[test]
fn parfillskip_without_fil_stretches_the_last_line() {
let text = "alpha beta";
let style = ParagraphStyle {
line_width: 120,
..ParagraphStyle::default()
};
let default = layout_paragraph(text, &style);
let mut flush = style.clone();
flush.par_fillskip_fil = false;
let justified = layout_paragraph(text, &flush);
let last_width = |paragraph: &Paragraph| {
paragraph
.lines
.last()
.expect("a line")
.iter()
.map(|item| match item {
HorizontalItem::Box(box_item) => box_item.width,
HorizontalItem::Glue { width, .. } => *width,
_ => 0,
})
.sum::<i64>()
};
assert!(last_width(&default) < 120, "fil leaves the last line short");
assert_eq!(last_width(&justified), 120, "0pt parfillskip is flush");
}
#[test]
fn parfillskip_width_leaves_a_gap_on_the_last_line() {
let text = "alpha beta";
let style = ParagraphStyle {
line_width: 120,
par_fillskip: 20,
par_fillskip_fil: false,
..ParagraphStyle::default()
};
let paragraph = layout_paragraph(text, &style);
let last_width: i64 = paragraph
.lines
.last()
.expect("a line")
.iter()
.map(|item| match item {
HorizontalItem::Box(box_item) => box_item.width,
HorizontalItem::Glue { width, .. } => *width,
_ => 0,
})
.sum();
assert_eq!(last_width, 100, "parfillskip leaves its width at the end");
}
#[test]
fn sentence_punctuation_scales_the_interword_glue() {
let style = ParagraphStyle::default();
let font = crate::cmr10::Cmr10Metrics::Roman;
let items = text_items_with_font("alpha. beta", &style, &font);
let (width, stretch, shrink) = items
.iter()
.find_map(|item| match item {
HorizontalItem::Glue {
width,
stretch,
shrink,
..
} => Some((*width, *stretch, *shrink)),
_ => None,
})
.expect("interword glue");
assert_eq!(width, font.space() + font.extra_space());
assert_eq!(stretch, font.stretch() * 3);
assert_eq!(shrink, font.shrink() * 1000 / 3000);
}
#[test]
fn explicit_space_factor_code_overrides_sentence_spacing() {
let font = crate::cmr10::Cmr10Metrics::Roman;
let glue_width = |style: &ParagraphStyle| {
text_items_with_font("alpha. beta", style, &font)
.iter()
.find_map(|item| match item {
HorizontalItem::Glue { width, .. } => Some(*width),
_ => None,
})
.expect("interword glue")
};
let default = glue_width(&ParagraphStyle::default());
let style = ParagraphStyle {
space_factor_codes: vec![('.', 1000)],
..ParagraphStyle::default()
};
assert_eq!(glue_width(&style), font.space());
assert!(glue_width(&style) < default);
}
#[test]
fn zero_space_factor_code_keeps_the_previous_factor() {
let font = crate::cmr10::Cmr10Metrics::Roman;
let style = ParagraphStyle {
space_factor_codes: vec![('.', 0)],
..ParagraphStyle::default()
};
let width = text_items_with_font("alpha. beta", &style, &font)
.iter()
.find_map(|item| match item {
HorizontalItem::Glue { width, .. } => Some(*width),
_ => None,
})
.expect("interword glue");
// "alpha" leaves the factor at 1000, and a zero `\sfcode` keeps it.
assert_eq!(width, font.space());
}
#[test]
fn explicit_spaceskip_replaces_the_font_glue() {
let font = crate::cmr10::Cmr10Metrics::Roman;
let style = ParagraphStyle {
space_skip: Some((6 * 65_536, 65_536, 32_768)),
..ParagraphStyle::default()
};
let items = text_items_with_font("alpha beta", &style, &font);
let (width, stretch, shrink) = items
.iter()
.find_map(|item| match item {
HorizontalItem::Glue {
width,
stretch,
shrink,
..
} => Some((*width, *stretch, *shrink)),
_ => None,
})
.expect("interword glue");
assert_eq!(width, 6 * 65_536);
assert_eq!(stretch, 65_536);
assert_eq!(shrink, 32_768);
}
#[test]
fn xspaceskip_applies_after_sentence_punctuation() {
let font = crate::cmr10::Cmr10Metrics::Roman;
let style = ParagraphStyle {
space_skip: Some((6 * 65_536, 65_536, 32_768)),
xspace_skip: Some((8 * 65_536, 4 * 65_536, 2 * 65_536)),
..ParagraphStyle::default()
};
let items = text_items_with_font("alpha. beta", &style, &font);
let (width, stretch, shrink) = items
.iter()
.find_map(|item| match item {
HorizontalItem::Glue {
width,
stretch,
shrink,
..
} => Some((*width, *stretch, *shrink)),
_ => None,
})
.expect("interword glue");
assert_eq!(width, 8 * 65_536);
assert_eq!(stretch, 4 * 65_536);
assert_eq!(shrink, 2 * 65_536);
}
#[test]
fn baselines_use_baselineskip_then_lineskip() {
let font = crate::cmr10::Cmr10Metrics::new();
let mut style = ParagraphStyle {
line_width: font.width('a') * 3,
line_height: 12 * 65_536,
..ParagraphStyle::default()
};
let first = layout_paragraph_with_font("a b c", &style, &font);
assert_eq!(first.lines.len(), 2);
assert_eq!(
first.line_baselines[1] - first.line_baselines[0],
12 * 65_536
);
style.lineskiplimit = 100 * 65_536;
let second = layout_paragraph_with_font("a b c", &style, &font);
assert_eq!(
second.line_baselines[1] - second.line_baselines[0],
font.height('a') + 65_536
);
}
#[test]
fn frenchspacing_keeps_a_plain_space() {
let style = ParagraphStyle {
frenchspacing: true,
..ParagraphStyle::default()
};
let font = crate::cmr10::Cmr10Metrics::Roman;
let items = text_items_with_font("alpha. beta", &style, &font);
let (width, stretch, shrink) = items
.iter()
.find_map(|item| match item {
HorizontalItem::Glue {
width,
stretch,
shrink,
..
} => Some((*width, *stretch, *shrink)),
_ => None,
})
.expect("interword glue");
assert_eq!(width, font.space());
assert_eq!(stretch, font.stretch());
assert_eq!(shrink, font.shrink());
}
#[test]
fn hfill_absorbs_the_line_stretch() {
let font = crate::cmr10::Cmr10Metrics::Roman;
let style = ParagraphStyle {
line_width: 200 * 65_536,
par_indent: 0,
line_height: 12 * 65_536,
..ParagraphStyle::default()
};
let paragraph = layout_paragraph_with_font("A \\hfill B", &style, &font);
assert_eq!(paragraph.lines.len(), 1);
let line = &paragraph.lines[0];
let fill = line
.iter()
.filter(|item| matches!(item, HorizontalItem::Glue { order: 2, .. }))
.count();
assert_eq!(fill, 1, "\\hfill should be one fill-order glue");
let width: i64 = line
.iter()
.map(|item| match item {
HorizontalItem::Box(box_) => box_.width,
HorizontalItem::Glue { width, .. } => *width,
HorizontalItem::Penalty { width, .. } => *width,
HorizontalItem::Discretionary { .. } => 0,
})
.sum();
assert_eq!(width, 200 * 65_536);
}
#[test]
fn fill_glue_wins_over_fil() {
let font = crate::cmr10::Cmr10Metrics::Roman;
let style = ParagraphStyle {
line_width: 300 * 65_536,
par_indent: 0,
line_height: 12 * 65_536,
..ParagraphStyle::default()
};
let paragraph = layout_paragraph_with_font("A \\hfil B \\hfill C", &style, &font);
assert_eq!(paragraph.lines.len(), 1);
let line = &paragraph.lines[0];
let fil: i64 = line
.iter()
.filter_map(|item| match item {
HorizontalItem::Glue {
width, order: 1, ..
} => Some(*width),
_ => None,
})
.sum();
let fill: i64 = line
.iter()
.filter_map(|item| match item {
HorizontalItem::Glue {
width, order: 2, ..
} => Some(*width),
_ => None,
})
.sum();
assert_eq!(fil, 0, "\\hfil must stay at its natural width");
assert!(fill > 0, "\\hfill must absorb the whole page set");
}
}