use super::assemble::is_footnote_symbol;
use super::patterns::*;
use super::*;
use crate::analysis::blocks::{LIST_LABEL, TextBlock};
use crate::analysis::page::DocStats;
use crate::model::LineGlyph;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ParagraphsConfig {
pub indent_sample_min_lines_count: usize,
pub indent_sample_size_tolerance_pt: f32,
pub first_line_indent_min_em: f32,
pub indent_min_paragraphs_count: i32,
pub indent_min_percent: i32,
pub labeled_refs_min_count: usize,
pub word_space_em: f32,
pub short_line_margin_pt: f32,
pub continuation_indent_min_em: f32,
pub ref_continuation_indent_min_em: f32,
pub size_tolerance_pt: f32,
pub footnote_size_tolerance_pt: f32,
pub same_leaf_max_gap_leading: f32,
pub spaced_cut_max_gap_leading: f32,
pub spaced_cut_min_width_ratio: f32,
pub cut_prose_min_letter_ratio: f32,
pub full_line_max_gap_em: f32,
pub ornament_max_chars_count: usize,
}
impl Default for ParagraphsConfig {
fn default() -> Self {
Self {
indent_sample_min_lines_count: 3,
indent_sample_size_tolerance_pt: 0.6,
first_line_indent_min_em: 0.8,
indent_min_paragraphs_count: 4,
indent_min_percent: 35,
labeled_refs_min_count: 3,
word_space_em: 0.25,
short_line_margin_pt: 1.0,
continuation_indent_min_em: 0.6,
ref_continuation_indent_min_em: 0.6,
size_tolerance_pt: 0.4,
footnote_size_tolerance_pt: 0.4,
same_leaf_max_gap_leading: 1.6,
spaced_cut_max_gap_leading: 2.5,
spaced_cut_min_width_ratio: 0.6,
cut_prose_min_letter_ratio: 0.6,
full_line_max_gap_em: 0.6,
ornament_max_chars_count: 12,
}
}
}
struct DocumentStyle<'a> {
fonts: &'a [FontInfo],
uses_indent: bool,
refs_labeled: bool,
spaced: bool,
}
struct Junction<'a> {
prev_class: &'a Class,
next_class: &'a Class,
next_leaf_left: f32,
last: &'a Line,
first: &'a Line,
em: f32,
last_text: String,
first_text: String,
hyphenated: bool,
short_last: bool,
indented_first: bool,
labeled_first: bool,
run_in_first: bool,
}
pub(crate) fn merge_paragraphs(nodes: &mut Vec<Node>, stats: &DocStats, fonts: &[FontInfo], cfg: &SemanticsConfig) {
let cfg = &cfg.paragraphs;
let style = DocumentStyle {
fonts,
uses_indent: uses_first_line_indent(nodes, stats, cfg),
refs_labeled: references_are_labeled(nodes, cfg),
spaced: stats.spaced_paragraphs,
};
join_chapter_labels(nodes);
join_heading_ornaments(nodes, cfg);
merge_cut_paragraphs(nodes, stats, cfg);
merge_split_blocks(nodes, &style, cfg);
merge_split_footnotes(nodes, cfg);
}
fn join_chapter_labels(nodes: &mut Vec<Node>) {
let mut i = 0;
while i + 1 < nodes.len() {
if let Some(class) = chapter_title_class(&nodes[i], &nodes[i + 1]) {
if let NodeKind::Text(title) = &nodes[i + 1].kind {
let bbox = title.bbox;
if let NodeKind::Text(label) = &mut nodes[i].kind {
label.bbox = label.bbox.union(&bbox);
}
}
nodes[i].class = class;
append_text_node(nodes, i, i + 1);
}
i += 1;
}
}
fn join_heading_ornaments(nodes: &mut Vec<Node>, cfg: &ParagraphsConfig) {
let mut i = 0;
while i + 1 < nodes.len() {
let joins = matches!(nodes[i].class, Class::Heading { .. })
&& nodes[i].text_block().is_some()
&& nodes[i + 1].loc.page == nodes[i].loc.page
&& nodes[i + 1]
.text_block()
.is_some_and(|block| is_ornament(&block_text(&block.lines), cfg.ornament_max_chars_count));
if joins {
if let NodeKind::Text(ornament) = &nodes[i + 1].kind {
let bbox = ornament.bbox;
if let NodeKind::Text(heading) = &mut nodes[i].kind {
heading.bbox = heading.bbox.union(&bbox);
}
}
append_text_node(nodes, i, i + 1);
}
i += 1;
}
}
fn chapter_title_class(label: &Node, title: &Node) -> Option<Class> {
let (
Class::Heading { number, .. },
Class::Heading {
number: title_number, ..
},
) = (&label.class, &title.class)
else {
return None;
};
let label_text = block_text(&label.text_block()?.lines);
let label_text = label_text.trim();
let title_text = block_text(&title.text_block()?.lines);
let whole_label = CHAPTER_LABEL
.find(label_text)
.is_some_and(|found| found.end() == label_text.len());
(label.loc.page == title.loc.page && whole_label && !CHAPTER_LABEL.is_match(title_text.trim())).then(|| {
Class::Heading {
level: 1,
number: number.clone().or_else(|| title_number.clone()),
}
})
}
fn merge_cut_paragraphs(nodes: &mut Vec<Node>, stats: &DocStats, cfg: &ParagraphsConfig) {
let mut i = 0;
while i + 1 < nodes.len() {
if is_cut_paragraph(&nodes[i], &nodes[i + 1], stats, cfg) {
append_text_node(nodes, i, i + 1);
} else {
i += 1;
}
}
}
fn is_cut_paragraph(prev: &Node, next: &Node, stats: &DocStats, cfg: &ParagraphsConfig) -> bool {
let same_flow = match (&prev.class, &next.class) {
(Class::Paragraph { in_abstract: a }, Class::Paragraph { in_abstract: b }) => a == b,
(Class::ListItem { .. } | Class::ListContinuation, Class::ListContinuation) => true,
_ => false,
};
if !same_flow {
return false;
}
let (Some(prev_block), Some(next_block)) = (prev.text_block(), next.text_block()) else {
return false;
};
let (last, first) = (prev_block.lines.last().unwrap(), &next_block.lines[0]);
let full_last = prev_block.right - last.bbox.x1 <= cfg.full_line_max_gap_em * last.size
&& next_block.gap_before <= cfg.same_leaf_max_gap_leading * stats.leading;
let column = prev.leaf_right - prev.leaf_left;
let spaced_cut = stats.spaced_paragraphs
&& last.text().trim_end().ends_with(char::is_alphanumeric)
&& (prev_block.lines.len() >= 2 || last.bbox.x1 - prev.leaf_left >= cfg.spaced_cut_min_width_ratio * column)
&& next_block.gap_before <= cfg.spaced_cut_max_gap_leading * stats.leading;
((full_last && (prev_block.lines.len() >= 2 || last.text().ends_with('-'))) || spaced_cut)
&& prev.tail == (next.loc.page, next.loc.leaf)
&& (last.size - first.size).abs() <= cfg.size_tolerance_pt
&& !ends_terminal(&last.text())
&& first_alpha_lower(&first.text())
&& prose_line(&last.text(), cfg)
&& prose_line(&first.text(), cfg)
}
fn prose_line(text: &str, cfg: &ParagraphsConfig) -> bool {
let visible: Vec<char> = text.chars().filter(|ch| !ch.is_whitespace()).collect();
let letters = visible.iter().filter(|ch| ch.is_alphabetic()).count();
!visible.first().is_some_and(char::is_ascii_digit)
&& letters as f32 >= cfg.cut_prose_min_letter_ratio * visible.len() as f32
}
fn uses_first_line_indent(nodes: &[Node], stats: &DocStats, cfg: &ParagraphsConfig) -> bool {
let (mut indented, mut total) = (0, 0);
for node in nodes {
if let (Some(block), Class::Paragraph { .. }) = (node.text_block(), &node.class)
&& block.lines.len() >= cfg.indent_sample_min_lines_count
&& (block_size(&block.lines) - stats.body_size).abs() < cfg.indent_sample_size_tolerance_pt
{
total += 1;
let rest = block.lines[1..]
.iter()
.map(|line| line.bbox.x0)
.fold(f32::INFINITY, f32::min);
if block.lines[0].bbox.x0 > rest + cfg.first_line_indent_min_em * stats.body_size {
indented += 1;
}
}
}
total >= cfg.indent_min_paragraphs_count && indented * 100 >= total * cfg.indent_min_percent
}
fn references_are_labeled(nodes: &[Node], cfg: &ParagraphsConfig) -> bool {
nodes
.iter()
.filter(|node| node.class == Class::Reference)
.filter_map(|node| node.text_block())
.filter(|block| REF_LABEL.is_match(block_text(&block.lines).trim()))
.count()
>= cfg.labeled_refs_min_count
}
fn merge_split_blocks(nodes: &mut Vec<Node>, style: &DocumentStyle, cfg: &ParagraphsConfig) {
let mut i = 0;
while i < nodes.len() {
match continuation_of(nodes, i, style, cfg) {
Some(j) => append_text_node(nodes, i, j),
None => i += 1,
}
}
}
fn continuation_of(nodes: &[Node], i: usize, style: &DocumentStyle, cfg: &ParagraphsConfig) -> Option<usize> {
let mergeable = matches!(
nodes[i].class,
Class::Paragraph { .. } | Class::Reference | Class::ListItem { .. }
) && nodes[i].text_block().is_some();
if !mergeable {
return None;
}
let tail = nodes[i].tail;
let mut j = i + 1;
while j < nodes.len() && (nodes[j].loc.page, nodes[j].loc.leaf) == tail {
if is_flow(&nodes[j]) {
return None;
}
j += 1;
}
while j < nodes.len() && !is_flow(&nodes[j]) {
j += 1;
}
if j >= nodes.len() || nodes[j].loc.page > tail.0 + 1 {
return None;
}
let next_leaf = (nodes[j].loc.page, nodes[j].loc.leaf);
let first_in_leaf = !nodes[..j]
.iter()
.rev()
.take_while(|node| (node.loc.page, node.loc.leaf) == next_leaf)
.any(is_flow);
if !first_in_leaf || !compatible_classes(&nodes[i].class, &nodes[j].class) || next_leaf == tail {
return None;
}
let junction = Junction::new(&nodes[i], &nodes[j], style.fonts, cfg);
junction.joins(style, cfg).then_some(j)
}
fn is_flow(node: &Node) -> bool {
matches!(node.kind, NodeKind::Text(_) | NodeKind::Equation(_))
}
fn compatible_classes(prev: &Class, next: &Class) -> bool {
match (prev, next) {
(Class::Paragraph { in_abstract: a }, Class::Paragraph { in_abstract: b }) => a == b,
(Class::Reference, Class::Reference) => true,
(Class::ListItem { .. } | Class::ListContinuation, Class::Paragraph { .. } | Class::ListContinuation) => true,
(Class::Paragraph { .. }, Class::ListItem { bullet: false }) => true,
_ => false,
}
}
impl<'a> Junction<'a> {
fn new(prev: &'a Node, next: &'a Node, fonts: &[FontInfo], cfg: &ParagraphsConfig) -> Self {
let (prev_block, next_block) = (prev.text_block().unwrap(), next.text_block().unwrap());
let (last, first) = (prev_block.lines.last().unwrap(), &next_block.lines[0]);
let em = first.size;
let last_text = last.text();
let first_text = first.text();
let same_page: Vec<f32> = prev_block
.lines
.iter()
.filter(|line| line.page == last.page)
.map(|line| line.bbox.x1)
.collect();
let right_edge = if prev_block.lines.len() >= 2 && same_page.len() == prev_block.lines.len() {
prev_block.right
} else if same_page.len() >= 2 {
same_page.iter().copied().fold(f32::NEG_INFINITY, f32::max)
} else {
prev.leaf_right
};
let hyphenated = last_text.ends_with('-');
let short_last =
last.bbox.x1 + cfg.word_space_em * em + first.first_word_width() < right_edge - cfg.short_line_margin_pt;
let indented_first = if next_block.lines.len() >= 2 {
let rest = next_block.lines[1..]
.iter()
.map(|line| line.bbox.x0)
.fold(f32::INFINITY, f32::min);
first.bbox.x0 > rest + cfg.continuation_indent_min_em * em
} else {
first.bbox.x0 > next.leaf_left + cfg.continuation_indent_min_em * em
};
let labeled_first = LIST_LABEL.is_match(first_text.trim());
let bold = |glyph: Option<&LineGlyph>| {
glyph
.and_then(|glyph| fonts.get(glyph.font as usize))
.is_some_and(|font| font.bold)
};
let visible = |glyph: &&LineGlyph| !glyph.text.trim().is_empty();
let run_in_first = bold(first.glyphs.iter().find(visible)) && !bold(last.glyphs.iter().rev().find(visible));
Self {
prev_class: &prev.class,
next_class: &next.class,
next_leaf_left: next.leaf_left,
last,
first,
em,
last_text,
first_text,
hyphenated,
short_last,
indented_first,
labeled_first,
run_in_first,
}
}
fn joins(&self, style: &DocumentStyle, cfg: &ParagraphsConfig) -> bool {
self.size_rule(cfg)
.or_else(|| self.reference_rule(style, cfg))
.or_else(|| self.run_in_rule())
.or_else(|| self.list_label_rule())
.or_else(|| self.hyphen_rule())
.or_else(|| self.spaced_sentence_rule(style))
.or_else(|| self.layout_break_rule())
.or_else(|| self.sentence_rule())
.unwrap_or(style.uses_indent)
}
fn size_rule(&self, cfg: &ParagraphsConfig) -> Option<bool> {
((self.last.size - self.first.size).abs() > cfg.size_tolerance_pt).then_some(false)
}
fn reference_rule(&self, style: &DocumentStyle, cfg: &ParagraphsConfig) -> Option<bool> {
if *self.prev_class != Class::Reference {
return None;
}
let labeled = REF_LABEL.is_match(self.first_text.trim());
Some(
!labeled
&& (style.refs_labeled
|| self.first.bbox.x0 > self.next_leaf_left + cfg.ref_continuation_indent_min_em * self.em),
)
}
fn run_in_rule(&self) -> Option<bool> {
self.run_in_first.then_some(false)
}
fn list_label_rule(&self) -> Option<bool> {
(self.labeled_first
&& (matches!(self.next_class, Class::ListItem { bullet: true })
|| ends_terminal(&self.last_text)
|| self.short_last))
.then_some(false)
}
fn hyphen_rule(&self) -> Option<bool> {
self.hyphenated.then_some(true)
}
fn spaced_sentence_rule(&self, style: &DocumentStyle) -> Option<bool> {
(style.spaced
&& !self.indented_first
&& !ends_terminal(&self.last_text)
&& first_alpha_lower(&self.first_text)
&& self.last_text.chars().any(char::is_lowercase))
.then_some(true)
}
fn layout_break_rule(&self) -> Option<bool> {
(self.short_last || self.indented_first).then_some(false)
}
fn sentence_rule(&self) -> Option<bool> {
(first_alpha_lower(&self.first_text) || !ends_terminal(&self.last_text)).then_some(true)
}
}
fn append_text_node(nodes: &mut Vec<Node>, i: usize, j: usize) {
let removed = nodes.remove(j);
let NodeKind::Text(appended) = removed.kind else {
unreachable!()
};
let NodeKind::Text(target) = &mut nodes[i].kind else {
unreachable!()
};
target.lines.extend(appended.lines);
nodes[i].tail = removed.tail;
nodes[i].leaf_right = removed.leaf_right;
}
fn merge_split_footnotes(nodes: &mut Vec<Node>, cfg: &ParagraphsConfig) {
let mut last_footnote: Option<usize> = None;
let mut i = 0;
while i < nodes.len() {
let NodeKind::Footnote(block) = &nodes[i].kind else {
i += 1;
continue;
};
if let Some(prev_idx) = last_footnote
&& continues_footnote(&nodes[prev_idx], &nodes[i], block, cfg)
{
let removed = nodes.remove(i);
let NodeKind::Footnote(appended) = removed.kind else {
unreachable!()
};
let NodeKind::Footnote(target) = &mut nodes[prev_idx].kind else {
unreachable!()
};
target.lines.extend(appended.lines);
continue;
}
last_footnote = Some(i);
i += 1;
}
}
fn continues_footnote(prev: &Node, node: &Node, block: &TextBlock, cfg: &ParagraphsConfig) -> bool {
let NodeKind::Footnote(prev_block) = &prev.kind else {
unreachable!()
};
let prev_text = prev_block.lines.last().unwrap().text();
let different_leaf = (prev.loc.page, prev.loc.leaf) != (node.loc.page, node.loc.leaf);
different_leaf
&& !has_footnote_mark(block)
&& has_footnote_mark(prev_block)
&& (prev_text.ends_with('-') || !ends_terminal(&prev_text))
&& (prev_block.lines[0].size - block.lines[0].size).abs() < cfg.footnote_size_tolerance_pt
}
fn has_footnote_mark(block: &TextBlock) -> bool {
block.lines[0].starts_with_superscript()
|| block.lines[0]
.glyphs
.first()
.is_some_and(|glyph| is_footnote_symbol(&glyph.text))
}
#[cfg(test)]
mod tests {
use super::ParagraphsConfig;
use crate::analysis::semantics::is_ornament;
#[test]
fn ornaments_have_no_letters_or_digits() {
let cfg = ParagraphsConfig::default();
for ornament in ["◄○►", "* * *", "❦", "~ ~"] {
assert!(is_ornament(ornament, cfg.ornament_max_chars_count), "{ornament}");
}
for text in ["2", "A", "* * * * * * * * * * * * *", "", "(1)"] {
assert!(!is_ornament(text, cfg.ornament_max_chars_count), "{text}");
}
}
}