A fast, helpful, and open-source document parser
feat/fix: improve list vs table detection
Logan Markewich1f32a62076f2
diff --git a/crates/liteparse/src/markdown_layout/classify.rs b/crates/liteparse/src/markdown_layout/classify.rsindex a9340c2..2858d2b 100644--- a/crates/liteparse/src/markdown_layout/classify.rs+++ b/crates/liteparse/src/markdown_layout/classify.rs@@ -10,10 +10,13 @@ use super::hr::detect_horizontal_rules;use super::inline::{append_inline_continuation, line_uniform_style, render_line_inline, render_list_item_text,};-use super::lists::{LIST_INDENT_STEP_PT, parse_list_marker};+use super::lists::{+ LIST_INDENT_STEP_PT, detect_ordered_list_lines, parse_list_marker,+ split_ordered_marker_for_emit,+};use super::paragraphs::{- ParaAccum, append_to_paragraph, collapse_whitespace, continues_heading, continues_paragraph,- ends_hyphenated, ends_sentence_final, is_soft_hyphen_break,+ ParaAccum, append_to_paragraph, collapse_whitespace, continues_heading, continues_list_item,+ continues_paragraph, ends_hyphenated, ends_sentence_final, is_soft_hyphen_break,};use super::repetition::is_header_or_footer;use super::tables::{detect_ruled_tables, detect_tables, merge_table_runs};@@ -491,6 +494,18 @@ fn classify_region(let borderless_runs = precomputed_tables.unwrap_or_else(|| detect_tables(lines));let table_runs = merge_table_runs(ruled_runs, borderless_runs);+ // Region-wide pre-pass: which line indices carry a lettered/roman marker+ // (`a.`, `i.`) that belongs to a confirmed sequential list run. Only these+ // are treated as list items below — a lone `A.` / initial is left alone.+ // Lines already inside a detected table are excluded so enumerated table+ // footnotes (`(a)`, `(b)` below a table) aren't pulled out as a list,+ // which would disturb the table's row/track inference.+ let table_covered: std::collections::HashSet<usize> = table_runs+ .iter()+ .flat_map(|run| run.start..run.end)+ .collect();+ let ordered_list_lines = detect_ordered_list_lines(lines, &table_covered);+const TABLE_HR_SUPPRESS_HEADROOM_ROWS: f32 = 4.0;let table_y_extents: Vec<(f32, f32)> = table_runs.iter()@@ -805,8 +820,20 @@ fn classify_region(}}- // List item?- if let Some((ordered, marker, rest)) = parse_list_marker(text) {+ // List item? Bullets/decimals come from `parse_list_marker`; lettered+ // and roman markers are only accepted when the region pre-pass+ // confirmed them as part of a sequential run.+ let list_marker: Option<(bool, String, String)> = parse_list_marker(text)+ .map(|(o, m, r)| (o, m, r.to_string()))+ .or_else(|| {+ if ordered_list_lines.contains(&line_idx) {+ split_ordered_marker_for_emit(text).map(|(m, r)| (true, m, r))+ } else {+ None+ }+ });+ if let Some((ordered, marker, rest)) = list_marker {+ let rest = rest.as_str();// Numbered bold-section heading: "1. **Foo**" / "5. **The dynamics**".// When the post-marker body is uniformly bold + body-sized,// standalone (paragraph-break gap above and below), short, and@@ -859,12 +886,13 @@ fn classify_region(continue;}- // 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.+ // Continuation of a list item: same gap/font rules as paragraphs, but+ // hanging-indent tolerant. Wrapped bodies either left-flush below the+ // marker (footnote style) or align under the marker's text (indented+ // right) — `continues_list_item` accepts both.if let Some(item_idx) = state.last_list_item_idx&& let Some(prev_idx) = state.last_list_line- && continues_paragraph(&lines[prev_idx], line)+ && continues_list_item(&lines[prev_idx], line)&& let Some(Block::ListItem {text: prev_text, ..}) = blocks.get_mut(item_idx)diff --git a/crates/liteparse/src/markdown_layout/lists.rs b/crates/liteparse/src/markdown_layout/lists.rsindex aaaa22d..191aff5 100644--- a/crates/liteparse/src/markdown_layout/lists.rs+++ b/crates/liteparse/src/markdown_layout/lists.rs@@ -1,10 +1,17 @@+use std::collections::HashSet;++use crate::types::ProjectedLine;+/// Roughly one indent step in PDF points. Used to bucket list items into/// nesting levels relative to the first item of the list.pub(super) const LIST_INDENT_STEP_PT: f32 = 12.0;/// Characters recognized as bullet markers when followed by whitespace./// Limited to glyphs that are unlikely to appear at line-start in normal prose.-const BULLET_CHARS: &[char] = &['•', '·', '◦', '▪', '▸', '▶', '●', '○', '■', '□'];+/// `\u{f0b7}` is the Symbol-font bullet (0xB7) that Word/Adobe emit into the+/// Private Use Area; it isn't remapped to `•` during extraction, so recognize+/// it here rather than let it read as an undecodable label.+const BULLET_CHARS: &[char] = &['•', '·', '◦', '▪', '▸', '▶', '●', '○', '■', '□', '\u{f0b7}'];/// Detect a list marker at the start of `text`. Returns `(ordered, marker_str,/// remainder)` when matched; otherwise `None`.@@ -60,6 +67,245 @@ pub(super) fn parse_list_marker(text: &str) -> Option<(bool, String, &str)> {None}+// ── Lettered / roman ordered-list detection ───────────────────────────────+//+// `parse_list_marker` deliberately ignores alphabetic (`a.`) and roman (`i.`)+// markers because a single one is indistinguishable from an initial+// ("J. Smith") or a section letter ("A. Background"). The disambiguating+// signal is *sequence*: a real lettered/roman list has consecutive siblings+// (`a, b, c` / `i, ii, iii`) starting at value 1, at a consistent indent.+// `detect_ordered_list_lines` does a region-wide pre-pass to find those runs;+// only their member lines are then treated as list items by the classifier.++/// Marker family. Case is tracked so an `a, b, c` run doesn't absorb an+/// unrelated `A.` and vice-versa.+#[derive(Clone, Copy, PartialEq, Eq)]+enum MarkerKind {+ AlphaLower,+ AlphaUpper,+ RomanLower,+ RomanUpper,+}++/// Max line-index gap between consecutive members of one run. A list item may+/// wrap over a few body lines, but a marker sitting dozens of lines below its+/// predecessor belongs to different content — don't chain across it.+const ORDERED_RUN_MAX_LINE_GAP: usize = 12;+/// Indent tolerance for members of one run (same as the description-list+/// track tolerance — sub-point jitter from projection).+const ORDERED_RUN_INDENT_TOL_PT: f32 = 8.0;++/// Value of a lowercase roman-numeral string, or `None` if not a valid roman+/// numeral. Case-normalize before calling.+fn roman_value(s: &str) -> Option<u32> {+ if s.is_empty() {+ return None;+ }+ let mut total: i64 = 0;+ let mut prev: i64 = 0;+ for c in s.chars().rev() {+ let v: i64 = match c {+ 'i' => 1,+ 'v' => 5,+ 'x' => 10,+ 'l' => 50,+ 'c' => 100,+ 'd' => 500,+ 'm' => 1000,+ _ => return None,+ };+ if v < prev {+ total -= v;+ } else {+ total += v;+ prev = v;+ }+ }+ if total > 0 { Some(total as u32) } else { None }+}++/// Possible `(kind, value)` interpretations of a marker body. A single letter+/// like `i` is ambiguous — both alpha (9th letter) and roman (1) — so both are+/// returned and the sequencer picks whichever continues a run.+fn marker_interpretations(body: &str) -> Vec<(MarkerKind, u32)> {+ let mut out = Vec::new();+ let chars: Vec<char> = body.chars().collect();+ if chars.len() == 1 && chars[0].is_ascii_alphabetic() {+ let c = chars[0];+ if c.is_ascii_lowercase() {+ out.push((MarkerKind::AlphaLower, (c as u32) - ('a' as u32) + 1));+ if let Some(v) = roman_value(&c.to_string()) {+ out.push((MarkerKind::RomanLower, v));+ }+ } else {+ out.push((MarkerKind::AlphaUpper, (c as u32) - ('A' as u32) + 1));+ if let Some(v) = roman_value(&c.to_ascii_lowercase().to_string()) {+ out.push((MarkerKind::RomanUpper, v));+ }+ }+ return out;+ }+ // Multi-char: only roman numerals qualify (real lists don't use "ab.").+ if chars.iter().all(|c| c.is_ascii_lowercase()) {+ if let Some(v) = roman_value(body) {+ out.push((MarkerKind::RomanLower, v));+ }+ } else if chars.iter().all(|c| c.is_ascii_uppercase()) {+ if let Some(v) = roman_value(&body.to_ascii_lowercase()) {+ out.push((MarkerKind::RomanUpper, v));+ }+ }+ out+}++/// Split a leading ordered-marker token (`a.`, `iv)`, `(a)`) off `text`,+/// returning `(body, marker, rest)` where `body` is the inner letters, `marker`+/// is the full token as written, and `rest` is the trimmed remainder. Requires+/// whitespace after the marker and a non-empty remainder. Does *not* validate+/// that `body` is a real letter/roman marker — the caller does that via+/// `marker_interpretations`.+fn split_ordered_marker(text: &str) -> Option<(&str, String, &str)> {+ let t = text.trim_start();+ let chars: Vec<char> = t.chars().collect();+ if chars.is_empty() {+ return None;+ }+ // Paren-wrapped: "(a)" / "(iv)"+ if chars[0] == '(' {+ let close = chars.iter().position(|&c| c == ')')?;+ if close < 2 {+ return None; // "()"+ }+ let body_len: usize = chars[1..close].iter().map(|c| c.len_utf8()).sum();+ let after_paren = &t[1 + body_len + 1..];+ let rest = after_paren.strip_prefix(|c: char| c.is_whitespace())?;+ let rest = rest.trim_start();+ if rest.is_empty() {+ return None;+ }+ let body = &t[1..1 + body_len];+ let marker = format!("({body})");+ return Some((body, marker, rest));+ }+ // Suffix form: letters followed by '.' or ')'+ let letter_chars = chars.iter().take_while(|c| c.is_ascii_alphabetic()).count();+ if letter_chars == 0 || letter_chars > 7 {+ return None;+ }+ let body_len: usize = chars[..letter_chars].iter().map(|c| c.len_utf8()).sum();+ let punct = chars.get(letter_chars).copied()?;+ if punct != '.' && punct != ')' {+ return None;+ }+ let after_punct = &t[body_len + punct.len_utf8()..];+ let rest = after_punct.strip_prefix(|c: char| c.is_whitespace())?;+ let rest = rest.trim_start();+ if rest.is_empty() {+ return None;+ }+ let body = &t[..body_len];+ let marker = format!("{body}{punct}");+ Some((body, marker, rest))+}++/// A candidate marker line, in region-local index order.+struct OrderedCandidate {+ idx: usize,+ indent: f32,+ interps: Vec<(MarkerKind, u32)>,+}++/// An in-progress run of sequential markers sharing kind + indent.+struct OrderedRun {+ kind: MarkerKind,+ next: u32,+ indent: f32,+ last_idx: usize,+ members: Vec<usize>,+}++/// Region-wide pre-pass: return the set of line indices whose leading+/// alphabetic / roman marker belongs to a confirmed ordered-list run (≥2+/// sequential siblings starting at value 1, consistent indent, no large+/// document-order gap). Callers treat those lines as ordered list items;+/// unconfirmed one-off markers (initials, lone section letters) are left alone.+pub(super) fn detect_ordered_list_lines(+ lines: &[ProjectedLine],+ table_covered: &HashSet<usize>,+) -> HashSet<usize> {+ let candidates: Vec<OrderedCandidate> = lines+ .iter()+ .enumerate()+ .filter_map(|(i, l)| {+ if table_covered.contains(&i) {+ return None;+ }+ let (body, _marker, _rest) = split_ordered_marker(l.text.trim())?;+ let interps = marker_interpretations(body);+ if interps.is_empty() {+ None+ } else {+ Some(OrderedCandidate {+ idx: i,+ indent: l.indent_x,+ interps,+ })+ }+ })+ .collect();++ let mut runs: Vec<OrderedRun> = Vec::new();+ for c in &candidates {+ // Prefer extending the most recently touched matching run (keeps nested+ // levels — an inner `i.` opens its own run while the outer `a,b,c` run+ // stays open at its own indent).+ let mut extended = false;+ for run in runs.iter_mut().rev() {+ if c.idx - run.last_idx <= ORDERED_RUN_MAX_LINE_GAP+ && (run.indent - c.indent).abs() <= ORDERED_RUN_INDENT_TOL_PT+ && c.interps+ .iter()+ .any(|(k, v)| *k == run.kind && *v == run.next)+ {+ run.members.push(c.idx);+ run.next += 1;+ run.last_idx = c.idx;+ extended = true;+ break;+ }+ }+ if extended {+ continue;+ }+ // Start a new run only at the first item of a sequence (value 1):+ // `a`, `A`, `i`, `I`. This is what keeps stray `J.` / `A.` out.+ if let Some(&(kind, _)) = c.interps.iter().find(|(_, v)| *v == 1) {+ runs.push(OrderedRun {+ kind,+ next: 2,+ indent: c.indent,+ last_idx: c.idx,+ members: vec![c.idx],+ });+ }+ }++ let mut confirmed = HashSet::new();+ for run in runs {+ if run.members.len() >= 2 {+ confirmed.extend(run.members);+ }+ }+ confirmed+}++/// For a line already confirmed as an ordered-list member by+/// `detect_ordered_list_lines`, extract `(marker, rest)` for emission.+pub(super) fn split_ordered_marker_for_emit(text: &str) -> Option<(String, String)> {+ let (_body, marker, rest) = split_ordered_marker(text)?;+ Some((marker, rest.to_string()))+}+#[cfg(test)]mod tests {use super::*;@@ -93,4 +339,124 @@ mod tests {// Footnote caller / page number style — no whitespace afterassert!(parse_list_marker("1.5x growth").is_none());}++ fn ll(text: &str, x: f32, y: f32) -> ProjectedLine {+ super::super::test_helpers::line(text, x, y, 11.0, 10.0)+ }++ #[test]+ fn roman_value_parses() {+ assert_eq!(roman_value("i"), Some(1));+ assert_eq!(roman_value("iv"), Some(4));+ assert_eq!(roman_value("ix"), Some(9));+ assert_eq!(roman_value("xiv"), Some(14));+ assert_eq!(roman_value("q"), None);+ }++ #[test]+ fn split_ordered_marker_forms() {+ assert_eq!(+ split_ordered_marker("a. hello"),+ Some(("a", "a.".to_string(), "hello"))+ );+ assert_eq!(+ split_ordered_marker("iv) hello"),+ Some(("iv", "iv)".to_string(), "hello"))+ );+ assert_eq!(+ split_ordered_marker("(a) hello"),+ Some(("a", "(a)".to_string(), "hello"))+ );+ // No space after marker → not a marker ("i.e." must not split).+ assert!(split_ordered_marker("i.e. therefore").is_none());+ // No remainder.+ assert!(split_ordered_marker("a.").is_none());+ }++ #[test]+ fn detects_lettered_and_roman_sequences() {+ // a./b./c. at one indent, i./ii./iii. deeper — both confirmed.+ let lines = vec![+ ll("a. first item", 20.0, 100.0),+ ll("b. second item", 20.0, 120.0),+ ll("c. third item", 20.0, 140.0),+ ll("i. sub one", 40.0, 160.0),+ ll("ii. sub two", 40.0, 180.0),+ ll("iii. sub three", 40.0, 200.0),+ ];+ let got = detect_ordered_list_lines(&lines, &HashSet::new());+ assert_eq!(got.len(), 6, "all six markers should be confirmed");+ assert!((0..6).all(|i| got.contains(&i)));+ }++ #[test]+ fn lone_marker_is_not_a_list() {+ // A single "A. Background" heading letter has no sibling → not a list.+ let lines = vec![+ ll("A. Background", 20.0, 100.0),+ ll(+ "Some prose about the background of the matter at hand.",+ 20.0,+ 120.0,+ ),+ ];+ assert!(detect_ordered_list_lines(&lines, &HashSet::new()).is_empty());+ }++ #[test]+ fn initials_are_not_a_list() {+ // "J. Smith" / "M. Jones" are initials, not sequential markers (J=10,+ // M=13, neither starts a run and they aren't consecutive).+ let lines = vec![+ ll(+ "J. Smith reported the findings to the committee.",+ 20.0,+ 100.0,+ ),+ ll(+ "M. Jones seconded the motion without objection.",+ 20.0,+ 120.0,+ ),+ ];+ assert!(detect_ordered_list_lines(&lines, &HashSet::new()).is_empty());+ }++ #[test]+ fn does_not_chain_across_large_gaps() {+ // "a." then "b." tens of lines apart are unrelated, not a 2-item list.+ let mut lines = vec![ll("a. opening clause", 20.0, 100.0)];+ for k in 0..14 {+ lines.push(ll(+ "ordinary body prose line here",+ 20.0,+ 120.0 + k as f32 * 20.0,+ ));+ }+ lines.push(ll("b. much later clause", 20.0, 420.0));+ assert!(detect_ordered_list_lines(&lines, &HashSet::new()).is_empty());+ }++ #[test]+ fn table_covered_markers_are_excluded() {+ // Enumerated table footnotes `(a)`, `(b)` inside a detected table must+ // not be pulled out as a list — that would disturb the table.+ let lines = vec![+ ll(+ "(a) first footnote of the table below the divider rule",+ 20.0,+ 100.0,+ ),+ ll(+ "(b) second footnote of the table below the divider rule",+ 20.0,+ 120.0,+ ),+ ];+ // Without the guard they'd confirm as a 2-item run…+ assert_eq!(detect_ordered_list_lines(&lines, &HashSet::new()).len(), 2);+ // …but excluding their line indices leaves nothing.+ let covered: HashSet<usize> = [0usize, 1].into_iter().collect();+ assert!(detect_ordered_list_lines(&lines, &covered).is_empty());+ }}diff --git a/crates/liteparse/src/markdown_layout/paragraphs.rs b/crates/liteparse/src/markdown_layout/paragraphs.rsindex 20c60dc..a6141fb 100644--- a/crates/liteparse/src/markdown_layout/paragraphs.rs+++ b/crates/liteparse/src/markdown_layout/paragraphs.rs@@ -164,6 +164,18 @@ pub(super) fn continues_heading(prev: &ProjectedLine, cur: &ProjectedLine) -> bo/// Decide whether `cur` continues the paragraph started by `prev`.pub(super) fn continues_paragraph(prev: &ProjectedLine, cur: &ProjectedLine) -> bool {+ paragraph_flow(prev, cur, false)+}++/// List-item continuation: like `continues_paragraph`, but tolerant of a+/// hanging indent. A wrapped list-item body commonly aligns under the marker's+/// *text* — i.e. indented to the right of the marker line — which+/// `continues_paragraph` would read as a new indented block.+pub(super) fn continues_list_item(prev: &ProjectedLine, cur: &ProjectedLine) -> bool {+ paragraph_flow(prev, cur, true)+}++fn paragraph_flow(prev: &ProjectedLine, cur: &ProjectedLine, allow_hanging_indent: bool) -> bool {// Anchor only signals a paragraph break when one of the lines is clearly// centered while the other isn't — justified prose routinely alternates// between Left / Right / Floating dominant anchors as line widths flex,@@ -217,7 +229,10 @@ pub(super) fn continues_paragraph(prev: &ProjectedLine, cur: &ProjectedLine) ->.is_some_and(|c| c.is_lowercase());return ends_open && starts_lower;}- if (prev.indent_x - cur.indent_x).abs() > INDENT_TOLERANCE && cur.anchor == Anchor::Left {+ if !allow_hanging_indent+ && (prev.indent_x - cur.indent_x).abs() > INDENT_TOLERANCE+ && cur.anchor == Anchor::Left+ {// Indent change on a left-aligned block usually means a new paragraph// (block-quote, list, indented passage, etc.). Allow first-line indent// by checking only when the *next* line shifts right relative to prev.diff --git a/crates/liteparse/src/markdown_layout/tables.rs b/crates/liteparse/src/markdown_layout/tables.rsindex f1a1a6c..f4039ee 100644--- a/crates/liteparse/src/markdown_layout/tables.rs+++ b/crates/liteparse/src/markdown_layout/tables.rs@@ -1276,18 +1276,23 @@ fn is_bullet_only(text: &str) -> bool {| '⮚'| '►'| '▶'+ // Symbol-font bullet in the Private Use Area (undecoded 0xB7).+ | '\u{f0b7}')});if only_glyph {return true;}- // Numeric list marker: "1.", "1)", "(1)", "i.", "ii." etc. — all are list- // markers, not table labels.+ // Numeric list marker: "1.", "1)", "(1)", "i.", "ii.", "a.", "(a)" etc. —+ // all are list markers, not table labels.let chars: Vec<char> = t.chars().collect();- let is_paren_num = chars.first() == Some(&'(')- && chars.last() == Some(&')')- && chars[1..chars.len() - 1].iter().all(|c| c.is_ascii_digit());- if is_paren_num && chars.len() <= 5 {+ // Paren-wrapped marker: "(1)" or single-letter "(a)".+ let is_paren_marker = chars.first() == Some(&'(') && chars.last() == Some(&')') && {+ let inner = &chars[1..chars.len() - 1];+ inner.iter().all(|c| c.is_ascii_digit())+ || (inner.len() == 1 && inner[0].is_ascii_alphabetic())+ };+ if is_paren_marker && chars.len() <= 5 {return true;}let trailing = chars.last().copied();@@ -1297,7 +1302,12 @@ fn is_bullet_only(text: &str) -> bool {&& (body.chars().all(|c| c.is_ascii_digit())|| body.chars()- .all(|c| matches!(c, 'i' | 'v' | 'x' | 'I' | 'V' | 'X')))+ .all(|c| matches!(c, 'i' | 'v' | 'x' | 'I' | 'V' | 'X'))+ // Single-letter lettered-list marker: "a.", "b)", "A." — a+ // short marker column beside wrapped body text is a nested+ // ordered list, not a 2-column description table.+ || (body.chars().count() == 1+ && body.chars().next().is_some_and(|c| c.is_ascii_alphabetic()))){return true;}@@ -4344,4 +4354,58 @@ mod tests {other => panic!("expected Block::Table, got {other:?}"),}}++ #[test]+ fn is_bullet_only_recognizes_lettered_markers() {+ // Digit and roman markers were already handled; lettered ordered-list+ // markers must be too, so a nested a./b./c. list is not mistaken for a+ // description-list table label.+ for m in ["a.", "b.", "c.", "z.", "A.", "a)", "B)", "(a)", "(B)"] {+ assert!(is_bullet_only(m), "{m:?} should be a bullet/list marker");+ assert!(+ !is_label_like(m),+ "{m:?} should not be treated as a table label"+ );+ }+ // Genuine short labels stay labels.+ for l in ["Name:", "Term", "Rate", "Fee.", "AB.", "ab."] {+ assert!(!is_bullet_only(l), "{l:?} should not be a bullet marker");+ }+ }++ #[test]+ fn lettered_list_is_not_a_description_table() {+ // Two-level lettered list: short marker column (col 0) beside wrapped+ // body text (col 1). Regression for the nested-list → pipe-table bug.+ let lines = vec![+ line_with_spans(+ &[+ ("a.", 80.0),+ ("The Committee may retain outside advisors.", 120.0),+ ],+ 100.0,+ 10.0,+ ),+ line_with_spans(+ &[+ ("b.", 80.0),+ ("The Committee shall have sole authority.", 120.0),+ ],+ 88.0,+ 10.0,+ ),+ line_with_spans(+ &[+ ("c.", 80.0),+ ("In retaining advice the Committee considers:", 120.0),+ ],+ 76.0,+ 10.0,+ ),+ ];+ assert!(+ try_detect_description_list(&lines, 0).is_none(),+ "lettered list must not be detected as a description-list table"+ );+ }}