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

3497 lines
131 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,
/// Font face for this glyph when it comes from a styled run.
#[serde(default)]
pub font: Option<ParagraphFont>,
/// The inline formula this box paints, when it came from `$...$`.
#[serde(default)]
pub math: Option<Box<crate::math::MathAtom>>,
/// Link target when this glyph came from `\href`.
#[serde(default)]
pub link: Option<String>,
/// Explicit glyph size in scaled points for a sized run.
#[serde(default)]
pub size: Option<i64>,
/// Vertical offset in scaled points; positive raises the glyphs.
#[serde(default)]
pub raise: i64,
/// Explicit RGB fill when this glyph came from `\textcolor`.
#[serde(default)]
pub color: Option<[u8; 3]>,
/// Background colour painted behind a `\\colorbox` run.
pub background: Option<[u8; 3]>,
/// A frame colour and line width drawn around the box, like `\fcolorbox`.
#[serde(default)]
pub frame: Option<([u8; 3], i64)>,
}
/// A run of paragraph material: text in one face or an inline formula.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum InlineSegment {
Text(ParagraphFont, String),
/// A run carrying its own type size, such as `{\small ...}`.
SizedText(ParagraphFont, i64, String),
/// A run raised or lowered like `\textsuperscript`.
Script(ParagraphFont, i64, i64, String),
/// A run painted with an explicit RGB colour.
Color(ParagraphFont, i64, i64, [u8; 3], String),
/// A run painted over an optional RGB background, like `\\colorbox` or `\\fbox`.
ColorBox(
ParagraphFont,
i64,
i64,
Option<[u8; 3]>,
Option<[u8; 3]>,
String,
),
Math(crate::math::MathAtom),
/// Material that never breaks internally, like an `\mbox` or a measured
/// savebox: interword spaces become fixed-width boxes instead of glue.
/// A positive size freezes the box at the size it was measured at; zero
/// follows the surrounding paragraph size.
NoBreak(ParagraphFont, i64, String),
Link {
font: ParagraphFont,
url: String,
text: String,
color: Option<[u8; 3]>,
},
}
#[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
}
/// Base font size for unscaled paragraphs (10pt in scaled points).
const BASE_FONT_SIZE: i64 = 655_360;
fn default_font_size() -> i64 {
BASE_FONT_SIZE
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ParagraphStyle {
pub line_width: i64,
/// Bounded line expansion in thousandths, microtype-like. A line may be
/// broken up to `line_width * (1000 + line_expansion) / 1000` and is
/// compressed back to the real measure when painted.
#[serde(default)]
pub line_expansion: 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,
/// TeX `\looseness`: shift the final line count by this many lines (an
/// alternative is only taken when it is feasible, as in TeX).
#[serde(default)]
pub looseness: i64,
/// 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,
/// Base font size in scaled points (`\fontsize`, `\large`, ...). Glyph
/// metrics and the default interline glue scale by this over 10pt.
#[serde(default = "default_font_size")]
pub font_size: 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
}
}
pub fn line_measure(&self, line: usize) -> i64 {
let (_, width) = self.line_geometry(line);
(width - self.left_skip - self.right_skip).max(1) - self.par_indent_for(line)
}
fn line_target(&self, line: usize) -> i64 {
let measure = self.line_measure(line);
(measure * (1000 + self.line_expansion) / 1000).max(measure)
}
}
impl Default for ParagraphStyle {
fn default() -> Self {
Self {
line_width: 400,
line_expansion: 0,
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,
looseness: 0,
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,
font_size: BASE_FONT_SIZE,
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,
BoldItalic,
Mono,
Sans,
SansBold,
SansItalic,
/// Roman small caps (`cmcsc10`, TeX `\scshape`).
SmallCaps,
/// Roman slanted (`cmsl10`, TeX `\slshape`).
Slanted,
/// Bold extended slanted (`cmbxsl10`).
BoldSlanted,
/// Italic typewriter (`cmitt10`, TeX `\ttfamily\itshape`).
MonoItalic,
/// Times Roman text selected by `\rmdefault{ptm}` (`ptmr8t`).
TimesRoman,
/// Times bold text (`ptmb8t`).
TimesBold,
/// Times italic text (`ptmri8t`).
TimesItalic,
/// Times bold italic text (`ptmbi8t`).
TimesBoldItalic,
}
impl ParagraphFont {
/// `\emph`: toggles italic, combining with an inherited bold face.
pub const fn emphasized(self) -> Self {
match self {
Self::Roman => Self::Italic,
Self::Italic => Self::Roman,
Self::Bold => Self::BoldItalic,
Self::BoldItalic => Self::Bold,
Self::Mono => self,
Self::Sans => Self::SansItalic,
Self::SansBold => Self::SansBold,
Self::SansItalic => Self::Sans,
Self::SmallCaps => Self::Italic,
Self::Slanted => Self::Italic,
Self::BoldSlanted => Self::BoldItalic,
Self::MonoItalic => Self::Mono,
Self::TimesRoman => Self::TimesItalic,
Self::TimesItalic => Self::TimesRoman,
Self::TimesBold => Self::TimesBoldItalic,
Self::TimesBoldItalic => Self::TimesBold,
}
}
/// `\textbf`.
pub const fn bolded(self) -> Self {
match self {
Self::Roman | Self::Bold => Self::Bold,
Self::Italic | Self::BoldItalic => Self::BoldItalic,
Self::Mono => self,
Self::Sans | Self::SansBold | Self::SansItalic => Self::SansBold,
Self::SmallCaps => Self::Bold,
Self::Slanted | Self::BoldSlanted => Self::BoldSlanted,
Self::MonoItalic => Self::MonoItalic,
Self::TimesRoman => Self::TimesBold,
Self::TimesItalic => Self::TimesBoldItalic,
Self::TimesBold => Self::TimesBold,
Self::TimesBoldItalic => Self::TimesBoldItalic,
}
}
/// `\mdseries`.
pub const fn medium(self) -> Self {
match self {
Self::Bold | Self::Roman => Self::Roman,
Self::BoldItalic | Self::Italic => Self::Italic,
Self::Mono => self,
Self::Sans | Self::SansItalic => self,
Self::SansBold => Self::Sans,
Self::SmallCaps => Self::SmallCaps,
Self::Slanted | Self::BoldSlanted => Self::Slanted,
Self::MonoItalic => Self::MonoItalic,
Self::TimesRoman => Self::TimesRoman,
Self::TimesBold => Self::TimesRoman,
Self::TimesItalic => Self::TimesItalic,
Self::TimesBoldItalic => Self::TimesItalic,
}
}
/// `\textit`.
pub const fn italicized(self) -> Self {
match self {
Self::Roman | Self::Italic => Self::Italic,
Self::Bold | Self::BoldItalic => Self::BoldItalic,
Self::Mono => Self::MonoItalic,
Self::MonoItalic => Self::MonoItalic,
Self::Sans => Self::SansItalic,
Self::SansBold => Self::SansBold,
Self::SansItalic => Self::SansItalic,
Self::SmallCaps => Self::Italic,
Self::Slanted => Self::Italic,
Self::BoldSlanted => Self::BoldItalic,
Self::TimesRoman => Self::TimesItalic,
Self::TimesItalic => Self::TimesItalic,
Self::TimesBold => Self::TimesBoldItalic,
Self::TimesBoldItalic => Self::TimesBoldItalic,
}
}
/// `\textsl`.
pub const fn slanted(self) -> Self {
match self {
Self::Roman | Self::Slanted => Self::Slanted,
Self::Bold | Self::BoldSlanted => Self::BoldSlanted,
Self::Italic => Self::Slanted,
Self::BoldItalic => Self::BoldSlanted,
Self::Mono => Self::MonoItalic,
Self::MonoItalic => Self::MonoItalic,
Self::Sans | Self::SansItalic => Self::SansItalic,
Self::SansBold => Self::SansBold,
Self::SmallCaps => Self::Slanted,
Self::TimesRoman => Self::TimesItalic,
Self::TimesItalic => Self::TimesItalic,
Self::TimesBold => Self::TimesBoldItalic,
Self::TimesBoldItalic => Self::TimesBoldItalic,
}
}
/// `\textup`.
pub const fn upright(self) -> Self {
match self {
Self::Roman | Self::Italic => Self::Roman,
Self::Bold | Self::BoldItalic => Self::Bold,
Self::Mono => self,
Self::Sans | Self::SansItalic => Self::Sans,
Self::SansBold => Self::SansBold,
Self::SmallCaps => Self::SmallCaps,
Self::Slanted | Self::BoldSlanted => Self::Roman,
Self::MonoItalic => Self::Mono,
Self::TimesRoman => Self::TimesRoman,
Self::TimesItalic => Self::TimesRoman,
Self::TimesBold => Self::TimesBold,
Self::TimesBoldItalic => Self::TimesBold,
}
}
/// `\textrm`.
pub const fn roman_family(self) -> Self {
match self {
Self::Mono | Self::Sans => Self::Roman,
Self::SansBold => Self::Bold,
Self::SansItalic => Self::Italic,
other => other,
}
}
/// `\textsc` / `\scshape`: roman small caps, with TeX's substitution for
/// a bold series (Computer Modern has no bold small caps).
pub const fn small_caps(self) -> Self {
match self {
Self::Roman | Self::Italic => Self::SmallCaps,
Self::Bold | Self::BoldItalic => Self::Bold,
Self::SmallCaps => Self::SmallCaps,
Self::Mono => Self::Mono,
Self::Sans | Self::SansBold | Self::SansItalic => self,
Self::Slanted => Self::SmallCaps,
Self::BoldSlanted => Self::Bold,
Self::MonoItalic => Self::Mono,
Self::TimesRoman => Self::TimesRoman,
Self::TimesItalic => Self::TimesRoman,
Self::TimesBold => Self::TimesBold,
Self::TimesBoldItalic => Self::TimesBold,
}
}
/// `\textsf`: change family, keeping the inherited weight and shape.
pub const fn sans_family(self) -> Self {
match self {
Self::Bold | Self::BoldItalic | Self::BoldSlanted => Self::SansBold,
Self::Italic | Self::Slanted | Self::MonoItalic => Self::SansItalic,
_ => Self::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,
/// TeX depth of the paragraph box: the descent of its last line.
#[serde(default)]
pub depth: i64,
#[serde(default)]
pub font: ParagraphFont,
/// Base font size used when painting the glyphs of this paragraph.
#[serde(default = "default_font_size")]
pub font_size: i64,
#[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>,
/// Horizontal compression per line (thousandths), used by the bounded
/// expansion model when a line was broken against an expanded measure.
#[serde(default)]
pub line_scales: 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);
let head_depth = line_extent(self.lines.last().map(Vec::as_slice).unwrap_or(&[])).1;
let tail_depth = line_extent(tail_lines.last().map(Vec::as_slice).unwrap_or(&[])).1;
self.height = head_height;
self.depth = head_depth;
let tail_scales = if self.line_scales.len() > lines {
self.line_scales.split_off(lines)
} else {
Vec::new()
};
Paragraph {
lines: tail_lines,
height: tail_height,
width: self.width,
depth: tail_depth,
font: self.font,
font_size: self.font_size,
left_skip: self.left_skip,
line_indents: tail_indents,
line_baselines: tail_baselines,
line_scales: tail_scales,
centered: self.centered,
right_aligned: self.right_aligned,
}
}
}
/// Scale a font-derived dimension by the paragraph's base font size.
fn scale_font_size(value: i64, size: i64) -> i64 {
value.saturating_mul(size) / BASE_FONT_SIZE
}
/// Scale a shaped run by an arbitrary rational factor (used to freeze a
/// savebox measured at another base size).
fn scale_items_ratio(items: &mut [HorizontalItem], numerator: i64, denominator: i64) {
if numerator == denominator || denominator == 0 {
return;
}
let scale = |value: i64| value.saturating_mul(numerator) / denominator;
for item in items {
match item {
HorizontalItem::Box(box_) => {
box_.width = scale(box_.width);
box_.height = scale(box_.height);
box_.depth = scale(box_.depth);
box_.italic = scale(box_.italic);
}
HorizontalItem::Glue {
width,
stretch,
shrink,
..
} => {
*width = scale(*width);
*stretch = scale(*stretch);
*shrink = scale(*shrink);
}
HorizontalItem::Penalty { width, .. } => *width = scale(*width),
HorizontalItem::Discretionary {
pre_break_width,
no_break_width,
} => {
*pre_break_width = scale(*pre_break_width);
*no_break_width = scale(*no_break_width);
}
}
}
}
/// Scale every glyph and glue in a shaped item stream for the paragraph's
/// base font size. Scaling after shaping is linear, so it matches shaping with
/// scaled TFM metrics.
fn scale_items_for_size(items: &mut [HorizontalItem], size: i64) {
if size == BASE_FONT_SIZE {
return;
}
for item in items {
match item {
HorizontalItem::Box(box_) => {
box_.width = scale_font_size(box_.width, size);
box_.height = scale_font_size(box_.height, size);
box_.depth = scale_font_size(box_.depth, size);
box_.italic = scale_font_size(box_.italic, size);
}
HorizontalItem::Glue {
width,
stretch,
shrink,
..
} => {
*width = scale_font_size(*width, size);
*stretch = scale_font_size(*stretch, size);
*shrink = scale_font_size(*shrink, size);
}
HorizontalItem::Discretionary {
pre_break_width,
no_break_width,
} => {
*pre_break_width = scale_font_size(*pre_break_width, size);
*no_break_width = scale_font_size(*no_break_width, size);
}
HorizontalItem::Penalty { .. } => {}
}
}
}
/// Clone a paragraph style with its font-derived defaults scaled to the
/// paragraph's base size. Explicitly authored glue is left alone, and the
/// measure, indentation and skips stay absolute as in TeX.
fn sized_style(style: &ParagraphStyle) -> ParagraphStyle {
if style.font_size == BASE_FONT_SIZE {
return style.clone();
}
let mut sized = style.clone();
if sized.baselineskip == default_baselineskip() {
sized.baselineskip = scale_font_size(sized.baselineskip, style.font_size);
}
if sized.lineskip == default_lineskip() {
sized.lineskip = scale_font_size(sized.lineskip, style.font_size);
}
sized.line_height = scale_font_size(sized.line_height, style.font_size);
sized.char_width = scale_font_size(sized.char_width, style.font_size);
sized.space_width = scale_font_size(sized.space_width, style.font_size);
sized.space_stretch = scale_font_size(sized.space_stretch, style.font_size);
sized.space_shrink = scale_font_size(sized.space_shrink, style.font_size);
sized
}
/// 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,
font: None,
math: None,
raise: 0,
color: None,
background: None,
frame: None,
size: None,
link: None,
}));
}
}
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,
depth: 0,
font: ParagraphFont::Roman,
font_size: style.font_size,
left_skip: style.left_skip,
line_indents: Vec::new(),
line_baselines: Vec::new(),
line_scales: 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_index: usize,
previous_state: usize,
line: usize,
}
/// TeX keeps one active node per fitness class, but \looseness needs
/// alternative line counts to survive pruning; keep the cheapest few
/// candidates per class, deduplicated by line count.
const CANDIDATES_PER_STATE: usize = 6;
// Prefix sums make every candidate line metrics O(1). The previous
// implementation rescanned items[start..end] for each break pair, which is
// cubic in practice and made a 900-word paragraph take seconds to break.
let mut prefix_natural = vec![0_i64; items.len() + 1];
let mut prefix_stretch = vec![0_i64; items.len() + 1];
let mut prefix_shrink = vec![0_i64; items.len() + 1];
let mut prefix_order = vec![[0_i64; 4]; items.len() + 1];
let mut prefix_boxes = vec![0_usize; items.len() + 1];
let mut prefix_last_penalty = vec![usize::MAX; items.len() + 1];
for (index, item) in items.iter().enumerate() {
prefix_natural[index + 1] = prefix_natural[index];
prefix_stretch[index + 1] = prefix_stretch[index];
prefix_shrink[index + 1] = prefix_shrink[index];
prefix_order[index + 1] = prefix_order[index];
prefix_boxes[index + 1] = prefix_boxes[index];
prefix_last_penalty[index + 1] = prefix_last_penalty[index];
match item {
HorizontalItem::Box(box_item) => {
prefix_natural[index + 1] += box_item.width;
prefix_boxes[index + 1] += 1;
}
HorizontalItem::Glue {
width,
stretch,
shrink,
order,
..
} => {
prefix_natural[index + 1] += *width;
prefix_shrink[index + 1] += *shrink;
if *order == 0 {
prefix_stretch[index + 1] += *stretch;
} else {
prefix_order[index + 1][*order as usize] += *stretch;
}
}
HorizontalItem::Penalty { .. } => {
prefix_last_penalty[index + 1] = index;
}
HorizontalItem::Discretionary { no_break_width, .. } => {
prefix_natural[index + 1] += *no_break_width;
}
}
}
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<[Vec<Candidate>; 8]> = (0..count)
.map(|_| std::array::from_fn(|_| Vec::new()))
.collect();
best[0][2].push(Candidate {
cost: 0,
previous: 0,
previous_index: 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 = prefix_natural[end] - prefix_natural[start];
let mut stretch = prefix_stretch[end] - prefix_stretch[start];
let mut shrink = prefix_shrink[end] - prefix_shrink[start];
let mut stretch_by_order = [0_i64; 4];
for order in 0..4 {
stretch_by_order[order] = prefix_order[end][order] - prefix_order[start][order];
}
let has_box = prefix_boxes[end] > prefix_boxes[start];
let mut trailing_penalty = 0_i64;
let last_penalty = prefix_last_penalty[end];
if last_penalty != usize::MAX && last_penalty >= start {
if let HorizontalItem::Penalty { penalty, .. } = &items[last_penalty] {
trailing_penalty = *penalty;
}
}
match &items[end - 1] {
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::Discretionary {
pre_break_width,
no_break_width,
} => {
natural += *pre_break_width - *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 {
if best[start_index][previous_state].is_empty() {
continue;
}
let previous_bucket = best[start_index][previous_state].clone();
for (previous_index, node) in previous_bucket.into_iter().enumerate() {
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 rejects such lines in every ordinary pass,
// regardless of \tolerance, and only admits them in the
// final/emergency pass.
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 bucket = &mut best[end_index][state];
if let Some(current) = bucket.iter_mut().find(|entry| entry.line == line) {
if cost < current.cost {
*current = Candidate {
cost,
previous: start_index,
previous_index,
previous_state,
line,
};
}
} else {
bucket.push(Candidate {
cost,
previous: start_index,
previous_index,
previous_state,
line,
});
bucket.sort_unstable_by_key(|candidate| candidate.cost);
bucket.truncate(CANDIDATES_PER_STATE);
}
}
}
}
}
let final_index = count - 1;
let mut finals: Vec<(i64, usize, usize, usize)> = Vec::new();
for state in 0..8 {
for (index, node) in best[final_index][state].iter().enumerate() {
finals.push((node.cost, node.line, state, index));
}
}
finals.sort_unstable();
if let Some(&(_, best_line, _, _)) = finals.first() {
// TeX's looseness asks for `best + looseness` lines; if that count
// has no feasible solution the ordinary optimum is used.
let looseness = style.looseness.clamp(-9, 9);
let target = (best_line as i64 + looseness).max(0) as usize;
let chosen = if looseness == 0 {
finals[0]
} else {
finals
.iter()
.copied()
.find(|entry| entry.1 == target)
.unwrap_or(finals[0])
};
let (_, _, mut state, mut index) = chosen;
let mut ranges = Vec::new();
let mut end_index = final_index;
while end_index > 0 {
let node = best[end_index][state][index];
ranges.push((breakpoints[node.previous], breakpoints[end_index]));
end_index = node.previous;
state = node.previous_state;
index = node.previous_index;
}
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 mut measure = 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,
font: None,
math: None,
raise: 0,
color: None,
background: None,
frame: None,
size: None,
link: None,
}));
} 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,
font: None,
math: None,
raise: 0,
color: None,
background: None,
frame: None,
size: None,
link: None,
}));
}
}
_ => 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);
measure = measure.max(target);
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);
}
}
let depth = extents.last().map_or(0, |(_, descent)| *descent);
let line_scales: Vec<i64> = lines
.iter()
.enumerate()
.map(|(index, line)| {
let actual = style.line_measure(index).max(1);
let natural: 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();
if natural > actual {
(actual * 1000 / natural).clamp(900, 1000)
} else {
1000
}
})
.collect();
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: if style.centered || style.right_aligned {
max_width.max(measure)
} else {
max_width
},
depth,
lines,
font: ParagraphFont::Roman,
font_size: style.font_size,
left_skip: style.left_skip,
line_indents,
line_baselines,
line_scales,
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),
font: None,
math: None,
raise: 0,
color: None,
background: None,
frame: None,
size: None,
link: None,
}));
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 mut items = text_items_with_font(text, style, font);
scale_items_for_size(&mut items, style.font_size);
let mut paragraph = layout_items(&items, &sized_style(style));
paragraph.font_size = style.font_size;
paragraph
}
/// Lay out a paragraph whose text is split into styled runs.
///
/// Each run is shaped with the TFM of its face, so bold and italic runs get
/// their own advances; a single interword glue is inserted at a run boundary
/// when the source text had whitespace there.
pub fn layout_paragraph_runs(
runs: &[(ParagraphFont, String)],
style: &ParagraphStyle,
) -> Paragraph {
let mut items = Vec::new();
let mut previous: Option<(ParagraphFont, String)> = None;
for (font, text) in runs {
if text.is_empty() {
continue;
}
if let Some((previous_font, previous_text)) = &previous {
let boundary_space = previous_text
.chars()
.next_back()
.is_some_and(char::is_whitespace)
|| text.chars().next().is_some_and(char::is_whitespace);
if boundary_space {
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(*previous_font);
items.push(HorizontalItem::Glue {
width: metrics.space(),
stretch: metrics.stretch(),
shrink: metrics.shrink(),
order: 0,
});
}
}
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(*font);
let mut run = text_items_with_font(text, style, &metrics);
for item in &mut run {
if let HorizontalItem::Box(box_) = item {
box_.font = Some(*font);
}
}
items.extend(run);
previous = Some((*font, text.clone()));
}
scale_items_for_size(&mut items, style.font_size);
let mut paragraph = layout_items(&items, &sized_style(style));
paragraph.font = runs.first().map(|run| run.0).unwrap_or_default();
paragraph.font_size = style.font_size;
paragraph
}
/// Lay out a paragraph mixing styled text with inline formulas.
pub fn layout_paragraph_segments(segments: &[InlineSegment], style: &ParagraphStyle) -> Paragraph {
let mut items = Vec::new();
let mut previous: Option<(ParagraphFont, String)> = None;
let mut seen_content = false;
for segment in segments {
match segment {
InlineSegment::Text(font, text) => {
if text.is_empty() {
continue;
}
let starts_with_space = text.chars().next().is_some_and(char::is_whitespace);
let boundary_space = match &previous {
Some((_previous_font, previous_text)) => {
previous_text
.chars()
.next_back()
.is_some_and(char::is_whitespace)
|| starts_with_space
}
None => seen_content && starts_with_space,
};
if boundary_space {
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(
previous.as_ref().map_or(*font, |(font, _)| *font),
);
items.push(HorizontalItem::Glue {
width: metrics.space(),
stretch: metrics.stretch(),
shrink: metrics.shrink(),
order: 0,
});
}
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(*font);
let mut run = text_items_with_font(text, style, &metrics);
for item in &mut run {
if let HorizontalItem::Box(box_) = item {
box_.font = Some(*font);
}
}
items.extend(run);
previous = Some((*font, text.clone()));
seen_content = true;
}
InlineSegment::SizedText(font, size, text) => {
if text.is_empty() {
continue;
}
let starts_with_space = text.chars().next().is_some_and(char::is_whitespace);
let boundary_space = match &previous {
Some((_previous_font, previous_text)) => {
previous_text
.chars()
.next_back()
.is_some_and(char::is_whitespace)
|| starts_with_space
}
None => seen_content && starts_with_space,
};
if boundary_space {
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(
previous.as_ref().map_or(*font, |(font, _)| *font),
);
items.push(HorizontalItem::Glue {
width: scale_font_size(metrics.space(), *size),
stretch: scale_font_size(metrics.stretch(), *size),
shrink: scale_font_size(metrics.shrink(), *size),
order: 0,
});
}
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(*font);
let mut run = text_items_with_font(text, style, &metrics);
scale_items_for_size(&mut run, *size);
for item in &mut run {
if let HorizontalItem::Box(box_) = item {
box_.font = Some(*font);
box_.size = Some(*size);
}
}
items.extend(run);
previous = Some((*font, text.clone()));
seen_content = true;
}
InlineSegment::Script(font, size, raise, text) => {
if text.is_empty() {
continue;
}
let starts_with_space = text.chars().next().is_some_and(char::is_whitespace);
let boundary_space = match &previous {
Some((_previous_font, previous_text)) => {
previous_text
.chars()
.next_back()
.is_some_and(char::is_whitespace)
|| starts_with_space
}
None => seen_content && starts_with_space,
};
if boundary_space {
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(
previous.as_ref().map_or(*font, |(font, _)| *font),
);
items.push(HorizontalItem::Glue {
width: scale_font_size(metrics.space(), *size),
stretch: scale_font_size(metrics.stretch(), *size),
shrink: scale_font_size(metrics.shrink(), *size),
order: 0,
});
}
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(*font);
let mut run = text_items_with_font(text, style, &metrics);
scale_items_for_size(&mut run, *size);
for item in &mut run {
if let HorizontalItem::Box(box_) = item {
box_.font = Some(*font);
box_.size = Some(*size);
box_.raise = *raise;
}
}
items.extend(run);
previous = Some((*font, text.clone()));
seen_content = true;
}
InlineSegment::Color(font, size, raise, color, text) => {
if text.is_empty() {
continue;
}
let starts_with_space = text.chars().next().is_some_and(char::is_whitespace);
let boundary_space = match &previous {
Some((_previous_font, previous_text)) => {
previous_text
.chars()
.next_back()
.is_some_and(char::is_whitespace)
|| starts_with_space
}
None => seen_content && starts_with_space,
};
if boundary_space {
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(
previous.as_ref().map_or(*font, |(font, _)| *font),
);
items.push(HorizontalItem::Glue {
width: scale_font_size(metrics.space(), *size),
stretch: scale_font_size(metrics.stretch(), *size),
shrink: scale_font_size(metrics.shrink(), *size),
order: 0,
});
}
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(*font);
let mut run = text_items_with_font(text, style, &metrics);
scale_items_for_size(&mut run, *size);
for item in &mut run {
if let HorizontalItem::Box(box_) = item {
box_.font = Some(*font);
box_.size = Some(*size);
box_.raise = *raise;
box_.color = Some(*color);
}
}
items.extend(run);
previous = Some((*font, text.clone()));
}
InlineSegment::ColorBox(font, size, raise, color, frame, text) => {
if text.is_empty() {
continue;
}
let starts_with_space = text.chars().next().is_some_and(char::is_whitespace);
let boundary_space = match &previous {
Some((_previous_font, previous_text)) => {
previous_text
.chars()
.next_back()
.is_some_and(char::is_whitespace)
|| starts_with_space
}
None => seen_content && starts_with_space,
};
if boundary_space {
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(
previous.as_ref().map_or(*font, |(font, _)| *font),
);
items.push(HorizontalItem::Glue {
width: scale_font_size(metrics.space(), *size),
stretch: scale_font_size(metrics.stretch(), *size),
shrink: scale_font_size(metrics.shrink(), *size),
order: 0,
});
}
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(*font);
let mut run = text_items_with_font(text, style, &metrics);
scale_items_for_size(&mut run, *size);
for item in &mut run {
if let HorizontalItem::Box(box_) = item {
box_.font = Some(*font);
box_.size = Some(*size);
box_.raise = *raise;
box_.background = *color;
box_.frame = frame.map(|frame| (frame, 26_214));
}
}
items.extend(run);
previous = Some((*font, text.clone()));
seen_content = true;
}
InlineSegment::NoBreak(font, block_size, text) => {
if text.is_empty() {
continue;
}
let starts_with_space = text.chars().next().is_some_and(char::is_whitespace);
let boundary_space = match &previous {
Some((_previous_font, previous_text)) => {
previous_text
.chars()
.next_back()
.is_some_and(char::is_whitespace)
|| starts_with_space
}
None => seen_content && starts_with_space,
};
if boundary_space {
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(
previous.as_ref().map_or(*font, |(font, _)| *font),
);
items.push(HorizontalItem::Glue {
width: metrics.space(),
stretch: metrics.stretch(),
shrink: metrics.shrink(),
order: 0,
});
}
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(*font);
let freeze_ratio = if *block_size > 0 && *block_size != style.font_size {
Some((*block_size, style.font_size.max(1)))
} else {
None
};
let space_width = match freeze_ratio {
Some((numerator, denominator)) => metrics.space() * numerator / denominator,
None => metrics.space(),
};
let mut first_word = true;
for word in text.split_whitespace() {
if !first_word {
items.push(HorizontalItem::Box(HorizontalBox {
width: space_width,
height: 0,
depth: 0,
character: None,
italic: 0,
font: Some(*font),
math: None,
raise: 0,
color: None,
background: None,
frame: None,
size: None,
link: None,
}));
}
first_word = false;
let mut run = text_items_with_font(word, style, &metrics);
run.retain(|item| matches!(item, HorizontalItem::Box(_)));
if let Some((numerator, denominator)) = freeze_ratio {
scale_items_ratio(&mut run, numerator, denominator);
}
for item in &mut run {
if let HorizontalItem::Box(box_) = item {
box_.font = Some(*font);
}
}
items.extend(run);
}
previous = Some((*font, text.clone()));
seen_content = true;
}
InlineSegment::Link {
font,
url,
text,
color,
} => {
if text.is_empty() {
continue;
}
let starts_with_space = text.chars().next().is_some_and(char::is_whitespace);
let boundary_space = match &previous {
Some((_previous_font, previous_text)) => {
previous_text
.chars()
.next_back()
.is_some_and(char::is_whitespace)
|| starts_with_space
}
None => seen_content && starts_with_space,
};
if boundary_space {
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(
previous.as_ref().map_or(*font, |(font, _)| *font),
);
items.push(HorizontalItem::Glue {
width: metrics.space(),
stretch: metrics.stretch(),
shrink: metrics.shrink(),
order: 0,
});
}
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(*font);
let mut run = text_items_with_font(text, style, &metrics);
for item in &mut run {
if let HorizontalItem::Box(box_) = item {
box_.font = Some(*font);
box_.color = *color;
box_.link = Some(url.clone());
}
}
items.extend(run);
previous = Some((*font, text.clone()));
seen_content = true;
}
InlineSegment::Math(atom) => {
if let Some((previous_font, previous_text)) = &previous
&& previous_text
.chars()
.next_back()
.is_some_and(char::is_whitespace)
{
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(*previous_font);
items.push(HorizontalItem::Glue {
width: metrics.space(),
stretch: metrics.stretch(),
shrink: metrics.shrink(),
order: 0,
});
}
let math = crate::math::layout_math(atom, &crate::cmr10::Cmr10Metrics::default());
items.push(HorizontalItem::Box(HorizontalBox {
width: math.width,
height: math.height,
depth: math.depth,
character: None,
italic: 0,
font: None,
math: Some(Box::new(atom.clone())),
size: None,
raise: 0,
color: None,
background: None,
frame: None,
link: None,
}));
previous = None;
seen_content = true;
}
}
}
scale_items_for_size(&mut items, style.font_size);
let mut paragraph = layout_items(&items, &sized_style(style));
paragraph.font = match segments.first() {
Some(InlineSegment::Text(font, _))
| Some(InlineSegment::SizedText(font, _, _))
| Some(InlineSegment::Script(font, _, _, _))
| Some(InlineSegment::Color(font, _, _, _, _))
| Some(InlineSegment::ColorBox(font, _, _, _, _, _))
| Some(InlineSegment::Link { font, .. }) => *font,
_ => ParagraphFont::Roman,
};
paragraph.font_size = style.font_size;
paragraph
}
pub fn layout_paragraph(text: &str, style: &ParagraphStyle) -> Paragraph {
let mut items = text_items(text, style);
scale_items_for_size(&mut items, style.font_size);
let mut paragraph = layout_items(&items, &sized_style(style));
paragraph.font_size = style.font_size;
paragraph
}
#[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 bounded_expansion_records_per_line_scales() {
let text = "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu";
let base = ParagraphStyle {
line_width: 180,
..ParagraphStyle::default()
};
let expanded = ParagraphStyle {
line_width: 180,
line_expansion: 30,
..ParagraphStyle::default()
};
let plain = layout_paragraph(text, &base);
let stretched = layout_paragraph(text, &expanded);
assert!(stretched.lines.len() <= plain.lines.len());
assert_eq!(stretched.line_scales.len(), stretched.lines.len());
assert!(
stretched
.line_scales
.iter()
.all(|scale| (900..=1000).contains(scale)),
"{:?}",
stretched.line_scales
);
assert!(
stretched.line_scales.iter().any(|scale| *scale < 1000),
"no line was compressed: {:?}",
stretched.line_scales
);
}
#[test]
fn font_size_scales_glyphs_and_line_spacing() {
let font = crate::cmr10::Cmr10Metrics::Roman;
let base = ParagraphStyle {
line_width: 150 * 65_536,
par_indent: 0,
..ParagraphStyle::default()
};
let ten = layout_paragraph_with_font("hello world", &base, &font);
let large = ParagraphStyle {
font_size: 12 * 65_536,
..base.clone()
};
let twelve = layout_paragraph_with_font("hello world", &large, &font);
assert!(twelve.width > ten.width);
assert!(twelve.height > ten.height);
let glyphs = |paragraph: &Paragraph| {
paragraph
.lines
.iter()
.flatten()
.filter(|item| matches!(item, HorizontalItem::Box(_)))
.count()
};
assert_eq!(glyphs(&ten), glyphs(&twelve));
}
#[test]
fn aligned_paragraphs_keep_the_measure_width() {
let font = crate::cmr10::Cmr10Metrics::Roman;
let base = ParagraphStyle {
line_width: 300 * 65_536,
par_indent: 0,
..ParagraphStyle::default()
};
let centered = layout_paragraph_with_font(
"short",
&ParagraphStyle {
centered: true,
..base.clone()
},
&font,
);
let right = layout_paragraph_with_font(
"short",
&ParagraphStyle {
right_aligned: true,
..base.clone()
},
&font,
);
assert_eq!(centered.width, 300 * 65_536);
assert_eq!(right.width, 300 * 65_536);
assert!(
centered.lines[0]
.iter()
.map(|item| match item {
HorizontalItem::Box(box_) => box_.width,
HorizontalItem::Glue { width, .. } => *width,
_ => 0,
})
.sum::<i64>()
< centered.width
);
}
#[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() >= 1);
}
#[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 paragraph_depth_is_the_last_line_descent() {
let font = crate::cmr10::Cmr10Metrics::new();
let style = ParagraphStyle {
line_width: 400 * 65_536,
..ParagraphStyle::default()
};
let paragraph = layout_paragraph_with_font("gyp", &style, &font);
assert_eq!(paragraph.lines.len(), 1);
assert_eq!(
paragraph.depth,
font.depth('p').max(font.depth('y')).max(font.depth('g'))
);
}
#[test]
fn linked_boxes_carry_their_target() {
let style = ParagraphStyle::default();
let segments = vec![
InlineSegment::Text(ParagraphFont::Roman, "Go ".into()),
InlineSegment::Link {
font: ParagraphFont::Roman,
url: "https://example.com".into(),
text: "there".into(),
color: None,
},
InlineSegment::Text(ParagraphFont::Roman, " now".into()),
];
let paragraph = layout_paragraph_segments(&segments, &style);
let linked: Vec<&HorizontalBox> = paragraph
.lines
.iter()
.flatten()
.filter_map(|item| match item {
HorizontalItem::Box(box_) if box_.link.is_some() => Some(box_),
_ => None,
})
.collect();
assert_eq!(linked.len(), 5);
assert!(
linked
.iter()
.all(|box_| box_.link.as_deref() == Some("https://example.com"))
);
assert!(linked.iter().all(|box_| box_.character.is_some()));
}
#[test]
fn raised_segments_carry_their_size_and_shift() {
let style = ParagraphStyle {
line_width: 480 * 65_536,
par_indent: 0,
..ParagraphStyle::default()
};
let paragraph = layout_paragraph_segments(
&[
InlineSegment::Text(ParagraphFont::Roman, "x".into()),
InlineSegment::Script(ParagraphFont::Roman, 458_752, 262_144, "2".into()),
],
&style,
);
let boxes: Vec<_> = paragraph
.lines
.iter()
.flatten()
.filter_map(|item| match item {
HorizontalItem::Box(box_) if box_.character.is_some() => Some(box_),
_ => None,
})
.collect();
assert_eq!(boxes.len(), 2);
assert_eq!(boxes[0].raise, 0);
assert_eq!(boxes[1].size, Some(458_752));
assert_eq!(boxes[1].raise, 262_144);
assert!(boxes[1].width < boxes[0].width);
}
#[test]
fn color_segments_tag_their_boxes_with_the_color() {
let style = ParagraphStyle {
line_width: 480 * 65_536,
..Default::default()
};
let segments = vec![
InlineSegment::Text(ParagraphFont::Roman, "a ".to_string()),
InlineSegment::Color(
ParagraphFont::Roman,
655_360,
0,
[255, 0, 0],
"red".to_string(),
),
];
let paragraph = layout_paragraph_segments(&segments, &style);
let boxes: Vec<&HorizontalBox> = paragraph
.lines
.iter()
.flatten()
.filter_map(|item| match item {
HorizontalItem::Box(box_) => Some(box_),
_ => None,
})
.collect();
assert!(boxes.iter().any(|box_| box_.color == Some([255, 0, 0])));
assert!(boxes.iter().filter(|box_| box_.color.is_none()).count() >= 1);
}
#[test]
fn long_paragraph_breaks_without_rescanning_candidates() {
// 900 words is the size of the server edit fixture; the breaker used to
// rescan every candidate line, turning this into tens of seconds.
let font = crate::cmr10::Cmr10Metrics::new();
let style = ParagraphStyle {
line_width: 480 * 65_536,
..ParagraphStyle::default()
};
let text = "word ".repeat(900);
let started = std::time::Instant::now();
let paragraph = layout_paragraph_with_font(&text, &style, &font);
let elapsed = started.elapsed();
assert!(paragraph.lines.len() > 30, "{}", paragraph.lines.len());
assert!(elapsed < std::time::Duration::from_secs(10), "{elapsed:?}");
}
#[test]
fn no_break_segments_replace_spaces_with_fixed_boxes() {
let style = ParagraphStyle {
line_width: 40 * 65_536,
..ParagraphStyle::default()
};
let segments = vec![InlineSegment::NoBreak(
ParagraphFont::Roman,
0,
"alpha beta gamma".to_string(),
)];
let paragraph = layout_paragraph_segments(&segments, &style);
assert_eq!(paragraph.lines.len(), 1, "the box must not wrap");
let line = &paragraph.lines[0];
assert!(
!line
.iter()
.any(|item| matches!(item, HorizontalItem::Glue { .. })),
"spaces inside a no-break box must be fixed boxes"
);
let characters: String = line
.iter()
.filter_map(|item| match item {
HorizontalItem::Box(box_) => box_.character,
_ => None,
})
.collect();
assert_eq!(characters, "alphabetagamma");
}
#[test]
fn frozen_no_break_box_keeps_its_definition_size() {
let style = ParagraphStyle {
line_width: 200 * 65_536,
..ParagraphStyle::default()
};
let width = |paragraph: &Paragraph| -> i64 {
paragraph.lines[0]
.iter()
.map(|item| match item {
HorizontalItem::Box(box_) => box_.width,
HorizontalItem::Glue { width, .. } => *width,
_ => 0,
})
.sum()
};
let normal = layout_paragraph_segments(
&[InlineSegment::NoBreak(
ParagraphFont::Roman,
0,
"ab".to_string(),
)],
&style,
);
let frozen = layout_paragraph_segments(
&[InlineSegment::NoBreak(
ParagraphFont::Roman,
2 * 655_360,
"ab".to_string(),
)],
&style,
);
let ratio = width(&frozen) as f64 / width(&normal) as f64;
assert!((ratio - 2.0).abs() < 0.05, "frozen ratio {ratio}");
}
#[test]
fn sized_segments_keep_their_own_glyph_size() {
let style = ParagraphStyle {
line_width: 480 * 65_536,
..ParagraphStyle::default()
};
let segments = vec![
InlineSegment::Text(ParagraphFont::Roman, "x ".into()),
InlineSegment::SizedText(ParagraphFont::Roman, 786_432, "x".into()),
];
let paragraph = layout_paragraph_segments(&segments, &style);
let boxes: Vec<&HorizontalBox> = paragraph
.lines
.iter()
.flatten()
.filter_map(|item| match item {
HorizontalItem::Box(box_) => Some(box_),
_ => None,
})
.collect();
assert_eq!(boxes.len(), 2);
assert_eq!(boxes[0].size, None);
assert_eq!(boxes[1].size, Some(786_432));
assert!(boxes[1].width > boxes[0].width);
}
#[test]
fn inline_math_boxes_sit_between_words() {
let style = ParagraphStyle {
line_width: 300 * 65_536,
par_indent: 0,
..ParagraphStyle::default()
};
let atom = crate::math::parse_math("x^2");
let segments = vec![
InlineSegment::Text(ParagraphFont::Roman, "Value ".into()),
InlineSegment::Math(atom.clone()),
InlineSegment::Text(ParagraphFont::Roman, " tail".into()),
];
let paragraph = layout_paragraph_segments(&segments, &style);
let boxes: Vec<&HorizontalBox> = paragraph
.lines
.iter()
.flatten()
.filter_map(|item| match item {
HorizontalItem::Box(box_) => Some(box_),
_ => None,
})
.collect();
let math = boxes
.iter()
.find(|box_| box_.math.is_some())
.expect("math box");
assert!(math.character.is_none());
assert_eq!(
math.width,
crate::math::layout_math(&atom, &crate::cmr10::Cmr10Metrics::default()).width
);
let glues = paragraph
.lines
.iter()
.flatten()
.filter(|item| matches!(item, HorizontalItem::Glue { .. }))
.count();
assert!(glues >= 2, "spaces on both sides of the formula");
assert!(paragraph.font_size == 655_360);
}
#[test]
fn split_at_keeps_each_part_last_line_descent() {
let boxed = |character: char, depth: i64| {
HorizontalItem::Box(HorizontalBox {
width: 5 * 65_536,
height: 5 * 65_536,
depth,
character: Some(character),
italic: 0,
font: None,
math: None,
raise: 0,
color: None,
background: None,
frame: None,
size: None,
link: None,
})
};
let items = vec![
boxed('a', 0),
HorizontalItem::Glue {
width: 65_536,
stretch: 0,
shrink: 5 * 65_536,
order: 0,
},
boxed('g', 2 * 65_536),
HorizontalItem::Penalty {
width: 0,
penalty: -10_000,
flagged: false,
},
boxed('x', 0),
];
let style = ParagraphStyle {
line_width: 9 * 65_536,
line_height: 12 * 65_536,
..ParagraphStyle::default()
};
let mut paragraph = layout_items(&items, &style);
assert_eq!(paragraph.lines.len(), 2);
let tail = paragraph.split_at(1);
assert_eq!(paragraph.depth, 2 * 65_536);
assert_eq!(tail.depth, 0);
assert_eq!(paragraph.height, 12 * 65_536);
assert_eq!(tail.height, 12 * 65_536);
assert_eq!(paragraph.height + tail.height, 24 * 65_536);
}
#[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");
}
#[test]
fn looseness_shifts_the_line_count_when_feasible() {
let font = crate::cmr10::Cmr10Metrics::default();
let text = "alpha beta gamma delta epsilon zeta eta theta iota kappa \
lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega";
let base = ParagraphStyle {
line_width: 120 * 65_536,
par_indent: 0,
tolerance: 10_000,
pretolerance: 10_000,
..ParagraphStyle::default()
};
let measured = |looseness: i64| {
let mut style = base.clone();
style.looseness = looseness;
layout_paragraph_with_font(text, &style, &font).lines.len()
};
assert_eq!(measured(0), 5, "default optimum");
// A four-line setting would need an overfull line, which TeX refuses
// outside the final pass, so the optimum is kept.
assert_eq!(measured(-1), 5, "infeasible tighter paragraph");
assert_eq!(measured(1), 6, "looser paragraph");
}
}
#[cfg(test)]
mod font_tests {
use super::ParagraphFont;
#[test]
fn sans_faces_compose_with_weight_and_shape() {
assert_eq!(ParagraphFont::Sans.bolded(), ParagraphFont::SansBold);
assert_eq!(ParagraphFont::Sans.emphasized(), ParagraphFont::SansItalic);
assert_eq!(ParagraphFont::SansItalic.emphasized(), ParagraphFont::Sans);
assert_eq!(
ParagraphFont::SansBold.emphasized(),
ParagraphFont::SansBold
);
assert_eq!(ParagraphFont::SansBold.medium(), ParagraphFont::Sans);
assert_eq!(ParagraphFont::SansItalic.upright(), ParagraphFont::Sans);
assert_eq!(ParagraphFont::SansBold.roman_family(), ParagraphFont::Bold);
assert_eq!(
ParagraphFont::SansItalic.roman_family(),
ParagraphFont::Italic
);
assert_eq!(ParagraphFont::Bold.sans_family(), ParagraphFont::SansBold);
assert_eq!(
ParagraphFont::Italic.sans_family(),
ParagraphFont::SansItalic
);
assert_eq!(ParagraphFont::Mono.sans_family(), ParagraphFont::Sans);
assert_eq!(ParagraphFont::SmallCaps.emphasized(), ParagraphFont::Italic);
assert_eq!(ParagraphFont::Bold.small_caps(), ParagraphFont::Bold);
assert_eq!(ParagraphFont::Italic.small_caps(), ParagraphFont::SmallCaps);
assert_eq!(ParagraphFont::SmallCaps.upright(), ParagraphFont::SmallCaps);
assert_eq!(ParagraphFont::Slanted.italicized(), ParagraphFont::Italic);
assert_eq!(ParagraphFont::Italic.slanted(), ParagraphFont::Slanted);
assert_eq!(ParagraphFont::Bold.slanted(), ParagraphFont::BoldSlanted);
assert_eq!(ParagraphFont::BoldSlanted.medium(), ParagraphFont::Slanted);
assert_eq!(ParagraphFont::Slanted.upright(), ParagraphFont::Roman);
assert_eq!(ParagraphFont::Slanted.emphasized(), ParagraphFont::Italic);
assert_eq!(ParagraphFont::Mono.italicized(), ParagraphFont::MonoItalic);
assert_eq!(ParagraphFont::MonoItalic.upright(), ParagraphFont::Mono);
assert_eq!(ParagraphFont::Mono.slanted(), ParagraphFont::MonoItalic);
assert_eq!(
ParagraphFont::Slanted.small_caps(),
ParagraphFont::SmallCaps
);
assert_eq!(ParagraphFont::BoldSlanted.small_caps(), ParagraphFont::Bold);
assert_eq!(
ParagraphFont::Slanted.sans_family(),
ParagraphFont::SansItalic
);
}
}