A fast, helpful, and open-source document parser
clean up
Logan Markewichbfada7213775
diff --git a/crates/liteparse/src/extract.rs b/crates/liteparse/src/extract.rsindex 45fbd4d..44a79ae 100644--- a/crates/liteparse/src/extract.rs+++ b/crates/liteparse/src/extract.rs@@ -276,6 +276,7 @@ fn extract_page_image_refs(page: &Page, page_number: u32) -> Vec<ImageRef> {/// code-block fills / banner fills regardless of internal complexity);/// - stroked paths → one `Stroke` per `LineTo` between consecutive points,/// plus the implicit closing stroke when a subpath has its close flag set.+////// BezierTo segments don't emit strokes (we just advance the current point so/// later LineTos start from the right place).fn extract_page_graphics(page: &Page, view_box: &RectF) -> Vec<GraphicPrimitive> {diff --git a/crates/liteparse/src/markdown_layout/blocks.rs b/crates/liteparse/src/markdown_layout/blocks.rsindex a737a37..548773b 100644--- a/crates/liteparse/src/markdown_layout/blocks.rs+++ b/crates/liteparse/src/markdown_layout/blocks.rs@@ -2,8 +2,8 @@ use super::inline::escape_inline;use super::paragraphs::ParaAccum;use super::tables::escape_table_cell;-/// Coarse block representation. Intentionally minimal — extended as later-/// build-order steps land (tables, figures).+/// Coarse block representation: the output of page classification, consumed by+/// `render_blocks` to produce the final markdown string.#[derive(Debug, Clone)]pub enum Block {Heading {@@ -51,7 +51,6 @@ pub enum Block {id: String,bbox: crate::types::Rect,},- Blank,}/// Resolve a `ParaAccum` to a `Block::Paragraph`. When the paragraph was@@ -164,7 +163,7 @@ pub fn render_blocks(blocks: &[Block]) -> String {// CommonMark/GFM requires a header row before the// separator; synthesize a blank header so renderers that// refuse header-less tables still display the body.- out.push_str("|");+ out.push('|');for _ in 0..column_count {out.push_str(" |");}@@ -218,7 +217,6 @@ pub fn render_blocks(blocks: &[Block]) -> String {out.push_str(id);out.push_str(".png)");}- Block::Blank => {}}}outdiff --git a/crates/liteparse/src/markdown_layout/classify.rs b/crates/liteparse/src/markdown_layout/classify.rsindex c57d1a3..a440926 100644--- a/crates/liteparse/src/markdown_layout/classify.rs+++ b/crates/liteparse/src/markdown_layout/classify.rs@@ -14,6 +14,16 @@ use super::paragraphs::{ParaAccum, append_to_paragraph, collapse_whitespace, conuse super::repetition::is_header_or_footer;use super::tables::{detect_ruled_tables, detect_tables, merge_table_runs};+/// A document-order page interruption that breaks the normal text flow: either+/// a horizontal rule (from vector graphics) or a figure injection (a raster+/// image ref). Collected into one y-sorted stream so the two kinds interleave+/// correctly by vertical position rather than emitting all of one before the+/// other.+enum Interruption {+ Hr,+ Figure(crate::types::ImageRef),+}+/// Returns true if any span on the line is rotated more than ~5° off/// horizontal — used to exclude sidebar / margin-stamp text (arXiv banners,/// watermarks, vertical legends) from the body-size and heading-size@@ -67,15 +77,16 @@ pub fn classify_page_with_filters(// Index into `blocks` of the most recent ListItem in the current run — used// to merge wrapped continuation lines into the same item.let mut last_list_item_idx: Option<usize> = None;- // Most recent ProjectedLine appended to the active list item, for- // gap/font-size checks on continuation lines.- let mut last_list_line: Option<ProjectedLine> = None;+ // Index (into `lines`) of the most recent line appended to the active list+ // item, for gap/font-size checks on continuation lines. An index rather than+ // a cloned line so the per-line hot loop doesn't deep-copy `spans` each time.+ let mut last_list_line: Option<usize> = None;// (level, last line) of a heading block currently being accumulated. Lets a// multi-line wrapped heading/caption (e.g. a photo caption set one size// above body) merge into one Heading block instead of shredding into one// `###` per wrapped line. Adjacency is enforced by checking `blocks.last()`,// so this never reaches across an intervening block.- let mut heading_run: Option<(u8, ProjectedLine)> = None;+ let mut heading_run: Option<(u8, usize)> = None;let flush_paragraph = |blocks: &mut Vec<Block>, p: Option<ParaAccum>| {if let Some(acc) = p@@ -160,92 +171,61 @@ pub fn classify_page_with_filters(let mut table_iter = table_runs.into_iter().peekable();- // Pre-pass: detect horizontal rules from vector graphics so they can be- // emitted in document order between surrounding text lines.- let hr_ys: Vec<f32> = detect_horizontal_rules(page)+ // Pre-pass: collect document-order "interruptions" — horizontal rules+ // (from vector graphics) and figure injections (raster image refs when+ // image mode is on) — into one y-sorted stream. Emitting them from a single+ // stream keeps HRs and figures correctly interleaved by y; a per-type pass+ // would emit all HRs before all figures regardless of vertical position.+ // Both are suppressed inside table y-extents so a row divider or a+ // cell-spanning raster background doesn't spawn a block mid-table.+ let in_table_band = |y: f32| {+ table_y_extents+ .iter()+ .any(|(top, bot)| y >= *top - 2.0 && y <= *bot + 2.0)+ };+ let mut interruptions: Vec<(f32, Interruption)> = detect_horizontal_rules(page).into_iter()- .filter(|y| {- !table_y_extents- .iter()- .any(|(top, bot)| *y >= *top - 2.0 && *y <= *bot + 2.0)- })+ .filter(|y| !in_table_band(*y))+ .map(|y| (y, Interruption::Hr)).collect();- let mut hr_iter = hr_ys.into_iter().peekable();-- // Figure injection: when image mode is on, walk the page's image refs in- // y-order and inject `Block::Figure` between text lines whose y has- // already passed. Suppressed inside table y-extents to keep cell-spanning- // raster cell backgrounds (rare but possible) from spawning a figure- // mid-table.- let figure_entries: Vec<(f32, crate::types::ImageRef)> =- if matches!(image_mode, crate::config::ImageMode::Off) {- Vec::new()- } else {- let mut v: Vec<(f32, crate::types::ImageRef)> = page- .image_refs- .iter()- .filter(|r| {- !table_y_extents- .iter()- .any(|(top, bot)| r.bbox.y >= *top - 2.0 && r.bbox.y <= *bot + 2.0)- })- .map(|r| (r.bbox.y, r.clone()))- .collect();- v.sort_by(|a, b| a.0.total_cmp(&b.0));- v- };- let mut figure_iter = figure_entries.into_iter().peekable();-- // Emit any HRs whose y is at or above `before_y`. Flushes the active- // paragraph/code/list state first so the rule lands as its own block.- let emit_hrs_before = |blocks: &mut Vec<Block>,- paragraph: &mut Option<ParaAccum>,- code: &mut Option<Vec<String>>,- list_base: &mut Option<f32>,- last_item: &mut Option<usize>,- last_line: &mut Option<ProjectedLine>,- hr_iter: &mut std::iter::Peekable<std::vec::IntoIter<f32>>,- before_y: f32| {- while let Some(&hy) = hr_iter.peek() {- if hy > before_y {- break;+ if !matches!(image_mode, crate::config::ImageMode::Off) {+ for r in &page.image_refs {+ if !in_table_band(r.bbox.y) {+ interruptions.push((r.bbox.y, Interruption::Figure(r.clone())));}- hr_iter.next();- flush_paragraph(blocks, paragraph.take());- flush_code(blocks, code.take());- *list_base = None;- *last_item = None;- *last_line = None;- blocks.push(Block::HorizontalRule);}- };-- // Mirror of `emit_hrs_before` for figure entries. Same flush semantics so- // a figure sitting between two paragraphs lands as its own block in the- // correct y order.- let emit_figures_before = |blocks: &mut Vec<Block>,- paragraph: &mut Option<ParaAccum>,- code: &mut Option<Vec<String>>,- list_base: &mut Option<f32>,- last_item: &mut Option<usize>,- last_line: &mut Option<ProjectedLine>,- figure_iter: &mut std::iter::Peekable<- std::vec::IntoIter<(f32, crate::types::ImageRef)>,- >,- before_y: f32| {- while let Some((fy, _)) = figure_iter.peek() {- if *fy > before_y {+ }+ // Stable sort by y. HRs were pushed before figures, so an exact-y tie keeps+ // the prior HR-before-figure ordering.+ interruptions.sort_by(|a, b| a.0.total_cmp(&b.0));+ let mut interruptions = interruptions.into_iter().peekable();++ // Emit any interruptions whose y is at or above `before_y`, flushing the+ // active paragraph/code/list state first so each lands as its own block.+ let emit_before = |blocks: &mut Vec<Block>,+ paragraph: &mut Option<ParaAccum>,+ code: &mut Option<Vec<String>>,+ list_base: &mut Option<f32>,+ last_item: &mut Option<usize>,+ last_line: &mut Option<usize>,+ iter: &mut std::iter::Peekable<std::vec::IntoIter<(f32, Interruption)>>,+ before_y: f32| {+ while let Some((y, _)) = iter.peek() {+ if *y > before_y {break;}- let (_, r) = figure_iter.next().unwrap();+ let (_, kind) = iter.next().unwrap();flush_paragraph(blocks, paragraph.take());flush_code(blocks, code.take());*list_base = None;*last_item = None;*last_line = None;- blocks.push(Block::Figure {- id: r.id,- bbox: r.bbox,+ blocks.push(match kind {+ Interruption::Hr => Block::HorizontalRule,+ Interruption::Figure(r) => Block::Figure {+ id: r.id,+ bbox: r.bbox,+ },});}};@@ -255,26 +235,16 @@ pub fn classify_page_with_filters(if let Some(run) = table_iter.peek()&& run.start == idx{- // Flush any HRs above this table's top edge first.+ // Flush any interruptions above this table's top edge first.let table_top = lines[run.start].bbox.y;- emit_hrs_before(- &mut blocks,- &mut paragraph,- &mut code,- &mut list_base_indent,- &mut last_list_item_idx,- &mut last_list_line,- &mut hr_iter,- table_top,- );- emit_figures_before(+ emit_before(&mut blocks,&mut paragraph,&mut code,&mut list_base_indent,&mut last_list_item_idx,&mut last_list_line,- &mut figure_iter,+ &mut interruptions,table_top,);flush_paragraph(&mut blocks, paragraph.take());@@ -287,26 +257,17 @@ pub fn classify_page_with_filters(idx = run.end;continue;}- let line = &lines[idx];- // Emit any HRs that fall above this line.- emit_hrs_before(- &mut blocks,- &mut paragraph,- &mut code,- &mut list_base_indent,- &mut last_list_item_idx,- &mut last_list_line,- &mut hr_iter,- line.bbox.y,- );- emit_figures_before(+ let line_idx = idx;+ let line = &lines[line_idx];+ // Emit any interruptions that fall above this line.+ emit_before(&mut blocks,&mut paragraph,&mut code,&mut list_base_indent,&mut last_list_item_idx,&mut last_list_line,- &mut figure_iter,+ &mut interruptions,line.bbox.y,);idx += 1;@@ -373,7 +334,7 @@ pub fn classify_page_with_filters(let prev = paragraph.as_ref().map(|p| &p.last)- .or(last_list_line.as_ref());+ .or(last_list_line.map(|i| &lines[i]));!(starts_lower && prev.is_some_and(|p| continues_paragraph(p, line)))});// A standalone "Contents" / "Table of Contents" / "Index" line is@@ -392,9 +353,9 @@ pub fn classify_page_with_filters(// emitted block, and the line continues the paragraph. A real// section heading is followed by body text (which breaks the run),// so only a genuinely multi-line heading/caption merges here.- if let Some((run_level, run_line)) = heading_run.as_ref()+ if let Some((run_level, run_idx)) = heading_run.as_ref()&& *run_level == level- && continues_paragraph(run_line, line)+ && continues_paragraph(&lines[*run_idx], line)&& let Some(Block::Heading {level: last_level,text: htext,@@ -402,7 +363,7 @@ pub fn classify_page_with_filters(&& *last_level == level{append_inline_continuation(htext, text, &collapse_whitespace(text));- heading_run = Some((level, line.clone()));+ heading_run = Some((level, line_idx));continue;}flush_paragraph(&mut blocks, paragraph.take());@@ -413,7 +374,7 @@ pub fn classify_page_with_filters(level,text: collapse_whitespace(text),});- heading_run = Some((level, line.clone()));+ heading_run = Some((level, line_idx));continue;}@@ -434,8 +395,7 @@ pub fn classify_page_with_filters(paragraph.as_ref().map(|p| &p.last)- .or(last_list_line.as_ref()),- lines.get(idx),+ .or(last_list_line.map(|i| &lines[i])),){flush_paragraph(&mut blocks, paragraph.take());@@ -455,7 +415,7 @@ pub fn classify_page_with_filters(.round().max(0.0)) as u8;last_list_item_idx = Some(blocks.len());- last_list_line = Some(line.clone());+ last_list_line = Some(line_idx);// Render the list-item text via the inline pipeline so per-span// emphasis surfaces. We strip the marker from `rest` (already// done by `parse_list_marker`), but emphasis lives on `line.spans`,@@ -476,18 +436,18 @@ pub fn classify_page_with_filters(// Continuation of a list item: same gap/font rules as paragraphs.// Footnote-style continuations often left-flush below the marker's// hanging indent, so we don't require indent ≥ marker indent.- if let Some(idx) = last_list_item_idx- && let Some(prev_line) = last_list_line.as_ref()- && continues_paragraph(prev_line, line)+ if let Some(item_idx) = last_list_item_idx+ && let Some(prev_idx) = last_list_line+ && continues_paragraph(&lines[prev_idx], line)&& let Some(Block::ListItem {text: prev_text, ..- }) = blocks.get_mut(idx)+ }) = blocks.get_mut(item_idx){// De-hyphenate against the prior rendered text, then append the// inline-styled continuation.let cont_inline = render_line_inline(line);append_inline_continuation(prev_text, text, &cont_inline);- last_list_line = Some(line.clone());+ last_list_line = Some(line_idx);continue;}@@ -499,7 +459,7 @@ pub fn classify_page_with_filters(let prev_for_gap = paragraph.as_ref().map(|p| &p.last)- .or(last_list_line.as_ref());+ .or(last_list_line.map(|i| &lines[i]));let next_for_gap = lines.get(idx);if !toc_suppress && looks_like_bold_heading(line, prev_for_gap, next_for_gap) {flush_paragraph(&mut blocks, paragraph.take());@@ -541,25 +501,15 @@ pub fn classify_page_with_filters(flush_paragraph(&mut blocks, paragraph.take());flush_code(&mut blocks, code.take());- // Flush any trailing HRs / figures that sat below the last text line.- emit_hrs_before(- &mut blocks,- &mut paragraph,- &mut code,- &mut list_base_indent,- &mut last_list_item_idx,- &mut last_list_line,- &mut hr_iter,- f32::INFINITY,- );- emit_figures_before(+ // Flush any trailing interruptions that sat below the last text line.+ emit_before(&mut blocks,&mut paragraph,&mut code,&mut list_base_indent,&mut last_list_item_idx,&mut last_list_line,- &mut figure_iter,+ &mut interruptions,f32::INFINITY,);blocksdiff --git a/crates/liteparse/src/markdown_layout/headings.rs b/crates/liteparse/src/markdown_layout/headings.rsindex 2a987f6..5dab41b 100644--- a/crates/liteparse/src/markdown_layout/headings.rs+++ b/crates/liteparse/src/markdown_layout/headings.rs@@ -165,7 +165,7 @@ pub(super) fn looks_like_toc_entry(text: &str) -> bool {tail_start -= 1;}let tail_len = n - tail_start;- if tail_len < 2 || tail_len > 6 {+ if !(2..=6).contains(&tail_len) {return false;}let mut sep_end = tail_start;@@ -279,18 +279,7 @@ pub(super) fn looks_like_bold_heading(// pick up (results tables, scoreboards, math display). A real section// heading is mostly letters: "1 Introduction" passes (~92% alpha across// non-whitespace chars), "47.5 14" doesn't (0%), "BLEU-1 25.87" doesn't.- let mut alpha = 0usize;- let mut total = 0usize;- for c in text.chars() {- if c.is_whitespace() {- continue;- }- total += 1;- if c.is_alphabetic() {- alpha += 1;- }- }- if total == 0 || (alpha as f32) / (total as f32) < 0.5 {+ if alpha_ratio(text) < 0.5 {return false;}// Reject when the line itself looks tabular: ≥3 cells separated by font-size@@ -322,24 +311,22 @@ pub(super) fn looks_like_bold_heading(if !gap_above_ok {return false;}- let gap_below_ok = match next {+ match next {None => true,Some(n) => !continues_paragraph(line, n),- };- gap_below_ok+ }}/// Returns true if `line` is a numbered section heading like "1. **Foo**" —/// `parse_list_marker` already matched the "N." / "N)" prefix; this checks/// that the body after the marker is uniformly bold body-size text and that-/// the line stands alone (paragraph break above and below). When true the-/// caller should emit a Heading at `heading_map.len()+1` rather than a-/// ListItem. Mirrors `looks_like_bold_heading`'s gating modulo the marker.+/// the line has a paragraph break above it. When true the caller should emit a+/// Heading at `heading_map.len()+1` rather than a ListItem. Mirrors+/// `looks_like_bold_heading`'s gating modulo the marker.pub(super) fn looks_like_numbered_bold_heading(line: &ProjectedLine,rest: &str,prev: Option<&ProjectedLine>,- _next: Option<&ProjectedLine>,) -> bool {let rest_trim = rest.trim();if rest_trim.is_empty() || rest_trim.chars().count() > BOLD_HEADING_MAX_CHARS {@@ -388,17 +375,7 @@ pub(super) fn looks_like_numbered_bold_heading(}// Mostly alphabetic — same intuition as `looks_like_bold_heading`'s// alpha-ratio filter: rejects tabular bold rows of digits.- let (mut alpha, mut total) = (0usize, 0usize);- for c in rest_trim.chars() {- if c.is_whitespace() {- continue;- }- total += 1;- if c.is_alphabetic() {- alpha += 1;- }- }- if total == 0 || (alpha as f32) / (total as f32) < 0.5 {+ if alpha_ratio(rest_trim) < 0.5 {return false;}// Paragraph-break gap above. We deliberately don't require gap_below:@@ -485,9 +462,10 @@ const MAX_HEADING_AVG_LINE_CHARS: f32 = 200.0;const MIN_HEADING_ALPHA_RATIO: f32 = 0.5;/// Build a heading-size → level map: sizes strictly larger than `body_size`,-/// filtered to those with at least `MIN_HEADING_LINES` distinct occurrences-/// (drops one-off equation/figure-label artifacts), sorted descending, mapped-/// to levels 1..=MAX_HEADING_LEVELS.+/// filtered by the quality guards `MIN_HEADING_TOTAL_CHARS`,+/// `MIN_HEADING_AVG_LINE_CHARS`, `MAX_HEADING_AVG_LINE_CHARS`, and+/// `MIN_HEADING_ALPHA_RATIO` (drop one-off equation / figure-label / legend+/// artifacts), sorted descending, mapped to levels 1..=MAX_HEADING_LEVELS.pub fn build_heading_map(pages: &[ParsedPage], body_size: f32) -> Vec<(f32, u8)> {use std::collections::HashMap;// (size_key → (size, line_count, total_chars, alpha_chars))@@ -540,8 +518,8 @@ pub fn build_heading_map(pages: &[ParsedPage], body_size: f32) -> Vec<(f32, u8)>};let avg_line_chars = *chars as f32 / (*lines).max(1) as f32;*chars >= MIN_HEADING_TOTAL_CHARS- && avg_line_chars >= MIN_HEADING_AVG_LINE_CHARS- && avg_line_chars <= MAX_HEADING_AVG_LINE_CHARS+ && (MIN_HEADING_AVG_LINE_CHARS..=MAX_HEADING_AVG_LINE_CHARS)+ .contains(&avg_line_chars)&& alpha_ratio >= MIN_HEADING_ALPHA_RATIO}).map(|(s, _, _, _)| *s)@@ -554,6 +532,28 @@ pub fn build_heading_map(pages: &[ParsedPage], body_size: f32) -> Vec<(f32, u8)>.collect()}+/// Fraction of non-whitespace characters in `text` that are alphabetic.+/// Returns 0.0 for an empty/all-whitespace string. The heading heuristics use+/// this to reject digit-dominated tabular rows ("47.5 14", "BLEU-1 25.87")+/// that would otherwise be promoted to headings.+fn alpha_ratio(text: &str) -> f32 {+ let mut alpha = 0usize;+ let mut total = 0usize;+ for c in text.chars() {+ if c.is_whitespace() {+ continue;+ }+ total += 1;+ if c.is_alphabetic() {+ alpha += 1;+ }+ }+ if total == 0 {+ return 0.0;+ }+ alpha as f32 / total as f32+}+pub(super) fn heading_level_for(size: f32, heading_map: &[(f32, u8)]) -> Option<u8> {for (s, level) in heading_map {if (size - *s).abs() < FONT_SIZE_HEADING_TOLERANCE {@@ -753,7 +753,7 @@ mod tests {#[test]fn heading_map_descending_levels() {- // Heading text needs to clear `MIN_HEADING_TOTAL_CHARS` (25) so the+ // Heading text needs to clear `MIN_HEADING_TOTAL_CHARS` (10) so the// size qualifies as a real heading rather than chart-legend noise.let pages = vec![page(vec![line("The largest heading on the page", 50.0, 50.0, 24.0, 24.0),diff --git a/crates/liteparse/src/markdown_layout/inline.rs b/crates/liteparse/src/markdown_layout/inline.rsindex e66fbbe..67e5e52 100644--- a/crates/liteparse/src/markdown_layout/inline.rs+++ b/crates/liteparse/src/markdown_layout/inline.rs@@ -1,7 +1,7 @@use crate::projection::{is_bold_item, is_italic_item, is_mono_item};use crate::types::{ProjectedLine, TextItem};-use super::paragraphs::collapse_whitespace;+use super::paragraphs::{collapse_whitespace, dehyphenate_join};/// Lightweight bold detection on a raw `TextItem`. Delegates to/// `projection::is_bold_item` so per-span and per-line logic stay in sync.@@ -123,11 +123,11 @@ pub(super) fn render_line_inline(line: &ProjectedLine) -> String {j += 1;}let mut group_text = String::new();- for k in i..j {+ for span in &spans[i..j] {if !group_text.is_empty() && !group_text.ends_with(' ') {group_text.push(' ');}- group_text.push_str(spans[k].text.trim());+ group_text.push_str(span.text.trim());}let group_text = collapse_whitespace(&group_text);let escaped = escape_inline(&group_text);@@ -196,25 +196,7 @@ pub(super) fn append_inline_continuation(next_inline: &str,) {let next_raw = collapse_whitespace(next_raw);- if next_raw.is_empty() {- return;- }- if prev_text.is_empty() {- prev_text.push_str(next_inline);- return;- }- let dehyphenate = prev_text.ends_with('-')- && next_raw- .chars()- .next()- .is_some_and(|c| c.is_ascii_lowercase());- if dehyphenate {- prev_text.pop();- prev_text.push_str(next_inline);- } else {- prev_text.push(' ');- prev_text.push_str(next_inline);- }+ dehyphenate_join(prev_text, &next_raw, next_inline);}/// Returns the shared `SpanStyle` of `line` when every non-whitespace span ondiff --git a/crates/liteparse/src/markdown_layout/mod.rs b/crates/liteparse/src/markdown_layout/mod.rsindex ade82bc..6064479 100644--- a/crates/liteparse/src/markdown_layout/mod.rs+++ b/crates/liteparse/src/markdown_layout/mod.rs@@ -1,9 +1,10 @@//! Block classification for the markdown emitter.//!//! Consumes `ProjectedLine` entries from each `ParsedPage` and groups them into-//! a sequence of `Block`s: headings, paragraphs, and (for now) raw lines that-//! don't fit a recognized shape. Tables, lists, and code blocks land in later-//! build-order steps.+//! a sequence of `Block`s: headings, paragraphs, list items, code blocks,+//! tables (ruled and borderless), horizontal rules, and figures. Tabular+//! regions that can't be classified confidently fall back to a fenced grid+//! projection rather than a mangled pipe table.mod blocks;mod classify;diff --git a/crates/liteparse/src/markdown_layout/paragraphs.rs b/crates/liteparse/src/markdown_layout/paragraphs.rsindex ba866ec..478f8a1 100644--- a/crates/liteparse/src/markdown_layout/paragraphs.rs+++ b/crates/liteparse/src/markdown_layout/paragraphs.rs@@ -37,27 +37,29 @@ pub(super) fn collapse_whitespace(s: &str) -> String {out}-/// Append `next` to `accum` as the continuation of a paragraph. De-hyphenates-/// when `accum` ends with `-` and `next` starts with an ASCII lowercase letter;-/// otherwise joins with a single space.-#[cfg(test)]-pub(super) fn append_paragraph_line(accum: &mut String, next: &str) {- let next = collapse_whitespace(next);- if next.is_empty() {+/// Append `to_append` onto `prev`, de-hyphenating across the boundary. When+/// `prev` ends with `-` and `check` (the plain text of the continuation) starts+/// with an ASCII lowercase letter, the trailing hyphen is dropped and the text+/// concatenated directly (`co-` + `operate` → `cooperate`); otherwise the join+/// is a single space.+///+/// `check` and `to_append` are separate so a caller tracking a styled `inline`+/// representation can test the condition against the raw text while appending+/// the inline-rendered chunk. Plain-text callers pass the same string twice.+pub(super) fn dehyphenate_join(prev: &mut String, check: &str, to_append: &str) {+ if check.is_empty() {return;}- if accum.is_empty() {- accum.push_str(&next);+ if prev.is_empty() {+ prev.push_str(to_append);return;}- let dehyphenate =- accum.ends_with('-') && next.chars().next().is_some_and(|c| c.is_ascii_lowercase());- if dehyphenate {- accum.pop(); // drop the '-'- accum.push_str(&next);+ if prev.ends_with('-') && check.chars().next().is_some_and(|c| c.is_ascii_lowercase()) {+ prev.pop();+ prev.push_str(to_append);} else {- accum.push(' ');- accum.push_str(&next);+ prev.push(' ');+ prev.push_str(to_append);}}@@ -164,30 +166,13 @@ pub(super) fn append_to_paragraph(accum: &mut ParaAccum, next_line: &ProjectedLireturn;}- let dehyphenate = accum.raw.ends_with('-')- && next_raw- .chars()- .next()- .is_some_and(|c| c.is_ascii_lowercase());- if dehyphenate {- accum.raw.pop();- accum.raw.push_str(&next_raw);- if accum.inline.ends_with('-') {- accum.inline.pop();- accum.inline.push_str(&next_inline);- } else {- // Hyphen sits inside an emphasis wrap — give up on stripping it- // from `inline` cleanly. Join with a space; raw is still correct- // for the uniform-paragraph case.- accum.inline.push(' ');- accum.inline.push_str(&next_inline);- }- } else {- accum.raw.push(' ');- accum.raw.push_str(&next_raw);- accum.inline.push(' ');- accum.inline.push_str(&next_inline);- }+ // Raw side de-hyphenates against its own boundary. The inline side keys off+ // the same raw lowercase test but checks *its own* trailing char: a hyphen+ // tucked inside an emphasis wrap ends in `*`/`` ` `` rather than `-`, so it+ // 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);// Maintain the running uniform-style flag.accum.uniform = match (accum.uniform, next_uniform) {@@ -202,13 +187,13 @@ mod tests {use super::*;#[test]- fn dehyphenation_only_for_lowercase_followups() {+ fn dehyphenate_join_only_strips_before_lowercase() {let mut s = String::from("co-");- append_paragraph_line(&mut s, "operate");+ dehyphenate_join(&mut s, "operate", "operate");assert_eq!(s, "cooperate");let mut s = String::from("Vitamin-");- append_paragraph_line(&mut s, "A");+ dehyphenate_join(&mut s, "A", "A");assert_eq!(s, "Vitamin- A");}}diff --git a/crates/liteparse/src/markdown_layout/repetition.rs b/crates/liteparse/src/markdown_layout/repetition.rsindex 99be88e..22e3080 100644--- a/crates/liteparse/src/markdown_layout/repetition.rs+++ b/crates/liteparse/src/markdown_layout/repetition.rs@@ -108,12 +108,6 @@ const SP_BOTTOM_BAND_FRACTION: f32 = 0.15;/// and the rest of the page content. A real header/footer is visually/// separated; body lines that happen to sit near the top/bottom are not.const SP_ISOLATION_GAP_RATIO: f32 = 1.0;-/// Font-size delta threshold: lines whose size differs from body by this-/// fraction (smaller OR larger) are size-suspicious chrome candidates. The-/// 0.15 floor admits typical 8/9pt chrome on 10pt body and 12+pt banner-/// chrome on 10pt body without sweeping in sub-headings (which usually-/// differ by ≥ 25%).-const SP_FONT_DELTA: f32 = 0.15;/// Heuristic check: does the line text match a known running-chrome/// signature? URLs/DOIs, journal-article preamble ("Please cite this@@ -202,13 +196,14 @@ fn has_year(lower: &str) -> bool {if !starts_word {continue;}- if (bytes[i] == b'1' && bytes[i + 1] == b'9') || (bytes[i] == b'2' && bytes[i + 1] == b'0')+ if ((bytes[i] == b'1' && bytes[i + 1] == b'9')+ || (bytes[i] == b'2' && bytes[i + 1] == b'0'))+ && bytes[i + 2].is_ascii_digit()+ && bytes[i + 3].is_ascii_digit(){- if bytes[i + 2].is_ascii_digit() && bytes[i + 3].is_ascii_digit() {- let ends_word = i + 4 >= bytes.len() || !bytes[i + 4].is_ascii_alphanumeric();- if ends_word {- return true;- }+ let ends_word = i + 4 >= bytes.len() || !bytes[i + 4].is_ascii_alphanumeric();+ if ends_word {+ return true;}}}@@ -343,9 +338,6 @@ pub fn detect_single_page_chrome(if !matches_chrome_pattern(text) {continue;}- // SP_FONT_DELTA reserved for a future size-aware pass; keep the- // constant so the threshold stays documented.- let _ = SP_FONT_DELTA;// Length guard: avoid stripping long paragraphs that happen to sit in// the band and start with a URL — chrome lines are short. 200 chardiff --git a/crates/liteparse/src/markdown_layout/tables.rs b/crates/liteparse/src/markdown_layout/tables.rsindex bc23097..2eb4aa2 100644--- a/crates/liteparse/src/markdown_layout/tables.rs+++ b/crates/liteparse/src/markdown_layout/tables.rs@@ -164,9 +164,7 @@ pub(super) fn recover_merged_cell(best_contained = contained;}}- let Some(i) = best_i else {- return None;- };+ let i = best_i?;let cell = cells[i].clone();let chars: Vec<char> = cell.text.trim().chars().collect();let n = chars.len();@@ -404,9 +402,7 @@ fn infer_tracks_from_raw_items(lines: &[ProjectedLine], start_idx: usize) -> Veclet mut current_count = 0usize;let mut current_anchor = f32::NEG_INFINITY;for &x in &xs {- if current_count == 0- || (x - current_anchor).abs() <= TABLE_TRACK_TOLERANCE_PT- {+ if current_count == 0 || (x - current_anchor).abs() <= TABLE_TRACK_TOLERANCE_PT {current_sum += x;current_count += 1;current_anchor = current_sum / current_count as f32;@@ -1269,15 +1265,14 @@ fn try_detect_description_list(lines: &[ProjectedLine], start_idx: usize) -> Opt// Merged-span row: single cell starts at col 0 but extends past// col 1's anchor. Split on the whitespace closest to col 1.let straddles = c0_aligned && cell.end_x > col1_x + DESC_LIST_TRACK_TOL_PT;- if straddles {- if let Some((left, right)) =+ if straddles+ && let Some((left, right)) =split_merged_at_anchor(&cell.text, cell.start_x, cell.end_x, col1_x)- && is_label_like(&left)- {- rows.push((j, left, right));- j += 1;- continue;- }+ && is_label_like(&left)+ {+ rows.push((j, left, right));+ j += 1;+ continue;}break;}@@ -1423,12 +1418,12 @@ fn merge_consecutive_table_runs(runs: Vec<TableRun>, lines: &[ProjectedLine]) ->}let mut out: Vec<TableRun> = Vec::with_capacity(runs.len());for run in runs {- if let Some(prev) = out.last() {- if let Some(merged) = try_merge_pair(prev, &run, lines) {- out.pop();- out.push(merged);- continue;- }+ if let Some(prev) = out.last()+ && let Some(merged) = try_merge_pair(prev, &run, lines)+ {+ out.pop();+ out.push(merged);+ continue;}out.push(run);}@@ -1453,8 +1448,8 @@ fn run_column_count(run: &TableRun) -> Option<usize> {fn run_body_tracks(run: &TableRun, lines: &[ProjectedLine]) -> Option<Vec<(f32, f32)>> {let n_cols = run_column_count(run)?;let mut acc: Option<Vec<(f32, f32)>> = None;- for idx in run.start..run.end.min(lines.len()) {- let cells = split_cells(&lines[idx]);+ for line in &lines[run.start..run.end.min(lines.len())] {+ let cells = split_cells(line);if cells.len() != n_cols {continue;}@@ -1523,9 +1518,9 @@ fn subset_mapping(a: &[(f32, f32)], b: &[(f32, f32)]) -> Option<Vec<usize>> {let mut mapping = Vec::with_capacity(a.len());let mut total = 0.0f32;let mut ok = true;- for i in 0..a.len() {+ for (i, &ai) in a.iter().enumerate() {let bi = if i < skip { i } else { i + 1 };- match subset_match_score(a[i], b[bi], tol) {+ match subset_match_score(ai, b[bi], tol) {Some(d) => {mapping.push(bi);total += d;@@ -1536,7 +1531,7 @@ fn subset_mapping(a: &[(f32, f32)], b: &[(f32, f32)]) -> Option<Vec<usize>> {}}}- if ok && best.as_ref().map_or(true, |(_, e)| total < *e) {+ if ok && best.as_ref().is_none_or(|(_, e)| total < *e) {best = Some((mapping, total));}}@@ -1575,10 +1570,11 @@ fn is_absorbable_interstitial(line: &ProjectedLine) -> bool {return false;}// Reject sentence-shaped prose: ends in . ! ? (a real label rarely does)- if let Some(last) = text.chars().last() {- if matches!(last, '.' | '!' | '?') && text.len() > 6 {- return false;- }+ if let Some(last) = text.chars().last()+ && matches!(last, '.' | '!' | '?')+ && text.len() > 6+ {+ return false;}true}@@ -1645,10 +1641,11 @@ fn try_merge_pair(a: &TableRun, b: &TableRun, lines: &[ProjectedLine]) -> Option}// If both runs had explicit headers, we kept A's; preserve B's// header text as a body row so its content isn't dropped.- if a_header.is_some() && b_header.is_some() {- if let Some(bh) = b_header.clone() {- rows.push(bh);- }+ if a_header.is_some()+ && b_header.is_some()+ && let Some(bh) = b_header.clone()+ {+ rows.push(bh);}rows.extend(b_rows.iter().cloned());return Some(TableRun {@@ -1939,8 +1936,8 @@ fn find_grid_components(hs: &[HSeg], vs: &[VSeg]) -> Vec<(Vec<usize>, Vec<usize>use std::collections::HashMap;let mut groups: HashMap<usize, (Vec<usize>, Vec<usize>)> = HashMap::new();- for i in 0..n_h {- if !connected[i] {+ for (i, &is_connected) in connected[..n_h].iter().enumerate() {+ if !is_connected {continue;}let r = uf_find(&mut parent, i);@@ -1953,10 +1950,16 @@ fn find_grid_components(hs: &[HSeg], vs: &[VSeg]) -> Vec<(Vec<usize>, Vec<usize>let r = uf_find(&mut parent, n_h + j);groups.entry(r).or_default().1.push(j);}- groups+ let mut comps: Vec<(Vec<usize>, Vec<usize>)> = groups.into_values().filter(|(h_idx, v_idx)| h_idx.len() >= 2 && v_idx.len() >= 2)- .collect()+ .collect();+ // `HashMap::into_values` yields components in nondeterministic order, which+ // leaks into table emission order and downstream overlap resolution. Sort+ // by the topmost horizontal-segment index (h_idx is ascending by+ // construction) so the output is stable run-to-run.+ comps.sort_by_key(|(h_idx, _)| h_idx[0]);+ comps}/// Build a `TableRun` for one ruled-grid component. Returns `None` if thediff --git a/crates/liteparse/src/ocr_merge.rs b/crates/liteparse/src/ocr_merge.rsindex 12c428d..fe6a191 100644--- a/crates/liteparse/src/ocr_merge.rs+++ b/crates/liteparse/src/ocr_merge.rs@@ -481,6 +481,9 @@ mod tests {page_width: 100.0,page_height: 100.0,text_items: Vec::new(),+ graphics: Vec::new(),+ struct_nodes: Vec::new(),+ image_refs: Vec::new(),}}@@ -510,6 +513,9 @@ mod tests {height: 50.0,..Default::default()}],+ graphics: Vec::new(),+ struct_nodes: Vec::new(),+ image_refs: Vec::new(),}}@@ -530,6 +536,9 @@ mod tests {height: 5.0,..Default::default()}],+ graphics: Vec::new(),+ struct_nodes: Vec::new(),+ image_refs: Vec::new(),}}diff --git a/crates/liteparse/src/output/markdown.rs b/crates/liteparse/src/output/markdown.rsindex 1dc9504..2090bf3 100644--- a/crates/liteparse/src/output/markdown.rs+++ b/crates/liteparse/src/output/markdown.rs@@ -7,10 +7,11 @@ use crate::types::{OutlineTarget, ParsedPage};/// Format parsed pages as markdown.///-/// Current coverage (build-order step 3): char-weighted font-size histogram →-/// heading detection, paragraph grouping with de-hyphenation. Lines that don't-/// classify as a heading are joined into paragraphs. Lists, code blocks,-/// tables, and inline styling are still pending.+/// Whole-document signals (body font size, heading-level map, repeating+/// header/footer set) are computed once up front, then each page is classified+/// into blocks ([`classify_page_with_filters`]) and rendered. Block classes+/// cover headings, paragraphs (with de-hyphenation and inline emphasis), lists,+/// code blocks, ruled and borderless tables, horizontal rules, and figures.////// Pages are emitted in order, separated by `\n\n-----\n\n` with a/// `<!-- page N -->` marker. Pages that contain no projected lines (e.g. blankdiff --git a/crates/liteparse/src/projection.rs b/crates/liteparse/src/projection.rsindex 333004d..8652780 100644--- a/crates/liteparse/src/projection.rs+++ b/crates/liteparse/src/projection.rs@@ -2752,48 +2752,48 @@ fn name_contains_any(name: &str, hints: &[&str]) -> bool {}pub(crate) fn is_bold_item(item: &TextItem) -> bool {- if let Some(flags) = item.font_flags {- if flags & PDF_FONT_FLAG_FORCE_BOLD != 0 {- return true;- }+ if let Some(flags) = item.font_flags+ && flags & PDF_FONT_FLAG_FORCE_BOLD != 0+ {+ return true;}- if let Some(w) = item.font_weight {- if w >= 600 {- return true;- }+ if let Some(w) = item.font_weight+ && w >= 600+ {+ return true;}- if let Some(n) = &item.font_name {- if name_contains_any(n, BOLD_NAME_HINTS) {- return true;- }+ if let Some(n) = &item.font_name+ && name_contains_any(n, BOLD_NAME_HINTS)+ {+ return true;}false}pub(crate) fn is_italic_item(item: &TextItem) -> bool {- if let Some(flags) = item.font_flags {- if flags & PDF_FONT_FLAG_ITALIC != 0 {- return true;- }+ if let Some(flags) = item.font_flags+ && flags & PDF_FONT_FLAG_ITALIC != 0+ {+ return true;}- if let Some(n) = &item.font_name {- if name_contains_any(n, ITALIC_NAME_HINTS) {- return true;- }+ if let Some(n) = &item.font_name+ && name_contains_any(n, ITALIC_NAME_HINTS)+ {+ return true;}false}pub(crate) fn is_mono_item(item: &TextItem) -> bool {- if let Some(flags) = item.font_flags {- if flags & PDF_FONT_FLAG_FIXED_PITCH != 0 {- return true;- }+ if let Some(flags) = item.font_flags+ && flags & PDF_FONT_FLAG_FIXED_PITCH != 0+ {+ return true;}- if let Some(n) = &item.font_name {- if name_contains_any(n, MONO_NAME_HINTS) {- return true;- }+ if let Some(n) = &item.font_name+ && name_contains_any(n, MONO_NAME_HINTS)+ {+ return true;}false}@@ -3070,14 +3070,14 @@ fn xy_find_best_cut(// inter-cell gaps win on tables with sparsely-filled cells// (docs 120/180/150). Hard-reject any cut line that passes// strictly through an obstacle rect intersecting `bbox`.- if !cut_line_passes_through_obstacle(axis, position, bbox, figures) {- if best.as_ref().is_none_or(|b| score > b.score) {- best = Some(CutCandidate {- axis,- position,- score,- });- }+ if !cut_line_passes_through_obstacle(axis, position, bbox, figures)+ && best.as_ref().is_none_or(|b| score > b.score)+ {+ best = Some(CutCandidate {+ axis,+ position,+ score,+ });}}} else {@@ -3368,7 +3368,7 @@ fn xy_find_banner_cut(if bbox.width <= 1.0 || idxs.len() < 2 {return None;}- let mut sorted: Vec<usize> = idxs.iter().copied().collect();+ 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 min_clearance = (median_h * XY_BANNER_CLEARANCE_FACTOR).max(8.0);@@ -3702,7 +3702,7 @@ pub(crate) fn build_projected_lines(const Y_BAND_HEIGHT_CAP: f32 = 24.0;for idx in sorted {let y = items[idx].item.y;- let h = items[idx].item.height.max(1.0).min(Y_BAND_HEIGHT_CAP);+ let h = items[idx].item.height.clamp(1.0, Y_BAND_HEIGHT_CAP);if current.is_empty() {current.push(idx);current_y = y;@@ -3806,12 +3806,12 @@ fn build_one_line(let n = it.text.chars().count().max(1);total_chars += n;- if let Some(size) = it.font_size {- if size > 0.0 {- let key = (size * 100.0).round() as u32;- let e = size_weights.entry(key).or_insert((size, 0));- e.1 += n;- }+ if let Some(size) = it.font_size+ && size > 0.0+ {+ let key = (size * 100.0).round() as u32;+ let e = size_weights.entry(key).or_insert((size, 0));+ e.1 += n;}let h_key = (it.height.max(0.0) * 100.0).round() as u32;let e = height_weights.entry(h_key).or_insert((it.height, 0));@@ -3844,10 +3844,16 @@ fn build_one_line(}}+ // NOTE on tie-breaks: `max_by_key` over a HashMap returns the *last* max it+ // iterates, and HashMap iteration order is randomized per process. Ties on+ // char-weight would therefore pick a different winner every run, making the+ // line's font size / name / anchor non-deterministic (and with them, heading+ // and emphasis classification downstream). We break every tie on the bucket+ // key so the result is stable across runs.let dominant_size_from_font = size_weights- .values()- .max_by_key(|(_, n)| *n)- .map(|(s, _)| *s)+ .iter()+ .max_by_key(|(k, (_, n))| (*n, **k))+ .map(|(_, (s, _))| *s).unwrap_or(0.0);// Fallback: when PDFium reports font_size ≤ 1.5 (size baked into the text// matrix), use char-weighted bbox height instead so heading detection has@@ -3856,23 +3862,23 @@ fn build_one_line((dominant_size_from_font, false)} else {let h = height_weights- .values()- .max_by_key(|(_, n)| *n)- .map(|(h, _)| *h)+ .iter()+ .max_by_key(|(k, (_, n))| (*n, **k))+ .map(|(_, (h, _))| *h).unwrap_or(0.0);(h, true)};let dominant_font_name = name_weights- .into_iter()- .max_by_key(|(_, n)| *n)- .map(|(n, _)| n);+ .iter()+ .max_by_key(|(name, n)| (**n, *name))+ .map(|(name, _)| name.clone());let majority = |count: usize| total_chars > 0 && count * 2 > total_chars;let dominant_anchor_key = anchor_weights.iter()- .max_by_key(|(_, n)| **n)+ .max_by_key(|(k, n)| (**n, **k)).map(|(k, _)| *k).unwrap_or(0);let anchor = match dominant_anchor_key {@@ -3989,6 +3995,11 @@ mod tests {is_margin_line_number: false,rotated: false,d: 0.0,+ orig_x: x,+ orig_y: y,+ orig_width: w,+ orig_height: h,+ orig_rotation: 0.0,}}diff --git a/crates/pdfium-sys/src/dynamic.rs b/crates/pdfium-sys/src/dynamic.rsindex 8030b9f..8121a13 100644--- a/crates/pdfium-sys/src/dynamic.rs+++ b/crates/pdfium-sys/src/dynamic.rs@@ -529,10 +529,10 @@ fn search_paths() -> Vec<PathBuf> {}// 4. Next to the current executable- if let Ok(exe) = std::env::current_exe() {- if let Some(exe_dir) = exe.parent() {- paths.push(exe_dir.join(name));- }+ if let Ok(exe) = std::env::current_exe()+ && let Some(exe_dir) = exe.parent()+ {+ paths.push(exe_dir.join(name));}// 5. Bare library name (system search paths / LD_LIBRARY_PATH / DYLD_LIBRARY_PATH / PATH)