Skip to content

A fast, helpful, and open-source document parser

Layout and markdown: cut above column-spanning lines, keep prose columns apart, rotated page text, figure-split paragraphs, emphasis and super/subscript, stacked tables

Logan Markewiche9e7c030003c
diff --git a/crates/liteparse/examples/dump_regions.rs b/crates/liteparse/examples/dump_regions.rs
new file mode 100644
index 0000000..732aa18
--- /dev/null
+++ b/crates/liteparse/examples/dump_regions.rs
@@ -0,0 +1,69 @@
+//! Print a page's XY-cut region tree: each split's axis, each leaf's box and its first lines.
+//! Usage: dump_regions <pdf> [page] (OCR off; for diagnosing column interleave)
+use liteparse::config::{LiteParseConfig, OutputFormat};
+use liteparse::parser::LiteParse;
+use liteparse::types::{PdfInput, ProjectedLine, Region, RegionKind};
+
+fn walk(r: &Region, path: &mut Vec<u16>, lines: &[ProjectedLine], depth: usize) {
+ let b = &r.bbox;
+ let pad = " ".repeat(depth);
+ match &r.kind {
+ RegionKind::Split { axis, children } => {
+ println!(
+ "{pad}split {:?} [{:.0},{:.0} {:.0}x{:.0}] {} children",
+ axis,
+ b.x,
+ b.y,
+ b.width,
+ b.height,
+ children.len()
+ );
+ for (i, c) in children.iter().enumerate() {
+ path.push(i as u16);
+ walk(c, path, lines, depth + 1);
+ path.pop();
+ }
+ }
+ RegionKind::Leaf { item_indices } => {
+ let mine: Vec<&ProjectedLine> =
+ lines.iter().filter(|l| l.region_path == *path).collect();
+ println!(
+ "{pad}leaf {:?} [{:.0},{:.0} {:.0}x{:.0}] items={} lines={}",
+ path,
+ b.x,
+ b.y,
+ b.width,
+ b.height,
+ item_indices.len(),
+ mine.len()
+ );
+ for l in mine.iter().take(3) {
+ let t: String = l.text.trim().chars().take(90).collect();
+ println!("{pad} | {t}");
+ }
+ }
+ }
+}
+
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn std::error::Error>> {
+ let path = std::env::args()
+ .nth(1)
+ .ok_or("usage: dump_regions <pdf> [page]")?;
+ let page_num: usize = std::env::args()
+ .nth(2)
+ .and_then(|s| s.parse().ok())
+ .unwrap_or(1);
+ let cfg = LiteParseConfig {
+ output_format: OutputFormat::Markdown,
+ ocr_enabled: false,
+ quiet: true,
+ ..Default::default()
+ };
+ let r = LiteParse::new(cfg)
+ .parse_input(PdfInput::Path(path))
+ .await?;
+ let p = &r.pages[page_num - 1];
+ walk(&p.regions, &mut Vec::new(), &p.projected_lines, 0);
+ Ok(())
+}
diff --git a/crates/liteparse/src/extract.rs b/crates/liteparse/src/extract.rs
index 49a5441..2ce87eb 100644
--- a/crates/liteparse/src/extract.rs
+++ b/crates/liteparse/src/extract.rs
@@ -400,6 +400,7 @@ fn extract_single_page(
};
assign_links(&mut text_items, &links);
assign_strikethrough(&mut text_items, &graphics);
+ assign_underline(&mut text_items, &graphics);
Ok(PageExtraction {
page: LitePage {
@@ -687,6 +688,92 @@ fn assign_strikethrough(items: &mut [TextItem], graphics: &[GraphicPrimitive]) {
}
}
+/// Mark text items underlined by a thin horizontal line just below their baseline. Unlike a
+/// strikethrough, an underline is judged per line rather than per item: the text sitting on it
+/// must cover most of its length, so table borders, rules and dividers (which run on past the
+/// text above them) underline nothing, while one underline under several word items marks them
+/// all.
+fn assign_underline(items: &mut [TextItem], graphics: &[GraphicPrimitive]) {
+ let mut segs: Vec<(f32, f32, f32)> = Vec::new();
+ for g in graphics {
+ match g {
+ GraphicPrimitive::Stroke {
+ x1,
+ y1,
+ x2,
+ y2,
+ width,
+ ..
+ } => {
+ let (dx, dy) = ((x1 - x2).abs(), (y1 - y2).abs());
+ if dy <= STRIKE_MAX_THICKNESS_PT
+ && *width <= STRIKE_MAX_THICKNESS_PT
+ && dx > 4.0 * dy.max(0.1)
+ {
+ segs.push((x1.min(*x2), x1.max(*x2), (y1 + y2) * 0.5));
+ }
+ }
+ GraphicPrimitive::Rect { bbox, .. } => {
+ if bbox.height <= STRIKE_MAX_THICKNESS_PT && bbox.width > 4.0 * bbox.height.max(0.1)
+ {
+ segs.push((bbox.x, bbox.x + bbox.width, bbox.y + bbox.height * 0.5));
+ }
+ }
+ }
+ }
+ for &(sx0, sx1, sy) in &segs {
+ let len = sx1 - sx0;
+ if len < 2.0 {
+ continue;
+ }
+ // Items whose baseline region the line runs under: below the lower fifth of the box,
+ // at most a quarter of the box height (2 pt floor) beneath it.
+ let on: Vec<usize> = items
+ .iter()
+ .enumerate()
+ .filter(|(_, it)| {
+ !it.math
+ && it.width > 0.0
+ && it.height > 0.0
+ && it.rotation.rem_euclid(360.0) < 1.0
+ && !it.text.trim().is_empty()
+ && sy >= it.y + it.height * 0.80
+ && sy <= it.y + it.height + (it.height * 0.25).max(2.0)
+ && it.x < sx1
+ && it.x + it.width > sx0
+ })
+ .map(|(i, _)| i)
+ .collect();
+ if on.is_empty() {
+ continue;
+ }
+ // Covered length of the line (union of the items' clipped extents).
+ let mut spans: Vec<(f32, f32)> = on
+ .iter()
+ .map(|&i| (items[i].x.max(sx0), (items[i].x + items[i].width).min(sx1)))
+ .collect();
+ spans.sort_by(|a, b| a.0.total_cmp(&b.0));
+ let (mut covered, mut reach) = (0.0f32, f32::NEG_INFINITY);
+ for (a, b) in spans {
+ let a = a.max(reach);
+ if b > a {
+ covered += b - a;
+ }
+ reach = reach.max(b);
+ }
+ if covered < len * 0.7 {
+ continue;
+ }
+ for i in on {
+ let it = &mut items[i];
+ let overlap = ((it.x + it.width).min(sx1) - it.x.max(sx0)).max(0.0);
+ if overlap >= it.width * 0.5 {
+ it.underline = true;
+ }
+ }
+ }
+}
+
/// Walk the document outline (bookmarks). Returns entries in pre-order.
/// Empty when the PDF has no outline.
pub(crate) fn extract_outline(document: &Document) -> Vec<OutlineTarget> {
@@ -1791,7 +1878,30 @@ fn extract_page_text_items(
c,
);
}
- if !y_overlap || line_changed || gap >= MAX_INLINE_GAP || dot_leader_break {
+ // A size step with a baseline shift (a superscript / subscript run, or back from
+ // one) starts a new item, so projection can tell the raised or lowered run from the
+ // text it follows. A declared size change alone is no script: producers draw the same
+ // visible text with different size / matrix pairs ("290-300." after a reference's
+ // "Nat. Energy 2018, 3,"), and splitting those let projection misplace the piece.
+ let size_break = seg.font_height.is_some_and(|sh| {
+ let m = obj_meta.meta_for(&ch, cv.text_object());
+ let fh = if m.font_size > 0.0 {
+ m.scale_y.map(|sy| m.font_size * sy)
+ } else {
+ None
+ };
+ let shifted = (vp_strict.bottom - seg.last_char_bottom).abs()
+ > 0.15
+ * (seg.vp_bottom - seg.vp_top)
+ .abs()
+ .max(vp_strict.bottom - vp_strict.top);
+ shifted
+ && fh.is_some_and(|fh| {
+ sh > 0.0 && fh > 0.0 && (fh < sh * 0.78 || sh < fh * 0.78)
+ })
+ });
+ if !y_overlap || line_changed || gap >= MAX_INLINE_GAP || dot_leader_break || size_break
+ {
seg.flush(&mut items);
let meta = obj_meta.meta_for(&ch, cv.text_object());
seg.start(
@@ -3658,6 +3768,9 @@ impl SegmentBuilder {
confidence: None,
link: None,
strike: false,
+ underline: false,
+ sup: false,
+ sub: false,
math: false,
words: std::mem::take(&mut self.words),
});
diff --git a/crates/liteparse/src/markdown_layout/blocks.rs b/crates/liteparse/src/markdown_layout/blocks.rs
index 89ab502..caa4cfa 100644
--- a/crates/liteparse/src/markdown_layout/blocks.rs
+++ b/crates/liteparse/src/markdown_layout/blocks.rs
@@ -275,6 +275,326 @@ impl PositionedBlock {
}
}
+/// Rejoin a paragraph that a figure cut in two. Figures are placed by their top edge, so one set
+/// beside a paragraph lands between two of its lines ("... including ![](img) glasses, ...").
+/// When a paragraph is followed by figures and then a paragraph that continues it (the first
+/// does not end a sentence, the second starts lowercase, both share the paragraph style), the
+/// halves join (de-hyphenated) and the figures follow the joined paragraph.
+pub fn rejoin_paragraphs_around_figures(blocks: Vec<PositionedBlock>) -> Vec<PositionedBlock> {
+ let mut out: Vec<PositionedBlock> = Vec::with_capacity(blocks.len());
+ let mut it = blocks.into_iter().peekable();
+ while let Some(pb) = it.next() {
+ let Block::Paragraph { text, bold, italic } = pb.block else {
+ out.push(pb);
+ continue;
+ };
+ let (mut text, mut bbox) = (text, pb.bbox);
+ let mut held: Vec<PositionedBlock> = Vec::new();
+ loop {
+ // figures directly after this paragraph
+ let mut figs: Vec<PositionedBlock> = Vec::new();
+ while it
+ .peek()
+ .is_some_and(|b| matches!(b.block, Block::Figure { .. }))
+ {
+ figs.push(it.next().unwrap());
+ }
+ let continues = !figs.is_empty()
+ && !ends_sentence(&text)
+ && it.peek().is_some_and(|b| match &b.block {
+ Block::Paragraph {
+ text: t,
+ bold: b2,
+ italic: i2,
+ } => *b2 == bold && *i2 == italic && starts_continuation(t),
+ _ => false,
+ });
+ if !continues {
+ held.extend(figs);
+ break;
+ }
+ let next = it.next().unwrap();
+ if let Block::Paragraph { text: t, .. } = next.block {
+ let raw = super::paragraphs::collapse_whitespace(&t);
+ super::inline::append_inline_continuation(&mut text, &raw, &t);
+ }
+ if let Some(r) = &next.bbox {
+ Rect::extend(&mut bbox, r);
+ }
+ held.extend(figs);
+ }
+ out.push(PositionedBlock {
+ block: Block::Paragraph { text, bold, italic },
+ bbox,
+ });
+ out.extend(held);
+ }
+ out
+}
+
+fn ends_sentence(text: &str) -> bool {
+ let t = text
+ .trim_end()
+ .trim_end_matches(['*', '_', '~', '`', ')', '"', '\'', '”', '’', ']']);
+ t.ends_with(['.', '!', '?', ':', ';']) || t.is_empty()
+}
+
+fn starts_continuation(text: &str) -> bool {
+ text.trim_start()
+ .trim_start_matches(['*', '_', '~'])
+ .chars()
+ .next()
+ .is_some_and(|c| c.is_lowercase())
+}
+
+/// Split tables whose rows repeat an earlier column-header row: several tables with the same
+/// columns, stacked (rate tables per scenario, one schedule per year), that table detection read
+/// as one. A header-like row (three or more filled cells, at most a third of them numbers) that
+/// repeats one of the current table's first three rows starts a new table, taking with it a
+/// one-cell title row just above it ("Proposed Base Rate"). Tables set side by side with the
+/// same columns split at their shared empty gutter column ([`side_by_side_gutter`]).
+/// ParseBench v1 tables 65.6 -> 66.8; OPB, odl unchanged; ParseBench v2 tables 63.8 -> 63.7 core,
+/// 55.3 -> 55.5 full.
+pub fn split_repeated_header_tables(blocks: Vec<PositionedBlock>) -> Vec<PositionedBlock> {
+ let mut out = Vec::with_capacity(blocks.len());
+ for pb in blocks {
+ match pb.block {
+ Block::Table { header, rows } => {
+ let mut all: Vec<Vec<Cell>> = header.into_iter().collect();
+ let had_header = !all.is_empty();
+ all.extend(rows);
+ // side by side first: each half is then checked for stacked repeats
+ if let Some(gutter) = side_by_side_gutter(&all) {
+ let (mut left, mut right): (Vec<Vec<Cell>>, Vec<Vec<Cell>>) =
+ (Vec::new(), Vec::new());
+ for mut r in all {
+ r.resize(r.len().max(gutter + 1), Cell::from(""));
+ let tail = r.split_off(gutter + 1);
+ r.truncate(gutter);
+ left.push(r);
+ right.push(tail);
+ }
+ for part in [left, right] {
+ let bbox =
+ union_cells(part.iter().flatten().filter_map(|c| c.bbox.as_ref()))
+ .or(pb.bbox.clone());
+ let mut it = part.into_iter();
+ let header = if had_header { it.next() } else { None };
+ out.extend(split_repeated_header_tables(vec![PositionedBlock {
+ block: Block::Table {
+ header,
+ rows: it.collect(),
+ },
+ bbox,
+ }]));
+ }
+ continue;
+ }
+ let texts: Vec<Vec<&str>> = all
+ .iter()
+ .map(|r| r.iter().map(|c| c.as_str()).collect())
+ .collect();
+ let cuts = repeated_header_cuts(&texts, &vec![false; all.len()]);
+ if cuts.is_empty() {
+ let mut it = all.into_iter();
+ let header = if had_header { it.next() } else { None };
+ out.push(PositionedBlock {
+ block: Block::Table {
+ header,
+ rows: it.collect(),
+ },
+ bbox: pb.bbox,
+ });
+ continue;
+ }
+ let mut start = 0;
+ for (k, end) in cuts.iter().copied().chain([all.len()]).enumerate() {
+ let seg: Vec<Vec<Cell>> = all[start..end].to_vec();
+ let bbox = union_cells(seg.iter().flatten().filter_map(|c| c.bbox.as_ref()))
+ .or(pb.bbox.clone());
+ let mut it = seg.into_iter();
+ let header = if k > 0 || had_header { it.next() } else { None };
+ out.push(PositionedBlock {
+ block: Block::Table {
+ header,
+ rows: it.collect(),
+ },
+ bbox,
+ });
+ start = end;
+ }
+ }
+ Block::MergedTable { rows, header_rows } => {
+ // a cut may not fall inside a row span
+ let mut spanned = vec![false; rows.len()];
+ for (r, row) in rows.iter().enumerate() {
+ for c in row {
+ let end = (r + c.rowspan.max(1) as usize).min(rows.len());
+ for s in spanned.iter_mut().take(end).skip(r + 1) {
+ *s = true;
+ }
+ }
+ }
+ let texts: Vec<Vec<&str>> = rows
+ .iter()
+ .map(|r| r.iter().map(|c| c.text.as_str()).collect())
+ .collect();
+ let cuts = repeated_header_cuts(&texts, &spanned);
+ if cuts.is_empty() {
+ out.push(PositionedBlock {
+ block: Block::MergedTable { rows, header_rows },
+ bbox: pb.bbox,
+ });
+ continue;
+ }
+ let mut start = 0;
+ for (k, end) in cuts.iter().copied().chain([rows.len()]).enumerate() {
+ let seg: Vec<Vec<SpanCell>> = rows[start..end].to_vec();
+ let bbox = union_cells(seg.iter().flatten().filter_map(|c| c.bbox.as_ref()))
+ .or(pb.bbox.clone());
+ // later parts: their title row and repeated header row head the part
+ let hr = if k == 0 {
+ header_rows.min(seg.len())
+ } else {
+ (end - start).min(
+ if seg
+ .first()
+ .is_some_and(|r| nonempty(r.iter().map(|c| c.text.as_str())) == 1)
+ {
+ 2
+ } else {
+ 1
+ },
+ )
+ };
+ out.push(PositionedBlock {
+ block: Block::MergedTable {
+ rows: seg,
+ header_rows: hr,
+ },
+ bbox,
+ });
+ start = end;
+ }
+ }
+ block => out.push(PositionedBlock {
+ block,
+ bbox: pb.bbox,
+ }),
+ }
+ }
+ out
+}
+
+/// A column empty in every row that separates two tables set side by side: each side keeps at
+/// least two columns and the sides' first rows share at least half of the smaller side's
+/// non-empty header cells (the same columns repeated), so a spacer column inside one table
+/// (empty between a currency sign and its figures) is never a cut.
+fn side_by_side_gutter(rows: &[Vec<Cell>]) -> Option<usize> {
+ let width = rows.iter().map(|r| r.len()).max()?;
+ let empty = |c: usize| {
+ rows.iter()
+ .all(|r| r.get(c).is_none_or(|x| x.as_str().trim().is_empty()))
+ };
+ let norm = |s: &str| {
+ s.split_whitespace()
+ .collect::<Vec<_>>()
+ .join(" ")
+ .to_lowercase()
+ };
+ let head = rows.first()?;
+ (2..width.saturating_sub(2)).find(|&g| {
+ if !empty(g) || (0..g).all(empty) || (g + 1..width).all(empty) {
+ return false;
+ }
+ let left: Vec<String> = head
+ .iter()
+ .take(g)
+ .map(|c| norm(c.as_str()))
+ .filter(|s| !s.is_empty())
+ .collect();
+ let right: Vec<String> = head
+ .iter()
+ .skip(g + 1)
+ .map(|c| norm(c.as_str()))
+ .filter(|s| !s.is_empty())
+ .collect();
+ let shared = right.iter().filter(|s| left.contains(s)).count();
+ left.len() >= 2 && right.len() >= 2 && shared * 2 >= left.len().min(right.len())
+ })
+}
+
+fn nonempty<'a>(cells: impl Iterator<Item = &'a str>) -> usize {
+ cells.filter(|c| !c.trim().is_empty()).count()
+}
+
+/// Row indices where a new table starts (see [`split_repeated_header_tables`]); a row with
+/// `blocked[i]` (inside a row span) is never a cut.
+fn repeated_header_cuts(rows: &[Vec<&str>], blocked: &[bool]) -> Vec<usize> {
+ // a header row: three or more filled cells, mostly words (a repeated data row such as a
+ // regression table's reference category, "Non-snacker | 1.00 | 1.00", is no header)
+ let numeric = |c: &str| {
+ let c = c.trim();
+ !c.is_empty()
+ && c.chars().any(|ch| ch.is_ascii_digit())
+ && c.chars()
+ .all(|ch| ch.is_ascii_digit() || " .,%$()-–+*/".contains(ch))
+ };
+ let key = |r: &[&str]| -> Option<String> {
+ let filled = nonempty(r.iter().copied());
+ let nums = r.iter().filter(|c| numeric(c)).count();
+ (filled >= 3 && nums * 3 <= filled).then(|| {
+ r.iter()
+ .map(|c| {
+ c.split_whitespace()
+ .collect::<Vec<_>>()
+ .join(" ")
+ .to_lowercase()
+ })
+ .collect::<Vec<_>>()
+ .join("\u{1f}")
+ })
+ };
+ let mut cuts = Vec::new();
+ let mut seg_start = 0;
+ for i in 1..rows.len() {
+ let Some(k) = key(&rows[i]) else { continue };
+ // the earlier copy heads the current table (its first three rows)
+ if !(seg_start..i.min(seg_start + 3)).any(|j| key(&rows[j]).as_deref() == Some(k.as_str()))
+ {
+ continue;
+ }
+ // the title row above moves with the repeated header
+ let cut = if i - 1 > seg_start && nonempty(rows[i - 1].iter().copied()) == 1 {
+ i - 1
+ } else {
+ i
+ };
+ if cut > seg_start && !blocked[cut] {
+ cuts.push(cut);
+ seg_start = cut;
+ }
+ }
+ cuts
+}
+
+fn union_cells<'a>(rects: impl Iterator<Item = &'a Rect>) -> Option<Rect> {
+ let mut b: Option<(f32, f32, f32, f32)> = None;
+ for r in rects {
+ let (x0, y0, x1, y1) = (r.x, r.y, r.x + r.width, r.y + r.height);
+ b = Some(match b {
+ None => (x0, y0, x1, y1),
+ Some((a, c, d, e)) => (a.min(x0), c.min(y0), d.max(x1), e.max(y1)),
+ });
+ }
+ b.map(|(x0, y0, x1, y1)| Rect {
+ x: x0,
+ y: y0,
+ width: x1 - x0,
+ height: y1 - y0,
+ })
+}
+
/// Heal words hyphenated across a soft line wrap that the classifier split into
/// two *separate* paragraph blocks: `…they dis-` ‖ `lodged…`. When a plain
/// paragraph ends with `<letter>-` and the next is a plain paragraph starting
@@ -663,6 +983,131 @@ mod tests {
assert!(s.ends_with("~~~"));
}
+ fn grid(rows: &[&[&str]]) -> PositionedBlock {
+ let mut it = rows
+ .iter()
+ .map(|r| r.iter().map(|c| Cell::from(*c)).collect::<Vec<_>>());
+ let header = it.next();
+ PositionedBlock::new(
+ Block::Table {
+ header,
+ rows: it.collect(),
+ },
+ None,
+ )
+ }
+
+ fn table_count(blocks: &[PositionedBlock]) -> usize {
+ blocks
+ .iter()
+ .filter(|b| matches!(b.block, Block::Table { .. }))
+ .count()
+ }
+
+ fn para(text: &str) -> PositionedBlock {
+ PositionedBlock::new(
+ Block::Paragraph {
+ text: text.into(),
+ bold: false,
+ italic: false,
+ },
+ None,
+ )
+ }
+
+ fn fig(id: &str) -> PositionedBlock {
+ PositionedBlock::new(
+ Block::Figure {
+ id: id.into(),
+ format: "png".into(),
+ },
+ None,
+ )
+ }
+
+ #[test]
+ fn figure_inside_a_sentence_moves_after_the_paragraph() {
+ let out = rejoin_paragraphs_around_figures(vec![
+ para("Add the ability to engrave items, including"),
+ fig("a"),
+ fig("b"),
+ para("glasses, bottles, and more."),
+ ]);
+ assert_eq!(out.len(), 3);
+ let Block::Paragraph { text, .. } = &out[0].block else {
+ unreachable!()
+ };
+ assert_eq!(
+ text,
+ "Add the ability to engrave items, including glasses, bottles, and more."
+ );
+ assert!(
+ matches!(out[1].block, Block::Figure { .. })
+ && matches!(out[2].block, Block::Figure { .. })
+ );
+ // between complete sentences (or before a capitalised start) the figure stays put
+ let kept = rejoin_paragraphs_around_figures(vec![
+ para("One sentence."),
+ fig("a"),
+ para("next one."),
+ ]);
+ assert_eq!(kept.len(), 3);
+ let kept = rejoin_paragraphs_around_figures(vec![
+ para("A list of"),
+ fig("a"),
+ para("New section"),
+ ]);
+ assert_eq!(kept.len(), 3);
+ }
+
+ #[test]
+ fn repeated_header_row_starts_a_new_table() {
+ let b = grid(&[
+ &["", "Current Base Rate", "", ""],
+ &["CA", "PPO 1500", "PPO 2500", "HDHP 3000"],
+ &["Block A", "254.96", "207.94", "173.76"],
+ &["", "Proposed Base Rate", "", ""],
+ &["CA", "PPO 1500", "PPO 2500", "HDHP 3000"],
+ &["Block A", "284.28", "231.85", "193.74"],
+ ]);
+ let out = split_repeated_header_tables(vec![b]);
+ assert_eq!(table_count(&out), 2);
+ let Block::Table { header, rows } = &out[1].block else {
+ unreachable!()
+ };
+ assert_eq!(header.as_ref().unwrap()[1].as_str(), "Proposed Base Rate");
+ assert_eq!(rows.len(), 2);
+ }
+
+ #[test]
+ fn repeated_data_row_is_not_a_header() {
+ // a regression table's reference category repeats in every group: one table
+ let b = grid(&[
+ &["", "OR", "95% CI", "OR"],
+ &["Non-snacker", "1.00", "", "1.00"],
+ &["Low snacker", "0.68", "0.44-1.05", "0.80"],
+ &["Non-snacker", "1.00", "", "1.00"],
+ &["Low snacker", "0.96", "0.70-1.30", "0.36"],
+ ]);
+ assert_eq!(table_count(&split_repeated_header_tables(vec![b])), 1);
+ }
+
+ #[test]
+ fn side_by_side_tables_split_at_their_gutter() {
+ let b = grid(&[
+ &["Tier", "Type", "Rate", "", "Tier", "Type", "Rate"],
+ &["001", "AN", "1.000", "", "001", "AN", "1.000"],
+ &["001", "AN", "0.170", "", "001", "AN", "0.210"],
+ ]);
+ assert_eq!(table_count(&split_repeated_header_tables(vec![b])), 2);
+ // an empty spacer column inside one table (different headers either side) stays
+ let c = grid(&[
+ &["Item", "2024", "", "2023", "Change"],
+ &["Revenue", "10", "", "9", "1"],
+ ]);
+ assert_eq!(table_count(&split_repeated_header_tables(vec![c])), 1);
+ }
+
#[test]
fn renders_table_to_pipe_format() {
let blocks = vec![Block::Table {
diff --git a/crates/liteparse/src/markdown_layout/classify.rs b/crates/liteparse/src/markdown_layout/classify.rs
index e9c7482..ab9de13 100644
--- a/crates/liteparse/src/markdown_layout/classify.rs
+++ b/crates/liteparse/src/markdown_layout/classify.rs
@@ -96,6 +96,21 @@ pub(super) fn is_rotated_line(line: &ProjectedLine) -> bool {
})
}
+/// Whether the page's rotated lines are its content rather than margin furniture: they carry at
+/// least 30% of its non-whitespace characters. Banners, stamps and vertical legends are a sliver
+/// of a page; a table or figure set sideways is most of it.
+pub(super) fn rotated_text_is_content(page: &ParsedPage) -> bool {
+ let (mut rotated, mut all) = (0usize, 0usize);
+ for line in &page.projected_lines {
+ let n = line.text.chars().filter(|c| !c.is_whitespace()).count();
+ all += n;
+ if is_rotated_line(line) {
+ rotated += n;
+ }
+ }
+ all > 0 && rotated * 10 >= all * 3
+}
+
/// Classify a single page's `ProjectedLine`s into blocks.
#[cfg(test)]
pub(super) fn classify_page(page: &ParsedPage, heading_map: &[(f32, u8)]) -> Vec<PositionedBlock> {
@@ -541,6 +556,7 @@ fn classify_region(
let mut blocks: Vec<PositionedBlock> = Vec::new();
let mut state = FlowState::default();
let mut heading_run: Option<(u8, usize)> = None;
+ let rotated_content = rotated_text_is_content(page);
// Track whether we've already emitted a TOC title on this page. Once seen,
// any subsequent line matching `is_toc_title` (e.g. "Index", "List of
// Figures") is a TOC entry pointing at that chapter, not another title,
@@ -654,8 +670,10 @@ fn classify_region(
}
// Skip rotated text (vertical sidebars, arXiv banners, watermarks).
// Including it would either inject a paragraph of disconnected
- // characters or be misclassified as a heading.
- if is_rotated_line(line) {
+ // characters or be misclassified as a heading. Not when rotated text
+ // is the page's content (a table or figure set sideways): projection
+ // has already turned it upright, and skipping it drops the page.
+ if is_rotated_line(line) && !rotated_content {
continue;
}
if debug {
diff --git a/crates/liteparse/src/markdown_layout/cross_region.rs b/crates/liteparse/src/markdown_layout/cross_region.rs
index 7ccac18..43192fa 100644
--- a/crates/liteparse/src/markdown_layout/cross_region.rs
+++ b/crates/liteparse/src/markdown_layout/cross_region.rs
@@ -41,6 +41,10 @@ const CR_PROSE_MIN_LINES: usize = 3;
const CR_PROSE_WIDTH_FRAC: f32 = 0.7;
/// ...and whose summed line heights fill this fraction of the y-band.
const CR_PROSE_VFILL: f32 = 0.55;
+/// A single leaf judged as prose (see the per-leaf gate) needs a median line of this many
+/// characters: table cells ("1,644,143", "Rooms Occupied") stay under it, a narrow newsletter
+/// column's lines ("based on generations of") run 20 and more.
+const CR_PROSE_LEAF_MIN_CHARS: f32 = 16.0;
/// A prose side is dominated by single-cell lines: when this fraction or more
/// of a side's lines split into ≥2 cells, it's a sliced table half (row
/// fragments with internal column gaps), not flowing text.
@@ -634,8 +638,27 @@ pub(super) fn find_cross_region_table_merge(lines: &[ProjectedLine]) -> Option<C
}
// Either side reading as flowing prose means the V-cut was right:
// a body column next to a sidebar / second column must stay split.
+ // A side made of several leaves (two columns left of a third) is judged leaf by
+ // leaf as well: lumped together its lines fill only part of the side's width. A
+ // leaf holding one table column fills its own width too, so a prose leaf must also
+ // run to sentence-length lines.
+ let leaf_is_prose = || {
+ set_leaves.len() > 2
+ && set_leaves.iter().any(|&k| {
+ let leaf = &leaves[k];
+ let ls: Vec<&ProjectedLine> = lines[leaf.start..leaf.end].iter().collect();
+ let chars = median(
+ ls.iter()
+ .map(|l| l.text.trim().chars().count() as f32)
+ .collect(),
+ );
+ chars >= CR_PROSE_LEAF_MIN_CHARS
+ && side_looks_like_prose(&ls, leaf.x0, leaf.x1)
+ })
+ };
if side_looks_like_prose(&left_lines, lx0, lx1)
|| side_looks_like_prose(&right_lines, rx0, rx1)
+ || leaf_is_prose()
{
if debug {
eprintln!("[cross-region] reject cut@{cut_x:.1}: a side is prose-like");
diff --git a/crates/liteparse/src/markdown_layout/inline.rs b/crates/liteparse/src/markdown_layout/inline.rs
index db2576f..0dfc3dc 100644
--- a/crates/liteparse/src/markdown_layout/inline.rs
+++ b/crates/liteparse/src/markdown_layout/inline.rs
@@ -10,6 +10,9 @@ pub(super) struct SpanStyle {
pub(super) italic: bool,
pub(super) mono: bool,
pub(super) strike: bool,
+ pub(super) underline: bool,
+ pub(super) sup: bool,
+ pub(super) sub: bool,
}
impl SpanStyle {
@@ -19,11 +22,20 @@ impl SpanStyle {
italic: is_italic_item(item),
mono: is_mono_item(item),
strike: is_strike_item(item),
+ underline: item.underline,
+ sup: item.sup,
+ sub: item.sub,
}
}
pub(super) fn is_plain(self) -> bool {
- !self.bold && !self.italic && !self.mono && !self.strike
+ !self.bold
+ && !self.italic
+ && !self.mono
+ && !self.strike
+ && !self.underline
+ && !self.sup
+ && !self.sub
}
}
@@ -159,6 +171,9 @@ fn apply_style(inner: &str, style: SpanStyle) -> String {
let fence = "`".repeat(longest_run + 1);
format!("{fence} {inner} {fence}")
}
+ } else if style.sup || style.sub {
+ // a footnote marker or index: the script tag alone (`<sup>**1**</sup>` reads as noise)
+ inner.to_string()
} else {
match (style.bold, style.italic) {
(true, true) => format!("***{}***", inner),
@@ -167,6 +182,20 @@ fn apply_style(inner: &str, style: SpanStyle) -> String {
(false, false) => inner.to_string(),
}
};
+ // Raised / lowered script: HTML `<sup>` / `<sub>` (no markdown syntax).
+ let styled = if style.sup {
+ format!("<sup>{}</sup>", styled)
+ } else if style.sub {
+ format!("<sub>{}</sub>", styled)
+ } else {
+ styled
+ };
+ // Underline has no markdown syntax: HTML `<u>…</u>`, outside emphasis and code.
+ let styled = if style.underline {
+ format!("<u>{}</u>", styled)
+ } else {
+ styled
+ };
// Strikethrough (GFM `~~…~~`) wraps outermost so it composes with emphasis
// and inline code (`~~**foo**~~`, `~~`bar`~~`).
if style.strike {
@@ -247,7 +276,12 @@ pub(super) fn render_line_inline(line: &ProjectedLine) -> String {
if let Some(url) = link {
rendered = apply_link(&rendered, url);
}
- if !out.is_empty() && !out.ends_with(' ') {
+ // Between groups, a space only where the page has one: a style that changes inside a
+ // word (`Taha` + raised `1`, `**Note**` + `:`) abuts its neighbour.
+ if !out.is_empty()
+ && !out.ends_with(' ')
+ && (i == 0 || spans_separated(spans[i - 1], spans[i], &line.text, line.rtl))
+ {
out.push(' ');
}
out.push_str(&rendered);
@@ -256,6 +290,32 @@ pub(super) fn render_line_inline(line: &ProjectedLine) -> String {
out
}
+/// Whether two consecutive spans of a line (in reading order) are separated by a space. The
+/// line's own text (projection's join, which already decided word spacing) answers when it holds
+/// the two spans' touching words either joined or apart (not at a sub/superscript, which its
+/// join spaces off); otherwise the page geometry does: a
+/// gap over an eighth of the smaller span's height (a word space is a quarter em or more).
+fn spans_separated(a: &TextItem, b: &TextItem, line_text: &str, rtl: bool) -> bool {
+ let last = a.text.split_whitespace().next_back().unwrap_or("");
+ let first = b.text.split_whitespace().next().unwrap_or("");
+ // a raised / lowered script hugs its word: projection's join spaces it off, the page doesn't
+ let script = a.sup || a.sub || b.sup || b.sub;
+ if !script && !last.is_empty() && !first.is_empty() {
+ let (l, r) = if rtl { (first, last) } else { (last, first) };
+ let apart = line_text.contains(&format!("{l} {r}"));
+ let joined = line_text.contains(&format!("{l}{r}"));
+ if apart != joined {
+ return apart;
+ }
+ }
+ let gap = if rtl {
+ a.x - (b.x + b.width)
+ } else {
+ b.x - (a.x + a.width)
+ };
+ gap > a.height.min(b.height) * 0.125
+}
+
/// Render the text portion of a list item with per-span emphasis. The marker
/// itself isn't included in the output (the renderer handles it separately).
///
@@ -301,9 +361,45 @@ pub(super) fn append_inline_continuation(
next_inline: &str,
) {
let next_raw = collapse_whitespace(next_raw);
+ // An emphasis run that continues onto the next line ("*… Network on*" then "*Drug Use …*")
+ // stays one run: the closing marker and the reopening one are dropped at the seam.
+ let next_inline = if prev_text.ends_with("</u>")
+ && next_inline.starts_with("<u>")
+ && !next_inline.starts_with("<u></u>")
+ {
+ prev_text.truncate(prev_text.len() - "</u>".len());
+ &next_inline["<u>".len()..]
+ } else {
+ next_inline
+ };
+ let next_inline = match continued_emphasis(prev_text, next_inline) {
+ Some(n) => {
+ prev_text.truncate(prev_text.len() - n);
+ &next_inline[n..]
+ }
+ None => next_inline,
+ };
dehyphenate_join(prev_text, &next_raw, next_inline);
}
+/// Length of an emphasis marker (`*`, `**`, `***` or `~~`) that closes `prev` and reopens
+/// `next` identically, with text on both sides of the seam (not `\*`, not a lone marker).
+fn continued_emphasis(prev: &str, next: &str) -> Option<usize> {
+ for (ch, lens) in [('*', &[1usize, 2, 3][..]), ('~', &[2][..])] {
+ let tail = prev.chars().rev().take_while(|&c| c == ch).count();
+ let head = next.chars().take_while(|&c| c == ch).count();
+ if tail == 0 || tail != head || !lens.contains(&tail) {
+ continue;
+ }
+ let before = prev[..prev.len() - tail].chars().last();
+ let after = next[head..].chars().next();
+ let ok = before.is_some_and(|c| !c.is_whitespace() && c != '\\')
+ && after.is_some_and(|c| !c.is_whitespace());
+ return ok.then_some(tail);
+ }
+ None
+}
+
/// Returns the shared `SpanStyle` of `line` when every non-whitespace span on
/// the line has the same style; `None` when spans disagree. Mono is folded
/// into the style for the purpose of "uniform" — a fully-mono line is
@@ -487,6 +583,26 @@ mod tests {
assert_eq!(out, "[link](<https://example.com/a b>)");
}
+ #[test]
+ fn emphasis_continues_across_line_join() {
+ let mut prev = "hallucinogen. *South African Network on*".to_string();
+ append_inline_continuation(&mut prev, "Drug Use (2014)", "*Drug Use (2014)*");
+ assert_eq!(
+ prev,
+ "hallucinogen. *South African Network on Drug Use (2014)*"
+ );
+ let mut bold = "**Bold start**".to_string();
+ append_inline_continuation(&mut bold, "ends here", "**ends here** plain");
+ assert_eq!(bold, "**Bold start ends here** plain");
+ // different markers, escaped stars and lone markers are left alone
+ let mut mixed = "**bold**".to_string();
+ append_inline_continuation(&mut mixed, "italic", "*italic*");
+ assert_eq!(mixed, "**bold** *italic*");
+ let mut esc = "price 5\\*".to_string();
+ append_inline_continuation(&mut esc, "x", "*x*");
+ assert_eq!(esc, "price 5\\* *x*");
+ }
+
#[test]
fn render_line_inline_strike_span() {
// A struck-through span mid-line → `~~word~~`, plain neighbors untouched.
diff --git a/crates/liteparse/src/markdown_layout/mod.rs b/crates/liteparse/src/markdown_layout/mod.rs
index 6c9534c..5c0e385 100644
--- a/crates/liteparse/src/markdown_layout/mod.rs
+++ b/crates/liteparse/src/markdown_layout/mod.rs
@@ -18,7 +18,10 @@ mod paragraphs;
mod repetition;
mod tables;
-pub use blocks::{Block, Cell, PositionedBlock, SpanCell, render_blocks, splice_soft_hyphens};
+pub use blocks::{
+ Block, Cell, PositionedBlock, SpanCell, rejoin_paragraphs_around_figures, render_blocks,
+ splice_soft_hyphens, split_repeated_header_tables,
+};
pub use classify::classify_page_with_filters;
pub use headings::{build_heading_map, compute_body_size};
pub use inline::{apply_link, escape_inline};
diff --git a/crates/liteparse/src/markdown_layout/paragraphs.rs b/crates/liteparse/src/markdown_layout/paragraphs.rs
index 0722627..1a2862b 100644
--- a/crates/liteparse/src/markdown_layout/paragraphs.rs
+++ b/crates/liteparse/src/markdown_layout/paragraphs.rs
@@ -339,7 +339,9 @@ pub(super) fn append_to_paragraph(accum: &mut ParaAccum, next_line: &ProjectedLi
// won't strip and falls through to a space join — exactly the prior
// behavior, now via one helper.
dehyphenate_join(&mut accum.raw, &next_raw, &next_raw);
- dehyphenate_join(&mut accum.inline, &next_raw, &next_inline);
+ // the inline side first rejoins an emphasis run split at the line break ("*… Man-*" +
+ // "*ager …*"), so the hyphen is at its seam again
+ super::inline::append_inline_continuation(&mut accum.inline, &next_raw, &next_inline);
// Maintain the running uniform-style flag.
accum.uniform = match (accum.uniform, next_uniform) {
diff --git a/crates/liteparse/src/markdown_layout/repetition.rs b/crates/liteparse/src/markdown_layout/repetition.rs
index 60d2900..5c8cae6 100644
--- a/crates/liteparse/src/markdown_layout/repetition.rs
+++ b/crates/liteparse/src/markdown_layout/repetition.rs
@@ -335,7 +335,10 @@ pub fn detect_single_page_chrome(
for (idx, line) in page.projected_lines.iter().enumerate() {
let text = line.text.trim();
- if text.is_empty() {
+ // Running chrome is horizontal text; a rotated line (a sideways table, which projection
+ // sets upright in a frame taller than the page) would otherwise sit in the "bottom band"
+ // and its year-led rows match the date pattern.
+ if text.is_empty() || super::classify::is_rotated_line(line) {
continue;
}
let in_top = bots[idx] <= top_cutoff;
diff --git a/crates/liteparse/src/projection.rs b/crates/liteparse/src/projection.rs
index 5309c50..a557348 100644
--- a/crates/liteparse/src/projection.rs
+++ b/crates/liteparse/src/projection.rs
@@ -724,6 +724,10 @@ fn form_lines(
line.sort_by(|a, b| a.item.x.total_cmp(&b.item.x));
}
+ for line in lines.iter_mut() {
+ mark_script_items(line);
+ }
+
// sort lines by y
lines.sort_by(|a, b| {
let ay = a.first().map(|v| v.item.y).unwrap_or(f32::INFINITY);
@@ -842,9 +846,14 @@ fn form_lines(
.chars()
.next()
.is_some_and(|c| c.is_alphabetic());
+ // An emphasis change (bold / italic / struck / monospace) keeps the items
+ // apart: a merged item carries one font, so the second run would render in
+ // the first one's style.
+ let style_change = !same_emphasis(&prev.item, &item.item);
if y_compatible
&& !both_are_numbers
&& !alpha_alpha_gap
+ && !style_change
&& delta_x <= MERGE_THRESHOLD
{
prev.item.width = item.item.x + item.item.width - prev.item.x;
@@ -856,7 +865,7 @@ fn form_lines(
let prev_len = prev.item.text.chars().count().max(1) as f32;
let avg_char_width = prev.item.width / prev_len;
- if y_compatible && !both_are_numbers && delta_x < avg_char_width {
+ if y_compatible && !both_are_numbers && !style_change && delta_x < avg_char_width {
prev.item.width = item.item.x + item.item.width - prev.item.x;
join_in_reading_order(&mut prev.item.text, &item.item.text, " ");
prev.item.words.append(&mut item.item.words);
@@ -3052,37 +3061,140 @@ fn name_contains_any(name: &str, hints: &[&str]) -> bool {
hints.iter().any(|h| name.contains(h))
}
-pub(crate) fn is_bold_item(item: &TextItem) -> bool {
- if let Some(flags) = item.font_flags
- && flags & PDF_FONT_FLAG_FORCE_BOLD != 0
- {
- return true;
+/// Flag the line's short items set clearly smaller than its body text and raised above its
+/// baseline (superscripts: footnote markers, ordinals) or dropped below it (subscripts). The
+/// body is the line's tallest-run text by character count; OCR and math items are left alone
+/// (OCR boxes are too loose to tell a raised glyph from jitter).
+fn mark_script_items(line: &mut [ProjectedTextItem]) {
+ let native = |p: &ProjectedTextItem| p.item.confidence.is_none() && !p.item.math;
+ let mut hs: Vec<(f32, usize)> = line
+ .iter()
+ .filter(|p| native(p) && p.item.height > 0.0)
+ .map(|p| {
+ (
+ p.item.height,
+ p.item.text.chars().filter(|c| !c.is_whitespace()).count(),
+ )
+ })
+ .collect();
+ let total: usize = hs.iter().map(|h| h.1).sum();
+ if total < 4 {
+ return;
}
- if let Some(w) = item.font_weight
- && w >= 600
- {
- return true;
+ hs.sort_by(|a, b| a.0.total_cmp(&b.0));
+ let (mut acc, mut body_h) = (0, 0.0);
+ for (h, n) in hs {
+ acc += n;
+ if acc * 2 >= total {
+ body_h = h;
+ break;
+ }
}
- if let Some(n) = &item.font_name
- && name_contains_any(n, BOLD_NAME_HINTS)
- {
- return true;
+ let mut bottoms: Vec<f32> = line
+ .iter()
+ .filter(|p| native(p) && p.item.height >= body_h * 0.9)
+ .map(|p| p.item.y + p.item.height)
+ .collect();
+ if bottoms.is_empty() || body_h <= 0.0 {
+ return;
}
- false
+ bottoms.sort_by(f32::total_cmp);
+ let base = bottoms[bottoms.len() / 2];
+ for p in line.iter_mut().filter(|p| native(p)) {
+ let it = &mut p.item;
+ let n = it.text.trim().chars().count();
+ if n == 0 || n > 6 || it.height > body_h * 0.78 {
+ continue;
+ }
+ let bottom = it.y + it.height;
+ if bottom <= base - body_h * 0.2 {
+ it.sup = true;
+ } else if bottom >= base + body_h * 0.1 && it.y >= base - body_h * 0.6 {
+ it.sub = true;
+ }
+ }
+ // A script hugs the text it marks ("Taha¹", "CO₂", "substrate⁴¹"): a flagged run of three or
+ // more items or over 8 characters is a smaller-type phrase on a mixed line (a byline next
+ // to a drop cap), and a flagged item with no unflagged neighbour within half the body height
+ // is no script either.
+ let mut order: Vec<usize> = (0..line.len()).collect();
+ order.sort_by(|&a, &b| line[a].item.x.total_cmp(&line[b].item.x));
+ let script = |p: &ProjectedTextItem| p.item.sup || p.item.sub;
+ let mut k = 0;
+ while k < order.len() {
+ if !script(&line[order[k]]) {
+ k += 1;
+ continue;
+ }
+ let mut e = k;
+ while e + 1 < order.len() && script(&line[order[e + 1]]) {
+ e += 1;
+ }
+ let chars: usize = order[k..=e]
+ .iter()
+ .map(|&i| {
+ line[i]
+ .item
+ .text
+ .chars()
+ .filter(|c| !c.is_whitespace())
+ .count()
+ })
+ .sum();
+ let near = |i: Option<&usize>, left: bool| {
+ i.is_some_and(|&i| {
+ let (a, b) = (&line[order[k]].item, &line[order[e]].item);
+ let n = &line[i].item;
+ let gap = if left {
+ a.x - (n.x + n.width)
+ } else {
+ n.x - (b.x + b.width)
+ };
+ !script(&line[i]) && gap <= body_h * 0.5
+ })
+ };
+ let hugs = near(k.checked_sub(1).and_then(|j| order.get(j)), true)
+ || near(order.get(e + 1), false);
+ if e - k + 1 >= 3 || chars > 8 || !hugs {
+ for &i in &order[k..=e] {
+ line[i].item.sup = false;
+ line[i].item.sub = false;
+ }
+ }
+ k = e + 1;
+ }
+}
+
+/// Whether two items render with the same inline emphasis.
+fn same_emphasis(a: &TextItem, b: &TextItem) -> bool {
+ is_bold_item(a) == is_bold_item(b)
+ && is_italic_item(a) == is_italic_item(b)
+ && is_strike_item(a) == is_strike_item(b)
+ && is_mono_item(a) == is_mono_item(b)
+ && a.underline == b.underline
+ && a.sup == b.sup
+ && a.sub == b.sub
+}
+
+pub(crate) fn is_bold_item(item: &TextItem) -> bool {
+ font_is_bold(item.font_name.as_deref(), item.font_weight, item.font_flags)
}
pub(crate) fn is_italic_item(item: &TextItem) -> bool {
- if let Some(flags) = item.font_flags
- && flags & PDF_FONT_FLAG_ITALIC != 0
- {
- return true;
- }
- if let Some(n) = &item.font_name
- && name_contains_any(n, ITALIC_NAME_HINTS)
- {
- return true;
- }
- false
+ font_is_italic(item.font_name.as_deref(), item.font_flags)
+}
+
+/// Bold from a font's flags (ForceBold), weight (600+) or name.
+pub(crate) fn font_is_bold(name: Option<&str>, weight: Option<i32>, flags: Option<i32>) -> bool {
+ flags.is_some_and(|f| f & PDF_FONT_FLAG_FORCE_BOLD != 0)
+ || weight.is_some_and(|w| w >= 600)
+ || name.is_some_and(|n| name_contains_any(n, BOLD_NAME_HINTS))
+}
+
+/// Italic from a font's flags or name.
+pub(crate) fn font_is_italic(name: Option<&str>, flags: Option<i32>) -> bool {
+ flags.is_some_and(|f| f & PDF_FONT_FLAG_ITALIC != 0)
+ || name.is_some_and(|n| name_contains_any(n, ITALIC_NAME_HINTS))
}
pub(crate) fn is_strike_item(item: &TextItem) -> bool {
@@ -4181,6 +4293,57 @@ fn x_extent(items: &[ProjectedTextItem], idxs: &[usize]) -> (f32, f32) {
(lo, hi)
}
+/// Horizontal cut that isolates lines crossing a vertical gutter at `gutter_x` (see
+/// `xy_cut_rec`). A band crosses when one of its items reaches at least three line heights past
+/// the gutter on both sides (a heading or float spanning the columns, not a line of the left
+/// column overhanging a misplaced gutter), and at most a third of the bands cross. Cuts above the first crossing band that has non-crossing bands
+/// above it; when the crossing bands only open the region, cuts below them.
+fn xy_find_crossing_line_cut(
+ items: &[ProjectedTextItem],
+ idxs: &[usize],
+ gutter_x: f32,
+ median_h: f32,
+) -> Option<CutCandidate> {
+ let mut sorted: Vec<usize> = idxs.to_vec();
+ sorted.sort_by(|&a, &b| items[a].item.y.total_cmp(&items[b].item.y));
+ let band_tol = (median_h * 0.5).max(2.0);
+ let reach = 3.0 * median_h.max(4.0);
+ // (y_min, y_max, crosses)
+ let mut bands: Vec<(f32, f32, bool)> = Vec::new();
+ for &i in &sorted {
+ let it = &items[i].item;
+ let (y0, y1) = (it.y, it.y + it.height.max(0.0));
+ let crosses = it.x < gutter_x - reach && it.x + it.width > gutter_x + reach;
+ match bands.last_mut() {
+ Some(last)
+ if y0 <= last.1 - band_tol || (y0 - (last.0 + last.1) * 0.5).abs() <= band_tol =>
+ {
+ last.0 = last.0.min(y0);
+ last.1 = last.1.max(y1);
+ last.2 |= crosses;
+ }
+ _ => bands.push((y0, y1, crosses)),
+ }
+ }
+ // Spanning lines are a minority of a region's lines; when most lines cross, the gutter is
+ // misplaced (inside a column), not crossed.
+ let crossing = bands.iter().filter(|b| b.2).count();
+ if bands.len() < 3 || crossing == 0 || crossing * 3 > bands.len() {
+ return None;
+ }
+ let between = |a: usize| CutCandidate {
+ axis: CutAxis::Horizontal,
+ position: (bands[a].1 + bands[a + 1].0) * 0.5,
+ score: f32::INFINITY,
+ };
+ let first = bands.iter().position(|b| b.2)?;
+ if first > 0 {
+ return Some(between(first - 1));
+ }
+ let last_opening = bands.iter().position(|b| !b.2)? - 1;
+ Some(between(last_opening))
+}
+
fn xy_find_banner_cut(
items: &[ProjectedTextItem],
idxs: &[usize],
@@ -4347,6 +4510,17 @@ fn xy_cut_rec(
if let Some(bc) = banner {
candidates.push(bc);
}
+ // A line that crosses the would-be gutter (a section heading, a spanning float) separates
+ // column runs; the gutter is the density valley's when there is one (nothing crosses it, so
+ // the check stays quiet), else the column histogram's, which crossing lines don't block.
+ // Cut above it before cutting columns, or the columns of every section join into one
+ // page-long column and a heading is sliced in two.
+ if !effective_tabular
+ && let Some(x) = v.as_ref().or(column_full.as_ref()).map(|c| c.position)
+ && let Some(hc) = xy_find_crossing_line_cut(items, &idxs, x, median_h)
+ {
+ candidates.push(hc);
+ }
if let Some(cc) = column {
candidates.push(cc);
}
diff --git a/crates/liteparse/src/stages.rs b/crates/liteparse/src/stages.rs
index 244754c..f74eb07 100644
--- a/crates/liteparse/src/stages.rs
+++ b/crates/liteparse/src/stages.rs
@@ -481,6 +481,8 @@ pub fn extract_blocks(
blocks.retain(|b| !matches!(b.block, Block::HorizontalRule));
}
dedupe_rules(&mut blocks);
+ let blocks = markdown_layout::split_repeated_header_tables(blocks);
+ let blocks = markdown_layout::rejoin_paragraphs_around_figures(blocks);
Some(markdown_layout::splice_soft_hyphens(blocks))
}
diff --git a/crates/liteparse/src/types.rs b/crates/liteparse/src/types.rs
index 7103560..ec19a39 100644
--- a/crates/liteparse/src/types.rs
+++ b/crates/liteparse/src/types.rs
@@ -122,6 +122,18 @@ pub struct TextItem {
/// markdown emitter to wrap the text in `~~…~~`.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub strike: bool,
+ /// Whether a thin horizontal stroke/rect runs just under this item's
+ /// baseline and spans its text (an underline). Populated in `extract.rs`;
+ /// the markdown emitter wraps the text in `<u>…</u>`.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub underline: bool,
+ /// Raised (superscript) or lowered (subscript) small text relative to its
+ /// line, e.g. a footnote marker. Set in projection; the markdown emitter
+ /// wraps it in `<sup>…</sup>` / `<sub>…</sub>`.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub sup: bool,
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub sub: bool,
/// Whether this item is LaTeX rebuilt from TeX math fonts (`$…$`).
/// Populated in `extract.rs`.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]