Skip to content

A fast, helpful, and open-source document parser

table improvements: two-row tables + soft-wrap row grouping

Logan Markewich520413d04c41
diff --git a/TABLE_TEDS_PROGRESS.md b/TABLE_TEDS_PROGRESS.md
new file mode 100644
index 0000000..0e44f96
--- /dev/null
+++ b/TABLE_TEDS_PROGRESS.md
@@ -0,0 +1,197 @@
+# Table / TEDS gap vs pdf-inspector — progress & followups
+
+Goal: close the table-fidelity (TEDS) gap against **pdf-inspector** (firecrawl) on
+`opendataloader-bench` (200 PDFs). Started 2026-08-01.
+
+## Standing
+
+| metric | baseline (2.10.1) | round 1 (`093ddba`) | round 2 | Δ total | pdf-inspector |
+|---|---|---|---|---|---|
+| **overall** | 0.8732 | 0.8757 | **0.8783** | +0.0051 | 0.8753 |
+| TEDS | 0.6929 | 0.7128 | **0.7441** | **+0.0511** | 0.8141 |
+| MHS | 0.8114 | 0.8175 | **0.8179** | +0.0064 | 0.7879 |
+| NID | 0.9127 | 0.9129 | **0.9136** | +0.0009 | 0.9147 |
+
+We lead on overall + MHS, trail on TEDS by **0.070** (was 0.101) and NID by 0.001.
+**TEDS is scored on only 42 of the 200 docs**, so one doc = 0.024 of the mean.
+
+Round 1 shipped as `093ddba`; round 2 adds ~190 lines, all still in
+`crates/liteparse/src/markdown_layout/tables.rs`. 298 lib tests pass.
+
+## What shipped
+
+1. **`collapse_gutter_columns`** — called from `build_ruled_table` right after
+ `cluster_boundaries`. Padded cell borders contribute *paired* vertical edges
+ (15–25pt apart), leaving a sliver column between every real column — doc 200 had 13
+ columns for a 4-column table. `split_span_at_anchors` shreds text into the slivers, so
+ `collapse_phantom_cols` can't see they're empty and the grid dies on the empty-cell
+ gate. Fuse a column only when **no raw span center lands inside it** AND it is
+ < 0.5× the median *content-bearing* column width.
+ *Both halves are load-bearing*: a width-only/bimodal variant broke docs 178+120 from
+ 1.000 → 0.65, and the width guard is what preserves blank worksheet columns.
+
+2. **Merged-run recovery for absorbed headers** — in `absorb_header_lines`. PDFium emits
+ a header row's words as one run, so an 8-col table got a 2-cell header whose blob
+ bound to a single column (doc 190). Reuses the existing `recover_merged_cell`.
+ Needs **three** gates or it shreds prose into fake headers:
+ `absorbed.is_empty()` (first candidate line only), every recovered piece ≤ 30 chars,
+ and `cells.len() < column_count`. Dropping any one of these regressed NID.
+
+## What shipped — round 2 (followups 1 + 2)
+
+3. **Two-pass last-resort for header + single-data-row tables** (+0.0188 TEDS,
+ +0.0002 NID; doc 197 alone 0.000 → 0.789, *one* doc changed, no collateral).
+ `try_detect_table_inferred` takes `allow_two_row`; `two_row_second_pass` retries
+ only in the index gaps where the normal pass found no table.
+ *The gap restriction alone is NOT enough* — that was the plan and it failed:
+ doc 147 still broke (−0.82) and 14 docs lost NID. The real counterfeit is
+ **fully-justified prose**, whose stretched inter-word spaces infer as clean
+ tracks, so any two consecutive lines shred into
+ `| when travelling | to | conflict | zones, | more |`. What actually works is
+ `two_row_run_plausible`: **isolation** (neighbours not table-adjacent — a prose
+ pair is mid-paragraph) plus **header shape** (cells start uppercase/digit, no
+ trailing comma). Gates apply only when the relaxation actually fired, so they
+ can never reject something the normal pass accepted.
+
+4. **Multi-line cell / row grouping** (+0.0125 TEDS, 3 docs up, none down;
+ doc 150 0.446 → 0.861, now *beating* pdf-inspector's 0.847).
+ `merge_continuation_rows`, applied at the end of `merge_table_runs` — the one
+ funnel both ruled and borderless runs pass through. Post-hoc and text-only, as
+ predicted; the geometry really is unusable. A row folds into its predecessor
+ when it has an empty first cell, its filled columns are a **subset** of the
+ predecessor's, and at least one extended cell reads as a soft wrap.
+ Two vetoes are load-bearing, and **each was found by a different benchmark**:
+ - **Any value-like cell → not a continuation** (odl-bench). Numbers don't
+ soft-wrap, and a `Total` row has a blank label column precisely because the
+ label isn't its own. Vetoing on `all` value-like instead of `any` cost docs
+ 45 (−0.13) and 47 (−0.09); `any` turned both positive.
+ - **First column must be filled in ≥ half the rows** (ParseBench only —
+ see the cross-benchmark note below). "Empty first cell" only means "wrapped
+ line" if the first column is a *label* column; plenty of tables just have a
+ sparse one.
+
+## Cross-benchmark check is mandatory for table work
+
+**opendataloader-bench alone is not enough.** Round 2 looked perfect on it — four
+docs up, none down — while silently costing **−0.0048** on the ParseBench table
+dimension. Attribution (one run per variant):
+
+| variant | odl TEDS | ParseBench table composite |
+|---|---|---|
+| HEAD `093ddba` | 0.7128 | 0.4032 |
+| + two-row pass | 0.7316 | 0.4032 (free) |
+| + continuation merge | 0.7441 | **0.3984** ← regression |
+| + first-column fill guard | 0.7441 | **0.4034** |
+
+The continuation merge owned the whole regression, concentrated in a few docs
+(`1 timetable_page6` 0.859 → **0.006**, `sizingchart`, `myco hierarchical table
+header`). All were tables with a legitimately sparse first column, where every
+row reads as a continuation and the table collapses to one row. The fill guard
+fixes them at zero cost to odl-bench.
+
+Note `is_value_like` does **not** match bare times (`8:24`) or bare integers
+(`15`) — it needs `d.d` / `d,d` / `$` / `%`. Don't widen it to patch a table bug;
+it gates several unrelated paths. Prefer a structural guard.
+
+Run: `cd ParseBench && uv run parse-bench run liteparse_markdown --group table`
+(~12 min, 503 examples). Read `avg_grits_trm_composite` from
+`output/liteparse_markdown/_evaluation_report.json` — this is the leaderboard's
+"Tables" column (0.4032 = the 40.3 in `leaderboard.csv`). **The run overwrites
+that report in place**, so copy it aside before running a variant.
+
+## Tooling
+
+- **Per-doc deltas**: `opendataloader-bench/perdoc.py <label-b> [label-a] [metric]`
+ — prints every doc whose metric moved between two prediction labels, worst
+ first. Doc numbers match the ones used in this file. This is what caught that
+ the round-2 mean hid a −0.82 doc in the first two-row attempt.
+- **A/B harness**: `opendataloader-bench/ab.sh <label>` — parses all 200 PDFs with the
+ tuned bench config and prints the delta vs `prediction/liteparse` (the frozen 2.10.1
+ baseline). Verified byte-identical to the recorded baseline on all 200 docs.
+ Takes ~1–2 min. **Always A/B; per-doc deltas matter more than the mean.**
+- **Debug envs**: `LITEPARSE_DEBUG_TABLE=1 LITEPARSE_DEBUG_RULED=1` on a single
+ `lit parse ... --format markdown --image-mode off --no-ocr --no-links -q`.
+ These print every gate rejection with its numbers. **Use these first** — twice I
+ inferred a mechanism from the emitted markdown and was wrong.
+- **pdf-inspector repro**: `git clone --depth 1 https://github.com/firecrawl/pdf-inspector`,
+ `cargo build --release --bin pdf2md` (~28s), run `pdf2md <pdf> --raw`. Its outputs and
+ scores are already committed at `opendataloader-bench/prediction/pdf-inspector/`.
+ Re-evaluate with `uv run src/evaluator.py --engine pdf-inspector`.
+
+## Where the remaining 0.101 sits
+
+Measured by GT-cell-text retention (liteparse **0.747** vs pdf-inspector **0.870**):
+
+| class | TEDS cost | meaning | docs |
+|---|---|---|---|
+| **MISPLACED** | −0.073 | text is in the doc but never lands in a table | 165, 197, 200, 182, 116 |
+| **STRUCTURE-only** | −0.058 | text *is* in the table, structure wrong | 150, 146, 119, 190, 81, 84, 166, 188, 82, 90, 89 |
+| LOST-upstream | −0.008 | genuine extraction failure | 121, 46 |
+
+So the dominant problem is **misfiling**, not dropping, text.
+
+## Followups, ranked
+
+*(followups 1 and 2 are done — see "round 2" above.)*
+
+2b. **More of the continuation class is still available.** `merge_continuation_rows`
+ only fires on rows with an **empty first cell**. pdf-inspector's veto set is richer
+ (`looks_like_data_row`, `is_short_subheader`, `looks_like_hierarchical_subrow`,
+ `looks_like_spanning_first_column_row`), which lets them merge wraps where the first
+ column *is* populated. Worth trying next, but the empty-first-cell rule is what makes
+ the current version regression-free — relax it only behind an A/B.
+
+3. **Doc 200 (−0.737 alone, ~+0.018).** Columns are now correct after the gutter fix,
+ but the body rows come out empty. Cause: `flatten_header_band` absorbs the landscape
+ slide's full-width title rows into the colspan header, so rows 0..3 become a junk
+ header band. Note the obvious guard (skip rows whose `cells_repl` is uniform across
+ all columns) **does not fire** — PDFium splits the title into several spans.
+
+4. **Doc 165 worksheet (~+0.024).** Bordered worksheet whose second column is entirely
+ blank; the ruled grid is rejected (`rows-after-collapse 1`, `no-lines-consumed`).
+ Related: `TABLE_MAX_EMPTY_CELL_FRACTION` cannot be relaxed (see below), so this needs
+ a different route — likely the tagged struct tree (item 5).
+
+5. **Tagged `/Table` structure tree — unused by us entirely.** pdf-inspector's *highest
+ priority* detector (`detect_struct.rs`): walks StructTreeRoot for `/Table` `/TR`
+ `/TD`, links cells to text via **MCID**, gates on coverage (0.3 internal, 0.5 of band
+ items). We already parse `struct_nodes` (`extract.rs:134`, exposed on `ParsedPage`)
+ but consume it *only* for heading levels (`classify.rs:622`). The plumbing exists;
+ the detector does not. Biggest structural bet available.
+
+## Negative results — do not retry blind
+
+- **Relaxing `TABLE_MAX_EMPTY_CELL_FRACTION`** (swept 0.45/0.60/0.75): 0.45 neutral,
+ 0.60 −0.013 TEDS, 0.75 −0.040. `empty-frac` in the gate logs is a *symptom* of text
+ not being assigned, not a tight threshold.
+- **Relaxing the straddle-frac gate (0.45)**: zero TEDS gain, costs NID and MHS. High
+ straddle was a symptom of column over-segmentation — it fell 0.48 → 0.32 by itself
+ once gutters collapsed.
+- **Full-width-spanner exclusion in `flatten_header_band`**: exactly zero delta, guard
+ never fires (see item 3).
+- **Directly allowing 2-row header-led tables**: fixes doc 197 (+0.789) but breaks doc
+ 147 (−0.822) plus ~8 NID regressions. The existing code comment is right — a 2-row run
+ forms early and consumes the real table's header.
+- **Restricting the 2-row relaxation to table-free gaps, with no content gate**:
+ doc 147 still −0.822, 14 docs lose NID (−0.0030). The gap restriction addresses the
+ wrong mechanism. Justified prose is the counterfeit, and it lives *in* the gaps.
+- **A second full-width-spanner guard in `flatten_header_band`** (reject the flatten
+ when a produced header cell exceeds 100 chars, aimed at doc 200): **exactly zero
+ delta** — this is the second guard to die here. The `[ruled] colspan header flatten`
+ line you see in doc 200's debug output belongs to a component that is *rejected
+ later anyway*; the emitted 5-column table comes from a different component. Before
+ touching `flatten_header_band` again, confirm the component you're looking at is the
+ one that actually reaches the output.
+
+## Methodology gotchas (both bit me)
+
+- **Gate-reason histograms over the corpus are mostly noise.** `tracks < MIN_COLUMNS`
+ fires on every prose line; `grid-too-small ys=2 xs=2` is the page-background rect;
+ `no-lines-consumed` is every non-overlapping region/component pair. Rank by per-doc
+ loss instead, then read that doc's debug output.
+- **`difflib.SequenceMatcher` needs `autojunk=False`.** The default silently corrupts
+ comparisons on strings over 200 chars and produced impossible numbers (a doc's table
+ text matching better than the whole document containing it).
+- Table detection runs on region lines **before** interruptions (HRs, figures) are
+ interleaved (`classify.rs:499`), so thematic breaks do *not* fragment table rows —
+ an early theory of mine that the debug output disproved.
diff --git a/crates/liteparse/src/markdown_layout/tables.rs b/crates/liteparse/src/markdown_layout/tables.rs
index bad0793..4b783f4 100644
--- a/crates/liteparse/src/markdown_layout/tables.rs
+++ b/crates/liteparse/src/markdown_layout/tables.rs
@@ -650,6 +650,12 @@ fn finalize_table_run(
if header.is_none() && body_rows.len() < TABLE_MIN_ROWS {
return None;
}
+ // A header with no body is not a table. Reachable only via the bold-first-row
+ // promotion, which consumes rows[0] — harmless before the two-row relaxation,
+ // but with it rows[0] can be the *only* row.
+ if body_rows.is_empty() {
+ return None;
+ }
if *super::flags::DEBUG_TABLE {
eprintln!(
@@ -668,10 +674,16 @@ fn finalize_table_run(
})
}
+/// `allow_two_row` relaxes the two body-length gates below so a header row plus
+/// a *single* data row can form a table. Only ever set by the last-resort second
+/// pass in `detect_tables_impl`, which runs exclusively in regions where the
+/// normal pass found no table at all — see the comment there for why relaxing
+/// these gates globally is unsafe.
fn try_detect_table_inferred(
lines: &[ProjectedLine],
start_idx: usize,
floor: usize,
+ allow_two_row: bool,
) -> Option<TableRun> {
let dbgt = *super::flags::DEBUG_TABLE;
let seed_txt: String = lines[start_idx]
@@ -831,7 +843,8 @@ fn try_detect_table_inferred(
rows.push((j, &lines[j], cells));
j += 1;
}
- if rows.len() < TABLE_MIN_ROWS {
+ let min_rows = if allow_two_row { 1 } else { TABLE_MIN_ROWS };
+ if rows.len() < min_rows {
bail!("rows {} < MIN_ROWS", rows.len());
}
// When the body was seeded below `start_idx` (the lead line was a header
@@ -841,7 +854,7 @@ fn try_detect_table_inferred(
// header-seeded path of the real table below it. Already-strong seeds
// (body_start == start_idx) keep the
// standard MIN_ROWS threshold and are unaffected.
- if body_start > start_idx && rows.len() < 3 {
+ if body_start > start_idx && rows.len() < 3 && !allow_two_row {
bail!("advanced body_start but only {} rows", rows.len());
}
let cv = row_spacing_cv(&rows);
@@ -852,7 +865,7 @@ fn try_detect_table_inferred(
let end = j;
let bold_eligible = rows[0].2.iter().all(|c| c.bold && !c.text.is_empty());
- finalize_table_run(
+ let run = finalize_table_run(
lines,
body_start,
floor,
@@ -861,7 +874,64 @@ fn try_detect_table_inferred(
column_count,
end,
bold_eligible,
- )
+ )?;
+ // Runs that exist *only* because the relaxation fired must clear the extra
+ // content gates. Runs that would have passed the normal floor anyway are
+ // untouched, so this can never reject something the normal pass accepted.
+ if allow_two_row && rows.len() < TABLE_MIN_ROWS && !two_row_run_plausible(lines, &run) {
+ bail!("two-row run failed plausibility gates");
+ }
+ Some(run)
+}
+
+/// Plausibility gates for a header + single-data-row run.
+///
+/// Two rows is the weakest possible structural signal, and there is one thing
+/// that reliably counterfeits it: **fully-justified prose**. Justification
+/// stretches inter-word spaces until they read as column gutters, so any two
+/// consecutive lines of a justified paragraph infer clean tracks and shred into
+/// `| when travelling | to | conflict | zones, | more |`. Measured cost of not
+/// gating this: −0.0030 NID across 14 documents.
+///
+/// Two signals separate the real thing from the counterfeit:
+///
+/// 1. **Isolation.** A real 2-row table is surrounded by whitespace. A prose
+/// pair is mid-paragraph, so its neighbours are table-adjacent lines.
+/// 2. **Header shape.** Header cells are labels — they start with a capital or
+/// a digit and don't trail mid-sentence punctuation. Prose "headers" are
+/// lowercase words, often ending in a comma.
+fn two_row_run_plausible(lines: &[ProjectedLine], run: &TableRun) -> bool {
+ let Block::Table {
+ header: Some(header),
+ ..
+ } = &run.block
+ else {
+ return false;
+ };
+
+ if run.start > 0 && table_rows_adjacent(&lines[run.start - 1], &lines[run.start]) {
+ return false;
+ }
+ if run.end < lines.len() && table_rows_adjacent(&lines[run.end - 1], &lines[run.end]) {
+ return false;
+ }
+
+ let mut non_empty = 0;
+ for cell in header {
+ let t = cell.trim();
+ if t.is_empty() {
+ continue;
+ }
+ non_empty += 1;
+ let first = t.chars().next().unwrap();
+ if !(first.is_uppercase() || first.is_ascii_digit()) {
+ return false;
+ }
+ if t.ends_with(',') || t.ends_with(';') {
+ return false;
+ }
+ }
+ non_empty >= TABLE_MIN_COLUMNS
}
/// Try to extend a candidate table starting at `start_idx`. On success returns
@@ -1213,7 +1283,7 @@ fn detect_tables_impl(lines: &[ProjectedLine], include_desc_lists: bool) -> Vec<
let mut i = 0;
let mut floor = 0;
while i < lines.len() {
- if let Some(run) = try_detect_table_inferred(lines, i, floor) {
+ if let Some(run) = try_detect_table_inferred(lines, i, floor, false) {
floor = run.end;
i = run.end;
out.push(run);
@@ -1242,7 +1312,62 @@ fn detect_tables_impl(lines: &[ProjectedLine], include_desc_lists: bool) -> Vec<
break;
}
}
- merged
+ two_row_second_pass(lines, merged)
+}
+
+/// Last-resort pass for header + single-data-row tables.
+///
+/// Some real tables are a header row plus exactly one data row. Both length
+/// gates in `try_detect_table_inferred` reject them. Relaxing those gates
+/// *directly* is not safe: a 2-row run forms early, higher up the page, and
+/// consumes the header of the real multi-row table below it (doc 197 gains
+/// +0.789 that way but doc 147 loses −0.822, plus ~8 NID regressions).
+///
+/// So instead we keep the normal pass exactly as-is and only retry, with the
+/// relaxation on, inside the index gaps where it found *no* table at all. By
+/// construction a run detected here cannot steal rows from a real table: there
+/// isn't one in the gap. Runs that would spill past the gap end are discarded
+/// for the same reason.
+fn two_row_second_pass(lines: &[ProjectedLine], runs: Vec<TableRun>) -> Vec<TableRun> {
+ // Gaps between (and around) the runs the normal pass claimed.
+ let mut gaps: Vec<(usize, usize)> = Vec::new();
+ let mut cursor = 0;
+ for r in &runs {
+ if r.start > cursor {
+ gaps.push((cursor, r.start));
+ }
+ cursor = cursor.max(r.end);
+ }
+ if cursor < lines.len() {
+ gaps.push((cursor, lines.len()));
+ }
+
+ let mut extra: Vec<TableRun> = Vec::new();
+ for (gs, ge) in gaps {
+ let mut i = gs;
+ // `floor` starts at the gap start so header absorption can never walk
+ // back into the preceding table run.
+ let mut floor = gs;
+ while i < ge {
+ match try_detect_table_inferred(lines, i, floor, true) {
+ // A run that reaches past the gap is exactly the theft case the
+ // gap restriction exists to prevent.
+ Some(run) if run.end <= ge && run.start >= gs => {
+ floor = run.end;
+ i = run.end;
+ extra.push(run);
+ }
+ _ => i += 1,
+ }
+ }
+ }
+ if extra.is_empty() {
+ return runs;
+ }
+ let mut all = runs;
+ all.extend(extra);
+ all.sort_by_key(|r| r.start);
+ all
}
// ── Description-list 2-column table detector ──────────────────────────────
@@ -3807,9 +3932,123 @@ pub(super) fn merge_table_runs(
}
}
kept.sort_by_key(|r| r.start);
+ for run in &mut kept {
+ if let Block::Table { rows, .. } = &mut run.block {
+ merge_continuation_rows(rows);
+ }
+ }
kept
}
+/// Fold soft-wrapped cell continuations back into the row they belong to.
+///
+/// A table cell holding a sentence wraps across several projected lines, and
+/// every one of those lines becomes its own grid row:
+///
+/// ```text
+/// | Knowledge | | ● To understand the meaning of reducing, reusing and recycling |
+/// | | | and how they connect ● To understand the importance of the 3 Rs |
+/// ```
+///
+/// We long treated this as unsolvable, and *as geometry* it is: the gap between
+/// a wrapped line and a genuine next row is the same gap. But it is tractable
+/// once the grid exists, from the text alone — which is what pdf-inspector does
+/// and where most of our remaining structure-only TEDS loss sits.
+///
+/// A row is a continuation of its predecessor when all of these hold:
+///
+/// - it has the same width and an **empty first cell** (the row label lives on
+/// the first line of the row and is never repeated);
+/// - its filled columns are a **subset** of the predecessor's filled columns —
+/// a continuation can only extend cells that already have text;
+/// - it carries **no value-like cell** — numbers don't soft-wrap, so a
+/// blank-label row holding one is a real data row (typically a `Total`);
+/// - at least one extended cell reads as a soft wrap rather than a fresh
+/// sentence after a completed one.
+fn merge_continuation_rows(rows: &mut Vec<Vec<String>>) {
+ if rows.len() < 2 {
+ return;
+ }
+ // The whole rule keys off "empty first cell", which only means "wrapped
+ // line" when the first column is a *label* column. Plenty of tables just
+ // have a sparse first column — a timetable whose `Notes` column is blank on
+ // every run, a size chart, a hierarchical header. There, every row looks
+ // like a continuation and the table collapses into a single row (measured:
+ // one 37-row timetable went 0.859 -> 0.006 GriTS). Requiring the first
+ // column to be populated in at least half the rows separates the two, and
+ // is what keeps this net-neutral on ParseBench's table corpus.
+ let first_col_filled = rows
+ .iter()
+ .filter(|r| r.first().is_some_and(|c| !c.trim().is_empty()))
+ .count();
+ if first_col_filled * 2 < rows.len() {
+ return;
+ }
+ let mut out: Vec<Vec<String>> = Vec::with_capacity(rows.len());
+ for row in rows.drain(..) {
+ if let Some(prev) = out.last_mut() {
+ if is_continuation_row(prev, &row) {
+ for (i, cell) in row.iter().enumerate() {
+ let t = cell.trim();
+ if t.is_empty() {
+ continue;
+ }
+ // `prev[i]` is non-empty for every filled column of `row`;
+ // that is the subset rule `is_continuation_row` enforces.
+ prev[i].push(' ');
+ prev[i].push_str(t);
+ }
+ continue;
+ }
+ }
+ out.push(row);
+ }
+ *rows = out;
+}
+
+fn is_continuation_row(prev: &[String], cur: &[String]) -> bool {
+ if cur.len() != prev.len() || cur.len() < 2 {
+ return false;
+ }
+ // The row label is never repeated on a wrapped line.
+ if !cur[0].trim().is_empty() || prev[0].trim().is_empty() {
+ return false;
+ }
+ let filled: Vec<usize> = (0..cur.len())
+ .filter(|&i| !cur[i].trim().is_empty())
+ .collect();
+ if filled.is_empty() {
+ return false;
+ }
+ // A continuation extends existing text; it cannot introduce a new column.
+ if filled.iter().any(|&i| prev[i].trim().is_empty()) {
+ return false;
+ }
+ // Numbers never soft-wrap. A blank-label row carrying any value-like cell is
+ // a real data row — most often a `Total` line, whose label column is blank
+ // precisely because it isn't the row's own label. Vetoing on *any* value
+ // (not all of them) is what separates it from a genuine wrap, since such
+ // rows pair a short summary word with the figures.
+ if filled.iter().any(|&i| is_value_like(cur[i].trim())) {
+ return false;
+ }
+ filled
+ .iter()
+ .any(|&i| cell_continues(prev[i].trim_end(), cur[i].trim_start()))
+}
+
+/// Whether `cur` reads as the tail of `prev` rather than a new statement. The
+/// only shape we reject is a fresh capitalised sentence following a cell that
+/// already closed with terminal punctuation — that is a sub-row, not a wrap.
+fn cell_continues(prev: &str, cur: &str) -> bool {
+ let starts_new_sentence = cur
+ .chars()
+ .find(|c| c.is_alphabetic())
+ .is_some_and(|c| c.is_uppercase());
+ let prev_closed = prev.ends_with(['.', '!', '?']);
+ !(starts_new_sentence && prev_closed)
+}
+
/// Escape `|` and `\n` inside a markdown table cell so the pipe-table grammar
/// stays valid. Newlines should be impossible inside a single cell (we built
/// cells from spans on the same projected line) but guard anyway.
@@ -3824,6 +4063,74 @@ mod tests {
use super::super::test_helpers::{line, line_with_spans, rect_borders, stroke};
use super::*;
+ fn rows(v: &[&[&str]]) -> Vec<Vec<String>> {
+ v.iter()
+ .map(|r| r.iter().map(|s| s.to_string()).collect())
+ .collect()
+ }
+
+ #[test]
+ fn wrapped_cell_lines_fold_into_their_row() {
+ let mut r = rows(&[
+ &["Knowledge", "● To understand the meaning of reducing and recycling"],
+ &["", "and how they connect ● To be familiar with the 7 Rs"],
+ &["Skills", "● To implement waste management into daily"],
+ &["", "life ● To promote reducing before recycling"],
+ ]);
+ merge_continuation_rows(&mut r);
+ assert_eq!(r.len(), 2);
+ assert_eq!(
+ r[0][1],
+ "● To understand the meaning of reducing and recycling and how they connect ● To be familiar with the 7 Rs"
+ );
+ assert_eq!(r[1][0], "Skills");
+ }
+
+ #[test]
+ fn totals_row_with_blank_label_is_not_a_continuation() {
+ // Regression: doc 45/47. A `Total` line legitimately has an empty label
+ // column; folding it into the last data row destroys both rows.
+ let mut r = rows(&[
+ &["7", "Traditional and Modern Mental Health Organization", "15"],
+ &["", "Total", "27,926"],
+ ]);
+ merge_continuation_rows(&mut r);
+ assert_eq!(r.len(), 2);
+ assert_eq!(r[1][1], "Total");
+ }
+
+ #[test]
+ fn sparse_first_column_disables_continuation_merging() {
+ // Regression: a timetable whose `Notes` column is blank on every run.
+ // Every row looks like a continuation, and merging collapses the whole
+ // table into one row (0.859 -> 0.006 GriTS on ParseBench).
+ let mut r = rows(&[
+ &["", "8:24", "8:28", "8:41"],
+ &["", "8:29", "8:33", "8:46"],
+ &["", "8:33", "8:37", "8:50"],
+ &["", "8:38", "8:42", "8:55"],
+ ]);
+ merge_continuation_rows(&mut r);
+ assert_eq!(r.len(), 4);
+ }
+
+ #[test]
+ fn continuation_may_not_introduce_a_new_column() {
+ let mut r = rows(&[&["Label", "some text", ""], &["", "more text", "brand new"]]);
+ merge_continuation_rows(&mut r);
+ assert_eq!(r.len(), 2, "col 2 was empty above, so this is a real row");
+ }
+
+ #[test]
+ fn fresh_sentence_after_closed_cell_is_not_a_continuation() {
+ let mut r = rows(&[
+ &["Label", "A complete thought ending here."],
+ &["", "Another separate statement entirely."],
+ ]);
+ merge_continuation_rows(&mut r);
+ assert_eq!(r.len(), 2);
+ }
+
#[test]
fn gutter_columns_fused_but_narrow_real_column_kept() {
// Padded cell borders: real columns 40..140, 160..260, 280..380 with