use super::lines::{LinesConfig, merge_row};
use super::order::{ItemRef, Leaf};
use super::page::{DocStats, PageData};
use crate::backend::FontInfo;
use crate::common::geom::Rect;
use crate::model::Line;
use crate::model::Loc;
use regex::Regex;
use std::sync::LazyLock;
static NUMBERED_NOTE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\d{1,2}\.\s+\S").unwrap());
static VENUE_NOTE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"^\d{1,2}(?:st|nd|rd|th)\s+(?:[A-Z][\w-]*\s+){0,3}(?:Conference|Workshop|Symposium)\b").unwrap()
});
static EQNO: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\((?:[A-Z]\.?)?\d+(?:\.\d+)*[a-z]?\)$").unwrap());
pub static BULLET: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[•◦▪■–∗⋆·‣▶►○●◆\-]\s").unwrap());
pub static NUM_LABEL: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^(?:\(\d{1,2}\)|\([a-z]\)|\([ivx]{1,4}\)|\d{1,2}[.)]|[a-z]\))\s").unwrap());
pub static BRACKET_LABEL: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\[\d{1,3}\]\s").unwrap());
pub static LIST_LABEL: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"^(?:[•◦▪■–∗⋆·‣▶►○●◆\-]\s|\(\d{1,2}\)\s|\([a-z]\)\s|\([ivx]{1,4}\)\s|\d{1,2}[.)]\s|[a-z]\)\s)").unwrap()
});
const EQUATION_RULES: [EquationRule; 6] = [
displayed_formula,
symbol_row,
centred_relation,
stacked_formula,
centred_stacked_relation,
drawn_bracket,
];
const PARAGRAPH_RULES: [ParagraphRule; 4] = [
starts_with_marker,
new_enumeration_item,
follows_short_line,
indent_changes,
];
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BlocksConfig {
pub orphan_max_chars: usize,
pub orphan_max_width_em: f32,
pub right_percentile_min_rows: usize,
pub right_edge_percentile_ratio: f32,
pub justified_edge_tol_pt: f32,
pub justified_min_ratio: f32,
pub isolation_gap_em: f32,
pub eqno_margin_em: f32,
pub centered_tol_ratio: f32,
pub centered_min_tol_pt: f32,
pub centered_min_margin_em: f32,
pub multi_baseline_em: f32,
pub numbered_max_prose_ratio: f32,
pub display_min_math_ratio: f32,
pub display_max_prose_ratio: f32,
pub display_min_indent_em: f32,
pub symbolic_min_math_ratio: f32,
pub symbolic_max_prose_ratio: f32,
pub symbolic_min_chars: usize,
pub symbolic_min_indent_em: f32,
pub operator_min_math_ratio: f32,
pub operator_max_prose_ratio: f32,
pub stacked_min_math_ratio: f32,
pub stacked_max_prose_ratio: f32,
pub stacked_min_margin_em: f32,
pub weak_min_margin_em: f32,
pub weak_max_chars: usize,
pub weak_max_prose_ratio: f32,
pub weak_tiny_max_chars: usize,
pub weak_flush_max_indent_em: f32,
pub weak_full_max_slack_em: f32,
pub weak_full_min_prose_chars: f32,
pub weak_full_flat_min_chars: usize,
pub weak_min_math_ratio: f32,
pub weak_math_max_prose_ratio: f32,
pub promote_max_gap_leading: f32,
pub merge_max_gap_leading: f32,
pub enclosing_min_height_em: f32,
pub enclosing_tolerance_pt: f32,
pub fraction_bar_max_thickness_pt: f32,
pub fraction_bar_min_width_pt: f32,
pub fraction_part_max_gap_em: f32,
pub inline_fraction_min_chars: usize,
pub sentence_min_words: usize,
pub limit_max_size_ratio: f32,
pub footnote_size_drop_pt: f32,
pub footnote_rule_min_width_pt: f32,
pub footnote_rule_max_width_ratio: f32,
pub footnote_rule_min_leaf_pt: f32,
pub footnote_rule_align_pt: f32,
pub footnote_rule_tol_pt: f32,
pub footnote_rule_above_leaf_pt: f32,
pub footnote_same_size_max_excess_pt: f32,
pub footnote_run_size_drop_pt: f32,
pub footnote_gap_leading: f32,
pub centered_group_tol_pt: f32,
pub centered_group_min_offset_pt: f32,
pub para_word_space_em: f32,
pub para_short_line_slack_pt: f32,
pub ragged_min_lines_count: usize,
pub ragged_line_max_gap_em: f32,
pub ragged_prose_min_lower_ratio: f32,
pub para_right_overshoot_pt: f32,
pub para_label_align_em: f32,
pub para_indent_change_em: f32,
pub block_gap_leading: f32,
pub block_gap_slack_pt: f32,
pub block_ink_gap_em: f32,
pub block_size_change_pt: f32,
pub bold_flip_min_chars: usize,
pub bold_flip_gap_leading: f32,
pub bold_run_in_max_words_count: usize,
pub bold_dominant_ratio: f32,
pub main_text_min_width_ratio: f32,
pub margin_note_max_width_ratio: f32,
pub margin_note_max_size_ratio: f32,
pub main_text_min_lines_count: usize,
pub equation_join_min_overlap_ratio: f32,
pub equation_join_max_gap_em: f32,
pub equation_touch_max_gap_em: f32,
pub equation_absorb_min_overlap_ratio: f32,
}
const DEFAULT_CONFIG: BlocksConfig = BlocksConfig {
orphan_max_chars: 4,
orphan_max_width_em: 3.5,
right_percentile_min_rows: 8,
right_edge_percentile_ratio: 0.92,
justified_edge_tol_pt: 1.5,
justified_min_ratio: 0.4,
isolation_gap_em: 0.55,
eqno_margin_em: 2.5,
centered_tol_ratio: 0.03,
centered_min_tol_pt: 4.0,
centered_min_margin_em: 1.2,
multi_baseline_em: 0.25,
numbered_max_prose_ratio: 0.6,
display_min_math_ratio: 0.25,
display_max_prose_ratio: 0.5,
display_min_indent_em: 3.0,
symbolic_min_math_ratio: 0.45,
symbolic_max_prose_ratio: 0.15,
symbolic_min_chars: 6,
symbolic_min_indent_em: 1.0,
operator_min_math_ratio: 0.08,
operator_max_prose_ratio: 0.8,
stacked_min_math_ratio: 0.3,
stacked_max_prose_ratio: 0.3,
stacked_min_margin_em: 1.0,
weak_min_margin_em: 1.2,
weak_max_chars: 110,
weak_max_prose_ratio: 0.85,
weak_tiny_max_chars: 3,
weak_flush_max_indent_em: 0.5,
weak_full_max_slack_em: 0.5,
weak_full_min_prose_chars: 6.0,
weak_full_flat_min_chars: 30,
weak_min_math_ratio: 0.2,
weak_math_max_prose_ratio: 0.3,
promote_max_gap_leading: 0.9,
merge_max_gap_leading: 0.9,
enclosing_min_height_em: 1.8,
enclosing_tolerance_pt: 1.0,
fraction_bar_max_thickness_pt: 1.2,
fraction_bar_min_width_pt: 2.0,
fraction_part_max_gap_em: 0.6,
inline_fraction_min_chars: 30,
sentence_min_words: 4,
limit_max_size_ratio: 0.85,
footnote_size_drop_pt: 0.4,
footnote_rule_min_width_pt: 20.0,
footnote_rule_max_width_ratio: 0.62,
footnote_rule_min_leaf_pt: 120.0,
footnote_rule_align_pt: 8.0,
footnote_rule_tol_pt: 2.0,
footnote_rule_above_leaf_pt: 20.0,
footnote_same_size_max_excess_pt: 0.3,
footnote_run_size_drop_pt: 0.9,
footnote_gap_leading: 1.25,
centered_group_tol_pt: 2.5,
centered_group_min_offset_pt: 3.0,
para_word_space_em: 0.25,
para_short_line_slack_pt: 1.0,
ragged_min_lines_count: 4,
ragged_line_max_gap_em: 2.5,
ragged_prose_min_lower_ratio: 0.6,
para_right_overshoot_pt: 3.0,
para_label_align_em: 0.6,
para_indent_change_em: 0.6,
block_gap_leading: 1.25,
block_gap_slack_pt: 1.5,
block_ink_gap_em: 0.45,
block_size_change_pt: 0.6,
bold_flip_min_chars: 2,
bold_flip_gap_leading: 1.1,
bold_run_in_max_words_count: 12,
bold_dominant_ratio: 0.95,
main_text_min_width_ratio: 0.45,
margin_note_max_width_ratio: 0.22,
margin_note_max_size_ratio: 0.92,
main_text_min_lines_count: 5,
equation_join_min_overlap_ratio: 0.5,
equation_join_max_gap_em: 3.0,
equation_touch_max_gap_em: 0.5,
equation_absorb_min_overlap_ratio: 0.8,
};
impl Default for BlocksConfig {
fn default() -> Self {
DEFAULT_CONFIG
}
}
#[derive(Debug, Clone)]
pub struct TextBlock {
pub lines: Vec<Line>,
pub loc: Loc,
pub left: f32,
pub right: f32,
pub centered: bool,
pub gap_before: f32,
pub bbox: Rect,
}
#[derive(Debug, Clone)]
pub struct EquationBlock {
pub lines: Vec<Line>,
pub bbox: Rect,
pub number: Option<String>,
pub number_line: Option<Line>,
pub loc: Loc,
}
#[derive(Debug, Clone)]
pub enum RawBlock {
Text(TextBlock),
Equation(EquationBlock),
Float {
idx: usize,
loc: Loc,
},
Footnote(TextBlock),
}
struct RowStats {
n_chars: usize,
math_chars: usize,
prose_chars: usize,
}
enum Row {
Text(Line),
Equation {
lines: Vec<Line>,
bbox: Rect,
number: Option<String>,
number_line: Option<Line>,
},
Float(usize),
}
struct RowDraft {
lines: Vec<Line>,
float: Option<usize>,
bbox: Rect,
}
type WeakEquation = (Vec<Line>, Rect, bool);
struct LeafExtent {
left: f32,
right: f32,
width: f32,
justified: bool,
center_x: f32,
}
struct RowFeatures {
numbered: bool,
n_chars: usize,
math_frac: f32,
prose_frac: f32,
em: f32,
left_indent: f32,
right_slack: f32,
centered: bool,
isolated: bool,
multi: bool,
has_relation: bool,
continues_display: bool,
has_bracket_piece: bool,
}
type EquationRule = fn(&RowFeatures, &BlocksConfig) -> bool;
struct ParagraphBreak<'a> {
para: &'a [(Line, f32)],
line: &'a Line,
text: &'a str,
right: f32,
footnote: bool,
ragged: bool,
}
type ParagraphRule = fn(&ParagraphBreak, &BlocksConfig) -> bool;
#[derive(Clone, Copy)]
struct BlockContext<'a> {
page: &'a PageData,
stats: &'a DocStats,
fonts: &'a [FontInfo],
cfg: &'a BlocksConfig,
lines_cfg: &'a LinesConfig,
leaf_right: f32,
}
pub fn build_blocks(
page: &PageData,
leaves: &[Leaf],
stats: &DocStats,
fonts: &[FontInfo],
cfg: &BlocksConfig,
lines_cfg: &LinesConfig,
) -> Vec<RawBlock> {
let ctx = BlockContext {
page,
stats,
fonts,
cfg,
lines_cfg,
leaf_right: f32::INFINITY,
};
let mut out = Vec::new();
for (leaf_idx, leaf) in leaves.iter().enumerate() {
let loc = Loc {
page: page.index,
zone: leaf.zone,
zone_cols: leaf.zone_cols,
col: leaf.col,
leaf: leaf_idx,
};
let mut drafts = gather_rows(page, leaf);
join_orphan_rows(&mut drafts, stats, cfg);
let extent = LeafExtent::measure(&drafts, leaf, cfg);
let ctx = BlockContext {
leaf_right: if extent.justified { extent.right } else { f32::INFINITY },
..ctx
};
let (mut rows, mut weak) = classify_rows(ctx, drafts, &extent);
promote_weak_equations(&mut rows, &mut weak, stats, cfg);
attach_stray_numbers(&mut rows, &extent, stats, cfg);
let rows = merge_equation_rows(rows, stats, cfg);
let bars = fraction_bars(page, cfg);
let rows = inline_numerators(rows, &bars, ctx);
let rows = absorb_enclosed_rows(rows, &bars, cfg);
let fn_start = footnote_start(ctx, leaf, &rows, &extent);
emit_blocks(ctx, rows, fn_start, loc, &mut out);
}
out
}
pub fn mark_margin_notes(
blocks: &mut [RawBlock],
page_width: f32,
stats: &DocStats,
fonts: &[FontInfo],
cfg: &BlocksConfig,
) {
let max_size = cfg.margin_note_max_size_ratio * stats.body_size;
let main_lines: Vec<&Line> = blocks
.iter()
.filter_map(|block| match block {
RawBlock::Text(text) => Some(text.lines.iter()),
_ => None,
})
.flatten()
.filter(|line| line.size > max_size && line.bbox.width() >= cfg.main_text_min_width_ratio * page_width)
.collect();
if main_lines.len() < cfg.main_text_min_lines_count {
return;
}
let main = main_lines.iter().fold(Rect::EMPTY, |acc, line| acc.union(&line.bbox));
let bold = |line: &Line| fonts.get(usize::from(line.font)).is_some_and(|font| font.bold);
for block in blocks.iter_mut() {
let RawBlock::Text(text) = block else {
continue;
};
let small = text.lines.iter().all(|line| line.size <= max_size);
let narrow = text.bbox.width() <= cfg.margin_note_max_width_ratio * page_width;
let beside =
(text.bbox.x1 <= main.x0 || text.bbox.x0 >= main.x1) && text.bbox.y0 >= main.y0 && text.bbox.y1 <= main.y1;
let heading = text.lines.iter().all(bold);
if small && narrow && beside && !heading {
*block = RawBlock::Footnote(text.clone());
}
}
}
pub fn join_equation_parts(blocks: &mut Vec<RawBlock>, stats: &DocStats, cfg: &BlocksConfig) {
let mut i = 0;
while i < blocks.len() {
let RawBlock::Equation(equation) = &blocks[i] else {
i += 1;
continue;
};
let (target, loc) = (equation.bbox, equation.loc);
let part = (0..blocks.len()).find(|&j| j != i && is_equation_part(&target, loc, &blocks[j], stats, cfg));
let Some(j) = part else {
i += 1;
continue;
};
let other = blocks.remove(j);
let i_now = if j < i { i - 1 } else { i };
if let RawBlock::Equation(equation) = &mut blocks[i_now] {
match other {
RawBlock::Equation(part) => {
equation.bbox = equation.bbox.union(&part.bbox);
equation.lines.extend(part.lines);
if equation.number.is_none() {
equation.number = part.number;
equation.number_line = part.number_line;
}
}
RawBlock::Text(part) => {
equation.bbox = equation.bbox.union(&part.bbox);
equation.lines.extend(part.lines);
}
_ => {}
}
equation
.lines
.sort_by(|a, b| a.baseline.total_cmp(&b.baseline).then(a.bbox.x0.total_cmp(&b.bbox.x0)));
}
i = i_now;
}
}
fn is_equation_part(target: &Rect, loc: Loc, block: &RawBlock, stats: &DocStats, cfg: &BlocksConfig) -> bool {
match block {
RawBlock::Equation(other) if other.loc.zone != loc.zone => {
let bbox = other.bbox;
let gap_x = (bbox.x0 - target.x1).max(target.x0 - bbox.x1);
let gap_y = (bbox.y0 - target.y1).max(target.y0 - bbox.y1);
let max_gap = cfg.equation_touch_max_gap_em * stats.body_size;
gap_x <= max_gap && gap_y <= max_gap
}
RawBlock::Equation(other) if (other.loc.zone, other.loc.col) == (loc.zone, loc.col) => {
let bbox = other.bbox;
let overlap = (target.y1.min(bbox.y1) - target.y0.max(bbox.y0)).max(0.0);
let lower = target.height().min(bbox.height()).max(1.0);
let gap = (bbox.x0 - target.x1).max(target.x0 - bbox.x1);
overlap >= cfg.equation_join_min_overlap_ratio * lower
&& gap >= 0.0
&& gap <= cfg.equation_join_max_gap_em * stats.body_size
}
RawBlock::Text(text) => {
let bbox = text.bbox;
let width = (target.x1.min(bbox.x1) - target.x0.max(bbox.x0)).max(0.0);
let height = (target.y1.min(bbox.y1) - target.y0.max(bbox.y0)).max(0.0);
let area = (bbox.width() * bbox.height()).max(1.0);
width * height >= cfg.equation_absorb_min_overlap_ratio * area
}
_ => false,
}
}
impl LeafExtent {
fn measure(drafts: &[RowDraft], leaf: &Leaf, cfg: &BlocksConfig) -> Self {
let text_x1: Vec<f32> = drafts
.iter()
.filter(|draft| draft.float.is_none())
.map(|draft| draft.bbox.x1)
.collect();
let left = drafts
.iter()
.filter(|draft| draft.float.is_none())
.map(|draft| draft.bbox.x0)
.fold(f32::INFINITY, f32::min);
let enough_rows = text_x1.len() >= cfg.right_percentile_min_rows;
let right = if enough_rows {
percentile(text_x1.clone(), cfg.right_edge_percentile_ratio, leaf.bbox.x1)
} else {
text_x1.iter().copied().fold(f32::NEG_INFINITY, f32::max)
};
let flush_rows = text_x1
.iter()
.filter(|x1| (**x1 - right).abs() <= cfg.justified_edge_tol_pt)
.count();
let justified = enough_rows && flush_rows as f32 >= cfg.justified_min_ratio * text_x1.len() as f32;
Self {
left,
right,
justified,
width: (right - left).max(1.0),
center_x: (left + right) * 0.5,
}
}
}
fn is_math_char(ch: char) -> bool {
matches!(
ch,
'=' | '+'
| '−'
| '×'
| '÷'
| '·'
| '∑'
| '∏'
| '∫'
| '√'
| '∞'
| '≤'
| '≥'
| '≠'
| '≈'
| '∈'
| '∉'
| '⊂'
| '⊆'
| '∪'
| '∩'
| '∧'
| '∨'
| '¬'
| '→'
| '←'
| '↔'
| '⇒'
| '⇔'
| '∀'
| '∃'
| '∂'
| '∇'
| '∝'
| '∼'
| '≡'
| '⟨'
| '⟩'
| '‖'
| '|'
| '<'
| '>'
| '±'
| '∓'
| '⊕'
| '⊗'
| '∘'
| '′'
| '⊤'
| '⊥'
| '∥'
| '≜'
| '≪'
| '≫'
| '↦'
| '∖'
) || ('\u{0391}'..='\u{03C9}').contains(&ch)
|| ('\u{1D400}'..='\u{1D7FF}').contains(&ch)
}
fn is_relation(text: &str) -> bool {
matches!(text, "=" | "≤" | "≥" | "≈" | "∈" | "→" | "∝" | "≡" | "<" | ">")
}
fn row_stats(lines: &[&Line], fonts: &[FontInfo]) -> RowStats {
let mut stats = RowStats {
n_chars: 0,
math_chars: 0,
prose_chars: 0,
};
for line in lines {
let mut run = 0usize;
for glyph in &line.glyphs {
let font = &fonts[glyph.font as usize];
let nchars = glyph.text.chars().count();
stats.n_chars += nchars;
let mathy = font.math || glyph.text.chars().any(is_math_char);
if mathy {
stats.math_chars += nchars;
}
let alpha = !mathy && glyph.script == 0 && glyph.text.chars().all(|ch| ch.is_alphabetic());
if alpha && !glyph.space_before {
run += nchars;
} else {
if run >= 4 {
stats.prose_chars += run;
}
run = if alpha { nchars } else { 0 };
}
}
if run >= 4 {
stats.prose_chars += run;
}
}
stats
}
fn percentile(mut values: Vec<f32>, quantile: f32, default: f32) -> f32 {
if values.is_empty() {
return default;
}
values.sort_by(|a, b| a.total_cmp(b));
let idx = ((values.len() - 1) as f32 * quantile).round() as usize;
values[idx]
}
fn ends_with_hyphen(line: &Line) -> bool {
line.glyphs.last().is_some_and(|glyph| glyph.text.ends_with('-'))
}
fn bold_dominant(line: &Line, fonts: &[FontInfo], cfg: &BlocksConfig) -> bool {
line.font_frac(fonts, |font| font.bold) >= cfg.bold_dominant_ratio
}
fn starts_bold(line: &Line, fonts: &[FontInfo]) -> bool {
line.glyphs
.iter()
.find(|glyph| !glyph.text.trim().is_empty())
.and_then(|glyph| fonts.get(glyph.font as usize))
.is_some_and(|font| font.bold)
}
fn footnote_marked(line: &Line) -> bool {
line.starts_with_superscript()
|| line
.glyphs
.first()
.is_some_and(|glyph| matches!(glyph.text.as_str(), "∗" | "†" | "‡" | "§" | "¶" | "*"))
}
fn row_chars(draft: &RowDraft) -> usize {
draft.lines.iter().map(|line| line.char_count()).sum::<usize>()
}
fn gather_rows(page: &PageData, leaf: &Leaf) -> Vec<RowDraft> {
let mut drafts: Vec<RowDraft> = Vec::new();
for row in &leaf.rows {
let mut lines = Vec::new();
let mut float = None;
for item in row {
match *item {
ItemRef::Line(i) => lines.push(page.lines[i].clone()),
ItemRef::Float(i) => float = Some(i),
}
}
let bbox = lines.iter().fold(Rect::EMPTY, |acc, line| acc.union(&line.bbox));
drafts.push(RowDraft { lines, float, bbox });
}
drafts
}
fn join_orphan_rows(drafts: &mut Vec<RowDraft>, stats: &DocStats, cfg: &BlocksConfig) {
let mut i = 0;
while i < drafts.len() {
let tiny = drafts[i].float.is_none()
&& row_chars(&drafts[i]) <= cfg.orphan_max_chars
&& drafts[i].bbox.width() < cfg.orphan_max_width_em * stats.body_size;
if tiny && let Some(target) = orphan_target(drafts, i, stats, cfg) {
let row = drafts.remove(i);
let target = if target > i { target - 1 } else { target };
drafts[target].lines.extend(row.lines);
drafts[target].bbox = drafts[target].bbox.union(&row.bbox);
continue;
}
i += 1;
}
}
fn orphan_target(drafts: &[RowDraft], idx: usize, stats: &DocStats, cfg: &BlocksConfig) -> Option<usize> {
let orphan = drafts[idx].bbox;
let accepts = |other: &RowDraft| {
other.float.is_none()
&& other.bbox.y_overlap(&orphan) > 0.0
&& orphan.x0 >= other.bbox.x0 - stats.body_size
&& orphan.x1 <= other.bbox.x1 + stats.body_size
&& row_chars(other) > cfg.orphan_max_chars
};
let prev_ok = idx > 0 && accepts(&drafts[idx - 1]);
let next_ok = idx + 1 < drafts.len() && accepts(&drafts[idx + 1]);
match (prev_ok, next_ok) {
(true, true) => {
let dist_prev = (drafts[idx - 1].bbox.cy() - orphan.cy()).abs();
let dist_next = (drafts[idx + 1].bbox.cy() - orphan.cy()).abs();
Some(if dist_prev <= dist_next { idx - 1 } else { idx + 1 })
}
(true, false) => Some(idx - 1),
(false, true) => Some(idx + 1),
_ => None,
}
}
fn classify_rows(
ctx: BlockContext,
drafts: Vec<RowDraft>,
extent: &LeafExtent,
) -> (Vec<Row>, Vec<Option<WeakEquation>>) {
let mut rows: Vec<Row> = Vec::new();
let mut weak: Vec<Option<WeakEquation>> = Vec::new();
let ink_boxes: Vec<Rect> = drafts
.iter()
.map(|draft| draft.lines.iter().fold(Rect::EMPTY, |acc, line| acc.union(&line.ink)))
.collect();
for (draft_idx, draft) in drafts.into_iter().enumerate() {
let isolated = is_isolated(&ink_boxes, draft_idx, ctx.stats, ctx.cfg);
if let Some(float) = draft.float {
rows.push(Row::Float(float));
weak.push(None);
}
if draft.lines.is_empty() {
continue;
}
let (row, weak_eq) = classify_text_row(ctx, draft.lines, extent, isolated);
weak.push(weak_eq);
rows.push(row);
}
(rows, weak)
}
fn is_isolated(ink_boxes: &[Rect], idx: usize, stats: &DocStats, cfg: &BlocksConfig) -> bool {
let ink = ink_boxes[idx];
let above = idx == 0
|| ink_boxes[idx - 1].is_unset()
|| ink.y0 - ink_boxes[idx - 1].y1 > cfg.isolation_gap_em * stats.body_size;
let below = idx + 1 >= ink_boxes.len()
|| ink_boxes[idx + 1].is_unset()
|| ink_boxes[idx + 1].y0 - ink.y1 > cfg.isolation_gap_em * stats.body_size;
above && below
}
fn classify_text_row(
ctx: BlockContext,
mut lines: Vec<Line>,
extent: &LeafExtent,
isolated: bool,
) -> (Row, Option<WeakEquation>) {
lines.sort_by(|a, b| a.bbox.x0.total_cmp(&b.bbox.x0));
let number = equation_number(&lines, extent, ctx.stats, ctx.cfg);
let (is_eq, weak_eq, ink, flush) = {
let content: Vec<&Line> = if number.is_some() {
lines[..lines.len() - 1].iter().collect()
} else {
lines.iter().collect()
};
let features = RowFeatures::measure(ctx, &content, extent, isolated, number.is_some());
let sentence = number.is_none() && sentence_words(&content) >= ctx.cfg.sentence_min_words;
let is_eq = !sentence && is_equation(&features, ctx.cfg);
let flush = features.left_indent < ctx.cfg.weak_flush_max_indent_em * features.em;
let prose_chars = features.prose_frac * features.n_chars as f32;
let prose = prose_chars >= ctx.cfg.weak_full_min_prose_chars
|| (prose_chars > 0.0 && !features.multi && features.n_chars >= ctx.cfg.weak_full_flat_min_chars);
let full = flush && prose && features.right_slack < ctx.cfg.weak_full_max_slack_em * features.em;
let weak_eq = !is_eq && !full && !sentence && weak_equation(&features, ctx.cfg);
let ink = content.iter().fold(Rect::EMPTY, |acc, line| acc.union(&line.ink));
(is_eq, weak_eq, ink, flush)
};
if is_eq {
let number_line = if number.is_some() { lines.pop() } else { None };
let row = Row::Equation {
lines,
bbox: ink,
number,
number_line,
};
(row, None)
} else {
let weak = weak_eq.then_some((lines.clone(), ink, flush));
(Row::Text(merge_row(ctx.page.index, lines, ctx.lines_cfg)), weak)
}
}
const BIG_OPERATORS: &[&str] = &["∑", "∏", "∐", "⋃", "⋂", "⨁", "⨂", "⨀", "⋁", "⋀", "⨄", "⨆"];
static FUNCTION_TERM: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[A-Za-z]{1,4} ?\([^()]{1,40}\)$").unwrap());
const SENTENCE_WORDS: &[&str] = &[
"the", "we", "is", "are", "that", "this", "which", "for", "and", "with", "have", "has", "be", "can", "then",
"when", "one", "of", "to", "in", "by", "as", "on", "from", "it", "its", "our", "every", "all", "now", "so",
];
fn sentence_words(lines: &[&Line]) -> usize {
lines
.iter()
.map(|line| {
outside_parentheses(&line.text())
.split(|ch: char| !ch.is_ascii_alphabetic())
.filter(|word| SENTENCE_WORDS.iter().any(|known| known.eq_ignore_ascii_case(word)))
.count()
})
.sum()
}
fn outside_parentheses(text: &str) -> String {
let mut depth = 0usize;
let mut out = String::with_capacity(text.len());
for ch in text.chars() {
match ch {
'(' => depth += 1,
')' => depth = depth.saturating_sub(1),
_ if depth == 0 => out.push(ch),
_ => {}
}
}
out
}
fn equation_number(lines: &[Line], extent: &LeafExtent, stats: &DocStats, cfg: &BlocksConfig) -> Option<String> {
if lines.len() < 2 {
return None;
}
let last = lines.last().unwrap();
let text: String = last.text().chars().filter(|ch| !ch.is_whitespace()).collect();
(EQNO.is_match(&text) && last.bbox.x1 >= extent.right - cfg.eqno_margin_em * stats.body_size).then_some(text)
}
impl RowFeatures {
fn measure(ctx: BlockContext, content: &[&Line], extent: &LeafExtent, isolated: bool, numbered: bool) -> Self {
let cfg = ctx.cfg;
let stats = row_stats(content, ctx.fonts);
let content_box = content.iter().fold(Rect::EMPTY, |acc, line| acc.union(&line.bbox));
let em = content.iter().map(|line| line.size).fold(0.0, f32::max).max(1.0);
let left_indent = content_box.x0 - extent.left;
let right_slack = extent.right - content_box.x1;
let centered = (content_box.cx() - extent.center_x).abs()
<= (cfg.centered_tol_ratio * extent.width).max(cfg.centered_min_tol_pt)
&& left_indent >= cfg.centered_min_margin_em * em
&& right_slack >= cfg.centered_min_margin_em * em;
let multi = {
let mut baselines: Vec<f32> = content.iter().map(|line| line.baseline).collect();
baselines.sort_by(|a, b| a.total_cmp(b));
baselines.last().unwrap() - baselines[0] > cfg.multi_baseline_em * em
};
let has_relation = content
.iter()
.any(|line| line.glyphs.iter().any(|glyph| is_relation(&glyph.text)));
let text = content.iter().map(|line| line.text()).collect::<Vec<_>>().join(" ");
let text = text.trim();
let operator_start = text.starts_with([
'+', '\u{2212}', '=', '\u{D7}', '\u{B7}', '\u{2248}', '\u{2264}', '\u{2265}',
]);
let call_only = FUNCTION_TERM.is_match(text);
let has_bracket_piece = text.chars().any(is_bracket_piece);
Self {
numbered,
n_chars: stats.n_chars,
math_frac: stats.math_chars as f32 / stats.n_chars.max(1) as f32,
prose_frac: stats.prose_chars as f32 / stats.n_chars.max(1) as f32,
em,
left_indent,
right_slack,
centered,
isolated,
multi,
has_relation,
continues_display: operator_start || call_only,
has_bracket_piece,
}
}
}
fn is_equation(features: &RowFeatures, cfg: &BlocksConfig) -> bool {
if features.numbered {
return features.prose_frac < cfg.numbered_max_prose_ratio;
}
EQUATION_RULES.iter().any(|rule| rule(features, cfg))
}
fn displayed_formula(row: &RowFeatures, cfg: &BlocksConfig) -> bool {
row.math_frac >= cfg.display_min_math_ratio
&& row.prose_frac <= cfg.display_max_prose_ratio
&& (row.centered || row.left_indent >= cfg.display_min_indent_em * row.em)
}
fn drawn_bracket(row: &RowFeatures, cfg: &BlocksConfig) -> bool {
row.has_bracket_piece && row.prose_frac <= cfg.stacked_max_prose_ratio
}
fn is_bracket_piece(ch: char) -> bool {
('\u{239B}'..='\u{23AD}').contains(&ch)
}
fn symbol_row(row: &RowFeatures, cfg: &BlocksConfig) -> bool {
row.math_frac >= cfg.symbolic_min_math_ratio
&& row.prose_frac <= cfg.symbolic_max_prose_ratio
&& row.n_chars >= cfg.symbolic_min_chars
&& (row.left_indent >= cfg.symbolic_min_indent_em * row.em || row.isolated)
}
fn centred_relation(row: &RowFeatures, cfg: &BlocksConfig) -> bool {
row.centered
&& row.isolated
&& row.math_frac >= cfg.operator_min_math_ratio
&& row.prose_frac <= cfg.operator_max_prose_ratio
&& row.has_relation
}
fn stacked_formula(row: &RowFeatures, cfg: &BlocksConfig) -> bool {
row.multi
&& row.math_frac >= cfg.stacked_min_math_ratio
&& row.prose_frac <= cfg.stacked_max_prose_ratio
&& row.left_indent >= cfg.stacked_min_margin_em * row.em
&& row.right_slack >= cfg.stacked_min_margin_em * row.em
}
fn centred_stacked_relation(row: &RowFeatures, cfg: &BlocksConfig) -> bool {
row.centered
&& row.multi
&& row.has_relation
&& row.prose_frac == 0.0
&& row.math_frac >= cfg.operator_min_math_ratio
}
fn weak_equation(row: &RowFeatures, cfg: &BlocksConfig) -> bool {
(row.has_relation
&& row.left_indent >= cfg.weak_min_margin_em * row.em
&& row.right_slack >= cfg.weak_min_margin_em * row.em
&& row.n_chars <= cfg.weak_max_chars
&& row.prose_frac <= cfg.weak_max_prose_ratio)
|| (row.math_frac >= cfg.weak_min_math_ratio && row.prose_frac <= cfg.weak_math_max_prose_ratio)
|| (row.continues_display
&& row.n_chars <= cfg.weak_max_chars
&& row.left_indent >= cfg.weak_min_margin_em * row.em
&& row.right_slack >= cfg.weak_min_margin_em * row.em)
|| (row.n_chars <= cfg.weak_tiny_max_chars
&& row.prose_frac == 0.0
&& row.left_indent >= cfg.weak_min_margin_em * row.em
&& row.right_slack >= cfg.weak_min_margin_em * row.em)
}
fn promote_weak_equations(rows: &mut [Row], weak: &mut [Option<WeakEquation>], stats: &DocStats, cfg: &BlocksConfig) {
loop {
let mut changed = false;
for i in 0..rows.len() {
let Some((_, ink, flush)) = &weak[i] else { continue };
if *flush && i > 0 && matches!(rows[i - 1], Row::Text(_)) && weak[i - 1].is_none() {
continue;
}
let near = |j: usize| match &rows[j] {
Row::Equation { bbox, .. } => {
let gap = if bbox.cy() < ink.cy() {
ink.y0 - bbox.y1
} else {
bbox.y0 - ink.y1
};
gap < cfg.promote_max_gap_leading * stats.leading
}
_ => false,
};
if (i > 0 && near(i - 1)) || (i + 1 < rows.len() && near(i + 1)) {
let (lines, bbox, _) = weak[i].take().unwrap();
rows[i] = Row::Equation {
lines,
bbox,
number: None,
number_line: None,
};
changed = true;
}
}
if !changed {
break;
}
}
}
fn attach_stray_numbers(rows: &mut Vec<Row>, extent: &LeafExtent, stats: &DocStats, cfg: &BlocksConfig) {
let mut i = 0;
while i < rows.len() {
let Row::Text(line) = &rows[i] else {
i += 1;
continue;
};
let text: String = line.text().chars().filter(|ch| !ch.is_whitespace()).collect();
let at_margin = line.bbox.x1 >= extent.right - cfg.eqno_margin_em * stats.body_size;
if !(EQNO.is_match(&text) && at_margin) {
i += 1;
continue;
}
let max_gap = cfg.merge_max_gap_leading * stats.leading;
let ink = line.ink;
let takes = |row: Option<&Row>| match row {
Some(Row::Equation { number: None, bbox, .. }) => (ink.y0 - bbox.y1).max(bbox.y0 - ink.y1) < max_gap,
_ => false,
};
let target = if i > 0 && takes(rows.get(i - 1)) {
i - 1
} else if takes(rows.get(i + 1)) {
i + 1
} else {
i += 1;
continue;
};
let Row::Text(number_line) = rows.remove(i) else {
unreachable!()
};
let target = if target > i { target - 1 } else { target };
if let Row::Equation {
number,
number_line: slot,
..
} = &mut rows[target]
{
*number = Some(text);
*slot = Some(number_line);
}
}
}
fn merge_equation_rows(rows: Vec<Row>, stats: &DocStats, cfg: &BlocksConfig) -> Vec<Row> {
let mut merged: Vec<Row> = Vec::new();
for row in rows {
let Row::Equation {
lines,
bbox,
number,
number_line,
} = row
else {
merged.push(row);
continue;
};
if let Some(Row::Equation {
lines: prev_lines,
bbox: prev_bbox,
number: prev_number,
number_line: prev_number_line,
}) = merged.last_mut()
{
let gap = bbox.y0 - prev_bbox.y1;
let overlap = gap < 0.0;
if overlap
|| (gap < cfg.merge_max_gap_leading * stats.leading && !(prev_number.is_some() && number.is_some()))
{
prev_lines.extend(lines);
*prev_bbox = prev_bbox.union(&bbox);
if prev_number.is_none() {
*prev_number = number;
*prev_number_line = number_line;
} else if let Some(line) = number_line {
prev_lines.push(line);
}
continue;
}
}
merged.push(Row::Equation {
lines,
bbox,
number,
number_line,
});
}
merged
}
fn absorb_enclosed_rows(rows: Vec<Row>, bars: &[Rect], cfg: &BlocksConfig) -> Vec<Row> {
let tol = cfg.enclosing_tolerance_pt;
let belongs = |line: &Line, lines: &[Line], bbox: &Rect| {
let enclosed = enclosing_delimiters(lines, cfg)
.iter()
.any(|ink| line.ink.y0 >= ink.y0 - tol && line.ink.y1 <= ink.y1 + tol && line.ink.x0 >= ink.x1 - tol);
let gap = cfg.fraction_part_max_gap_em * line.size;
let fraction_part = bars.iter().any(|bar| {
let within = line.ink.x0 >= bar.x0 - tol && line.ink.x1 <= bar.x1 + tol;
let reaches = bar.x0 < bbox.x1 && bar.x1 > bbox.x0 && bar.y0 <= bbox.y1 + gap && bar.y1 >= bbox.y0 - gap;
let below = line.ink.y0 >= bar.y1 && line.ink.y0 - bar.y1 <= gap;
let above = line.ink.y1 <= bar.y0 && bar.y0 - line.ink.y1 <= gap;
within && reaches && (below || above)
});
let size = lines.iter().map(|line| line.size).fold(0.0, f32::max);
let limit = line.size <= cfg.limit_max_size_ratio * size
&& lines
.iter()
.flat_map(|eq_line| &eq_line.glyphs)
.filter(|glyph| BIG_OPERATORS.contains(&glyph.text.as_str()))
.any(|op| {
line.ink.x0 < op.ink.x1
&& line.ink.x1 > op.ink.x0
&& ((line.ink.y0 >= op.ink.y1 - tol && line.ink.y0 - op.ink.y1 <= gap)
|| (line.ink.y1 <= op.ink.y0 + tol && op.ink.y0 - line.ink.y1 <= gap))
});
enclosed || fraction_part || limit
};
let mut out: Vec<Row> = Vec::new();
for mut row in rows {
if let Row::Text(line) = &row
&& let Some(Row::Equation { lines, bbox, .. }) = out.last_mut()
&& belongs(line, lines, bbox)
{
*bbox = bbox.union(&line.ink);
if let Row::Text(line) = row {
lines.push(line);
}
continue;
}
if let Row::Equation { lines, bbox, .. } = &mut row {
while let Some(Row::Text(line)) = out.last()
&& belongs(line, lines, bbox)
{
*bbox = bbox.union(&line.ink);
if let Some(Row::Text(line)) = out.pop() {
lines.insert(0, line);
}
}
}
out.push(row);
}
out
}
fn inline_numerators(rows: Vec<Row>, bars: &[Rect], ctx: BlockContext) -> Vec<Row> {
let cfg = ctx.cfg;
let tol = cfg.enclosing_tolerance_pt;
let mut out: Vec<Row> = Vec::new();
for row in rows {
if let Row::Text(text) = &row
&& let Some(Row::Equation {
lines, number: None, ..
}) = out.last()
{
let gap = cfg.fraction_part_max_gap_em * text.size;
let numerator = |line: &Line| {
bars.iter().any(|bar| {
line.ink.x0 >= bar.x0 - tol
&& line.ink.x1 <= bar.x1 + tol
&& line.ink.y1 <= bar.y0
&& bar.y0 - line.ink.y1 <= gap
&& text.ink.y0 <= bar.y1 + gap
&& text.ink.y1 >= bar.y1
&& bar.x0 >= text.ink.x0 - tol
&& bar.x1 <= text.ink.x1 + tol
})
};
let inline = text.text().chars().count() >= cfg.inline_fraction_min_chars;
if lines.iter().all(numerator)
&& let Some(Row::Equation { mut lines, bbox, .. }) = out.pop()
&& let Row::Text(text) = row
{
if inline {
lines.push(text);
out.push(Row::Text(merge_row(ctx.page.index, lines, ctx.lines_cfg)));
} else {
let bbox = bbox.union(&text.ink);
lines.push(text);
out.push(Row::Equation {
lines,
bbox,
number: None,
number_line: None,
});
}
continue;
}
}
out.push(row);
}
out
}
fn fraction_bars(page: &PageData, cfg: &BlocksConfig) -> Vec<Rect> {
page.paths
.iter()
.filter(|path| !path.is_white())
.map(|path| path.bbox)
.filter(|bbox| {
bbox.height() <= cfg.fraction_bar_max_thickness_pt && bbox.width() >= cfg.fraction_bar_min_width_pt
})
.collect()
}
fn enclosing_delimiters(lines: &[Line], cfg: &BlocksConfig) -> Vec<Rect> {
lines
.iter()
.flat_map(|line| &line.glyphs)
.filter(|glyph| matches!(glyph.text.as_str(), "{" | "(" | "["))
.filter(|glyph| glyph.ink.height() > cfg.enclosing_min_height_em * glyph.size)
.map(|glyph| glyph.ink)
.collect()
}
fn footnote_start(ctx: BlockContext, leaf: &Leaf, rows: &[Row], extent: &LeafExtent) -> usize {
ruled_footnote_start(ctx, leaf, rows, extent)
.or_else(|| marked_footnote_start(rows, ctx.stats, ctx.cfg))
.unwrap_or(rows.len())
}
fn ruled_footnote_start(ctx: BlockContext, leaf: &Leaf, rows: &[Row], extent: &LeafExtent) -> Option<usize> {
let (stats, cfg) = (ctx.stats, ctx.cfg);
let text_rows: Vec<(usize, &Line)> = rows
.iter()
.enumerate()
.filter_map(|(i, row)| {
if let Row::Text(line) = row {
Some((i, line))
} else {
None
}
})
.collect();
let small = |line: &Line| line.size <= stats.body_size - cfg.footnote_size_drop_pt;
let mut best: Option<usize> = None;
for path in &ctx.page.paths {
if !path.is_hrule() {
continue;
}
let width = path.bbox.width();
if width < cfg.footnote_rule_min_width_pt
|| width > cfg.footnote_rule_max_width_ratio * extent.width.max(cfg.footnote_rule_min_leaf_pt)
{
continue;
}
let left_aligned = (path.bbox.x0 - extent.left).abs() <= cfg.footnote_rule_align_pt;
let centred = (path.bbox.cx() - extent.center_x).abs() <= cfg.footnote_rule_align_pt;
if !(left_aligned || centred) {
continue;
}
if path.bbox.y0 < leaf.bbox.y0 - cfg.footnote_rule_above_leaf_pt || path.bbox.y0 > leaf.bbox.y1 {
continue;
}
let below: Vec<&(usize, &Line)> = text_rows
.iter()
.filter(|(_, line)| line.bbox.y0 > path.bbox.y0 - cfg.footnote_rule_tol_pt)
.collect();
if below.is_empty() {
continue;
}
let marked_first = footnote_marked(below[0].1) || NUMBERED_NOTE.is_match(&below[0].1.text());
let fits = |line: &Line| {
small(line) || (marked_first && line.size <= stats.body_size + cfg.footnote_same_size_max_excess_pt)
};
if !below.iter().all(|(_, line)| fits(line)) {
continue;
}
let first = below[0].0;
if rows[first..].iter().any(|row| !matches!(row, Row::Text(_))) {
continue;
}
if best.is_none_or(|start| first < start) {
best = Some(first);
}
}
best
}
fn marked_footnote_start(rows: &[Row], stats: &DocStats, cfg: &BlocksConfig) -> Option<usize> {
let mut k = rows.len();
while k > 0 {
match &rows[k - 1] {
Row::Text(line) if line.size <= stats.body_size - cfg.footnote_run_size_drop_pt => k -= 1,
_ => break,
}
}
while k < rows.len() {
let Row::Text(line) = &rows[k] else { break };
let text = line.text();
let marked = footnote_marked(line) || NUMBERED_NOTE.is_match(&text) || VENUE_NOTE.is_match(&text);
let gap_ok = k == 0
|| match &rows[k - 1] {
Row::Text(prev) => {
line.baseline - prev.baseline
> cfg.footnote_gap_leading * stats.leading * line.size / stats.body_size
}
_ => true,
};
if marked && gap_ok && k > 0 {
return Some(k);
}
k += 1;
}
None
}
fn emit_blocks(ctx: BlockContext, rows: Vec<Row>, fn_start: usize, loc: Loc, out: &mut Vec<RawBlock>) {
let mut prev_baseline: Option<f32> = None;
let mut group: Vec<(Line, f32)> = Vec::new(); let n_rows = rows.len();
for (row_idx, row) in rows.into_iter().enumerate() {
let footnote = row_idx >= fn_start;
if row_idx == fn_start {
flush_group(ctx, &mut group, loc, out, false);
prev_baseline = None;
}
match row {
Row::Float(idx) => {
flush_group(ctx, &mut group, loc, out, footnote);
out.push(RawBlock::Float { idx, loc });
prev_baseline = None;
}
Row::Equation {
lines,
bbox,
number,
number_line,
} => {
flush_group(ctx, &mut group, loc, out, footnote);
out.push(RawBlock::Equation(EquationBlock {
lines,
bbox,
number,
number_line,
loc,
}));
prev_baseline = None;
}
Row::Text(line) => {
let gap = prev_baseline
.map(|baseline| line.baseline - baseline)
.unwrap_or(f32::INFINITY);
if let Some((last, _)) = group.last()
&& starts_new_group(ctx, last, &line, gap)
{
flush_group(ctx, &mut group, loc, out, footnote);
}
prev_baseline = Some(line.baseline);
group.push((line, gap));
}
}
if row_idx + 1 == n_rows {
flush_group(ctx, &mut group, loc, out, footnote);
}
}
flush_group(ctx, &mut group, loc, out, false);
}
fn starts_new_group(ctx: BlockContext, last: &Line, line: &Line, gap: f32) -> bool {
let (stats, cfg, fonts) = (ctx.stats, ctx.cfg, ctx.fonts);
let expected = stats.leading * last.size.max(line.size) / stats.body_size;
let ink_gap = line.ink.y0 - last.ink.y1;
let big_gap =
gap > cfg.block_gap_leading * expected + cfg.block_gap_slack_pt && ink_gap > cfg.block_ink_gap_em * line.size;
let size_change = (last.size - line.size).abs() > cfg.block_size_change_pt;
let bold_flip = bold_dominant(last, fonts, cfg) != bold_dominant(line, fonts, cfg)
&& last.char_count() > cfg.bold_flip_min_chars
&& line.char_count() > cfg.bold_flip_min_chars
&& (bold_dominant(last, fonts, cfg) || gap > cfg.bold_flip_gap_leading * expected)
&& !(bold_dominant(last, fonts, cfg) && starts_bold(line, fonts))
&& !(bold_dominant(last, fonts, cfg) && is_run_in_head(last, gap, expected, cfg));
big_gap || size_change || bold_flip
}
fn is_run_in_head(last: &Line, gap: f32, expected: f32, cfg: &BlocksConfig) -> bool {
let text = last.text();
let text = text.trim();
let words = text.split_whitespace().count();
let labeled = text
.split_whitespace()
.next()
.is_some_and(|word| word.chars().any(char::is_numeric) || word.trim_end_matches('.').chars().count() < 2);
text.ends_with('.')
&& !labeled
&& text.chars().next().is_some_and(char::is_uppercase)
&& (2..=cfg.bold_run_in_max_words_count).contains(&words)
&& gap <= cfg.bold_flip_gap_leading * expected
}
fn flush_group(ctx: BlockContext, group: &mut Vec<(Line, f32)>, loc: Loc, out: &mut Vec<RawBlock>, footnote: bool) {
if group.is_empty() {
return;
}
let cfg = ctx.cfg;
let lines: Vec<(Line, f32)> = std::mem::take(group);
let left = lines.iter().map(|line| line.0.bbox.x0).fold(f32::INFINITY, f32::min);
let right = lines
.iter()
.map(|line| line.0.bbox.x1)
.fold(f32::NEG_INFINITY, f32::max)
.min(ctx.leaf_right + cfg.para_right_overshoot_pt);
let centers: Vec<f32> = lines.iter().map(|line| line.0.bbox.cx()).collect();
let median_center = crate::common::geom::median(¢ers, 0.0);
let centered = lines.len() >= 2
&& centers
.iter()
.all(|center| (center - median_center).abs() <= cfg.centered_group_tol_pt)
&& lines
.iter()
.any(|line| (line.0.bbox.x0 - left).abs() > cfg.centered_group_min_offset_pt)
&& !footnote;
for para in split_paragraphs(lines, right, centered, footnote, ctx.fonts, cfg) {
let gap_before = para[0].1;
let lines: Vec<Line> = para.into_iter().map(|line| line.0).collect();
let bbox = lines.iter().fold(Rect::EMPTY, |acc, line| acc.union(&line.bbox));
let block = TextBlock {
lines,
loc,
left,
right,
centered,
gap_before,
bbox,
};
out.push(if footnote {
RawBlock::Footnote(block)
} else {
RawBlock::Text(block)
});
}
}
fn split_paragraphs(
lines: Vec<(Line, f32)>,
right: f32,
centered: bool,
footnote: bool,
fonts: &[FontInfo],
cfg: &BlocksConfig,
) -> Vec<Vec<(Line, f32)>> {
let ragged = is_ragged(&lines, right, fonts, cfg);
let mut paras: Vec<Vec<(Line, f32)>> = Vec::new();
for (line, gap) in lines {
let Some(para) = paras.last_mut() else {
paras.push(vec![(line, gap)]);
continue;
};
let breaks = !centered && {
let text = line.text();
let candidate = ParagraphBreak {
para,
line: &line,
text: &text,
right,
footnote,
ragged,
};
PARAGRAPH_RULES.iter().any(|rule| rule(&candidate, cfg))
};
if breaks {
paras.push(vec![(line, gap)]);
} else {
para.push((line, gap));
}
}
paras
}
fn starts_with_marker(candidate: &ParagraphBreak, _cfg: &BlocksConfig) -> bool {
(candidate.footnote && footnote_marked(candidate.line))
|| (BULLET.is_match(candidate.text) && !dash_goes_on(candidate))
}
fn dash_goes_on(candidate: &ParagraphBreak) -> bool {
let prev = candidate.para.last().map(|(line, _)| line.text()).unwrap_or_default();
let mut words = candidate.text.split_whitespace();
let dash = words.next().is_some_and(|word| matches!(word, "–" | "—" | "-"));
let lower = words
.next()
.and_then(|word| word.chars().next())
.is_some_and(char::is_lowercase);
dash && lower && !prev.trim_end().ends_with(['.', ':', ';', '!', '?'])
}
fn new_enumeration_item(candidate: &ParagraphBreak, cfg: &BlocksConfig) -> bool {
let first = &candidate.para[0].0;
let labelled = |text: &str| NUM_LABEL.is_match(text) || BRACKET_LABEL.is_match(text);
labelled(candidate.text)
&& labelled(&first.text())
&& (candidate.line.bbox.x0 - first.bbox.x0).abs() <= cfg.para_label_align_em * candidate.line.size
}
fn follows_short_line(candidate: &ParagraphBreak, cfg: &BlocksConfig) -> bool {
let prev = &candidate.para.last().unwrap().0;
let em = candidate.line.size;
let sentence_end = || {
prev.text()
.trim_end()
.trim_end_matches(['\u{2019}', '\u{201D}', '"', '\'', ')'])
.ends_with(['.', '!', '?', ':', ';'])
};
let nearly_full = candidate.right - prev.bbox.x1 <= cfg.ragged_line_max_gap_em * em;
!ends_with_hyphen(prev)
&& (!candidate.ragged || !nearly_full || sentence_end())
&& prev.bbox.x1 + cfg.para_word_space_em * em + candidate.line.first_word_width()
< candidate.right - cfg.para_short_line_slack_pt
}
fn is_ragged(lines: &[(Line, f32)], right: f32, fonts: &[FontInfo], cfg: &BlocksConfig) -> bool {
if lines.len() < cfg.ragged_min_lines_count {
return false;
}
let prose = lines.iter().all(|(line, _)| {
let text = line.text();
let words: Vec<&str> = text.split_whitespace().collect();
let lower = words
.iter()
.filter(|word| word.starts_with(|ch: char| ch.is_lowercase()))
.count();
line.font_frac(fonts, |font| font.mono) < cfg.bold_dominant_ratio
&& lower as f32 >= cfg.ragged_prose_min_lower_ratio * words.len() as f32
});
if !prose {
return false;
}
let body = &lines[..lines.len() - 1];
let flush = body
.iter()
.filter(|(line, _)| (line.bbox.x1 - right).abs() <= cfg.justified_edge_tol_pt)
.count();
(flush as f32) < cfg.justified_min_ratio * body.len() as f32
}
fn indent_changes(candidate: &ParagraphBreak, cfg: &BlocksConfig) -> bool {
if candidate.para.len() == 1 {
return false;
}
let em = candidate.line.size;
let rest_x0 = candidate.para[1..]
.iter()
.map(|line| line.0.bbox.x0)
.fold(f32::INFINITY, f32::min);
candidate.line.bbox.x0 > rest_x0 + cfg.para_indent_change_em * em
|| candidate.line.bbox.x0 < rest_x0 - cfg.para_indent_change_em * em
}
#[cfg(test)]
mod tests {
use super::{BlocksConfig, split_paragraphs};
use crate::analysis::lines::{LinesConfig, build_lines};
use crate::backend::{Dir, FontInfo, Glyph, RawPage};
use crate::common::geom::Rect;
use crate::model::Line;
fn lines_of(rows: &[&str]) -> Vec<(Line, f32)> {
let mut glyphs = Vec::new();
for (row, text) in rows.iter().enumerate() {
let y = 100.0 + 12.0 * row as f32;
for (i, ch) in text.chars().enumerate() {
let x = 40.0 + 5.0 * i as f32;
glyphs.push(Glyph {
text: ch.to_string(),
x,
y,
adv: 5.0,
size: 10.0,
font: 0,
dir: Dir::Horizontal,
angle: 0.0,
invisible: false,
color: [0; 3],
ink: Rect::new(x, y - 7.0, x + 5.0, y),
});
}
}
let raw = RawPage {
width: 600.0,
height: 800.0,
glyphs,
..Default::default()
};
let (lines, _) = build_lines(&raw, &LinesConfig::default());
lines.into_iter().map(|line| (line, 0.0)).collect()
}
fn paragraphs(rows: &[&str]) -> Vec<Vec<String>> {
let lines = lines_of(rows);
let right = lines
.iter()
.map(|(line, _)| line.bbox.x1)
.fold(f32::NEG_INFINITY, f32::max);
let fonts = [FontInfo::default()];
split_paragraphs(lines, right, false, false, &fonts, &BlocksConfig::default())
.into_iter()
.map(|para| para.iter().map(|(line, _)| line.text()).collect())
.collect()
}
#[test]
fn ragged_prose_breaks_only_at_the_end_of_a_sentence() {
let letter = [
"do not like it, for it will make the surprise the greater, when",
"I write to them and sign my name as his wife, and then you",
"will laugh at me and say that it is a good joke indeed. What",
"a good joke it will be! I can hardly write for laughing and",
"then I hope you will drink to our good journey.",
];
assert_eq!(paragraphs(&letter).len(), 1);
}
#[test]
fn ragged_list_of_names_keeps_its_lines_apart() {
let names = [
"Greg Brockman Infrastructure lead",
"Trevor Cai Throughput lead",
"David Farhi Optimization Team",
"Chris Hesse Usability Lead",
"Amin Tootoonchian Model Distribution, Systems & Networking Lead",
];
assert_eq!(paragraphs(&names).len(), names.len());
}
}