A fast, helpful, and open-source document parser
wip
Logan Markewich49b094354c56
diff --git a/MARKDOWN_PLAN.md b/MARKDOWN_PLAN.mdnew file mode 100644index 0000000..5daa78e--- /dev/null+++ b/MARKDOWN_PLAN.md@@ -0,0 +1,305 @@+# Markdown Output for LiteParse — Design Doc++Status: draft+Owner: @loganmarkewich+Last updated: 2026-05-29++## Goal++Add `OutputFormat::Markdown` to LiteParse — a 100% heuristic, dependency-light markdown emitter that produces output suitable for LLM ingestion (RAG, summarization, chunking).++Two non-negotiables:++1. **No new runtime deps.** Pure Rust, runs in Node / Python / WASM with the same code path. Our forked PDFium already ships in all three.+2. **Honest fallback.** When heuristics aren't confident (especially tables), emit the grid-projection text inside a fenced block. The structure stays readable even when we can't classify it.++We will lean on:++- The existing grid projection (anchor system, column detection, rotation, OCR merge).+- Signals our PDFium fork can expose that upstream cannot (structure tree, marked content, paths/rects with stroke+fill, image bounds, outline).++## Prior art: pymupdf4llm++Annotated read of `src/helpers/pymupdf_rag.py` in `pymupdf/RAG`. Worth knowing what they do — most of it is sound — and where they fall short.++### What they do well++| Feature | Approach |+|---|---|+| Heading detection | `IdentifyHeaders`: char-weighted font-size histogram. Body = most frequent size. Larger sizes mapped to `#`..`######` in descending order. |+| TOC-based headings | `TocHeaders`: alt path that uses doc outline; matches spans by string prefix to a TOC entry to get an exact level. |+| Inline styling | Per-span PDF font flags (`flags & 2/8/16`, `char_flags & 1/8`) for italic / mono / bold / strikeout. Per-line shortcut if whole line shares the style. |+| Code blocks | Consecutive all-mono lines → fenced block, with synthetic indent `(x0 - clip.x0) / (fontsize * 0.5)`. |+| Lists | `startswith_bullet()` regex on first char; leading-space indent from x-offset. |+| Tables | `page.find_tables(strategy=...)` (PyMuPDF's vector-graphics-based finder). Drop tables with <2 rows or <2 cols. Emit `Table.to_markdown()`. Subtract table rects from text rects so content doesn't double up. |+| Figures | `get_image_info()` + clustered vector graphics. `is_significant()` filter drops H/V-line-only clusters (underlines, dividers) so they don't become bogus figures. |+| Background-color awareness | Detects page bg color; vector paths filled with bg are ignored. |+| Multi-column | `column_boxes()` — geometry-based column boxes, processed top→bottom, left→right. |+| Annotations | Uses `page.get_links()` to wrap matching spans with markdown link syntax. |+| Header/footer | Fixed user-supplied top/bottom margin in points. |++### Where we can beat them++| Weakness | What we'll do |+|---|---|+| Actively **deletes** `StructTreeRoot` to avoid a perf bug. | Use the structure tree as the highest-priority signal. Our fork can expose it cheaply. |+| Pure Python, slow on large docs. | Native Rust, single-pass over already-projected lines. |+| Borderless tables fall back to nothing useful. | Use grid projection's column detection as a borderless-table detector. When uncertain → fenced projection text. |+| Header/footer = static margin. | Cross-page repetition detection on top/bottom bands. |+| No de-hyphenation. | Conservative join: `word-\nbreak` → `wordbreak` only when next line starts lowercase. |+| Paragraph break = big y-gap only. | Combine y-gap + font change + indent change + anchor change. |+| Reading order from generic column boxes. | We already have anchor-driven projection; reuse it directly. |+| Bold from font flag only (misses synthetic bold). | Combine flag + `font_weight` + font-name substring (`Bold`, `Black`, `Heavy`). |+| Drops invisible text by default. | Keep it gated by config; preserve `confidence` and OCR-vs-native source. |++## Architecture++```+┌─────────────────────────────────────────────────────────────┐+│ PDFium (forked) │+│ text items │ images │ paths │ struct tree │ outline │+└──────────┬──────────────────────────────────────────────────┘+ │+ extract.rs (existing) ────────────────┐+ │ │+ projection.rs (existing) ─────────────┤+ │ │+ ▼ ▼+ ┌──────────────┐ ┌────────────────────┐+ │ ProjectedLine│ │ PageGeometry │+ │ with style │ │ paths, images, │+ │ metadata │ │ struct nodes, │+ │ (NEW api) │ │ outline targets │+ └──────┬───────┘ └─────────┬──────────┘+ └───────────┬─────────────────────┘+ ▼+ ┌──────────────────────┐+ │ markdown_layout.rs │ (NEW)+ │ block classifier │+ └─────────┬────────────┘+ ▼+ Vec<Block>+ ▼+ ┌──────────────────────┐+ │ output/markdown.rs │ (NEW)+ │ block → markdown │+ └─────────┬────────────┘+ ▼+ String+```++### New types++In `types.rs`:++```rust+pub enum Block {+ Heading { level: u8, text: String, inline: Vec<Span> },+ Paragraph(Vec<Span>),+ ListItem { level: u8, ordered: bool, marker: String, inline: Vec<Span> },+ Table(TableBlock), // confident table+ GridFallback(String), // projection text in ```/<pre>+ CodeBlock { lang: Option<String>, body: String },+ Figure { image_id: Option<String>, alt: Option<String>, ocr_text: Option<String> },+ HorizontalRule,+ Raw(String), // escape hatch+}++pub struct Span {+ pub text: String,+ pub bold: bool,+ pub italic: bool,+ pub mono: bool,+ pub strike: bool,+ pub link: Option<String>,+}++pub struct TableBlock {+ pub header: Option<Vec<String>>,+ pub rows: Vec<Vec<String>>,+}+```++### `projection.rs` — exposing line metadata++Today projection produces a joined string. Add an internal API:++```rust+pub struct ProjectedLine {+ pub text: String,+ pub bbox: Rect,+ pub anchor: Anchor, // Left | Right | Center | Floating+ pub indent_x: f32, // from column left edge+ pub dominant_font_size: f32,+ pub dominant_font_name: Option<String>,+ pub all_bold: bool,+ pub all_italic: bool,+ pub all_mono: bool,+ pub all_strike: bool,+ pub spans: Vec<TextItem>, // raw items, preserved+ pub column_id: usize, // for multi-column reading order+ pub mcid: Option<i32>, // marked content id+}+```++The text emitter keeps working as-is by joining these lines; the markdown emitter consumes them structurally. **No behavior change to existing outputs.**++## Block classification (markdown_layout.rs)++Order matters — each pass either consumes lines or hands them to the next.++### Pass 0 — Whole-document signals (once per doc)++- Collect font-size → char-count histogram → `body_size`. For OCR, use height as a proxy.+- Build heading-level map: top N sizes > body_size → H1..HN (N capped at 6).+- Load outline / bookmarks → `Vec<OutlineTarget { page, y, level, title }>`. Not available for OCR docs.+- Walk structure tree → `Vec<StructNode { mcid, role, bbox }>` where role ∈ {H1..H6, P, L, LI, Table, TR, TH, TD, Figure, Caption}. Not available for OCR docs.+- Detect repeating top/bottom-band text across pages → header/footer set.++### Pass 1 — Page-level rect classification++Before touching lines, classify rects:++- **Image rects** — from PDFium image objects (already exposed).+- **Table rects** —+ - **Strong**: cluster ruled paths into a grid; verify ≥2 rows × ≥2 cols of cells. Use stroke geometry from the fork.+ - **Medium**: column-projection alignment — group of ≥3 vertically-aligned text "columns" repeated across ≥2 horizontal "rows" inside one column box. This works for docs that required OCR.+ - **Weak (fallback flag)**: lots of short text snippets in a clearly tabular layout but heuristic 1 & 2 disagree → mark as `GridFallback` candidate.+- **Code-block rects** — fill rect with a near-grey/near-white-non-bg color enclosing mono text (PyMuPDF-style is to skip this; we can do better).+- **HR rects** — long thin horizontal path, width > 50% column width, height ≤ 2pt.+- **Figure rects** — significant vector clusters + image rects, merged (`refine_boxes` analog).++Lines whose bbox falls inside a classified rect get tagged and skipped by Pass 2.++### Pass 2 — Line classification (in reading order)++For each `ProjectedLine` not consumed by a rect:++1. If line bbox is inside structure-tree `Figure`/`Table` node → emit accordingly.+2. If `mcid` maps to a structure node with role `H1..H6` → use that level. **Highest-priority heading signal.**+3. Else if bbox y matches an outline target (within tolerance) and text prefix-matches outline title → use outline level.+4. Else if `dominant_font_size > body_size` → use histogram heading map.+5. Else if `startswith_bullet(text)` or `^\d+[.)]\s` → list item; level from `indent_x` bucketing.+6. Else if `all_mono` → start/extend code block.+7. Else → paragraph line. Group consecutive paragraph lines with: same column, no major y-gap (> 1.5× line height), no font-size change, no anchor change.++De-hyphenation runs during paragraph join: if previous line ends `-` and next line starts lowercase ASCII, drop the hyphen and the newline.++### Pass 3 — Inline styling++Per span inside each emitted block:++- bold = font-flag-bold OR `font_weight ≥ 600` OR font-name contains `Bold|Black|Heavy|Semibold`.+- italic = font-flag-italic OR font-name contains `Italic|Oblique`.+- mono = font-flag-mono OR font-name in known mono list (`Courier`, `Mono`, `Consolas`, `Menlo`, `Source Code`, ...).+- link = bbox overlaps an annotation URI link rect.++Per-line shortcut: if all spans share a style, apply once around the whole line text (matches pymupdf4llm; avoids `**foo** **bar** **baz**` noise).++## Tables in detail++This is the hardest part and where we differentiate. Three modes, configurable via `MarkdownConfig::tables`:++- `Off` — never emit tables; tabular regions become `GridFallback`.+- `Auto` (default) — try strong → medium → fallback in order.+- `RuledOnly` — only emit when path-based grid detection succeeds; otherwise fallback.++### Strong: ruled grid++1. Collect horizontal segments (`y0 ≈ y1`, length > 1pt) and vertical segments inside the page clip.+2. Build a set of grid intersection x's and y's by clustering segment endpoints.+3. Walk cells; assign text items whose centroid falls in each cell.+4. Reject if rows < 2 or cols < 2, or if >30% of cells are empty.+5. First row → header iff its cells are bold or have a fill background.++### Medium: borderless via projection columns++The grid projection already tells us column boundaries (anchors). Inside a column box:++1. Look for ≥3 vertical "tracks" of text where x0 clusters within ±2pt.+2. Look for ≥2 horizontal "rows" of those tracks at distinct y bands.+3. Require row-spacing consistency (CV of gaps < 0.5).+4. If matched, emit as markdown table. Otherwise → `GridFallback`.++### Fallback: fenced projection++```text+\`\`\`+<projection.rs output for this rect, untouched>+\`\`\`+```++This preserves visual structure for the LLM and is **strictly better** than mangled markdown.++## Config++```rust+pub struct MarkdownConfig {+ pub headings: HeadingMode, // Auto | StructTree | Outline | FontSize | Off+ pub tables: TableMode, // Auto | RuledOnly | Off+ pub images: ImageMode, // Embed { dir } | Placeholder | Off+ pub code_blocks: bool, // default true+ pub strip_headers_footers: bool, // default true+ pub dehyphenate: bool, // default true+ pub keep_invisible_text: bool, // default false+ pub max_heading_levels: u8, // default 6+ pub body_size_floor: Option<f32>, // optional manual override+}+```++Sensible defaults so users can just pass `-f markdown` and get good output. Debatable if we should even expose any options at all in v1. We can always add them later if users want more control.++## Surface area++- `crates/liteparse/src/output/markdown.rs` — new.+- `crates/liteparse/src/markdown_layout.rs` — new.+- `crates/liteparse/src/types.rs` — add `Block`, `Span`, `TableBlock`.+- `crates/liteparse/src/config.rs` — add `OutputFormat::Markdown`, `MarkdownConfig`.+- `crates/liteparse/src/projection.rs` — expose `ProjectedLine` (additive).+- `crates/liteparse/src/main.rs` — `-f markdown`, plus subflags for the config above.+- `crates/liteparse-napi`, `liteparse-python`, `liteparse-wasm` — pass through the new format + config struct.+- `packages/node/src/lib.ts`, `packages/python/liteparse/parser.py` — wrapper API.++## PDFium fork additions needed (incremental)++Order roughly matches build order below.++1. **Image bbox enumeration** — likely already exposed; confirm.+2. **Path objects** with stroke + fill, in viewport coordinates. Needed for ruled-table detection, HR detection, code-block backgrounds.+3. **Structure tree walk** with role + mcid → bbox map. Highest leverage signal.+4. **Outline / bookmarks** with destination page+y per entry. Cheap.+5. **Page background color** — derivable from full-page fill paths once (2) lands.++Each of these is additive in the FFI; we can ship markdown v1 without (3)/(4) and add them later as quality bumps.++The PDFium fork is already on disk in `~/pdfium-binaries` -- we can directly modify here or the bindings in @crates/pdfium-sys and @crates/pdfium.++## Build order++1. **Wiring**: `OutputFormat::Markdown` end-to-end, returning current text output wrapped in `<pre>` fence. Proves CLI, napi, py, wasm plumbing.+2. **`ProjectedLine` API** in `projection.rs` (additive; text/json output unchanged).+3. **Font-size histogram + heading detection.** Paragraph grouping. De-hyphenation.+4. **Lists** (bullet + ordered + nesting from indent).+5. **Code blocks** (all-mono lines).+6. **Inline styling** (bold/italic/mono/strike/link) with per-line shortcut.+7. **Tables — medium (column-alignment) + fallback.** Ship without fork changes.+8. **Header/footer stripping** (cross-page repetition).+9. **Fork: paths exposed** → tables — strong (ruled grid), HR detection, figure-cluster refinement.+10. **Fork: structure tree + outline** → highest-priority heading + table + figure source. Replaces step 3 when available, falls back when not.+11. **Image extraction modes** (placeholder vs embed).++Steps 1–8 are a usable v1. Steps 9–11 are quality bumps that mostly improve specific document classes (tagged PDFs, ruled tables, image-heavy docs).++## Open questions++- **Image embed format in WASM.** No filesystem — base64 data URI? Return as separate blob array alongside the markdown string? Probably the latter; the markdown references `image_0.png` and the API returns a `images: { name, bytes }[]` sidecar.+- **Per-page vs whole-doc emission.** pymupdf4llm emits per page with `\n\n-----\n\n` separators. Cleaner for chunking but loses paragraphs that span page breaks. Recommend per-page by default with a `joinPages: true` option.+- **Should we expose `Block[]` as a structured output?** It's a natural intermediate. JSON consumers might prefer `Block[]` over a markdown string. Cheap to add (`OutputFormat::Blocks`).+- **Should `GridFallback` use `~~~text` or `<pre>`?** Code fence is friendlier to most LLMs; `<pre>` is friendlier to renderers. Default to fenced.+- **Confidence/OCR provenance in markdown.** Drop it? Encode as HTML comments? Most users won't want it; gate behind a config flag.++## Success criteria++- End-to-end on the eval set in `dataset_eval_utils/` produces markdown that scores ≥ pymupdf4llm on whatever similarity metric we settle on (the existing `*_report.html` runs suggest the harness is already there).+- Single-page parse time stays within 2× of current text output for typical documents.+- No new runtime deps; WASM bundle size growth < 100KB.diff --git a/MARKDOWN_PROGRESS.md b/MARKDOWN_PROGRESS.mdindex a71e2f6..cfd5932 100644--- a/MARKDOWN_PROGRESS.md+++ b/MARKDOWN_PROGRESS.md@@ -2,6 +2,51 @@Tracks build-order progress against [MARKDOWN_PLAN.md](MARKDOWN_PLAN.md). Update as steps complete.+> **2026-05-30 rebuild note.** Branch had been cleaned during a branch switch — `markdown_layout.rs` / `output/markdown.rs` were sitting untracked, the supporting types (`ProjectedLine`, `Rect`, `Anchor::Floating`, `ParsedPage.projected_lines`) didn't exist, `OutputFormat::Markdown` wasn't on the enum, and nothing was wired into `lib.rs` / `output/mod.rs`. Restored from `stash@{0}` (which had the plumbing diff) + reimplemented step 2 (`build_projected_lines` in `projection.rs` derives per-line metadata from the projected items). Tests pass; smoke on `paper.pdf` emits headings + bold + page separators end-to-end via `cargo run -p liteparse -- parse <pdf> --format markdown`. Steps 3–6 in the table below are status-accurate again as of this note.++> **2026-05-31 XY-cut layout decomposition.** Replaced the flat x-density histogram column detector with a recursive modified XY-cut. Motivation: the old detector failed on layouts where the gutter is interrupted by a wide element (figures straddling both columns, full-width headings/banners) — every page-1-style case in the eval set, and the open carry-forward "column interleaving on page 1" from 2026-05-30.+>+> - **Types** (`types.rs`): added `Region` / `RegionKind { Leaf, Split }` / `CutAxis`. `ProjectedLine.column_id: usize` → `region_path: Vec<u16>` (index trail from root; equality = same leaf, prefix = containment). `ParsedPage.regions: Region` added behind `#[serde(skip)]` so JSON/text outputs stay byte-identical.+> - **Algorithm** (`projection.rs::xy_cut`): char-weighted 1D projection onto each axis at 2pt buckets. A "valley" is a contiguous run of buckets where density < `T_DENS × median(non-zero buckets)`. Conservative defaults — `T_DENS=0.10`, min vertical-cut valley `8pt`, min horizontal-cut valley `1.4 × median line height`. Each recursion picks the best valley across both axes, tie-breaking 1.1× in favor of horizontal so pages slice into bands before columns (natural reading order). Hard recursion depth cap of 6; H-cuts require ≥2 distinct y-rows per side so we don't slice prose into slivers. Pre-order leaf walk produces reading order for free, including nested layouts.+> - **`build_projected_lines`** now takes `page_height` (additive) and returns `(Vec<ProjectedLine>, Region)`. Lines inside each leaf are y-banded and built with the leaf's `region_path`. `detect_columns` deleted entirely.+> - **`markdown_layout.rs`** paragraph-continuation and table-row-adjacency checks switched from `column_id` equality to `region_path` equality. No other consumers needed changes — `column_id` was internal.+> - **Tests**: 119 lib + 10 integration tests still pass. Added 3 unit tests on synthetic items: 2-column layout → single V-split, tight single-column prose → leaf root, pre-order walk of a 2-column layout → left-column lines all precede right-column lines (`region_path` prefix `[0]` vs `[1]`).+> - **Smoke on `paper.pdf`**:+> - **Pages 2+** (the multi-column case that interleaved before): now read coherently column-by-column. Resolves the 2026-05-30 column-interleaving carry-forward.+> - **Page 1** (title banner + abstract + figure straddle + intro): reading order is still wrong but shaped differently — title `# A-MEM…` now appears *after* the abstract block rather than at the top. Root cause: with the figure straddling both columns and the title+authors banner above them, no single H-cut or V-cut at the page root produces the right partition. Needs either (a) higher-level "wide-banner detector" that seeds an H-cut around full-page-width centered text, or (b) figure-rect-aware seeding so the recursion treats the figure as an obstacle and H-cuts above/below it first. Deferred — tracked as next layout-detection pass; not blocking v1.+> - **Threshold tuning** is the most likely future knob. Bumping `T_DENS` lets noisier gutters cut (e.g. page numbers in the gap); dropping `XY_V_PREFERENCE_MARGIN` toward 1.0 makes V-cuts more aggressive on pages where the page header has weak inter-line gaps but a strong central gutter.+>+> **2026-05-31 heading-quality pass.** Smoke on `paper.pdf` exposed two bad failure modes: (a) the size-based heading map was getting eaten by figure-label numbers (size 36/24pt), the rotated arXiv sidebar (size 20pt), and graph-axis values, pushing the real title to H6 and authors out of the map entirely; (b) academic section heads ("Abstract", "1 Introduction", "5 Conclusion") are body-sized + bold so the size-only detector missed them. Fixed in `markdown_layout.rs`:+> - **Rotation filter** (`is_rotated_line`): per-line check using `TextItem.rotation`. Excludes rotated text (arXiv banners, vertical legends, watermarks) from both `compute_body_size` and `build_heading_map`, and also from the per-line classifier pass so they don't surface as paragraphs. This is what finally drops the 20pt arXiv sidebar from H-slot competition.+> - **`build_heading_map` quality filters**, applied unconditionally (not gated on candidate count): sizes must clear `MIN_HEADING_TOTAL_CHARS=25` total non-whitespace chars *and* `avg_chars_per_line ≤ 200` *and* `alpha_ratio ≥ 0.5`. The total-char floor (instead of a line-count floor) is the key change — it lets a one-off paper title at 14.35pt survive (31 chars on a single line) while still excluding chart-legend tokens like "A-mem"×2 + "Base"×2 = 18–20 chars across 4 occurrences. Alpha-ratio kills scoreboard/equation/graph-axis sizes (36pt = 0% alpha, 18pt = 0% alpha, 24pt = 22% alpha on `paper.pdf`).+> - **`looks_like_bold_heading`** rule: a uniformly-bold body-size line ≤ 80 chars with paragraph-break gap above + below and alpha-ratio ≥ 0.5 becomes a heading at `heading_map.len() + 1`. Runs *after* list-marker detection so bold bullets stay as list items. Drives "Abstract" / "2 Related Work" / "5 Conclusion" detection on `paper.pdf`.+> - **Final `paper.pdf` headings**: `# A-MEM: Agentic Memory for LLM Agents` (title at H1) → `## Abstract` / `## 2 Related Work` / `## 3 Methodolodgy` / `## 4 Experiment` / `## 5 Conclusion` (section heads at H2) → `### 2.1 Memory for LLM Agents` (subsection at H3). Reads like the document.+> - **Known residuals on `paper.pdf`**:+> - Results-table header rows ("Category Average", "F1 BLEU-1 F1 BLEU-1 ...", "Qwen2.5 GPT Llama 3.2 ...") still classify as H3 because they're bold body-size short lines and the table detector doesn't fire on them. Needs better table detection (step 7 follow-up) — not a heading-detection problem.+> - "Abstract Write" — the figure label "Write" (at fs=1.0, height ~9pt) lands on the same projected line as the "Abstract" heading because column detection treats page 1's figure-bearing right half as part of the abstract column. Column-detection problem, not heading.+> - Authors / affiliation block at H2 — they share font size with section headings (11.96pt). Could plausibly be filtered as "page-1 top centered block before any body text" once title detection sees them, but not in this pass.+> - The dominant remaining quality issue on `paper.pdf` is column interleaving on page 1 (figure straddles both columns → projection mixes left/right column lines). This is layout-detection territory, not heading detection. Tracked as a separate carry-forward.++> **2026-06-01 step 9 partial — paths + HR + ruled tables.** No actual PDFium fork edits needed; all 10 missing path getters were already declared in `bindings.rs`, just absent from the runtime-loaded `PdfiumBindings` struct in `crates/pdfium-sys/src/dynamic.rs`. Wired them through; added `PathObject`/`PathSegment` in `crates/pdfium/src/page.rs::path_objects`; distilled to `GraphicPrimitive::{Stroke, Rect}` in `liteparse/src/types.rs` + `extract.rs::extract_page_graphics`; threaded `graphics` onto `Page` → `ParsedPage`. Added `Block::HorizontalRule` rendered as `---`, `detect_horizontal_rules` with underline-band filter, and `detect_ruled_tables` (union-find on crossing H/V grid lines, ≥2×2 grid, ≤30% empty cells, ≤95% page coverage). `merge_table_runs` runs ruled-grid before the existing borderless detector and drops overlapping borderless runs. 136 lib + 10 integration tests pass (11 new for the graphics pipeline). Figure clustering (9c-3) deferred — see carry-forwards.+>+> **Worth smoke-testing on real docs.** Ruled-table candidates: `Anonymized rate card.pdf` (the same doc step 8 was tested on), any tagged invoice / table-heavy spreadsheet export. HR candidates: anything with `<hr>`-style section dividers (letters, contracts, multi-section reports). `paper.pdf` has known residuals from step 7 that the borderless detector caught — confirm the new ruled-grid path doesn't regress them; if it does, `merge_table_runs` keeps the borderless run when ranges don't overlap, but a partial-overlap could still drop one. Command: `cargo run -p liteparse -- parse <pdf> --format markdown`.++> **2026-06-01 paper.pdf quality pass — table fragmentation, cross-region continuation, HR cleanup, figure misclassification.**+>+> - **Borderless-table merged-cell recovery** (`markdown_layout.rs::recover_merged_cell`). PDFium occasionally merges adjacent words into one text run when inter-word kerning is tight (e.g. "MEMORYBANK 5.00 4.77" emitted as one span on `paper.pdf` page 6's results table). That dropped the row's cell count below the established column count, so the table-row matcher closed the run — fragmenting the table into 2-row chunks around every shifted-indent row. Fix: when a candidate row has fewer cells than the established `tracks`, iteratively find the cell that straddles the most tracks (≥2), split its text on whitespace at the boundary positions linearly interpolated to track x-coords, replace with the split pieces. Handles off-by-N (loop), returns `None` cleanly when no whitespace boundary is available (e.g. hyphenated tokens). Added `end_x` to `TableCell`. 3 new unit tests (`recover_merged_cell_splits_off_by_one`, `recover_merged_cell_splits_off_by_two`, `recover_merged_cell_bails_without_enough_whitespace`). **Result on `paper.pdf` page 6:** the 15-row result-table chunks that were previously fragmented into 7+ 2-row pieces are now two coherent 15-row pipe tables (only split by a mid-table "Qwen2.5 GPT Llama 3.2 …" group-label row that's still classified as H3 — header-row absorption remains future work).+> - **Cross-region paragraph continuation** (`markdown_layout.rs::continues_paragraph`). The hard `prev.region_path == cur.region_path` gate broke the common 2-column-paper case where a sentence wraps from the bottom of column 1 into the top of column 2 (e.g. the `- *We present A-MEM …* tem … This system equips LLM agents with` bullet ending mid-thought, and resuming with `long-term interaction capabilities …` in column 2). Relaxed: when `region_path` differs, bridge regions iff the previous line ends without sentence-terminating punctuation (`. ! ? : ; ” " ) ] 。 』 」`) AND the next line starts with a lowercase character. Both conditions are strict signals — together they catch column-wraps cleanly while rejecting unrelated paragraphs that happen to land in adjacent leaves. Smoke on `paper.pdf` collapses ~50 erroneous mid-paragraph breaks (522→479 lines in the rendered markdown).+> - **HR suppression inside / near tables** (`markdown_layout.rs::classify_page_with_filters`). Table internal horizontal rules (row dividers) and the rules drawn above a table's column headers were being emitted as document-level `---`. Build a `table_y_extents` list once after `merge_table_runs`; filter `detect_horizontal_rules` output to drop any HR whose y falls inside `[top - 4 × row_height, bot + 2pt]`. The upward expansion catches header-band rules above the table data that we don't (yet) absorb into the table block. Eliminates the `---` chains that previously surrounded every table on `paper.pdf`.+> - **Figure misclassification of tables** (`figure_cluster.rs::text_coverage`). The old per-glyph area coverage was too tight — left huge gaps between numeric cells unaccounted for, so the page-6 results table (~32% glyph coverage) sneaked under the 55% threshold and got classified as a figure. The figure rect then got obstacle-seeded into XY-cut, which actually helped the rows stay together but the misclassification was waiting to break downstream consumers. Rewrote `text_coverage` to y-band overlapping text items into lines (median-height-based band tolerance) and sum the union bbox of each band — gives a far better proxy for "this region is dominated by text". Result on `paper.pdf`: page 6's table no longer matches as a figure (`figures = []`). No vector figures on `paper.pdf` to regression-test against (page 1's figure is a raster image with 0 vector primitives, so figure_cluster never saw it either way).+>+> **Test count:** 147 lib + 10 integration tests pass.+>+> **Known residuals on `paper.pdf`:**+> - **Page 1 banner-title layout** — unchanged, still tracked separately.+> - **Mid-table group-label rows** misclassified as H3 (e.g. `### Qwen2.5 GPT Llama 3.2 …`). Needs either header-row absorption from above/below a detected table, OR a "line is between two table runs sharing the same tracks → group label" detector.+> - **Single-column section-header rows** above tables (`### Category Average`, `### F1 BLEU-1 …`) still emit as H3. Same header-absorption story.+>+> **2026-06-01 step 9c-3 — figure clustering + XY-cut obstacle seeding.** New `crates/liteparse/src/figure_cluster.rs::detect_figure_rects(graphics, text_items, page_w, page_h) -> Vec<Rect>`. Pre-filters HR-like strokes (long thin horizontal, length ≥ 30% page width, ≤ 2pt thick) and full-page rects, then union-finds the remaining primitives by bbox proximity (within 10pt on both axes). Each cluster's union bbox is kept only when: min extent ≥ 30pt both axes, area ≥ 1500pt², not ≥95% page in both dims, aspect ratio ≤ 15, has ≥2 primitives OR a single primitive ≥ 5000pt², and text coverage inside the bbox ≤ 55% (rejects text-highlight backgrounds and banner fills). **Wired through XY-cut as obstacles:** `xy_cut`, `xy_cut_rec`, `xy_find_best_cut`, and `build_projected_lines` now take `figures: &[Rect]`. In `xy_find_best_cut`, each figure intersecting the current bbox is clipped and stamped into the density buckets along the axis being scanned, with `weight = perpendicular extent`. Effect: figures behave like very wide/tall pseudo-items, so the valley search naturally prefers cuts *adjacent* to figures over slicing through them. `figures` is also persisted on `ParsedPage` (#[serde(skip)]) so downstream passes can reuse it. `to_parsed_pages` computes figures from `page.graphics` + `page.text_items` before invoking `build_projected_lines`. **Test count:** 144 lib + 10 integration tests pass (7 new in `figure_cluster::tests` covering empty input, HR rejection, dense-stroke clustering, large-solo-rect acceptance, full-page-background rejection, text-heavy rejection, and distant-strokes-don't-merge; 1 new in `projection::tests::figure_obstacle_forces_h_cut_around_straddling_figure` confirming a wide figure between two text bands forces an H-cut at the root). **Smoke on `paper.pdf`:** pages 2+ unchanged (still clean), abstract column on page 1 still reads cleanly as before. Page 1's title-still-mid-document carry-forward is *unchanged* — the issue isn't the straddling figure (which the obstacle seeding does isolate), it's the arXiv stamp + affiliation lines at the top that satisfy the banner heuristic and disrupt the H-cut position above the title. Banner-detection refinement remains the next layout knob. **Carry-forward update:** the "feeding figure rects into XY-cut as obstacles" item is now resolved.+## Status legend- ✅ done@@ -17,10 +62,10 @@ Tracks build-order progress against [MARKDOWN_PLAN.md](MARKDOWN_PLAN.md). Update| 3 | Font-size histogram, headings, paragraph grouping, de-hyphenation | ✅ | New `markdown_layout.rs` builds a global char-weighted size histogram, maps sizes > body to H1..H6, groups consecutive lines into paragraphs (same anchor/column/font/indent + gap ≤ 1.5× line height), and de-hyphenates `word-\nlowercase` joins. `output/markdown.rs` now renders blocks instead of stubbing a fence (fence retained as fallback for pages without `projected_lines`). || 4 | Lists (bullet + ordered + nesting from indent) | ✅ | `parse_list_marker` recognizes Unicode bullets (`•·◦▪▸▶●○■□`) and decimal markers (`1.` / `12)`). Nesting derived from `indent_x` bucketed by 12pt steps relative to the first item of the run. Wrapped continuation lines reuse the paragraph-continuation rule so footnote-style hanging indents merge correctly. Original marker preserved (`138.` stays `138.`) so footnote/section numbering survives. ASCII `-`/`*`/`+` deliberately excluded to avoid false matches in prose. || 5 | Code blocks (all-mono lines) | ✅ | `Block::CodeBlock { lines }` accumulates consecutive `all_mono` lines and emits a triple-backtick fence (falls back to `~~~` if body contains `` ``` ``). Detection runs before heading/list/paragraph passes so mono content always wins. |-| 6 | Inline styling (bold/italic/mono/strike/link) with per-line shortcut | 🚧 | `ProjectedLine.all_bold/italic/mono` populated via char-weighted majority from `font_flags` (PDF descriptor bits: FixedPitch=1, Italic=64, ForceBold=262144) + `font_weight ≥ 600` + font-name heuristics (Bold/Black/Heavy/Semibold, Italic/Oblique, Courier/Mono/Consolas/Menlo/…). **Per-line shortcut only:** `Block::Paragraph`/`ListItem` carry `bold`/`italic` flags that flip off if any constituent line drops the style — when both stay true the whole block renders as `**…**` / `*…*` / `***…***`. Headings deliberately skip emphasis (the `#` is the marker). **Per-span (mid-line) styling, strike, and links are deferred.** |-| 7 | Tables — medium (column-alignment) + fallback | ⬜ | Ship without fork changes. |-| 8 | Header/footer stripping (cross-page repetition) | ⬜ | |-| 9 | Fork: paths exposed → strong (ruled grid) tables, HR detection, figure clustering | ⬜ | Requires PDFium fork changes. |+| 6 | Inline styling (bold/italic/mono/strike/link) with per-line shortcut | ✅ | Per-span (mid-line) emphasis now lands. `render_line_inline` walks `ProjectedLine.spans` in x-order, groups adjacent same-style spans (bold/italic/mono via the shared `projection::is_*_item` detectors, now `pub(crate)`), escapes `*`/`_`/`\\`, and emits `**…**` / `*…*` / `***…***` / `` `…` `` runs. Three-tier rendering: (1) per-line shortcut when all spans on a line agree; (2) paragraph-uniform shortcut preserved — when **every** line of a paragraph is uniformly the same non-plain style, we still wrap the whole paragraph once with `wrap_emphasis(raw, …)` to avoid `**foo** **bar**` per-line noise; (3) per-line inline strings otherwise. `Block::Paragraph`/`ListItem` carry both `raw` (plain) and the rendered text — the classifier picks one at flush time. List items strip the marker before rendering (uniform-style path peels it from `rest`; mixed-style path peels emphasis-wrapped marker prefixes via `strip_leading_marker_from_inline`). Smoke on `paper.pdf`: bold author block + mid-line `**Abstract**` + italic `*We present A-MEM…*` runs + backtick-fenced URLs + escaped `\*` corresponding-author marker all render correctly. **Strike + links still deferred** (no PDFium span attribute for strike; links need annotation rects from the fork, gated with step 10). |+| 7 | Tables — medium (column-alignment) + fallback | ✅ | `Block::Table { header, rows }` and `Block::GridFallback { lines }` added. `detect_tables` runs as a pre-pass over a page's `ProjectedLine`s before per-line classification. `split_cells` slices each line's `spans` into cells when adjacent-span gaps exceed `1.0 × dominant_font_size`. A run qualifies as a table when ≥3 cells per row repeat across ≥2 consecutive rows with column-track alignment (≤1 column allowed to drift outside ±6pt — handles indented sub-group row labels); if row-spacing CV > 0.5 the run is downgraded to `GridFallback`. First row promotes to header only when every cell is bold (synthesizes blank header otherwise). `table_rows_adjacent` deliberately doesn't gate on `region_path` because XY-cut sometimes puts an indented row in a different leaf than the rest of the table — column-alignment + y-gap are strong enough on their own. `looks_like_bold_heading` now rejects lines that look tabular (≥3 spans by `split_cells` OR ≥3 multi-space-separated tokens by text fallback) so multi-line table headers like "Model Method Single Hop Multi Hop ..." stop getting promoted to H3. Smoke on `paper.pdf` (results tables): 8 well-formed pipe tables emitted, "Model Method..." header line now lands as a bold paragraph instead of H3. **Known residuals**: (a) `MEMORYBANK` rows in academic results tables are at x=102.5 vs neighbor rows at x=70 — ALL column tracks shift by ~30pt so the 1-column-tolerance rule can't bridge them; tables still fragment into 2-4 row chunks around those rows. Fix needs ruled-grid detection from PDFium fork (step 9) — won't be solvable from text-only signals. (b) Short header rows like `Category Average` (2 cells) and the full-width `F1 BLEU-1 F1 BLEU-1...` (1 collapsed projection span, single-spaced text) still classify as H3 — text-only heuristics can't distinguish them from real one-line section headings without table-rect context. (c) Header absorption (walking back from a detected table to grab multi-line headers above) deliberately deferred — would need careful per-column concatenation against unaligned multi-line headers; better to wait for fork-driven cell-rect data. |+| 8 | Header/footer stripping (cross-page repetition) | ✅ | `compute_header_footer_set` collects normalized line text (lowercased, digit-runs collapsed to `#` so `Page 1 of 6`/`Page 2 of 6` match) appearing in the top 12% / bottom 12% page-height band on ≥ 50% of pages (floor of 2). Header and footer bands tracked separately so a heading that doubles as both running header on some pages and body title on others isn't stripped from the body. `format_markdown` builds the set once and passes it to `classify_page_with_filters`, which removes matching lines before table detection and per-line classification. Smoke-tested on `Anonymized rate card.pdf` — repeating `Page N of 6` chrome is gone from output. |+| 9 | Fork: paths exposed → strong (ruled grid) tables, HR detection, figure clustering | ✅ | **Paths exposed + HR + ruled-grid tables landed 2026-06-01; figure clustering deferred.** No actual PDFium fork modifications were required — every needed FFI symbol was already in `bindings.rs`; only the runtime-loaded `PdfiumBindings` struct in `crates/pdfium-sys/src/dynamic.rs` was missing the 10 path-related getters (`FPDFPageObj_GetMatrix`, `FPDFPath_CountSegments`, `FPDFPathSegment_*`, color/width getters, `FPDFPath_GetDrawMode`). Added all. **9a — pdfium wrapper:** new `PathObject` / `PathSegment` / `SegmentKind` in `crates/pdfium/src/page.rs`; `Page::path_objects(view_box)` iterates `FPDF_PAGEOBJ_PATH` objects, applies the object matrix → page → viewport so all segment points land in viewport coords for direct comparison against `ProjectedLine.bbox`. **9b — liteparse `GraphicPrimitive`:** added `GraphicPrimitive::{Stroke { x1,y1,x2,y2,color,width }, Rect { bbox, fill, stroke }}` to `types.rs` + `ParsedPage.graphics` (#[serde(skip)]). `extract.rs::extract_page_graphics` decomposes paths: filled paths → one `Rect` for the bbox (covers cell backgrounds / banner fills regardless of internal complexity); stroked paths → one `Stroke` per `MoveTo→LineTo` / `LineTo→LineTo` pair (plus the implicit closing stroke when a subpath's close flag is set). `BezierTo` segments advance the current point but don't emit a stroke (curves aren't useful for table/HR detection). **9c-1 — HR:** `detect_horizontal_rules(page)` filters strokes to `|y1-y2| ≤ 2pt`, length ≥ `0.3 × page_width`, stroke-width ≤ 2pt, with an underline-band filter that drops strokes within ±3pt of a text-line baseline whose x-extent matches the line. `Block::HorizontalRule` interleaves with text lines in `classify_page_with_filters` by y-coord via a peekable `hr_iter`; renders as `---`. 6 unit tests. **9c-2 — ruled-grid tables:** `detect_ruled_tables` extracts H/V segments from strokes + stroked Rect edges (so cell-rect-per-cell tables work too), clusters them into grid lines (`TABLE_GRID_CLUSTER_PT=2pt`), finds connected components via union-find on crossing pairs (`TABLE_CROSS_TOLERANCE_PT=3pt`), then per component: clusters distinct row/col coords, requires ≥2×2 cells, assigns text-line centroids to cells, rejects when empty-cell fraction > 30% or coverage > 95% of page (kills page-border rects), promotes the first row to header when all non-empty cells are `all_bold`. Runs *before* the existing borderless detector; `merge_table_runs` keeps both outputs but drops borderless runs whose range overlaps a ruled run (path geometry strictly beats text alignment). 5 unit tests. **9c-3 — figure clustering:** deferred to a later pass; limited value without image extraction (step 11) and the highest-leverage piece of figure detection (feeding figure rects into the XY-cut layout pass to fix the paper.pdf page-1 carry-forward) is now tracked as its own follow-up. **Test count:** 136 lib + 10 integration tests pass. **Smoke-test commands:** `cargo run -p liteparse -- parse <pdf> --format markdown`. Good test docs: `Anonymized rate card.pdf` (rate-card with ruled tables + HR-style dividers; should produce `---` and `|...|` table rows), any tagged invoice / financial statement / spreadsheet export. The `paper.pdf` results tables still have known residuals (MEMORYBANK row indent + short header rows) that the borderless detector handled; need to confirm the ruled detector doesn't regress those — if paper.pdf renders ruled tables incorrectly, the borderless fallback should still catch them via `merge_table_runs`. || 10 | Fork: structure tree + outline → highest-priority headings | ⬜ | Requires PDFium fork changes. || 11 | Image extraction modes (placeholder vs embed) | ⬜ | |@@ -30,10 +75,13 @@ Steps 1–8 = usable v1. Steps 9–11 = quality bumps for specific doc classes.Things deferred from earlier steps that need to be revisited:-- **`ProjectedLine.column_id`** — currently always `0`. Real column detection needs to mine projection.rs's existing block/anchor data. Required before tables (step 7) can do per-column reasoning.-- **`ProjectedLine.indent_x`** — currently equals `bbox.x`. Should become offset from the column's left edge once column_id is real. Needed for list nesting (step 4).+- **Figure clustering (step 9c-3)** — ✅ resolved 2026-06-01. `figure_cluster::detect_figure_rects` is wired through XY-cut as density-projection obstacles; `ParsedPage.figures` is persisted for downstream consumers (no `Block::Figure` emission yet — that lands with step 11 image extraction so figures can carry a real reference). On `paper.pdf` the abstract-column-next-to-straddling-figure case is now isolated correctly; the *separate* banner-title issue at the top of page 1 (arXiv stamp + affiliation triggering banner heuristic) is not improved by this work and remains tracked under "Page 1 banner-title layout".++- **`ProjectedLine.column_id`** — ✅ resolved 2026-05-30, then ♻️ superseded 2026-05-31 by `region_path` from the new XY-cut tree (see top note). Pages 2+ of `paper.pdf` now read coherently column-by-column. Page 1's banner-title / figure-straddle layout is still wrong but in a new shape — bumped to its own follow-up (banner detection / figure-rect-aware seeding).+- **Page 1 banner-title layout** — ⚠️ partially resolved 2026-05-31 by a text-only `xy_find_banner_cut` pre-pass in `projection.rs`. Detects y-bands (or runs of consecutive close y-bands) whose x-extent covers ≥ `XY_BANNER_WIDTH_FRACTION = 0.6` of the parent region width AND that have ≥ `XY_BANNER_CLEARANCE_FACTOR × median_h` of vertical clearance on both sides; emits a horizontal `CutCandidate` with `score = ∞` that wins unconditionally over density-based valleys. `XY_MIN_LINES_PER_H_SIDE` is bypassed for banner cuts **only at depth=0** — a 1-line title can be isolated at the page root, but aggressive single-line cuts mid-recursion (which fragment paragraphs around centered captions) are still blocked. Unit-tested: a wide centered title above a 2-column body now lands in its own root-leaf, separate from both columns; a plain 2-column layout with no banner still V-cuts at the gutter as before. Net real-doc impact: pages 2+ of `paper.pdf` gain a correct `### 4.4 Empirical Results` heading (previously absorbed into the prior paragraph). `paper.pdf` page 1 specifically (arXiv stamp + title + authors + a figure that straddles both columns + abstract) is still not fully untangled — the abstract column reads cleanly now (a win) but the title lands mid-document instead of at the top, because the arXiv timestamp and Rutgers affiliation lines satisfy the banner heuristic and disrupt the cut position. Fully solving page 1 needs ruled-figure-rect seeding from the PDFium fork (step 9) so the recursion treats the figure as an obstacle to V-cut around.+- **`ProjectedLine.indent_x`** — ✅ resolved 2026-05-31 (second pass). After `build_projected_lines` produces all lines, each leaf's min `indent_x` is subtracted from every line in that leaf, so the value is now an offset from the column's left edge. Fixes list-nesting buckets on multi-column pages — a column-2 bullet at page-x=300 previously looked indented +230pt vs column-1 prose, now reads as `indent_x ≈ 0`.- **`ProjectedLine.all_strike`** — still placeholder `false`. PDFium doesn't expose strikethrough as a span attribute; would need either path-cluster detection (a horizontal line at mid-glyph) or marked-content role hints. Not blocking v1.-- **Mid-line (per-span) emphasis** — current emitter only applies emphasis when *every* line of a paragraph/list-item shares the style. Mixed-style lines render plain. Picking this up requires rebuilding paragraph text from `ProjectedLine.spans` instead of `line.text`, escaping markdown specials per span, and a per-line shortcut when all spans agree.+- **Mid-line (per-span) emphasis** — ✅ resolved 2026-05-30. `render_line_inline` consumes `ProjectedLine.spans` directly. Known minor: when a styled span ends in a soft hyphen at end of line, dehyphenation skips it (so `*sys-*` + `tem` stays as `*sys-* tem` rather than merging into `*system*`). Acceptable trade-off vs. surgically stripping markers around emphasis wraps.- **Inline links** — needs PDF annotation link rects exposed via the fork; deferred with the rest of the structure-tree-tier work (step 10).- **`MarkdownConfig`** — not yet introduced. Holding off until at least one heuristic has a knob worth exposing. Default-only v1 is fine per the plan.@@ -46,7 +94,7 @@ Things deferred from earlier steps that need to be revisited:## Notes / surprises-- The Node CLI formats output client-side from `ParseResult`, so the markdown stub currently lives in *both* `output/markdown.rs` (Rust) and `formatResult()` (TS). The Rust path is now the real emitter; the TS path is still the old fenced-text stub. Needs to call into a native `format_markdown` (napi) before this becomes user-visible from the Node CLI — still pending; bumping to step 7/8 follow-up.+- The Node CLI formats output client-side from `ParseResult`. ✅ resolved 2026-05-31: `result.text` from the napi binding already carries the Rust-formatted markdown (parser's `parse_input` calls `markdown::format_markdown` when `output_format == Markdown` and stuffs the result into `ParseResult.text`). No separate TS-side stub turned out to be in the tree — the note pre-dated the wiring. `node dist/cli.js parse file.pdf --format markdown` and the Python CLI both produce real markdown end-to-end.- **Step 5/6 sanity check on `paper.pdf`:** headings still detect (`##` / `####` / `#####`), no false code blocks fired on prose (font-name heuristics correctly skip serif/sans body fonts), and no spurious bold paragraphs. No mono content on this paper to exercise the fence path — covered by unit tests instead.- Smoke test on `paper.pdf` (a two-column arXiv paper): headings (`#`/`##`/`###`/`####`) detect correctly and de-hyphenation joins `prede-/fined → predefined`. Two columns interleave on the same lines — expected until real `column_id` lands (carry-forward from step 2).- **Tuning that came out of single-column smoke tests (`hard_5.pdf`, `llama2_4pages.pdf`):**diff --git a/crates/liteparse-napi/src/types.rs b/crates/liteparse-napi/src/types.rsindex c38e1e8..130b633 100644--- a/crates/liteparse-napi/src/types.rs+++ b/crates/liteparse-napi/src/types.rs@@ -25,7 +25,7 @@ pub struct JsLiteParseConfig {pub target_pages: Option<String>,/// DPI for rendering pages (used for OCR and screenshots).pub dpi: Option<f64>,- /// Output format: "json" or "text".+ /// Output format: "json", "text", or "markdown".pub output_format: Option<String>,/// Keep very small text that would normally be filtered out.pub preserve_very_small_text: Option<bool>,@@ -64,6 +64,7 @@ impl JsLiteParseConfig {if let Some(v) = self.output_format {cfg.output_format = match v.as_str() {"text" => OutputFormat::Text,+ "markdown" | "md" => OutputFormat::Markdown,_ => OutputFormat::Json,};}@@ -94,6 +95,7 @@ impl JsLiteParseConfig {output_format: Some(match cfg.output_format {OutputFormat::Json => "json".to_string(),OutputFormat::Text => "text".to_string(),+ OutputFormat::Markdown => "markdown".to_string(),}),preserve_very_small_text: Some(cfg.preserve_very_small_text),password: cfg.password.clone(),diff --git a/crates/liteparse-python/src/cli.rs b/crates/liteparse-python/src/cli.rsindex fb2dffc..8fbb377 100644--- a/crates/liteparse-python/src/cli.rs+++ b/crates/liteparse-python/src/cli.rs@@ -105,7 +105,11 @@ fn parse_output_format(s: &str) -> Result<OutputFormat, String> {match s.to_lowercase().as_str() {"json" => Ok(OutputFormat::Json),"text" => Ok(OutputFormat::Text),- _ => Err(format!("unknown format '{}', expected 'json' or 'text'", s)),+ "markdown" | "md" => Ok(OutputFormat::Markdown),+ _ => Err(format!(+ "unknown format '{}', expected 'json', 'text', or 'markdown'",+ s+ )),}}@@ -139,6 +143,7 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {let formatted = match lp.config().output_format {OutputFormat::Json => json::format_json(&result.pages)?,OutputFormat::Text => text::format_text(&result.pages),+ OutputFormat::Markdown => result.text.clone(),};match cmd.output {Some(path) => {@@ -213,10 +218,10 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {}let lp = LiteParse::new(config);- let out_ext = if format == OutputFormat::Json {- "json"- } else {- "txt"+ let out_ext = match format {+ OutputFormat::Json => "json",+ OutputFormat::Markdown => "md",+ OutputFormat::Text => "txt",};std::fs::create_dir_all(&cmd.output_dir)?;@@ -252,6 +257,7 @@ pub fn run_cli(args: Vec<String>) -> Result<(), Box<dyn std::error::Error>> {json::format_json(&result.pages).map_err(|e| e.into())}OutputFormat::Text => Ok(text::format_text(&result.pages)),+ OutputFormat::Markdown => Ok(result.text.clone()),};match fmt_result {Ok(formatted) => {diff --git a/crates/liteparse-python/src/lib.rs b/crates/liteparse-python/src/lib.rsindex beb0f84..3f131ca 100644--- a/crates/liteparse-python/src/lib.rs+++ b/crates/liteparse-python/src/lib.rs@@ -239,6 +239,7 @@ impl PyLiteParseConfig {output_format: match cfg.output_format {OutputFormat::Json => "json".to_string(),OutputFormat::Text => "text".to_string(),+ OutputFormat::Markdown => "markdown".to_string(),},preserve_very_small_text: cfg.preserve_very_small_text,password: cfg.password.clone(),@@ -316,6 +317,7 @@ impl LiteParse {if let Some(v) = output_format {cfg.output_format = match v.as_str() {"text" => OutputFormat::Text,+ "markdown" | "md" => OutputFormat::Markdown,_ => OutputFormat::Json,};}diff --git a/crates/liteparse-wasm/src/lib.rs b/crates/liteparse-wasm/src/lib.rsindex 6c82a51..dbb1812 100644--- a/crates/liteparse-wasm/src/lib.rs+++ b/crates/liteparse-wasm/src/lib.rs@@ -78,9 +78,10 @@ impl JsLiteParseConfig {cfg.output_format = match v.as_str() {"json" => OutputFormat::Json,"text" => OutputFormat::Text,+ "markdown" | "md" => OutputFormat::Markdown,other => {return Err(JsError::new(&format!(- "invalid outputFormat: {} (expected 'json' or 'text')",+ "invalid outputFormat: {} (expected 'json', 'text', or 'markdown')",other)));}@@ -111,6 +112,7 @@ impl JsLiteParseConfig {output_format: Some(match cfg.output_format {OutputFormat::Json => "json".into(),OutputFormat::Text => "text".into(),+ OutputFormat::Markdown => "markdown".into(),}),preserve_very_small_text: Some(cfg.preserve_very_small_text),password: cfg.password.clone(),diff --git a/crates/liteparse/src/config.rs b/crates/liteparse/src/config.rsindex e01337d..ca1ce0a 100644--- a/crates/liteparse/src/config.rs+++ b/crates/liteparse/src/config.rs@@ -35,6 +35,7 @@ pub struct LiteParseConfig {pub enum OutputFormat {Json,Text,+ Markdown,}impl Default for LiteParseConfig {diff --git a/crates/liteparse/src/extract.rs b/crates/liteparse/src/extract.rsindex 09e9812..402f97b 100644--- a/crates/liteparse/src/extract.rs+++ b/crates/liteparse/src/extract.rs@@ -1,6 +1,6 @@use crate::error::LiteParseError;-use crate::types::{Page as LitePage, PdfInput, TextItem};-use pdfium::{Document, Font, FontType, Library, Page, RectF, TextPage};+use crate::types::{GraphicPrimitive, Page as LitePage, PdfInput, Rect, TextItem};+use pdfium::{Document, Font, FontType, Library, Page, PathObject, RectF, SegmentKind, TextPage};/// Open a PDF from path or bytes with an optional password.pub(crate) fn load_document_from_input(@@ -56,12 +56,14 @@ pub(crate) fn extract_pages_from_document(bottom: 0.0,});let text_items = extract_page_text_items(&page, &text_page, &view_box)?;+ let graphics = extract_page_graphics(&page, &view_box);pages.push(LitePage {page_number: page_number as usize,page_width: page.width(),page_height: page.height(),text_items,+ graphics,});}@@ -135,6 +137,90 @@ fn should_skip_invisible(text_page: &TextPage, char_count: i32) -> bool {invisible_ratio < 0.3}+/// Extract simplified vector graphics from a page. We keep only what the+/// markdown layout pass cares about:+/// - filled paths → a single bounding `Rect` (covers cell backgrounds /+/// 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> {+ let paths: Vec<PathObject> = page.path_objects(view_box);+ let mut out = Vec::new();++ for path in &paths {+ // Filled paths: emit one Rect for the full bbox. Cheap signal for+ // cell backgrounds / figure clusters / code-block fills.+ if path.is_filled {+ out.push(GraphicPrimitive::Rect {+ bbox: rectf_to_rect(&path.bbox),+ fill: path.fill_color.as_ref().map(color_to_argb_hex),+ stroke: path.stroke_color.as_ref().map(color_to_argb_hex),+ });+ }++ if !path.is_stroked {+ continue;+ }++ // Stroked paths: walk segments and emit one Stroke per LineTo.+ let color = path.stroke_color.as_ref().map(color_to_argb_hex);+ let mut current: Option<(f32, f32)> = None;+ let mut subpath_start: Option<(f32, f32)> = None;++ for seg in &path.segments {+ match seg.kind {+ SegmentKind::MoveTo => {+ current = Some((seg.x, seg.y));+ subpath_start = Some((seg.x, seg.y));+ }+ SegmentKind::LineTo => {+ if let Some((px, py)) = current {+ out.push(GraphicPrimitive::Stroke {+ x1: px,+ y1: py,+ x2: seg.x,+ y2: seg.y,+ color: color.clone(),+ width: path.stroke_width,+ });+ }+ current = Some((seg.x, seg.y));+ if seg.close+ && let (Some((cx, cy)), Some((sx, sy))) = (current, subpath_start)+ && (cx - sx).hypot(cy - sy) > 0.01+ {+ out.push(GraphicPrimitive::Stroke {+ x1: cx,+ y1: cy,+ x2: sx,+ y2: sy,+ color: color.clone(),+ width: path.stroke_width,+ });+ }+ }+ SegmentKind::BezierTo => {+ // Don't synthesize a stroke for a curve; just advance.+ current = Some((seg.x, seg.y));+ }+ }+ }+ }++ out+}++fn rectf_to_rect(r: &RectF) -> Rect {+ Rect {+ x: r.left,+ y: r.top,+ width: r.right - r.left,+ height: r.bottom - r.top,+ }+}+/// Character-level text extraction.////// Instead of using PDFium's rect API (which splits text at every font attributediff --git a/crates/liteparse/src/figure_cluster.rs b/crates/liteparse/src/figure_cluster.rsnew file mode 100644index 0000000..986292a--- /dev/null+++ b/crates/liteparse/src/figure_cluster.rs@@ -0,0 +1,390 @@+//! Figure-region clustering from page vector graphics.+//!+//! Groups significant vector graphics (filled rects, stroke clusters that+//! aren't HR-like or table-grid-like) into figure bounding rectangles. These+//! rects are fed into the XY-cut layout pass as obstacles, so the recursion+//! partitions around figures (e.g. an abstract column next to a figure that+//! straddles two columns on the first page of an academic paper).+//!+//! Detection is intentionally cautious — false positives here corrupt the+//! reading order. When in doubt we drop the cluster.++use crate::types::{GraphicPrimitive, Rect, TextItem};++/// Min figure dimension on each axis (points).+const FIG_MIN_EXTENT_PT: f32 = 30.0;+/// Min figure area (points²).+const FIG_MIN_AREA_PT2: f32 = 1500.0;+/// Max figure dimension as a fraction of the page (drop full-page backgrounds+/// and any cluster that has grown to consume virtually the whole page).+const FIG_MAX_FRACTION: f32 = 0.95;+/// Cluster two primitives when their bboxes overlap or are within this gap on+/// both axes.+const FIG_CLUSTER_GAP_PT: f32 = 10.0;+/// Drop horizontal-rule-like strokes (long thin horizontal) before clustering+/// so a section divider doesn't become a degenerate "figure".+const HR_MIN_WIDTH_FRACTION: f32 = 0.3;+const HR_MAX_THICKNESS_PT: f32 = 2.0;+/// Aspect ratio threshold above which a cluster is considered "linear" (e.g. a+/// single rule, an underline cluster) rather than a figure.+const FIG_MAX_ASPECT_RATIO: f32 = 15.0;+/// Min primitives in a cluster unless any single primitive is itself large.+const FIG_LARGE_SOLO_AREA: f32 = 5000.0;+/// Fraction of a cluster's area that may be covered by text before we treat+/// the cluster as a text background rather than a figure.+const FIG_MAX_TEXT_COVERAGE: f32 = 0.55;++/// Detect figure rectangles on a page.+///+/// Returns a list of bounding rectangles, each enclosing a vector-graphics+/// cluster judged to be a figure (chart, diagram, embedded illustration).+/// Empty when the page has no significant graphics.+pub fn detect_figure_rects(+ graphics: &[GraphicPrimitive],+ text_items: &[TextItem],+ page_width: f32,+ page_height: f32,+) -> Vec<Rect> {+ if graphics.is_empty() || page_width <= 0.0 || page_height <= 0.0 {+ return Vec::new();+ }++ // Pre-filter primitives.+ let hr_min_width = page_width * HR_MIN_WIDTH_FRACTION;+ let mut bboxes: Vec<Rect> = Vec::with_capacity(graphics.len());+ for g in graphics {+ let bbox = g.bbox();+ // Drop full-page rects (page background paint).+ if bbox.width >= page_width * FIG_MAX_FRACTION+ && bbox.height >= page_height * FIG_MAX_FRACTION+ {+ continue;+ }+ match g {+ GraphicPrimitive::Stroke {+ x1,+ y1,+ x2,+ y2,+ width,+ ..+ } => {+ let dx = (x2 - x1).abs();+ let dy = (y2 - y1).abs();+ // HR-like: long thin horizontal stroke → section divider, not figure.+ if dy <= HR_MAX_THICKNESS_PT && *width <= HR_MAX_THICKNESS_PT && dx >= hr_min_width+ {+ continue;+ }+ // Tiny strokes (glyph artifacts, sub-pixel cleanup).+ if dx < 4.0 && dy < 4.0 {+ continue;+ }+ }+ GraphicPrimitive::Rect { .. } => {+ // Tiny rects also dropped to avoid pulling glyph artifacts in.+ if bbox.width < 2.0 && bbox.height < 2.0 {+ continue;+ }+ }+ }+ bboxes.push(bbox);+ }+ if bboxes.is_empty() {+ return Vec::new();+ }++ // Union-find: link primitives whose bboxes are close on BOTH axes.+ let n = bboxes.len();+ let mut parent: Vec<usize> = (0..n).collect();+ for i in 0..n {+ for j in (i + 1)..n {+ if close_enough(&bboxes[i], &bboxes[j], FIG_CLUSTER_GAP_PT) {+ uf_union(&mut parent, i, j);+ }+ }+ }++ use std::collections::HashMap;+ let mut groups: HashMap<usize, (Rect, usize)> = HashMap::new();+ for (i, bb) in bboxes.iter().enumerate() {+ let r = uf_find(&mut parent, i);+ groups+ .entry(r)+ .and_modify(|entry| {+ entry.0 = union_rect(&entry.0, bb);+ entry.1 += 1;+ })+ .or_insert_with(|| (bb.clone(), 1));+ }++ let mut out = Vec::new();+ for (bbox, count) in groups.into_values() {+ if !is_figure_cluster(&bbox, count, page_width, page_height, text_items) {+ continue;+ }+ out.push(bbox);+ }+ // Sort by y then x so callers see deterministic ordering.+ out.sort_by(|a, b| a.y.total_cmp(&b.y).then(a.x.total_cmp(&b.x)));+ out+}++fn is_figure_cluster(+ bbox: &Rect,+ primitive_count: usize,+ page_width: f32,+ page_height: f32,+ text_items: &[TextItem],+) -> bool {+ if bbox.width < FIG_MIN_EXTENT_PT || bbox.height < FIG_MIN_EXTENT_PT {+ return false;+ }+ let area = bbox.width * bbox.height;+ if area < FIG_MIN_AREA_PT2 {+ return false;+ }+ if bbox.width >= page_width * FIG_MAX_FRACTION && bbox.height >= page_height * FIG_MAX_FRACTION+ {+ return false;+ }+ let ratio = if bbox.width >= bbox.height {+ bbox.width / bbox.height.max(0.01)+ } else {+ bbox.height / bbox.width.max(0.01)+ };+ if ratio > FIG_MAX_ASPECT_RATIO {+ return false;+ }+ if primitive_count < 2 && area < FIG_LARGE_SOLO_AREA {+ return false;+ }+ if text_coverage(bbox, text_items) > FIG_MAX_TEXT_COVERAGE {+ return false;+ }+ true+}++fn close_enough(a: &Rect, b: &Rect, gap: f32) -> bool {+ let x_gap = (a.x - (b.x + b.width)).max(b.x - (a.x + a.width));+ let y_gap = (a.y - (b.y + b.height)).max(b.y - (a.y + a.height));+ x_gap <= gap && y_gap <= gap+}++fn union_rect(a: &Rect, b: &Rect) -> Rect {+ let x = a.x.min(b.x);+ let y = a.y.min(b.y);+ let x2 = (a.x + a.width).max(b.x + b.width);+ let y2 = (a.y + a.height).max(b.y + b.height);+ Rect {+ x,+ y,+ width: x2 - x,+ height: y2 - y,+ }+}++/// Fraction of `bbox` area covered by text. Computed by y-banding the items+/// inside `bbox` into lines (same y within `±0.5 × median_h`) and taking the+/// union bbox of each band — that's a much better proxy for "this region is+/// dominated by text" than summing per-glyph rectangles, which leaves the+/// large inter-word and inter-cell gaps unaccounted for and lets text-dense+/// tables slip below a reasonable coverage threshold.+fn text_coverage(bbox: &Rect, text_items: &[TextItem]) -> f32 {+ let bbox_area = bbox.width * bbox.height;+ if bbox_area <= 0.0 {+ return 0.0;+ }+ // Collect items that overlap the bbox (any intersection), keep their+ // clipped extents.+ let mut clipped: Vec<(f32, f32, f32, f32)> = Vec::new();+ let mut heights: Vec<f32> = Vec::new();+ for it in text_items {+ let ix0 = it.x.max(bbox.x);+ let iy0 = it.y.max(bbox.y);+ let ix1 = (it.x + it.width).min(bbox.x + bbox.width);+ let iy1 = (it.y + it.height).min(bbox.y + bbox.height);+ if ix1 <= ix0 || iy1 <= iy0 {+ continue;+ }+ clipped.push((ix0, iy0, ix1, iy1));+ let h = it.height.max(iy1 - iy0).max(0.0);+ if h > 0.5 {+ heights.push(h);+ }+ }+ if clipped.is_empty() {+ return 0.0;+ }+ let median_h = {+ let mut h = heights;+ if h.is_empty() {+ 8.0+ } else {+ h.sort_by(|a, b| a.total_cmp(b));+ h[h.len() / 2].max(4.0)+ }+ };+ let band = median_h * 0.5;+ // Sort by y midpoint, then greedy y-band into "lines": items whose+ // y-midpoints are within `band` form one line.+ clipped.sort_by(|a, b| {+ let am = (a.1 + a.3) * 0.5;+ let bm = (b.1 + b.3) * 0.5;+ am.total_cmp(&bm)+ });+ let mut covered = 0.0f32;+ let mut iter = clipped.into_iter();+ let mut cur = iter.next().unwrap();+ for nxt in iter {+ let cur_mid = (cur.1 + cur.3) * 0.5;+ let nxt_mid = (nxt.1 + nxt.3) * 0.5;+ if (nxt_mid - cur_mid).abs() <= band {+ cur.0 = cur.0.min(nxt.0);+ cur.1 = cur.1.min(nxt.1);+ cur.2 = cur.2.max(nxt.2);+ cur.3 = cur.3.max(nxt.3);+ } else {+ covered += (cur.2 - cur.0) * (cur.3 - cur.1);+ cur = nxt;+ }+ }+ covered += (cur.2 - cur.0) * (cur.3 - cur.1);+ (covered / bbox_area).min(1.0)+}++fn uf_find(parent: &mut [usize], mut x: usize) -> usize {+ while parent[x] != x {+ parent[x] = parent[parent[x]];+ x = parent[x];+ }+ x+}++fn uf_union(parent: &mut [usize], a: usize, b: usize) {+ let ra = uf_find(parent, a);+ let rb = uf_find(parent, b);+ if ra != rb {+ parent[ra] = rb;+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn stroke(x1: f32, y1: f32, x2: f32, y2: f32) -> GraphicPrimitive {+ GraphicPrimitive::Stroke {+ x1,+ y1,+ x2,+ y2,+ color: None,+ width: 0.5,+ }+ }++ fn rect(x: f32, y: f32, w: f32, h: f32) -> GraphicPrimitive {+ GraphicPrimitive::Rect {+ bbox: Rect {+ x,+ y,+ width: w,+ height: h,+ },+ fill: None,+ stroke: None,+ }+ }++ #[test]+ fn empty_input_returns_no_figures() {+ let figs = detect_figure_rects(&[], &[], 612.0, 792.0);+ assert!(figs.is_empty());+ }++ #[test]+ fn long_thin_hr_is_not_a_figure() {+ // A divider stroke 400pt wide × 0.5pt thick.+ let g = vec![stroke(100.0, 400.0, 500.0, 400.0)];+ let figs = detect_figure_rects(&g, &[], 612.0, 792.0);+ assert!(figs.is_empty(), "HR should not be classified as figure");+ }++ #[test]+ fn dense_stroke_cluster_becomes_a_figure() {+ // 30 short strokes packed into a 200×150pt area — looks like a chart.+ let mut g = Vec::new();+ for i in 0..6 {+ for j in 0..5 {+ let x = 100.0 + i as f32 * 30.0;+ let y = 200.0 + j as f32 * 25.0;+ g.push(stroke(x, y, x + 20.0, y + 15.0));+ }+ }+ let figs = detect_figure_rects(&g, &[], 612.0, 792.0);+ assert_eq!(figs.len(), 1, "expected one figure cluster");+ let f = &figs[0];+ assert!(f.width >= 100.0 && f.height >= 100.0);+ assert!(f.x >= 90.0 && f.x <= 110.0);+ }++ #[test]+ fn large_solo_rect_qualifies_as_figure() {+ // A single filled rect 200×100pt — area > FIG_LARGE_SOLO_AREA.+ let g = vec![rect(100.0, 300.0, 200.0, 100.0)];+ let figs = detect_figure_rects(&g, &[], 612.0, 792.0);+ assert_eq!(figs.len(), 1);+ }++ #[test]+ fn full_page_background_rect_is_skipped() {+ let g = vec![rect(0.0, 0.0, 612.0, 792.0)];+ let figs = detect_figure_rects(&g, &[], 612.0, 792.0);+ assert!(figs.is_empty(), "full-page rect should not be a figure");+ }++ #[test]+ fn text_heavy_rect_is_treated_as_background_not_figure() {+ // A 200×100pt rect entirely filled with text — should be rejected.+ let g = vec![rect(100.0, 100.0, 200.0, 100.0)];+ let mut text = Vec::new();+ for row in 0..8 {+ text.push(TextItem {+ text: "lorem ipsum dolor".into(),+ x: 105.0,+ y: 105.0 + row as f32 * 12.0,+ width: 190.0,+ height: 10.0,+ ..Default::default()+ });+ }+ let figs = detect_figure_rects(&g, &text, 612.0, 792.0);+ assert!(+ figs.is_empty(),+ "text-covered rect should not be classified as a figure"+ );+ }++ #[test]+ fn distant_strokes_do_not_merge() {+ // Two clusters far apart (>>10pt gap on both axes).+ let mut g = Vec::new();+ for i in 0..6 {+ for j in 0..5 {+ let x = 50.0 + i as f32 * 25.0;+ let y = 100.0 + j as f32 * 20.0;+ g.push(stroke(x, y, x + 18.0, y + 12.0));+ }+ }+ for i in 0..6 {+ for j in 0..5 {+ let x = 400.0 + i as f32 * 25.0;+ let y = 500.0 + j as f32 * 20.0;+ g.push(stroke(x, y, x + 18.0, y + 12.0));+ }+ }+ let figs = detect_figure_rects(&g, &[], 612.0, 792.0);+ assert_eq!(figs.len(), 2, "expected two separate figure clusters");+ }+}diff --git a/crates/liteparse/src/lib.rs b/crates/liteparse/src/lib.rsindex f96e47c..72c68b6 100644--- a/crates/liteparse/src/lib.rs+++ b/crates/liteparse/src/lib.rs@@ -25,6 +25,10 @@ pub mod conversion;#[doc(hidden)]pub mod extract;#[doc(hidden)]+pub mod figure_cluster;+#[doc(hidden)]+pub mod markdown_layout;+#[doc(hidden)]pub mod ocr;#[doc(hidden)]pub mod ocr_merge;diff --git a/crates/liteparse/src/main.rs b/crates/liteparse/src/main.rsindex 974ce94..5c9e8d0 100644--- a/crates/liteparse/src/main.rs+++ b/crates/liteparse/src/main.rs@@ -42,7 +42,7 @@ struct ParseCommand {#[arg(short, long)]output: Option<String>,- /// Output format: json or text+ /// Output format: json, text, or markdown#[arg(long, default_value = "text")]format: String,@@ -125,7 +125,7 @@ struct BatchParseCommand {/// Output directoryoutput_dir: String,- /// Output format: json or text+ /// Output format: json, text, or markdown#[arg(long, default_value = "text")]format: String,@@ -189,7 +189,11 @@ fn parse_output_format(s: &str) -> Result<OutputFormat, String> {match s.to_lowercase().as_str() {"json" => Ok(OutputFormat::Json),"text" => Ok(OutputFormat::Text),- _ => Err(format!("unknown format '{}', expected 'json' or 'text'", s)),+ "markdown" | "md" => Ok(OutputFormat::Markdown),+ _ => Err(format!(+ "unknown format '{}', expected 'json', 'text', or 'markdown'",+ s+ )),}}@@ -224,6 +228,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {let formatted = match lp.config().output_format {OutputFormat::Json => json::format_json(&result.pages)?,OutputFormat::Text => text::format_text(&result.pages),+ OutputFormat::Markdown => result.text.clone(),};match cmd.output {@@ -302,10 +307,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {}let lp = LiteParse::new(config);- let out_ext = if format == OutputFormat::Json {- "json"- } else {- "txt"+ let out_ext = match format {+ OutputFormat::Json => "json",+ OutputFormat::Markdown => "md",+ OutputFormat::Text => "txt",};std::fs::create_dir_all(&cmd.output_dir)?;@@ -345,6 +350,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {json::format_json(&result.pages).map_err(|e| e.into())}OutputFormat::Text => Ok(text::format_text(&result.pages)),+ OutputFormat::Markdown => Ok(result.text.clone()),};match fmt_result {Ok(formatted) => {diff --git a/crates/liteparse/src/markdown_layout.rs b/crates/liteparse/src/markdown_layout.rsnew file mode 100644index 0000000..c7d255a--- /dev/null+++ b/crates/liteparse/src/markdown_layout.rs@@ -0,0 +1,3369 @@+//! 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.++use crate::projection::{is_bold_item, is_italic_item, is_mono_item};+use crate::types::{Anchor, GraphicPrimitive, ParsedPage, ProjectedLine, TextItem};++/// Maximum stroke thickness (or |y1-y2|) for a stroke to count as a candidate HR.+/// Thicker shapes are filled rects, not rules.+const HR_MAX_THICKNESS_PT: f32 = 2.0;++/// Minimum fraction of page width a horizontal stroke must span to count as an HR.+/// Shorter strokes are typically table borders, list bullets, or inline marks.+const HR_MIN_WIDTH_FRACTION: f32 = 0.3;++/// Vertical tolerance (points) for treating a stroke as "underlining" the+/// nearest text line. Strokes within this band of a text line's baseline are+/// dropped — they're underlines, not rules.+const HR_UNDERLINE_PROXIMITY_PT: f32 = 3.0;++/// Detect horizontal rules from a page's vector graphics.+///+/// Returns the y-coordinates (viewport space) of accepted HRs, sorted ascending.+/// An HR is a roughly horizontal stroke that spans at least+/// `HR_MIN_WIDTH_FRACTION` of the page width, is thinner than+/// `HR_MAX_THICKNESS_PT`, and does not sit on the baseline of any text line+/// (which would make it an underline).+pub fn detect_horizontal_rules(page: &ParsedPage) -> Vec<f32> {+ if page.graphics.is_empty() || page.page_width <= 0.0 {+ return Vec::new();+ }+ let min_width = page.page_width * HR_MIN_WIDTH_FRACTION;+ let mut ys: Vec<f32> = Vec::new();++ for g in &page.graphics {+ let GraphicPrimitive::Stroke {+ x1,+ y1,+ x2,+ y2,+ width,+ ..+ } = g+ else {+ continue;+ };+ let (x1, y1, x2, y2, width) = (*x1, *y1, *x2, *y2, *width);+ let dy = (y1 - y2).abs();+ let dx = (x1 - x2).abs();+ if dy > HR_MAX_THICKNESS_PT || width > HR_MAX_THICKNESS_PT {+ continue;+ }+ if dx < min_width {+ continue;+ }+ let y = (y1 + y2) * 0.5;+ let xmin = x1.min(x2);+ let xmax = x1.max(x2);++ // Drop if this stroke sits on a text-line baseline — it's an underline,+ // not a divider.+ let is_underline = page.projected_lines.iter().any(|line| {+ let bottom = line.bbox.y + line.bbox.height;+ (y - bottom).abs() < HR_UNDERLINE_PROXIMITY_PT+ && xmin >= line.bbox.x - 2.0+ && xmax <= line.bbox.x + line.bbox.width + 2.0+ });+ if is_underline {+ continue;+ }+ ys.push(y);+ }++ // Sort + dedup near-duplicates (some PDFs draw the same rule twice).+ ys.sort_by(|a, b| a.total_cmp(b));+ ys.dedup_by(|a, b| (*a - *b).abs() < 1.0);+ ys+}++/// Coarse block representation. Intentionally minimal — extended as later+/// build-order steps land (tables, figures).+#[derive(Debug, Clone)]+pub enum Block {+ Heading {+ level: u8,+ text: String,+ },+ Paragraph {+ text: String,+ bold: bool,+ italic: bool,+ },+ ListItem {+ ordered: bool,+ marker: String,+ level: u8,+ text: String,+ bold: bool,+ italic: bool,+ },+ /// Fenced code block — content rendered between triple-backtick fences.+ /// Each entry in `lines` is one source line; preserved as-is (only trailing+ /// whitespace stripped) so indentation survives.+ CodeBlock {+ lines: Vec<String>,+ },+ /// Confident table emitted as a markdown pipe table. `header` is `None`+ /// when the first row didn't qualify (e.g. wasn't bold and the table mode+ /// can't otherwise distinguish it).+ Table {+ header: Option<Vec<String>>,+ rows: Vec<Vec<String>>,+ },+ /// Tabular-looking region we couldn't classify confidently — rendered+ /// verbatim inside a fenced block to preserve visual structure for the+ /// downstream LLM. Strictly better than emitting a mangled pipe table.+ GridFallback {+ lines: Vec<String>,+ },+ /// A horizontal rule detected from a long thin horizontal stroke in the+ /// page's vector graphics (e.g. divider line between sections).+ HorizontalRule,+ Blank,+}++/// Minimum cells per row for a region to qualify as a table.+const TABLE_MIN_COLUMNS: usize = 3;++/// Minimum consecutive rows for a region to qualify as a table.+const TABLE_MIN_ROWS: usize = 2;++/// Gap between adjacent spans (in multiples of dominant font size) above which+/// we treat the gap as a cell boundary.+const TABLE_CELL_GAP_FONT_MULTIPLIER: f32 = 1.0;++/// Tolerance (points) for matching a cell's start-x to an existing column+/// track when extending a candidate table run.+const TABLE_TRACK_TOLERANCE_PT: f32 = 6.0;++/// Maximum vertical gap between consecutive table rows, expressed in multiples+/// of the line height. Looser than the paragraph rule because table rows often+/// have more vertical padding than prose lines.+const TABLE_ROW_GAP_MULTIPLIER: f32 = 2.5;++/// Maximum coefficient-of-variation for row spacing within a confident table+/// (rejecting irregular spacing that's more likely prose or a footer block).+const TABLE_ROW_SPACING_MAX_CV: f32 = 0.5;++/// One cell within a tabular row: contributing spans aggregated to text and+/// its leftmost x position, used to align cells across rows into column+/// "tracks".+#[derive(Debug, Clone)]+struct TableCell {+ start_x: f32,+ /// Right edge of the cell (x of the last span's right). Used by+ /// `recover_merged_cell` to detect cells that straddle two column tracks+ /// when the projection merged two adjacent words into one span.+ end_x: f32,+ text: String,+ bold: bool,+}++/// A contiguous tabular run: line indices `[start, end)` plus the detected+/// rows. Used so the line-classifier can skip the consumed range and so+/// fallback rendering can reach back for the original projected text.+#[derive(Debug, Clone)]+struct TableRun {+ start: usize,+ end: usize,+ block: Block,+}++/// Split a `ProjectedLine`'s spans into cells. A gap larger than+/// `TABLE_CELL_GAP_FONT_MULTIPLIER × font_size` between adjacent spans starts+/// a new cell; otherwise spans join into the same cell with a single space.+fn split_cells(line: &ProjectedLine) -> Vec<TableCell> {+ // Skip whitespace-only spans before computing gaps — leading/trailing+ // empty items would otherwise add spurious cell boundaries.+ let mut spans: Vec<&TextItem> = line+ .spans+ .iter()+ .filter(|s| !s.text.trim().is_empty())+ .collect();+ spans.sort_by(|a, b| a.x.total_cmp(&b.x));+ if spans.is_empty() {+ return Vec::new();+ }+ let font_size = if line.dominant_font_size > 0.0 {+ line.dominant_font_size+ } else {+ line.bbox.height.max(1.0)+ };+ let gap_threshold = font_size * TABLE_CELL_GAP_FONT_MULTIPLIER;++ let mut cells: Vec<TableCell> = Vec::new();+ let mut current_text = String::new();+ let mut current_start = spans[0].x;+ let mut current_bold_chars: usize = 0;+ let mut current_total_chars: usize = 0;+ let mut prev_right = spans[0].x;++ for (i, span) in spans.iter().enumerate() {+ let gap = span.x - prev_right;+ let break_cell = i > 0 && gap > gap_threshold;+ if break_cell {+ let bold = current_total_chars > 0 && current_bold_chars * 2 > current_total_chars;+ cells.push(TableCell {+ start_x: current_start,+ end_x: prev_right,+ text: collapse_whitespace(current_text.trim()),+ bold,+ });+ current_text.clear();+ current_start = span.x;+ current_bold_chars = 0;+ current_total_chars = 0;+ }+ if !current_text.is_empty() && !current_text.ends_with(' ') {+ current_text.push(' ');+ }+ current_text.push_str(&span.text);+ let n = span.text.chars().count();+ current_total_chars += n;+ if is_bold_span(span) {+ current_bold_chars += n;+ }+ prev_right = span.x + span.width.max(0.0);+ }+ if !current_text.trim().is_empty() {+ let bold = current_total_chars > 0 && current_bold_chars * 2 > current_total_chars;+ cells.push(TableCell {+ start_x: current_start,+ end_x: prev_right,+ text: collapse_whitespace(current_text.trim()),+ bold,+ });+ }+ cells+}++/// When a candidate row has fewer cells than the established column count,+/// look for cells whose x-range straddles multiple column tracks (likely two+/// or more adjacent words that PDFium merged into a single text run) and+/// split each on internal whitespace at the boundaries nearest to the+/// straddled tracks.+///+/// Returns the patched cells if every short cell could be cleanly split to+/// recover `tracks.len()` cells total; otherwise `None`.+fn recover_merged_cell(mut cells: Vec<TableCell>, tracks: &[f32]) -> Option<Vec<TableCell>> {+ let target = tracks.len();+ if cells.len() >= target {+ return None;+ }+ // Repeatedly find the cell that straddles the most tracks (≥2) and split+ // it. Each iteration strictly grows `cells.len()`, so termination is+ // guaranteed; if no cell straddles ≥2 tracks before we hit the target,+ // recovery fails.+ while cells.len() < target {+ let mut best_i: Option<usize> = None;+ let mut best_count: usize = 1;+ let mut best_contained: Vec<f32> = Vec::new();+ for (i, cell) in cells.iter().enumerate() {+ let contained: Vec<f32> = tracks+ .iter()+ .copied()+ .filter(|t| {+ *t >= cell.start_x - TABLE_TRACK_TOLERANCE_PT+ && *t <= cell.end_x + TABLE_TRACK_TOLERANCE_PT+ })+ .collect();+ if contained.len() > best_count {+ best_count = contained.len();+ best_i = Some(i);+ best_contained = contained;+ }+ }+ let Some(i) = best_i else {+ return None;+ };+ let cell = cells[i].clone();+ let chars: Vec<char> = cell.text.trim().chars().collect();+ let n = chars.len();+ if n == 0 || best_contained.len() < 2 {+ return None;+ }+ let text_width = (cell.end_x - cell.start_x).max(1.0);+ // For each track after the first, pick the whitespace boundary in+ // `chars` whose linearly-interpolated x is closest to the track.+ let mut split_indices: Vec<usize> = Vec::new();+ for t in best_contained.iter().skip(1) {+ let mut best: Option<(usize, f32)> = None;+ for (k, ch) in chars.iter().enumerate() {+ if !ch.is_whitespace() {+ continue;+ }+ if split_indices.contains(&k) {+ continue;+ }+ let frac = k as f32 / n as f32;+ let x = cell.start_x + frac * text_width;+ let d = (x - t).abs();+ if best.as_ref().is_none_or(|b| d < b.1) {+ best = Some((k, d));+ }+ }+ let (k, _) = best?;+ split_indices.push(k);+ }+ split_indices.sort();+ // Build the split pieces.+ let mut pieces: Vec<String> = Vec::new();+ let mut prev = 0usize;+ for k in &split_indices {+ let piece: String = chars[prev..*k]+ .iter()+ .collect::<String>()+ .trim()+ .to_string();+ if piece.is_empty() {+ return None;+ }+ pieces.push(piece);+ prev = *k;+ }+ let last: String = chars[prev..].iter().collect::<String>().trim().to_string();+ if last.is_empty() {+ return None;+ }+ pieces.push(last);+ if pieces.len() != best_contained.len() {+ return None;+ }+ // Synthesize new TableCells aligned with each track.+ let mut new_cells: Vec<TableCell> = Vec::with_capacity(pieces.len());+ for (p, piece) in pieces.iter().enumerate() {+ let start_x = if p == 0 {+ cell.start_x+ } else {+ best_contained[p]+ };+ let end_x = if p + 1 < best_contained.len() {+ (best_contained[p + 1] - 1.0).max(start_x)+ } else {+ cell.end_x+ };+ new_cells.push(TableCell {+ start_x,+ end_x,+ text: piece.clone(),+ bold: cell.bold,+ });+ }+ cells.remove(i);+ for (offset, c) in new_cells.into_iter().enumerate() {+ cells.insert(i + offset, c);+ }+ }+ if cells.len() == target {+ Some(cells)+ } else {+ None+ }+}++/// Lightweight bold detection on a raw `TextItem`. Delegates to+/// `projection::is_bold_item` so per-span and per-line logic stay in sync.+fn is_bold_span(s: &TextItem) -> bool {+ is_bold_item(s)+}++/// Per-span style flags used by the inline-emphasis renderer.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+struct SpanStyle {+ bold: bool,+ italic: bool,+ mono: bool,+}++impl SpanStyle {+ fn from_item(item: &TextItem) -> Self {+ SpanStyle {+ bold: is_bold_item(item),+ italic: is_italic_item(item),+ mono: is_mono_item(item),+ }+ }++ fn is_plain(self) -> bool {+ !self.bold && !self.italic && !self.mono+ }+}++/// Escape characters that would otherwise be interpreted as markdown emphasis.+/// Deliberately narrow: only `*`, `_`, and backslash. Aggressive escaping+/// (`#`, `[`, backticks, etc.) breaks more output than it saves in practice —+/// pymupdf4llm takes the same conservative stance.+fn escape_inline(s: &str) -> String {+ let mut out = String::with_capacity(s.len());+ for c in s.chars() {+ match c {+ '\\' | '*' | '_' => {+ out.push('\\');+ out.push(c);+ }+ _ => out.push(c),+ }+ }+ out+}++/// Wrap `inner` with the markdown markers for `style`. Mono wins over bold/italic:+/// inline code (`` `…` ``) doesn't compose with emphasis in CommonMark, so when+/// a span is mono we drop the `**/*` wrap. Bold + italic → `***…***`.+fn apply_style(inner: &str, style: SpanStyle) -> String {+ if style.mono {+ // Use backticks; if inner already contains backticks, switch to a+ // longer fence (pair of backticks plus a space buffer) per CommonMark.+ if inner.contains('`') {+ return format!("`` {} ``", inner);+ }+ return format!("`{}`", inner);+ }+ match (style.bold, style.italic) {+ (true, true) => format!("***{}***", inner),+ (true, false) => format!("**{}**", inner),+ (false, true) => format!("*{}*", inner),+ (false, false) => inner.to_string(),+ }+}++/// Render a `ProjectedLine` to markdown with per-span emphasis. Adjacent+/// same-style spans are merged into a single emphasis run; whitespace between+/// spans is preserved as one space (the underlying projection output already+/// has the right inter-word spacing baked into span text).+///+/// Per-line shortcut: when every non-whitespace span shares the same style,+/// emit one outer wrap around the collapsed line text instead of run-by-run+/// (matches pymupdf4llm; avoids `**foo** **bar** **baz**` noise on uniformly+/// styled lines).+///+/// Falls back to `collapse_whitespace(line.text)` when the line has no usable+/// spans (e.g. OCR-only lines where TextItem styling isn't populated).+fn render_line_inline(line: &ProjectedLine) -> String {+ let spans: Vec<&TextItem> = line+ .spans+ .iter()+ .filter(|s| !s.text.trim().is_empty())+ .collect();+ if spans.is_empty() {+ return collapse_whitespace(&line.text);+ }++ // Sort spans by x so we render in visual reading order regardless of+ // extraction order. Stable so equal-x spans keep their original sequence.+ let mut spans = spans;+ spans.sort_by(|a, b| a.x.total_cmp(&b.x));++ let styles: Vec<SpanStyle> = spans.iter().map(|s| SpanStyle::from_item(s)).collect();++ // Per-line shortcut.+ let uniform = styles.iter().all(|s| *s == styles[0]);+ if uniform {+ let joined = collapse_whitespace(&line.text);+ if joined.is_empty() {+ return joined;+ }+ let escaped = escape_inline(&joined);+ if styles[0].is_plain() {+ return escaped;+ }+ return apply_style(&escaped, styles[0]);+ }++ // Group consecutive spans by style. Within a group, span texts join with+ // a single space (we lose intra-group spacing precision; acceptable).+ let mut out = String::new();+ let mut i = 0;+ while i < spans.len() {+ let style = styles[i];+ let mut j = i + 1;+ while j < spans.len() && styles[j] == style {+ j += 1;+ }+ let mut group_text = String::new();+ for k in i..j {+ if !group_text.is_empty() && !group_text.ends_with(' ') {+ group_text.push(' ');+ }+ group_text.push_str(spans[k].text.trim());+ }+ let group_text = collapse_whitespace(&group_text);+ let escaped = escape_inline(&group_text);+ let rendered = if style.is_plain() {+ escaped+ } else {+ apply_style(&escaped, style)+ };+ if !out.is_empty() && !out.ends_with(' ') {+ out.push(' ');+ }+ out.push_str(&rendered);+ i = j;+ }+ out+}++/// 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).+///+/// When the line is uniformly styled we wrap the marker-stripped `rest` with+/// the line's style — this avoids the awkward emphasis-marker mismatch we'd+/// hit if we naively stripped a leading bullet out of an already-wrapped+/// rendered line (`**• item**` → `** item**`).+///+/// When the line is mixed-style we render the full line via the inline pipeline+/// and then best-effort-strip the marker prefix (with optional emphasis wrap+/// around it). On any failure we fall back to plain escaped `rest`.+fn render_list_item_text(line: &ProjectedLine, marker: &str, rest: &str) -> String {+ if let Some(style) = line_uniform_style(line) {+ let plain = collapse_whitespace(rest);+ let escaped = escape_inline(&plain);+ return if style.is_plain() {+ escaped+ } else {+ apply_style(&escaped, style)+ };+ }+ let full = render_line_inline(line);+ if let Some(stripped) = strip_leading_marker_from_inline(&full, marker) {+ return stripped;+ }+ escape_inline(&collapse_whitespace(rest))+}++/// Try to strip a leading list marker (optionally wrapped in emphasis markers)+/// off `s`. Recognizes `***MARK*** `, `**MARK** `, `*MARK* `, `` `MARK` ``,+/// and bare `MARK `. Returns the suffix on a match.+fn strip_leading_marker_from_inline(s: &str, marker: &str) -> Option<String> {+ for wrap in ["***", "**", "*", "`"] {+ let prefix = format!("{wrap}{marker}{wrap} ");+ if let Some(rest) = s.strip_prefix(&prefix) {+ return Some(rest.to_string());+ }+ }+ let prefix = format!("{marker} ");+ s.strip_prefix(&prefix).map(|r| r.to_string())+}++/// Append an inline-rendered continuation line to an existing list-item body.+/// De-hyphenates against the raw text boundary (mirrors the paragraph rule)+/// and falls back to a space join otherwise.+fn append_inline_continuation(prev_text: &mut String, next_raw: &str, 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);+ }+}++/// Vertical-gap check for table rows. Looser than paragraph continuation+/// because table rows often have extra padding between them.+fn table_rows_adjacent(prev: &ProjectedLine, cur: &ProjectedLine) -> bool {+ // Intentionally don't require region_path equality. Indented sub-group+ // rows (e.g. an indented "MEMORYBANK" row in a grouped academic results+ // table) sometimes land in a different XY-cut leaf than the rest of the+ // table — but the column-track alignment and y-gap checks below are+ // strong enough signals on their own to keep us from spuriously+ // bridging unrelated regions.+ let prev_bottom = prev.bbox.y + prev.bbox.height;+ let gap = cur.bbox.y - prev_bottom;+ let line_height = prev.bbox.height.max(cur.bbox.height).max(1.0);+ gap >= -line_height && gap <= line_height * TABLE_ROW_GAP_MULTIPLIER+}++/// Coefficient of variation (std-dev / mean) of inter-row vertical gaps.+/// Returns 0.0 for runs with <2 gaps (nothing to compare). Used to reject+/// runs whose row spacing is too irregular to be a real table.+fn row_spacing_cv(rows: &[(usize, &ProjectedLine, Vec<TableCell>)]) -> f32 {+ if rows.len() < 3 {+ return 0.0;+ }+ let gaps: Vec<f32> = rows+ .windows(2)+ .map(|w| (w[1].1.bbox.y - w[0].1.bbox.y).abs())+ .collect();+ let mean = gaps.iter().sum::<f32>() / gaps.len() as f32;+ if mean <= 0.0 {+ return f32::INFINITY;+ }+ let var = gaps.iter().map(|g| (g - mean).powi(2)).sum::<f32>() / gaps.len() as f32;+ var.sqrt() / mean+}++/// Try to extend a candidate table starting at `start_idx`. On success returns+/// a `TableRun` with `Block::Table` or `Block::GridFallback`; on failure+/// returns `None` (and the caller should fall through to per-line+/// classification).+fn try_detect_table(lines: &[ProjectedLine], start_idx: usize) -> Option<TableRun> {+ let first_cells = split_cells(&lines[start_idx]);+ if first_cells.len() < TABLE_MIN_COLUMNS {+ return None;+ }++ let mut rows: Vec<(usize, &ProjectedLine, Vec<TableCell>)> =+ vec![(start_idx, &lines[start_idx], first_cells.clone())];+ let column_count = first_cells.len();+ let tracks: Vec<f32> = first_cells.iter().map(|c| c.start_x).collect();++ let mut j = start_idx + 1;+ while j < lines.len() {+ if !table_rows_adjacent(rows.last().unwrap().1, &lines[j]) {+ break;+ }+ let mut cells = split_cells(&lines[j]);+ if cells.len() < column_count && cells.len() >= TABLE_MIN_COLUMNS {+ // PDFium occasionally merges two (or more) adjacent words into one+ // text run when inter-word kerning is tighter than the gap+ // threshold — common in tightly-set numeric tables (e.g. the+ // "MEMORYBANK 5.00 4.77" case on page 6 of the AMEM paper).+ // Recover by splitting straddling cells on internal whitespace.+ if let Some(patched) = recover_merged_cell(cells.clone(), &tracks) {+ cells = patched;+ }+ }+ if cells.len() != column_count {+ break;+ }+ // Allow at most one column track to drift out of tolerance, which lets+ // grouped row-labels in academic tables (e.g. an indented "MEMORYBANK"+ // row whose label column shifts right by ~30pt while the numeric+ // columns stay aligned) stay in the same run. Without this slack a+ // single indented label fragments a 6-row table into three 2-row chunks.+ let misaligned = cells+ .iter()+ .zip(tracks.iter())+ .filter(|(c, t)| (c.start_x - **t).abs() > TABLE_TRACK_TOLERANCE_PT)+ .count();+ if misaligned > 1 {+ break;+ }+ rows.push((j, &lines[j], cells));+ j += 1;+ }++ if rows.len() < TABLE_MIN_ROWS {+ return None;+ }++ let cv = row_spacing_cv(&rows);+ let end = j;++ if cv > TABLE_ROW_SPACING_MAX_CV {+ // Suggestive layout but the row cadence is too irregular to trust as a+ // clean table — surface as a fenced fallback so the structure is at+ // least preserved.+ let raw: Vec<String> = rows+ .iter()+ .map(|(_, line, _)| line.text.trim_end().to_string())+ .collect();+ return Some(TableRun {+ start: start_idx,+ end,+ block: Block::GridFallback { lines: raw },+ });+ }++ // Promote the first row to header iff every cell in it is bold (matches+ // pymupdf4llm's "bold-or-filled" heuristic; fills require fork data).+ let first_row = &rows[0].2;+ let header_qualifies = first_row.iter().all(|c| c.bold);+ let header = if header_qualifies {+ Some(first_row.iter().map(|c| c.text.clone()).collect())+ } else {+ None+ };+ let row_start = if header.is_some() { 1 } else { 0 };+ let body_rows: Vec<Vec<String>> = rows[row_start..]+ .iter()+ .map(|(_, _, cells)| cells.iter().map(|c| c.text.clone()).collect())+ .collect();+ if header.is_none() && body_rows.len() < TABLE_MIN_ROWS {+ return None;+ }++ Some(TableRun {+ start: start_idx,+ end,+ block: Block::Table {+ header,+ rows: body_rows,+ },+ })+}++/// Scan `lines` once and return all detected tabular regions (sorted by+/// `start`). Caller uses these as cut-points so the per-line classifier never+/// sees lines inside a table.+fn detect_tables(lines: &[ProjectedLine]) -> Vec<TableRun> {+ let mut out = Vec::new();+ let mut i = 0;+ while i < lines.len() {+ if let Some(run) = try_detect_table(lines, i) {+ i = run.end;+ out.push(run);+ } else {+ i += 1;+ }+ }+ out+}++// ── Ruled-grid table detection ─────────────────────────────────────────────+//+// Detect tables drawn with explicit horizontal + vertical rules (the "Strong"+// mode in MARKDOWN_PLAN.md). Strokes are clustered into H/V grid lines, then+// union-find groups crossing lines into table regions. For each region the+// distinct row/column boundaries form a cell grid; text lines are assigned to+// cells by centroid containment.+//+// Ruled tables are detected before the borderless `detect_tables`. The caller+// merges the two outputs; overlapping ranges defer to the ruled run because+// path-based geometry is a strictly stronger signal than text alignment alone.++/// Horizontal segment in viewport coords (top-left origin). `y` is the rule's+/// y-position; `x_min..x_max` is its horizontal span. Endpoints of multiple+/// short segments sharing a y get unioned into one wider segment during+/// clustering.+#[derive(Debug, Clone, Copy)]+struct HSeg {+ x_min: f32,+ x_max: f32,+ y: f32,+}++#[derive(Debug, Clone, Copy)]+struct VSeg {+ y_min: f32,+ y_max: f32,+ x: f32,+}++/// Strokes are considered "axis-aligned" when the perpendicular delta is at+/// most this many points. Generous to absorb antialiased near-pixel strokes.+const TABLE_AXIS_TOLERANCE_PT: f32 = 1.0;++/// Two H lines (or two V lines) are merged into one grid line when their+/// perpendicular coords are within this many points. Slightly looser than the+/// axis tolerance because rules drawn at the same row can have ±1pt jitter+/// from different stroke widths.+const TABLE_GRID_CLUSTER_PT: f32 = 2.0;++/// Slack added when checking whether a V line "crosses" an H line. Helps+/// when rules don't quite reach the corner because the PDF drew them as+/// individual segments with small gaps.+const TABLE_CROSS_TOLERANCE_PT: f32 = 3.0;++/// Reject ruled-table candidates whose empty-cell fraction exceeds this.+const TABLE_MAX_EMPTY_CELL_FRACTION: f32 = 0.30;++/// Reject candidates whose grid covers nearly the whole page — almost always+/// a page border, not a real table.+const TABLE_MAX_PAGE_COVERAGE: f32 = 0.95;++/// Extract horizontal and vertical line segments from a page's graphics. Each+/// `Stroke` becomes one HSeg or VSeg depending on orientation; each stroked+/// `Rect` contributes its four edges (cell-border rects, table frames).+fn extract_h_v_segments(graphics: &[GraphicPrimitive]) -> (Vec<HSeg>, Vec<VSeg>) {+ let mut hs = Vec::new();+ let mut vs = Vec::new();+ for g in graphics {+ match g {+ GraphicPrimitive::Stroke { x1, y1, x2, y2, .. } => {+ let (x1, y1, x2, y2) = (*x1, *y1, *x2, *y2);+ let dy = (y1 - y2).abs();+ let dx = (x1 - x2).abs();+ if dy <= TABLE_AXIS_TOLERANCE_PT && dx > 1.0 {+ hs.push(HSeg {+ x_min: x1.min(x2),+ x_max: x1.max(x2),+ y: (y1 + y2) * 0.5,+ });+ } else if dx <= TABLE_AXIS_TOLERANCE_PT && dy > 1.0 {+ vs.push(VSeg {+ y_min: y1.min(y2),+ y_max: y1.max(y2),+ x: (x1 + x2) * 0.5,+ });+ }+ }+ GraphicPrimitive::Rect { bbox, stroke, .. } => {+ if stroke.is_none() {+ continue;+ }+ let top = bbox.y;+ let bottom = bbox.y + bbox.height;+ let left = bbox.x;+ let right = bbox.x + bbox.width;+ if bbox.width > 1.0 {+ hs.push(HSeg {+ x_min: left,+ x_max: right,+ y: top,+ });+ hs.push(HSeg {+ x_min: left,+ x_max: right,+ y: bottom,+ });+ }+ if bbox.height > 1.0 {+ vs.push(VSeg {+ y_min: top,+ y_max: bottom,+ x: left,+ });+ vs.push(VSeg {+ y_min: top,+ y_max: bottom,+ x: right,+ });+ }+ }+ }+ }+ (hs, vs)+}++/// Cluster H segments sharing a y-coordinate (within `TABLE_GRID_CLUSTER_PT`)+/// into a single wider grid line whose x-extent is the union of the inputs.+fn cluster_h_segments(mut segs: Vec<HSeg>) -> Vec<HSeg> {+ if segs.is_empty() {+ return segs;+ }+ segs.sort_by(|a, b| a.y.total_cmp(&b.y));+ let mut out: Vec<HSeg> = Vec::with_capacity(segs.len());+ for seg in segs {+ if let Some(last) = out.last_mut()+ && (last.y - seg.y).abs() <= TABLE_GRID_CLUSTER_PT+ {+ last.x_min = last.x_min.min(seg.x_min);+ last.x_max = last.x_max.max(seg.x_max);+ continue;+ }+ out.push(seg);+ }+ out+}++fn cluster_v_segments(mut segs: Vec<VSeg>) -> Vec<VSeg> {+ if segs.is_empty() {+ return segs;+ }+ segs.sort_by(|a, b| a.x.total_cmp(&b.x));+ let mut out: Vec<VSeg> = Vec::with_capacity(segs.len());+ for seg in segs {+ if let Some(last) = out.last_mut()+ && (last.x - seg.x).abs() <= TABLE_GRID_CLUSTER_PT+ {+ last.y_min = last.y_min.min(seg.y_min);+ last.y_max = last.y_max.max(seg.y_max);+ continue;+ }+ out.push(seg);+ }+ out+}++/// Union-find root with path compression.+fn uf_find(parent: &mut [usize], mut x: usize) -> usize {+ while parent[x] != x {+ parent[x] = parent[parent[x]];+ x = parent[x];+ }+ x+}++fn uf_union(parent: &mut [usize], a: usize, b: usize) {+ let ra = uf_find(parent, a);+ let rb = uf_find(parent, b);+ if ra != rb {+ parent[ra] = rb;+ }+}++/// Group H/V grid lines that cross each other into connected components.+/// Each component is a candidate ruled table — typically one component per+/// distinct table on the page. Returns `(h_indices, v_indices)` per component,+/// dropping components without ≥2 H and ≥2 V lines (a single L-shape doesn't+/// make a table).+fn find_grid_components(hs: &[HSeg], vs: &[VSeg]) -> Vec<(Vec<usize>, Vec<usize>)> {+ let n_h = hs.len();+ let n_v = vs.len();+ if n_h < 2 || n_v < 2 {+ return Vec::new();+ }+ let n = n_h + n_v;+ let mut parent: Vec<usize> = (0..n).collect();+ let mut connected = vec![false; n];++ let tol = TABLE_CROSS_TOLERANCE_PT;+ for (i, h) in hs.iter().enumerate() {+ for (j, v) in vs.iter().enumerate() {+ let v_crosses_h_x = v.x >= h.x_min - tol && v.x <= h.x_max + tol;+ let h_crosses_v_y = h.y >= v.y_min - tol && h.y <= v.y_max + tol;+ if v_crosses_h_x && h_crosses_v_y {+ uf_union(&mut parent, i, n_h + j);+ connected[i] = true;+ connected[n_h + j] = true;+ }+ }+ }++ use std::collections::HashMap;+ let mut groups: HashMap<usize, (Vec<usize>, Vec<usize>)> = HashMap::new();+ for i in 0..n_h {+ if !connected[i] {+ continue;+ }+ let r = uf_find(&mut parent, i);+ groups.entry(r).or_default().0.push(i);+ }+ for j in 0..n_v {+ if !connected[n_h + j] {+ continue;+ }+ let r = uf_find(&mut parent, n_h + j);+ groups.entry(r).or_default().1.push(j);+ }+ groups+ .into_values()+ .filter(|(h_idx, v_idx)| h_idx.len() >= 2 && v_idx.len() >= 2)+ .collect()+}++/// Build a `TableRun` for one ruled-grid component. Returns `None` if the+/// resulting grid is too small (< 2 cols or < 2 rows), covers nearly the+/// whole page (likely the page border), or is mostly empty cells.+fn build_ruled_table(+ hs: &[HSeg],+ vs: &[VSeg],+ h_indices: &[usize],+ v_indices: &[usize],+ lines: &[ProjectedLine],+ page_width: f32,+ page_height: f32,+) -> Option<TableRun> {+ // Distinct row y-coords (cluster again — multiple H lines may share a y).+ let mut ys: Vec<f32> = h_indices.iter().map(|&i| hs[i].y).collect();+ ys.sort_by(|a, b| a.total_cmp(b));+ dedup_close(&mut ys, TABLE_GRID_CLUSTER_PT);++ let mut xs: Vec<f32> = v_indices.iter().map(|&i| vs[i].x).collect();+ xs.sort_by(|a, b| a.total_cmp(b));+ dedup_close(&mut xs, TABLE_GRID_CLUSTER_PT);++ // Need ≥2 cells per axis → ≥3 boundary lines.+ if ys.len() < 3 || xs.len() < 3 {+ return None;+ }++ let n_rows = ys.len() - 1;+ let n_cols = xs.len() - 1;+ let bbox = crate::types::Rect {+ x: xs[0],+ y: ys[0],+ width: xs[n_cols] - xs[0],+ height: ys[n_rows] - ys[0],+ };++ // Reject page-border-as-table.+ if page_width > 0.0 && page_height > 0.0 {+ let coverage = (bbox.width / page_width) * (bbox.height / page_height);+ if coverage > TABLE_MAX_PAGE_COVERAGE {+ return None;+ }+ }++ // Assign each text line to its cell by centroid.+ let mut cells: Vec<Vec<String>> = vec![vec![String::new(); n_cols]; n_rows];+ let mut cell_is_bold: Vec<Vec<bool>> = vec![vec![true; n_cols]; n_rows];+ let mut cell_has_text: Vec<Vec<bool>> = vec![vec![false; n_cols]; n_rows];+ let mut consumed_indices: Vec<usize> = Vec::new();++ for (idx, line) in lines.iter().enumerate() {+ let cx = line.bbox.x + line.bbox.width * 0.5;+ let cy = line.bbox.y + line.bbox.height * 0.5;+ if cy < ys[0] || cy > ys[n_rows] || cx < xs[0] || cx > xs[n_cols] {+ continue;+ }+ let row = match find_bucket(&ys, cy) {+ Some(r) => r,+ None => continue,+ };+ let col = match find_bucket(&xs, cx) {+ Some(c) => c,+ None => continue,+ };+ let txt = line.text.trim();+ if txt.is_empty() {+ continue;+ }+ if !cells[row][col].is_empty() {+ cells[row][col].push(' ');+ }+ cells[row][col].push_str(txt);+ cell_has_text[row][col] = true;+ if !line.all_bold {+ cell_is_bold[row][col] = false;+ }+ consumed_indices.push(idx);+ }++ if consumed_indices.is_empty() {+ return None;+ }++ let total = n_rows * n_cols;+ let empty_count = cell_has_text+ .iter()+ .flatten()+ .filter(|filled| !**filled)+ .count();+ if (empty_count as f32) / (total as f32) > TABLE_MAX_EMPTY_CELL_FRACTION {+ return None;+ }++ // Header = first row iff every non-empty cell in it is bold.+ let header_qualifies = cell_has_text[0]+ .iter()+ .zip(cell_is_bold[0].iter())+ .all(|(has, bold)| !has || *bold)+ && cell_has_text[0].iter().any(|has| *has);+ let header = if header_qualifies {+ Some(cells[0].clone())+ } else {+ None+ };+ let body_start = if header.is_some() { 1 } else { 0 };+ let body_rows: Vec<Vec<String>> = cells[body_start..].to_vec();+ if body_rows.is_empty() {+ return None;+ }++ // Line index span this table covers.+ let start = *consumed_indices.iter().min().unwrap();+ let end = *consumed_indices.iter().max().unwrap() + 1;++ Some(TableRun {+ start,+ end,+ block: Block::Table {+ header,+ rows: body_rows,+ },+ })+}++/// In-place dedup of a sorted Vec, collapsing entries within `tol` to the+/// first of each cluster.+fn dedup_close(v: &mut Vec<f32>, tol: f32) {+ if v.len() < 2 {+ return;+ }+ let mut out: Vec<f32> = Vec::with_capacity(v.len());+ for x in v.iter().copied() {+ if let Some(&last) = out.last()+ && (x - last).abs() <= tol+ {+ continue;+ }+ out.push(x);+ }+ *v = out;+}++/// Find the bucket index `i` such that `boundaries[i] <= val < boundaries[i+1]`.+/// Returns `None` if `val` is outside the boundaries.+fn find_bucket(boundaries: &[f32], val: f32) -> Option<usize> {+ if boundaries.len() < 2 || val < boundaries[0] || val > *boundaries.last().unwrap() {+ return None;+ }+ for (i, w) in boundaries.windows(2).enumerate() {+ if val >= w[0] && val <= w[1] {+ return Some(i);+ }+ }+ None+}++/// Detect ruled-grid tables on a page from its vector graphics. Returns runs+/// in document order (sorted by `start`).+fn detect_ruled_tables(+ lines: &[ProjectedLine],+ graphics: &[GraphicPrimitive],+ page_width: f32,+ page_height: f32,+) -> Vec<TableRun> {+ let (hs, vs) = extract_h_v_segments(graphics);+ let hs = cluster_h_segments(hs);+ let vs = cluster_v_segments(vs);+ if hs.len() < 2 || vs.len() < 2 {+ return Vec::new();+ }+ let components = find_grid_components(&hs, &vs);+ let mut out = Vec::new();+ for (h_idx, v_idx) in components {+ if let Some(run) =+ build_ruled_table(&hs, &vs, &h_idx, &v_idx, lines, page_width, page_height)+ {+ out.push(run);+ }+ }+ out.sort_by_key(|r| r.start);+ out+}++/// Merge ruled-grid runs with borderless runs into a single sorted list. When+/// ranges overlap the ruled run wins (path-based geometry is strictly stronger+/// than text-alignment heuristics) — overlapping borderless runs are dropped.+fn merge_table_runs(mut ruled: Vec<TableRun>, borderless: Vec<TableRun>) -> Vec<TableRun> {+ for b in borderless {+ let overlaps = ruled+ .iter()+ .any(|r| !(b.end <= r.start || b.start >= r.end));+ if !overlaps {+ ruled.push(b);+ }+ }+ ruled.sort_by_key(|r| r.start);+ ruled+}++/// 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.+fn escape_table_cell(s: &str) -> String {+ s.replace('\\', "\\\\")+ .replace('|', "\\|")+ .replace('\n', " ")+}++/// Tolerance in points for "is this size larger than the body size".+const HEADING_SIZE_EPSILON: f32 = 0.5;++/// Cap on heading levels (matches plan: H1..H6).+const MAX_HEADING_LEVELS: usize = 6;++/// Multiplier on line height used as the paragraph-break threshold.+const PARAGRAPH_GAP_MULTIPLIER: f32 = 1.5;++/// Tolerance for treating two font sizes as "the same" when grouping+/// paragraph lines. Generous because we sometimes derive the "size" from+/// `bbox.height`, which varies a few points line-to-line based on whether+/// the glyphs include descenders (`y`, `g`, `p`).+const FONT_SIZE_PARAGRAPH_TOLERANCE: f32 = 2.5;++/// Tighter tolerance for matching against the heading-size map. Keeps the+/// heading detector strict so descender-induced height jitter doesn't promote+/// regular body lines to headings.+const FONT_SIZE_HEADING_TOLERANCE: f32 = 0.6;++/// Tolerance in points for treating two indent positions as "the same column".+const INDENT_TOLERANCE: f32 = 6.0;++/// Fraction of page height treated as the "top band" for header detection.+/// Most running headers sit within the top 8–12% of a page; 12% gives some+/// slack for two-line headers without sweeping in body text.+const HEADER_BAND_FRACTION: f32 = 0.12;++/// Fraction of page height treated as the "bottom band" for footer detection.+const FOOTER_BAND_FRACTION: f32 = 0.12;++/// Fraction of pages on which a normalized line must appear (in the same+/// band) to be classified as a running header/footer.+const HEADER_FOOTER_MIN_FRACTION: f32 = 0.5;++/// Absolute floor on header/footer matches — single-page docs can't have a+/// "running" header by definition, and a single match on a 2-page doc is too+/// weak to act on.+const HEADER_FOOTER_MIN_PAGES: usize = 2;++/// Roughly one indent step in PDF points. Used to bucket list items into+/// nesting levels relative to the first item of the list.+const LIST_INDENT_STEP_PT: f32 = 12.0;++/// Maximum characters in a "bold body-size heading" candidate. Section+/// headings like "Abstract", "1 Introduction", "2.1 Related Work" are short;+/// a bold body-size line longer than this is almost always a bold *sentence*+/// inside a paragraph, not a heading.+const BOLD_HEADING_MAX_CHARS: usize = 80;++/// Returns true if `line` looks like a section heading rendered in body-size+/// bold text (a very common style for academic / technical PDFs where every+/// "real" heading uses the same font size as body, distinguished only by+/// weight). Requires:+/// - uniformly bold across all spans+/// - short (≤ `BOLD_HEADING_MAX_CHARS`)+/// - paragraph-break gap above (or first line on the page)+/// - paragraph-break gap below (or last line on the page)+fn looks_like_bold_heading(+ line: &ProjectedLine,+ prev: Option<&ProjectedLine>,+ next: Option<&ProjectedLine>,+) -> bool {+ let text = line.text.trim();+ if text.is_empty() || text.chars().count() > BOLD_HEADING_MAX_CHARS {+ return false;+ }+ let style = match line_uniform_style(line) {+ Some(s) => s,+ None => return false,+ };+ if !style.bold || style.mono {+ return false;+ }+ // Reject bold-uniform lines dominated by digits / punctuation — these are+ // almost always cells inside a tabular layout the table detector didn't+ // 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 {+ return false;+ }+ // Reject when the line itself looks tabular: ≥3 cells separated by font-size+ // gaps. A bold body-size line with that many cell tracks is almost always a+ // table header row, not a section heading. Without this guard, multi-line+ // table headers ("Model Method ... | F1 BLEU-1 F1 BLEU-1 ...") get promoted+ // to H3 instead of being absorbed by the table detector.+ // Tabular shape rejection. Two passes because the projection sometimes+ // collapses a wide multi-column line into a single span with column-+ // padding spaces — span-based detection misses those.+ if split_cells(line).len() >= TABLE_MIN_COLUMNS {+ return false;+ }+ // Text-based fallback: ≥3 tokens separated by runs of 2+ spaces (the+ // projection inserts alignment padding between cells) → table header row+ // collapsed into one span, not a section heading.+ let multi_space_tokens = text+ .split(" ")+ .map(|s| s.trim())+ .filter(|s| !s.is_empty())+ .count();+ if multi_space_tokens >= TABLE_MIN_COLUMNS {+ return false;+ }+ let gap_above_ok = match prev {+ None => true,+ Some(p) => !continues_paragraph(p, line),+ };+ if !gap_above_ok {+ return false;+ }+ let gap_below_ok = match next {+ None => true,+ Some(n) => !continues_paragraph(line, n),+ };+ gap_below_ok+}++/// 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] = &['•', '·', '◦', '▪', '▸', '▶', '●', '○', '■', '□'];++/// Detect a list marker at the start of `text`. Returns `(ordered, marker_str,+/// remainder)` when matched; otherwise `None`.+///+/// Recognizes:+/// - Unicode bullet characters (`BULLET_CHARS`) followed by whitespace.+/// - Decimal-prefix markers like `1.` / `1)` / `12.` / `12)` followed by+/// whitespace — kept strict (digits only) so things like footnote callers+/// (`1` alone) and section refs (`A.1`) don't match.+fn parse_list_marker(text: &str) -> Option<(bool, String, &str)> {+ let trimmed = text.trim_start();+ if trimmed.is_empty() {+ return None;+ }++ let mut chars = trimmed.chars();+ let first = chars.next()?;++ // Unicode bullet+ if BULLET_CHARS.contains(&first) {+ let rest = chars.as_str();+ if let Some(rest_trim) = rest.strip_prefix(|c: char| c.is_whitespace()) {+ return Some((false, first.to_string(), rest_trim.trim_start()));+ }+ }++ // Decimal: 1. / 1) / 12. / 12)+ if first.is_ascii_digit() {+ let mut digit_end = 1;+ for c in trimmed[1..].chars() {+ if c.is_ascii_digit() {+ digit_end += c.len_utf8();+ } else {+ break;+ }+ }+ // Cap to keep us from matching page-number-like prefixes+ if digit_end <= 3 {+ let after_digits = &trimmed[digit_end..];+ let mut after_iter = after_digits.chars();+ if let Some(punct) = after_iter.next()+ && (punct == '.' || punct == ')')+ {+ let after_punct = after_iter.as_str();+ if let Some(rest_trim) = after_punct.strip_prefix(|c: char| c.is_whitespace()) {+ let marker = format!("{}{}", &trimmed[..digit_end], punct);+ return Some((true, marker, rest_trim.trim_start()));+ }+ }+ }+ }++ None+}++/// 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+/// histograms so it doesn't compete with normal-flow text for heading slots.+fn is_rotated_line(line: &ProjectedLine) -> bool {+ line.spans.iter().any(|s| {+ let r = s.rotation.abs() % 360.0;+ // Anything more than ~5° off the horizontal axes is "rotated" for+ // our purposes. 0° and 180° are both horizontal text.+ !(r < 5.0 || (175.0..=185.0).contains(&r) || (355.0..=360.0).contains(&r))+ })+}++/// Compute the body font size as the char-weighted mode across all lines in+/// all pages. Rotated lines are excluded so a long rotated sidebar can't+/// pull the body estimate. Falls back to `0.0` when no font-size info is+/// available.+pub fn compute_body_size(pages: &[ParsedPage]) -> f32 {+ use std::collections::HashMap;+ let mut weights: HashMap<u32, (f32, usize)> = HashMap::new();+ for page in pages {+ for line in &page.projected_lines {+ if is_rotated_line(line) {+ continue;+ }+ let size = line.dominant_font_size;+ if size <= 0.0 {+ continue;+ }+ let chars = line.text.chars().count().max(1);+ let key = (size * 100.0).round() as u32;+ let entry = weights.entry(key).or_insert((size, 0));+ entry.1 += chars;+ }+ }+ weights+ .values()+ .max_by_key(|(_, n)| *n)+ .map(|(s, _)| *s)+ .unwrap_or(0.0)+}++/// Minimum total non-whitespace characters across all occurrences at a font+/// size for it to qualify as a heading level. Calibrated against `paper.pdf`:+/// the 30pt chart-legend tokens ("A-mem"×2 + "Base"×2 = 18-20 chars) need to+/// fail this filter, while the 14.35pt title ("A-MEM: Agentic Memory for LLM+/// Agents" = 31 chars on a single line) needs to pass. 25 is the gap. Smaller+/// single-word headings like a lone "Summary" on a short doc still survive+/// because they share their font size with other (larger) headings in the+/// histogram entry.+const MIN_HEADING_TOTAL_CHARS: usize = 25;++/// Maximum average characters per line for a size to qualify as a heading.+/// A "size larger than body" with very long lines is almost always a+/// large-print body block (callouts, footnotes-as-display, intro paragraph),+/// not a real heading.+const MAX_HEADING_AVG_LINE_CHARS: f32 = 200.0;++/// Minimum fraction of non-whitespace chars at a size that must be alphabetic+/// for it to qualify as a heading. Drops sizes dominated by digits (graph+/// axes, results tables, math display) which otherwise pollute the top+/// heading slots.+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.+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))+ let mut sizes: HashMap<u32, (f32, usize, usize, usize)> = HashMap::new();+ for page in pages {+ for line in &page.projected_lines {+ if is_rotated_line(line) {+ continue;+ }+ let size = line.dominant_font_size;+ if size > body_size + HEADING_SIZE_EPSILON {+ let key = (size * 100.0).round() as u32;+ let entry = sizes.entry(key).or_insert((size, 0, 0, 0));+ entry.1 += 1;+ for c in line.text.chars() {+ if c.is_whitespace() {+ continue;+ }+ entry.2 += 1;+ if c.is_alphabetic() {+ entry.3 += 1;+ }+ }+ }+ }+ }+ let all: Vec<(f32, usize, usize, usize)> = sizes.into_values().collect();+ // Always apply quality filters: total-char floor, average-line cap, and+ // alpha-ratio floor. The total-char floor (rather than a line-count one)+ // lets one-off titles survive — a 31-char title on a single line passes —+ // while still rejecting chart-legend tokens like "A-mem" + "Base" that+ // total fewer chars across 4 occurrences than a single heading line does.+ let mut kept: Vec<f32> = all+ .iter()+ .filter(|(_, lines, chars, alpha)| {+ let alpha_ratio = if *chars == 0 {+ 0.0+ } else {+ (*alpha as f32) / (*chars as f32)+ };+ *chars >= MIN_HEADING_TOTAL_CHARS+ && (*chars as f32 / (*lines).max(1) as f32) <= MAX_HEADING_AVG_LINE_CHARS+ && alpha_ratio >= MIN_HEADING_ALPHA_RATIO+ })+ .map(|(s, _, _, _)| *s)+ .collect();+ kept.sort_by(|a, b| b.total_cmp(a));+ kept.truncate(MAX_HEADING_LEVELS);+ kept.into_iter()+ .enumerate()+ .map(|(i, s)| (s, (i + 1) as u8))+ .collect()+}++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 {+ return Some(*level);+ }+ }+ None+}++/// Collapse runs of whitespace into single spaces. The projected text from+/// `projection.rs` pads with column-alignment spaces (e.g. `for instance`)+/// which look fine as a layout grid but are wrong for prose.+fn collapse_whitespace(s: &str) -> String {+ let mut out = String::with_capacity(s.len());+ let mut prev_space = false;+ for c in s.chars() {+ if c.is_whitespace() {+ if !prev_space && !out.is_empty() {+ out.push(' ');+ }+ prev_space = true;+ } else {+ out.push(c);+ prev_space = false;+ }+ }+ if out.ends_with(' ') {+ out.pop();+ }+ 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)]+fn append_paragraph_line(accum: &mut String, next: &str) {+ let next = collapse_whitespace(next);+ if next.is_empty() {+ return;+ }+ if accum.is_empty() {+ accum.push_str(&next);+ 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);+ } else {+ accum.push(' ');+ accum.push_str(&next);+ }+}++/// Decide whether `cur` continues the paragraph started by `prev`.+fn continues_paragraph(prev: &ProjectedLine, cur: &ProjectedLine) -> 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,+ // and treating those as paragraph breaks shreds normal text.+ let centered_mismatch = (prev.anchor == Anchor::Center) ^ (cur.anchor == Anchor::Center);+ if centered_mismatch {+ return false;+ }+ if (prev.dominant_font_size - cur.dominant_font_size).abs() > FONT_SIZE_PARAGRAPH_TOLERANCE {+ return false;+ }+ if prev.region_path != cur.region_path {+ // Cross-region continuation: the same paragraph can wrap from the+ // bottom of one column into the top of the next. Only bridge regions+ // when the previous line clearly breaks mid-sentence (no terminal+ // punctuation) AND the next line starts with a lowercase letter — a+ // strict signal that catches the column-wrap case while rejecting+ // unrelated paragraphs that happen to sit in adjacent leaves.+ let prev_trim = prev.text.trim_end();+ let ends_open = !prev_trim.ends_with(|c: char| {+ matches!(+ c,+ '.' | '!' | '?' | ':' | ';' | '”' | '"' | ')' | ']' | '。' | '』' | '」'+ )+ });+ let starts_lower = cur+ .text+ .trim_start()+ .chars()+ .next()+ .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 {+ // 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.+ if cur.indent_x > prev.indent_x + INDENT_TOLERANCE {+ return false;+ }+ }+ // Vertical gap check.+ let prev_bottom = prev.bbox.y + prev.bbox.height;+ let gap = cur.bbox.y - prev_bottom;+ let line_height = prev.bbox.height.max(cur.bbox.height).max(1.0);+ gap <= line_height * PARAGRAPH_GAP_MULTIPLIER+}++/// Paragraph accumulator state. We track two parallel representations of the+/// running paragraph text:+///+/// - `raw` — plain text (no emphasis markers). Used for the paragraph-uniform+/// shortcut: if every contributing line had the same uniform style, we wrap+/// the whole paragraph once with `wrap_emphasis(raw, …)` to avoid the+/// `**foo** **bar** **baz**` per-line noise pymupdf4llm warns about.+/// - `inline` — per-line markdown with emphasis baked in via+/// `render_line_inline`. Used when the paragraph contains mid-line emphasis+/// shifts or lines with differing uniform styles.+///+/// `uniform` is `Some((bold, italic))` while every line so far has been a+/// uniformly-styled line sharing the same (bold, italic) flags, and `None` as+/// soon as that invariant breaks.+struct ParaAccum {+ raw: String,+ inline: String,+ last: ProjectedLine,+ uniform: Option<(bool, bool)>,+}++/// 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+/// uniform-mono. Used by the paragraph-level optimization to decide whether+/// to wrap once around the whole paragraph or fall back to per-line inline.+fn line_uniform_style(line: &ProjectedLine) -> Option<SpanStyle> {+ let mut iter = line+ .spans+ .iter()+ .filter(|s| !s.text.trim().is_empty())+ .map(SpanStyle::from_item);+ let first = iter.next()?;+ for s in iter {+ if s != first {+ return None;+ }+ }+ Some(first)+}++/// Append `next_line` to a paragraph accumulator. Maintains both the `raw` and+/// `inline` text representations and updates the running `uniform` flag.+/// De-hyphenation runs on the `raw` boundary; the `inline` boundary mirrors it+/// when the trailing char is still a literal `-` (i.e. the hyphen sits outside+/// any emphasis wrap — the common case).+fn append_to_paragraph(accum: &mut ParaAccum, next_line: &ProjectedLine) {+ let next_raw = collapse_whitespace(next_line.text.trim());+ if next_raw.is_empty() {+ return;+ }+ let next_inline = render_line_inline(next_line);+ let next_uniform = line_uniform_style(next_line);++ if accum.raw.is_empty() {+ accum.raw.push_str(&next_raw);+ accum.inline.push_str(&next_inline);+ accum.uniform = next_uniform.map(|s| (s.bold, s.italic));+ accum.last = next_line.clone();+ return;+ }++ 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);+ }++ // Maintain the running uniform-style flag.+ accum.uniform = match (accum.uniform, next_uniform) {+ (Some(cur), Some(s)) if cur == (s.bold, s.italic) => Some(cur),+ _ => None,+ };+ accum.last = next_line.clone();+}++/// Resolve a `ParaAccum` to a `Block::Paragraph`. When the paragraph was+/// uniformly styled across all lines, return the raw text with block-level+/// `bold`/`italic` flags set so the renderer wraps it once. Otherwise return+/// the per-line inline-styled text with the flags cleared.+fn paragraph_from_accum(accum: ParaAccum) -> Block {+ match accum.uniform {+ Some((bold, italic)) if bold || italic => Block::Paragraph {+ text: escape_inline(&accum.raw),+ bold,+ italic,+ },+ Some(_) => Block::Paragraph {+ // Uniformly plain — no emphasis markers anywhere, so the raw text+ // (with markdown specials escaped) is the right rendering.+ text: escape_inline(&accum.raw),+ bold: false,+ italic: false,+ },+ None => Block::Paragraph {+ text: accum.inline,+ bold: false,+ italic: false,+ },+ }+}++/// Normalize a line for cross-page header/footer matching. Lowercases,+/// collapses whitespace, and replaces every run of ASCII digits with `#` so+/// `Page 1 of 6` and `Page 2 of 6` collapse to the same key.+fn normalize_for_repetition(s: &str) -> String {+ let collapsed = collapse_whitespace(s).to_lowercase();+ let mut out = String::with_capacity(collapsed.len());+ let mut in_digits = false;+ for c in collapsed.chars() {+ if c.is_ascii_digit() {+ if !in_digits {+ out.push('#');+ in_digits = true;+ }+ } else {+ out.push(c);+ in_digits = false;+ }+ }+ out+}++/// Cross-page repetition detector. Returns the set of normalized strings that+/// appear in the top or bottom band of ≥ `HEADER_FOOTER_MIN_FRACTION` of+/// pages (capped below by `HEADER_FOOTER_MIN_PAGES`). The caller uses this to+/// filter `ProjectedLine`s before classification.+///+/// "Same band" means a line whose top is within `HEADER_BAND_FRACTION` of the+/// page top (header) or whose bottom is within `FOOTER_BAND_FRACTION` of the+/// page bottom (footer). Header and footer bands are tracked separately so a+/// company name that appears as both a header and a body-section title on+/// different pages isn't stripped from the body.+pub fn compute_header_footer_set(pages: &[ParsedPage]) -> std::collections::HashSet<String> {+ use std::collections::{HashMap, HashSet};+ let mut set: HashSet<String> = HashSet::new();+ if pages.len() < HEADER_FOOTER_MIN_PAGES {+ return set;+ }+ // Two counters keyed by `(band, normalized_text)` — band is `'h'` or `'f'`.+ let mut counts: HashMap<(char, String), HashSet<usize>> = HashMap::new();+ for page in pages {+ let header_cutoff = page.page_height * HEADER_BAND_FRACTION;+ let footer_cutoff = page.page_height * (1.0 - FOOTER_BAND_FRACTION);+ for line in &page.projected_lines {+ let text = line.text.trim();+ if text.is_empty() {+ continue;+ }+ let norm = normalize_for_repetition(text);+ if norm.is_empty() {+ continue;+ }+ // Header band: top of line within the top band.+ if line.bbox.y <= header_cutoff {+ counts+ .entry(('h', norm.clone()))+ .or_default()+ .insert(page.page_number);+ }+ // Footer band: bottom of line at or below the footer cutoff.+ let line_bottom = line.bbox.y + line.bbox.height;+ if line_bottom >= footer_cutoff {+ counts+ .entry(('f', norm))+ .or_default()+ .insert(page.page_number);+ }+ }+ }+ let threshold = (pages.len() as f32 * HEADER_FOOTER_MIN_FRACTION)+ .ceil()+ .max(HEADER_FOOTER_MIN_PAGES as f32) as usize;+ for ((_, norm), pages_seen) in counts {+ if pages_seen.len() >= threshold {+ set.insert(norm);+ }+ }+ set+}++/// Returns true if `line` (located on `page`) matches the running+/// header/footer set: the line sits in the top or bottom band AND its+/// normalized text is in `header_footer`.+fn is_header_or_footer(+ line: &ProjectedLine,+ page: &ParsedPage,+ header_footer: &std::collections::HashSet<String>,+) -> bool {+ if header_footer.is_empty() {+ return false;+ }+ let header_cutoff = page.page_height * HEADER_BAND_FRACTION;+ let footer_cutoff = page.page_height * (1.0 - FOOTER_BAND_FRACTION);+ let in_band = line.bbox.y <= header_cutoff || line.bbox.y + line.bbox.height >= footer_cutoff;+ if !in_band {+ return false;+ }+ let norm = normalize_for_repetition(line.text.trim());+ header_footer.contains(&norm)+}++/// Classify a single page's `ProjectedLine`s into blocks.+pub fn classify_page(page: &ParsedPage, heading_map: &[(f32, u8)]) -> Vec<Block> {+ classify_page_with_filters(page, heading_map, &std::collections::HashSet::new())+}++/// Same as `classify_page` but also strips lines matching a precomputed+/// running header/footer set. Use this when emitting a whole document so+/// repeating chrome (titles, page numbers) doesn't show up in every page.+pub fn classify_page_with_filters(+ page: &ParsedPage,+ heading_map: &[(f32, u8)],+ header_footer: &std::collections::HashSet<String>,+) -> Vec<Block> {+ let mut blocks: Vec<Block> = Vec::new();+ let mut paragraph: Option<ParaAccum> = None;+ // Active fenced code block being accumulated (consecutive `all_mono` lines).+ let mut code: Option<Vec<String>> = None;+ // Tracks the "level 0" indent of the current contiguous list run so we can+ // bucket deeper items into nesting levels. Reset whenever a non-list block+ // breaks the run.+ let mut list_base_indent: Option<f32> = None;+ // 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;++ let flush_paragraph = |blocks: &mut Vec<Block>, p: Option<ParaAccum>| {+ if let Some(acc) = p+ && !acc.raw.trim().is_empty()+ {+ blocks.push(paragraph_from_accum(acc));+ }+ };+ let flush_code = |blocks: &mut Vec<Block>, c: Option<Vec<String>>| {+ if let Some(lines) = c+ && !lines.is_empty()+ {+ blocks.push(Block::CodeBlock { lines });+ }+ };++ let debug = std::env::var("LITEPARSE_DEBUG_MD").is_ok();++ // Strip running header/footer lines up-front so they don't leak into+ // table detection (a repeating two-column footer would otherwise look+ // like a 2-row table) or paragraph grouping.+ let filtered_owned: Vec<ProjectedLine> = if header_footer.is_empty() {+ Vec::new()+ } else {+ page.projected_lines+ .iter()+ .filter(|l| !is_header_or_footer(l, page, header_footer))+ .cloned()+ .collect()+ };+ let lines: &[ProjectedLine] = if header_footer.is_empty() {+ &page.projected_lines+ } else {+ &filtered_owned+ };++ // Pre-pass: detect tabular regions so the per-line classifier below can+ // skip over them. Tables take priority over heading / paragraph / list+ // classification because a row of bold short cells would otherwise be+ // misread as a heading or list item.+ //+ // Two detectors run in sequence: ruled-grid (path-based, strongest signal)+ // and the borderless column-alignment fallback. Where ranges overlap, the+ // ruled output wins.+ let ruled_runs = detect_ruled_tables(lines, &page.graphics, page.page_width, page.page_height);+ let borderless_runs = detect_tables(lines);+ let table_runs = merge_table_runs(ruled_runs, borderless_runs);++ // Suppress HRs that fall inside a detected table's y-range — they're the+ // table's own row dividers, not document-level section breaks. Build the+ // y-extents once before we move table_runs into the iterator.+ // Extend each table's HR-suppression band upward to cover any+ // header/sub-header rows we didn't absorb into the table. The expansion+ // is a few row heights — large enough to catch a 2–3 line bold/italic+ // header sitting just above the table, small enough not to swallow a+ // real section divider belonging to a different block. The downward+ // edge gets a small slack to catch HRs drawn flush with the last row.+ const TABLE_HR_SUPPRESS_HEADROOM_ROWS: f32 = 4.0;+ let table_y_extents: Vec<(f32, f32)> = table_runs+ .iter()+ .map(|run| {+ let top_line = &lines[run.start];+ let row_h = top_line.bbox.height.max(8.0);+ let top = top_line.bbox.y - row_h * TABLE_HR_SUPPRESS_HEADROOM_ROWS;+ let last = &lines[run.end.saturating_sub(1).max(run.start)];+ let bot = last.bbox.y + last.bbox.height;+ (top, bot)+ })+ .collect();++ 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)+ .into_iter()+ .filter(|y| {+ !table_y_extents+ .iter()+ .any(|(top, bot)| *y >= *top - 2.0 && *y <= *bot + 2.0)+ })+ .collect();+ let mut hr_iter = hr_ys.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;+ }+ 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);+ }+ };++ let mut idx = 0;+ while idx < lines.len() {+ if let Some(run) = table_iter.peek()+ && run.start == idx+ {+ // Flush any HRs 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,+ );+ flush_paragraph(&mut blocks, paragraph.take());+ flush_code(&mut blocks, code.take());+ list_base_indent = None;+ last_list_item_idx = None;+ last_list_line = None;+ let run = table_iter.next().unwrap();+ blocks.push(run.block);+ 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,+ );+ idx += 1;+ let text = line.text.trim();+ if text.is_empty() {+ continue;+ }+ // 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) {+ continue;+ }+ if debug {+ eprintln!(+ "[md] y={:.1} h={:.1} size={:.2} anchor={:?} indent={:.1} text={:?}",+ line.bbox.y,+ line.bbox.height,+ line.dominant_font_size,+ line.anchor,+ line.indent_x,+ text+ );+ }++ // Code block detection runs first so a mono heading-shaped line+ // (rare but plausible — e.g., a code identifier in a large mono font)+ // still becomes code. Mono content also wouldn't make a useful+ // heading.+ if line.all_mono {+ flush_paragraph(&mut blocks, paragraph.take());+ list_base_indent = None;+ last_list_item_idx = None;+ last_list_line = None;+ code.get_or_insert_with(Vec::new)+ .push(line.text.trim_end().to_string());+ continue;+ }+ // Any non-mono line ends the current code block (if any).+ flush_code(&mut blocks, code.take());++ if let Some(level) = heading_level_for(line.dominant_font_size, heading_map) {+ flush_paragraph(&mut blocks, paragraph.take());+ list_base_indent = None;+ last_list_item_idx = None;+ last_list_line = None;+ blocks.push(Block::Heading {+ level,+ text: collapse_whitespace(text),+ });+ continue;+ }++ // List item?+ if let Some((ordered, marker, rest)) = parse_list_marker(text) {+ flush_paragraph(&mut blocks, paragraph.take());+ let base = *list_base_indent.get_or_insert(line.indent_x);+ let level = (((line.indent_x - base) / LIST_INDENT_STEP_PT)+ .round()+ .max(0.0)) as u8;+ last_list_item_idx = Some(blocks.len());+ last_list_line = Some(line.clone());+ // 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`,+ // which still contain the marker span — render the line and then+ // peel the marker off the front of the rendered string.+ let item_text = render_list_item_text(line, &marker, rest);+ blocks.push(Block::ListItem {+ ordered,+ marker,+ level,+ text: item_text,+ bold: false,+ italic: false,+ });+ 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.+ if let Some(idx) = last_list_item_idx+ && let Some(prev_line) = last_list_line.as_ref()+ && continues_paragraph(prev_line, line)+ && let Some(Block::ListItem {+ text: prev_text, ..+ }) = blocks.get_mut(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());+ continue;+ }++ // Bold body-size heading. Section headings in academic / technical+ // PDFs are routinely body-sized + bold (e.g. "Abstract",+ // "1 Introduction"); without this rule they look just like a bold+ // first sentence of a paragraph. Runs after list-marker detection so+ // bold bullet items stay as list items.+ let prev_for_gap = paragraph+ .as_ref()+ .map(|p| &p.last)+ .or(last_list_line.as_ref());+ let next_for_gap = lines.get(idx);+ if looks_like_bold_heading(line, prev_for_gap, next_for_gap) {+ flush_paragraph(&mut blocks, paragraph.take());+ list_base_indent = None;+ last_list_item_idx = None;+ last_list_line = None;+ // Level: one deeper than the deepest size-based level we already+ // have. With an empty heading_map this lands on H1; with a full+ // 6-level map it caps at H6.+ let level = (heading_map.len() as u8 + 1).clamp(1, MAX_HEADING_LEVELS as u8);+ blocks.push(Block::Heading {+ level,+ text: collapse_whitespace(text),+ });+ continue;+ }++ match paragraph.as_mut() {+ Some(acc) if continues_paragraph(&acc.last, line) => {+ append_to_paragraph(acc, line);+ }+ _ => {+ flush_paragraph(&mut blocks, paragraph.take());+ list_base_indent = None;+ last_list_item_idx = None;+ last_list_line = None;+ let inline = render_line_inline(line);+ let raw = collapse_whitespace(text);+ let uniform = line_uniform_style(line).map(|s| (s.bold, s.italic));+ paragraph = Some(ParaAccum {+ raw,+ inline,+ last: line.clone(),+ uniform,+ });+ }+ }+ }++ flush_paragraph(&mut blocks, paragraph.take());+ flush_code(&mut blocks, code.take());+ // Flush any trailing HRs 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,+ );+ blocks+}++/// Wrap `text` in markdown emphasis markers based on `bold`/`italic`. Both →+/// `***text***`. Headings deliberately skip this (the `#` is the emphasis).+fn wrap_emphasis(text: &str, bold: bool, italic: bool) -> String {+ if text.trim().is_empty() {+ return text.to_string();+ }+ match (bold, italic) {+ (true, true) => format!("***{text}***"),+ (true, false) => format!("**{text}**"),+ (false, true) => format!("*{text}*"),+ (false, false) => text.to_string(),+ }+}++/// Render a list of blocks to a markdown string.+pub fn render_blocks(blocks: &[Block]) -> String {+ let mut out = String::new();+ for (i, block) in blocks.iter().enumerate() {+ if i > 0 {+ // Consecutive list items render as a tight list (single newline).+ // Everything else gets a blank line between blocks.+ let tight = matches!(block, Block::ListItem { .. })+ && matches!(blocks[i - 1], Block::ListItem { .. });+ if tight {+ out.push('\n');+ } else {+ out.push_str("\n\n");+ }+ }+ match block {+ Block::Heading { level, text } => {+ let level = (*level).clamp(1, 6) as usize;+ out.push_str(&"#".repeat(level));+ out.push(' ');+ out.push_str(text);+ }+ Block::Paragraph { text, bold, italic } => {+ out.push_str(&wrap_emphasis(text, *bold, *italic));+ }+ Block::ListItem {+ ordered,+ marker,+ level,+ text,+ bold,+ italic,+ } => {+ let indent = " ".repeat((*level).min(6) as usize);+ out.push_str(&indent);+ if *ordered {+ // Preserve the original marker (e.g. `138.` for footnotes+ // or `iii)` for roman numerals) so semantic numbering+ // survives the round-trip. CommonMark requires `1.` /+ // `1)` style but most LLM consumers tolerate alt forms,+ // and the alternative — renumbering as `1.` — drops info.+ out.push_str(marker);+ out.push(' ');+ } else {+ out.push_str("- ");+ }+ out.push_str(&wrap_emphasis(text, *bold, *italic));+ }+ Block::Table { header, rows } => {+ let column_count = header+ .as_ref()+ .map(|h| h.len())+ .or_else(|| rows.first().map(|r| r.len()))+ .unwrap_or(0);+ if column_count == 0 {+ continue;+ }+ if let Some(h) = header {+ out.push_str("| ");+ for (i, cell) in h.iter().enumerate() {+ if i > 0 {+ out.push_str(" | ");+ }+ out.push_str(&escape_table_cell(cell));+ }+ out.push_str(" |\n");+ } else {+ // 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("|");+ for _ in 0..column_count {+ out.push_str(" |");+ }+ out.push('\n');+ }+ out.push('|');+ for _ in 0..column_count {+ out.push_str("---|");+ }+ for row in rows {+ out.push_str("\n| ");+ for (i, cell) in row.iter().enumerate() {+ if i > 0 {+ out.push_str(" | ");+ }+ out.push_str(&escape_table_cell(cell));+ }+ out.push_str(" |");+ }+ }+ Block::GridFallback { lines } => {+ out.push_str("```text\n");+ for line in lines {+ out.push_str(line);+ out.push('\n');+ }+ out.push_str("```");+ }+ Block::CodeBlock { lines } => {+ // Pick a fence that doesn't appear inside the body. Standard+ // triple-backtick handles ~all real-world code; bump to ~~~ if+ // the body itself contains ``` (rare).+ let fence = if lines.iter().any(|l| l.contains("```")) {+ "~~~"+ } else {+ "```"+ };+ out.push_str(fence);+ out.push('\n');+ for line in lines {+ out.push_str(line);+ out.push('\n');+ }+ out.push_str(fence);+ }+ Block::HorizontalRule => {+ out.push_str("---");+ }+ Block::Blank => {}+ }+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::types::{Rect, TextItem};++ fn line(text: &str, x: f32, y: f32, h: f32, size: f32) -> ProjectedLine {+ ProjectedLine {+ text: text.into(),+ bbox: Rect {+ x,+ y,+ width: text.chars().count() as f32 * (size * 0.5),+ height: h,+ },+ anchor: Anchor::Left,+ indent_x: x,+ dominant_font_size: size,+ dominant_font_name: Some("Arial".into()),+ all_bold: false,+ all_italic: false,+ all_mono: false,+ all_strike: false,+ spans: vec![TextItem::default()],+ region_path: Vec::new(),+ mcid: None,+ }+ }++ fn page(lines: Vec<ProjectedLine>) -> ParsedPage {+ ParsedPage {+ page_number: 1,+ page_width: 612.0,+ page_height: 792.0,+ text: String::new(),+ text_items: vec![],+ projected_lines: lines,+ regions: crate::types::Region::default(),+ graphics: vec![],+ figures: vec![],+ }+ }++ #[test]+ fn body_size_picks_most_common() {+ let pages = vec![page(vec![+ line("Title", 50.0, 50.0, 18.0, 18.0),+ line("body line one", 50.0, 80.0, 10.0, 10.0),+ line("body line two", 50.0, 92.0, 10.0, 10.0),+ line("body line three", 50.0, 104.0, 10.0, 10.0),+ ])];+ let body = compute_body_size(&pages);+ assert!((body - 10.0).abs() < 0.01, "body size = {body}");+ }++ #[test]+ fn heading_map_descending_levels() {+ // Heading text needs to clear `MIN_HEADING_TOTAL_CHARS` (25) 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),+ line("A smaller heading right below it", 50.0, 80.0, 18.0, 18.0),+ // Several lines of body so it beats the heading text in the+ // char-weighted body-size mode.+ line(+ "body text line one with plenty of content",+ 50.0,+ 110.0,+ 10.0,+ 10.0,+ ),+ line(+ "body text line two with plenty of content",+ 50.0,+ 122.0,+ 10.0,+ 10.0,+ ),+ line(+ "body text line three with even more content",+ 50.0,+ 134.0,+ 10.0,+ 10.0,+ ),+ line(+ "body text line four with even more content",+ 50.0,+ 146.0,+ 10.0,+ 10.0,+ ),+ ])];+ let body = compute_body_size(&pages);+ let map = build_heading_map(&pages, body);+ assert_eq!(map.len(), 2);+ assert_eq!(map[0].1, 1);+ assert_eq!(map[1].1, 2);+ assert!(map[0].0 > map[1].0);+ }++ #[test]+ fn classify_emits_heading_and_paragraph() {+ let p = page(vec![+ line("Title of the document goes here", 50.0, 50.0, 18.0, 18.0),+ line("First sentence of the para-", 50.0, 80.0, 10.0, 10.0),+ line("graph continues here.", 50.0, 92.0, 10.0, 10.0),+ line("Another paragraph.", 50.0, 130.0, 10.0, 10.0),+ ]);+ let pages = vec![p];+ let body = compute_body_size(&pages);+ let map = build_heading_map(&pages, body);+ let blocks = classify_page(&pages[0], &map);+ assert_eq!(blocks.len(), 3);+ match &blocks[0] {+ Block::Heading { level, text } => {+ assert_eq!(*level, 1);+ assert_eq!(text, "Title of the document goes here");+ }+ other => panic!("expected heading, got {other:?}"),+ }+ match &blocks[1] {+ Block::Paragraph { text: t, .. } => {+ assert!(t.contains("paragraph continues"), "got: {t}");+ assert!(!t.contains("para-"), "de-hyphenation failed: {t}");+ }+ other => panic!("expected paragraph, got {other:?}"),+ }+ match &blocks[2] {+ Block::Paragraph { text: t, .. } => assert_eq!(t, "Another paragraph."),+ other => panic!("expected paragraph, got {other:?}"),+ }+ }++ #[test]+ fn paragraph_break_on_big_gap() {+ let p = page(vec![+ line("Line A.", 50.0, 80.0, 10.0, 10.0),+ line("Line B.", 50.0, 200.0, 10.0, 10.0),+ ]);+ let pages = vec![p];+ let body = compute_body_size(&pages);+ let map = build_heading_map(&pages, body);+ let blocks = classify_page(&pages[0], &map);+ assert_eq!(blocks.len(), 2);+ }++ #[test]+ fn render_blocks_formats_markdown() {+ let blocks = vec![+ Block::Heading {+ level: 1,+ text: "Title".into(),+ },+ Block::Paragraph {+ text: "A paragraph.".into(),+ bold: false,+ italic: false,+ },+ Block::Heading {+ level: 2,+ text: "Sub".into(),+ },+ ];+ let s = render_blocks(&blocks);+ assert_eq!(s, "# Title\n\nA paragraph.\n\n## Sub");+ }++ #[test]+ fn parse_list_marker_bullets() {+ let (ordered, marker, rest) = parse_list_marker("• item one").unwrap();+ assert!(!ordered);+ assert_eq!(marker, "•");+ assert_eq!(rest, "item one");+ }++ #[test]+ fn parse_list_marker_decimal() {+ let (ordered, marker, rest) = parse_list_marker("1. first").unwrap();+ assert!(ordered);+ assert_eq!(marker, "1.");+ assert_eq!(rest, "first");++ let (ordered, marker, rest) = parse_list_marker("12) twelfth").unwrap();+ assert!(ordered);+ assert_eq!(marker, "12)");+ assert_eq!(rest, "twelfth");+ }++ #[test]+ fn parse_list_marker_rejects_prose() {+ assert!(parse_list_marker("This sentence.").is_none());+ // Bare digit with no terminator → not a list+ assert!(parse_list_marker("2023 was a year").is_none());+ // Footnote caller / page number style — no whitespace after+ assert!(parse_list_marker("1.5x growth").is_none());+ }++ #[test]+ fn classify_emits_list_items() {+ let p = page(vec![+ line("Intro line.", 50.0, 50.0, 10.0, 10.0),+ line("• first bullet", 60.0, 80.0, 10.0, 10.0),+ line("• second bullet", 60.0, 92.0, 10.0, 10.0),+ line("◦ nested item", 72.0, 104.0, 10.0, 10.0),+ line("• back to top", 60.0, 116.0, 10.0, 10.0),+ ]);+ let pages = vec![p];+ let body = compute_body_size(&pages);+ let map = build_heading_map(&pages, body);+ let blocks = classify_page(&pages[0], &map);+ let list_items: Vec<&Block> = blocks+ .iter()+ .filter(|b| matches!(b, Block::ListItem { .. }))+ .collect();+ assert_eq!(list_items.len(), 4);+ if let Block::ListItem { level, text, .. } = list_items[0] {+ assert_eq!(*level, 0);+ assert_eq!(text, "first bullet");+ } else {+ panic!();+ }+ // The "- nested item" line is indented +12pt from the base bullet.+ if let Block::ListItem { level, .. } = list_items[2] {+ assert_eq!(*level, 1);+ } else {+ panic!();+ }+ }++ #[test]+ fn render_lists_are_tight() {+ let blocks = vec![+ Block::Paragraph {+ text: "Intro.".into(),+ bold: false,+ italic: false,+ },+ Block::ListItem {+ ordered: false,+ marker: "•".into(),+ level: 0,+ text: "a".into(),+ bold: false,+ italic: false,+ },+ Block::ListItem {+ ordered: false,+ marker: "•".into(),+ level: 0,+ text: "b".into(),+ bold: false,+ italic: false,+ },+ Block::Paragraph {+ text: "Outro.".into(),+ bold: false,+ italic: false,+ },+ ];+ let s = render_blocks(&blocks);+ assert_eq!(s, "Intro.\n\n- a\n- b\n\nOutro.");++ // Ordered: original marker preserved+ let s = render_blocks(&[+ Block::ListItem {+ ordered: true,+ marker: "138.".into(),+ level: 0,+ text: "footnote".into(),+ bold: false,+ italic: false,+ },+ Block::ListItem {+ ordered: true,+ marker: "139.".into(),+ level: 0,+ text: "next footnote".into(),+ bold: false,+ italic: false,+ },+ ]);+ assert_eq!(s, "138. footnote\n139. next footnote");+ }++ fn mono_line(text: &str, y: f32) -> ProjectedLine {+ let mut l = line(text, 50.0, y, 10.0, 10.0);+ l.all_mono = true;+ l+ }++ #[test]+ fn classify_emits_code_block() {+ let p = page(vec![+ line("Intro line.", 50.0, 50.0, 10.0, 10.0),+ mono_line(" let x = 1;", 80.0),+ mono_line(" let y = x + 2;", 92.0),+ line("After the code.", 50.0, 120.0, 10.0, 10.0),+ ]);+ let pages = vec![p];+ let body = compute_body_size(&pages);+ let map = build_heading_map(&pages, body);+ let blocks = classify_page(&pages[0], &map);+ // Expect: Paragraph("Intro line."), CodeBlock(2 lines), Paragraph("After...")+ assert_eq!(blocks.len(), 3);+ match &blocks[1] {+ Block::CodeBlock { lines } => {+ assert_eq!(lines.len(), 2);+ assert!(lines[0].contains("let x = 1;"));+ assert!(lines[1].contains("let y = x + 2;"));+ }+ other => panic!("expected code block, got {other:?}"),+ }+ let s = render_blocks(&blocks);+ assert!(s.contains("```\n let x = 1;"));+ assert!(s.ends_with("After the code."));+ }++ #[test]+ fn classify_marks_paragraph_bold_when_all_lines_bold() {+ let mut a = line("Bold line one.", 50.0, 50.0, 10.0, 10.0);+ let mut b = line("bold continuation.", 50.0, 62.0, 10.0, 10.0);+ // Mark the underlying spans as bold so per-span style detection sees+ // it — the new inline pipeline reads from `spans`, not the per-line+ // `all_bold` shortcut flag.+ let bold_span = TextItem {+ text: "x".into(),+ font_name: Some("Arial-Bold".into()),+ ..Default::default()+ };+ a.spans = vec![bold_span.clone()];+ b.spans = vec![bold_span];+ a.all_bold = true;+ b.all_bold = true;+ let p = page(vec![a, b]);+ let pages = vec![p];+ let body = compute_body_size(&pages);+ let map = build_heading_map(&pages, body);+ let blocks = classify_page(&pages[0], &map);+ assert_eq!(blocks.len(), 1);+ match &blocks[0] {+ Block::Paragraph { bold, italic, .. } => {+ assert!(*bold);+ assert!(!*italic);+ }+ other => panic!("expected paragraph, got {other:?}"),+ }+ let s = render_blocks(&blocks);+ assert!(s.starts_with("**") && s.ends_with("**"), "got: {s}");+ }++ #[test]+ fn render_emphasis_combinations() {+ assert_eq!(wrap_emphasis("hi", false, false), "hi");+ assert_eq!(wrap_emphasis("hi", true, false), "**hi**");+ assert_eq!(wrap_emphasis("hi", false, true), "*hi*");+ assert_eq!(wrap_emphasis("hi", true, true), "***hi***");+ }++ #[test]+ fn code_block_escapes_internal_fence() {+ let blocks = vec![Block::CodeBlock {+ lines: vec!["body containing ``` backticks".into()],+ }];+ let s = render_blocks(&blocks);+ assert!(s.starts_with("~~~\n"));+ assert!(s.ends_with("~~~"));+ }++ /// Build a line whose spans are placed at explicit x positions — used to+ /// drive the table detector, which relies on per-span x for cell splitting.+ fn line_with_spans(cells: &[(&str, f32)], y: f32, size: f32) -> ProjectedLine {+ let spans: Vec<TextItem> = cells+ .iter()+ .map(|(t, x)| TextItem {+ text: (*t).into(),+ x: *x,+ y,+ width: t.chars().count() as f32 * size * 0.5,+ height: size,+ font_size: Some(size),+ font_name: Some("Arial".into()),+ ..Default::default()+ })+ .collect();+ let min_x = spans.iter().map(|s| s.x).fold(f32::INFINITY, f32::min);+ let max_x = spans+ .iter()+ .map(|s| s.x + s.width)+ .fold(f32::NEG_INFINITY, f32::max);+ ProjectedLine {+ text: cells+ .iter()+ .map(|(t, _)| *t)+ .collect::<Vec<_>>()+ .join(" "),+ bbox: Rect {+ x: min_x,+ y,+ width: (max_x - min_x).max(0.0),+ height: size,+ },+ anchor: Anchor::Left,+ indent_x: min_x,+ dominant_font_size: size,+ dominant_font_name: Some("Arial".into()),+ all_bold: false,+ all_italic: false,+ all_mono: false,+ all_strike: false,+ spans,+ region_path: Vec::new(),+ mcid: None,+ }+ }++ #[test]+ fn split_cells_splits_on_wide_gaps() {+ let l = line_with_spans(&[("A", 50.0), ("B", 150.0), ("C", 250.0)], 100.0, 10.0);+ let cells = split_cells(&l);+ assert_eq!(cells.len(), 3);+ assert_eq!(cells[0].text, "A");+ assert_eq!(cells[1].text, "B");+ assert_eq!(cells[2].text, "C");+ }++ #[test]+ fn recover_merged_cell_splits_off_by_one() {+ // Mimics the page-6 case: row 0 establishes 3 tracks at 50/150/250.+ // Row 1's projection merges "MEMORYBANK" + "5.00" into one span at+ // x=50 width=110, so split_cells yields 2 cells while the table+ // expects 3. Recovery must split on whitespace at the missing track.+ let row = vec![+ TableCell {+ start_x: 50.0,+ end_x: 160.0,+ text: "MEMORYBANK 5.00".into(),+ bold: false,+ },+ TableCell {+ start_x: 250.0,+ end_x: 280.0,+ text: "4.77".into(),+ bold: false,+ },+ ];+ let tracks = vec![50.0, 150.0, 250.0];+ let out = recover_merged_cell(row, &tracks).expect("recovery should succeed");+ assert_eq!(out.len(), 3);+ assert_eq!(out[0].text, "MEMORYBANK");+ assert_eq!(out[1].text, "5.00");+ assert_eq!(out[2].text, "4.77");+ }++ #[test]+ fn recover_merged_cell_splits_off_by_two() {+ // Three merged tokens in one cell: "MEMORYBANK 13.18 10.03" straddles+ // tracks at 50/150/250 and the row has only 2 cells, off by 2.+ let row = vec![+ TableCell {+ start_x: 50.0,+ end_x: 260.0,+ text: "MEMORYBANK 13.18 10.03".into(),+ bold: false,+ },+ TableCell {+ start_x: 350.0,+ end_x: 380.0,+ text: "7.61".into(),+ bold: false,+ },+ ];+ let tracks = vec![50.0, 150.0, 250.0, 350.0];+ let out = recover_merged_cell(row, &tracks).expect("recovery should succeed");+ assert_eq!(out.len(), 4);+ assert_eq!(out[0].text, "MEMORYBANK");+ assert_eq!(out[1].text, "13.18");+ assert_eq!(out[2].text, "10.03");+ assert_eq!(out[3].text, "7.61");+ }++ #[test]+ fn recover_merged_cell_bails_without_enough_whitespace() {+ // A cell that straddles two tracks but has no internal whitespace+ // (e.g. a hyphenated token) can't be safely split — return None.+ let row = vec![TableCell {+ start_x: 50.0,+ end_x: 200.0,+ text: "ABC-DEF-GHI".into(),+ bold: false,+ }];+ let tracks = vec![50.0, 150.0];+ assert!(recover_merged_cell(row, &tracks).is_none());+ }++ #[test]+ fn split_cells_keeps_close_spans_together() {+ // Two spans 2pt apart at 10pt font (gap < font_size) → same cell.+ let l = line_with_spans(&[("Hello", 50.0), ("world", 80.0)], 100.0, 10.0);+ let cells = split_cells(&l);+ assert_eq!(cells.len(), 1);+ assert_eq!(cells[0].text, "Hello world");+ }++ #[test]+ fn detects_simple_borderless_table() {+ let lines = vec![+ line_with_spans(+ &[("Name", 50.0), ("Age", 150.0), ("City", 250.0)],+ 100.0,+ 10.0,+ ),+ line_with_spans(+ &[("Alice", 50.0), ("30", 150.0), ("NYC", 250.0)],+ 115.0,+ 10.0,+ ),+ line_with_spans(&[("Bob", 50.0), ("25", 150.0), ("LA", 250.0)], 130.0, 10.0),+ ];+ let p = page(lines);+ let pages = vec![p];+ let body = compute_body_size(&pages);+ let map = build_heading_map(&pages, body);+ let blocks = classify_page(&pages[0], &map);+ assert_eq!(blocks.len(), 1, "got: {blocks:?}");+ match &blocks[0] {+ Block::Table { header, rows } => {+ // Header isn't bold so no header row promoted.+ assert!(header.is_none());+ assert_eq!(rows.len(), 3);+ assert_eq!(rows[0][0], "Name");+ assert_eq!(rows[1][2], "NYC");+ }+ other => panic!("expected table, got {other:?}"),+ }+ }++ #[test]+ fn rejects_table_when_row_count_too_low() {+ let lines = vec![line_with_spans(+ &[("A", 50.0), ("B", 150.0), ("C", 250.0)],+ 100.0,+ 10.0,+ )];+ let runs = detect_tables(&lines);+ assert!(runs.is_empty());+ }++ #[test]+ fn rejects_table_when_column_count_too_low() {+ let lines = vec![+ line_with_spans(&[("A", 50.0), ("B", 200.0)], 100.0, 10.0),+ line_with_spans(&[("C", 50.0), ("D", 200.0)], 115.0, 10.0),+ ];+ let runs = detect_tables(&lines);+ assert!(runs.is_empty());+ }++ #[test]+ fn renders_table_to_pipe_format() {+ let blocks = vec![Block::Table {+ header: Some(vec!["a".into(), "b".into()]),+ rows: vec![vec!["1".into(), "2".into()], vec!["3".into(), "4".into()]],+ }];+ let s = render_blocks(&blocks);+ assert_eq!(s, "| a | b |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |");+ }++ #[test]+ fn render_table_without_header_synthesizes_blank_header() {+ let blocks = vec![Block::Table {+ header: None,+ rows: vec![vec!["1".into(), "2".into()]],+ }];+ let s = render_blocks(&blocks);+ // GFM/CommonMark needs a header row before the separator; we emit a+ // blank one so renderers don't choke.+ assert!(s.contains("|---|---|"));+ assert!(s.ends_with("| 1 | 2 |"));+ }++ #[test]+ fn normalize_collapses_digits_and_case() {+ assert_eq!(normalize_for_repetition("Page 1 of 6"), "page # of #");+ assert_eq!(normalize_for_repetition("PAGE 12 OF 6"), "page # of #");+ assert_eq!(normalize_for_repetition("Confidential"), "confidential");+ }++ fn header_footer_page(n: usize, header: &str, footer: &str, body: &str) -> ParsedPage {+ // Page height 100 → header band ≤12pt, footer band ≥88pt.+ let mut lines = vec![+ line(header, 50.0, 5.0, 8.0, 8.0),+ line(body, 50.0, 50.0, 10.0, 10.0),+ line(footer, 50.0, 92.0, 6.0, 6.0),+ ];+ for l in &mut lines {+ l.region_path = Vec::new();+ }+ ParsedPage {+ page_number: n,+ page_width: 612.0,+ page_height: 100.0,+ text: String::new(),+ text_items: vec![],+ projected_lines: lines,+ regions: crate::types::Region::default(),+ graphics: vec![],+ figures: vec![],+ }+ }++ #[test]+ fn detects_repeating_header_and_footer() {+ let pages = vec![+ header_footer_page(1, "Acme Confidential", "Page 1 of 3", "Body one."),+ header_footer_page(2, "Acme Confidential", "Page 2 of 3", "Body two."),+ header_footer_page(3, "Acme Confidential", "Page 3 of 3", "Body three."),+ ];+ let set = compute_header_footer_set(&pages);+ assert!(set.contains("acme confidential"));+ assert!(set.contains("page # of #"));+ }++ #[test]+ fn skips_repetition_check_on_single_page() {+ let pages = vec![header_footer_page(1, "Solo", "footer", "body")];+ let set = compute_header_footer_set(&pages);+ assert!(set.is_empty());+ }++ #[test]+ fn body_text_not_classified_as_header() {+ // Same text in the body of every page should NOT be stripped — only+ // text within the top/bottom band qualifies.+ let mut pages = Vec::new();+ for n in 1..=3 {+ let mut p = header_footer_page(n, "unique header", "unique footer", "shared body text");+ // Move "shared body text" out of header/footer bands (already at y=50 in mid-page).+ // No-op — just illustrating intent.+ p.projected_lines[0].text = format!("unique header {n}");+ p.projected_lines[2].text = format!("unique footer {n}");+ pages.push(p);+ }+ let set = compute_header_footer_set(&pages);+ // "shared body text" sits mid-page — never matched.+ assert!(!set.contains("shared body text"));+ }++ #[test]+ fn full_format_strips_header_footer() {+ let pages = vec![+ header_footer_page(1, "Acme Confidential", "Page 1 of 2", "First page body."),+ header_footer_page(2, "Acme Confidential", "Page 2 of 2", "Second page body."),+ ];+ let body = compute_body_size(&pages);+ let map = build_heading_map(&pages, body);+ let set = compute_header_footer_set(&pages);+ let blocks = classify_page_with_filters(&pages[0], &map, &set);+ let s = render_blocks(&blocks);+ assert!(!s.contains("Acme Confidential"), "got: {s}");+ assert!(!s.contains("Page 1 of 2"), "got: {s}");+ assert!(s.contains("First page body."));+ }++ #[test]+ fn escapes_pipe_inside_cell() {+ assert_eq!(escape_table_cell("a|b"), "a\\|b");+ }++ #[test]+ fn dehyphenation_only_for_lowercase_followups() {+ let mut s = String::from("co-");+ append_paragraph_line(&mut s, "operate");+ assert_eq!(s, "cooperate");++ let mut s = String::from("Vitamin-");+ append_paragraph_line(&mut s, "A");+ assert_eq!(s, "Vitamin- A");+ }++ /// Build a line whose spans carry explicit per-span font metadata. Lets us+ /// exercise the mid-line emphasis pipeline without needing real PDF input.+ fn styled_line(spans: &[(&str, f32, Option<&str>)], y: f32, size: f32) -> ProjectedLine {+ let items: Vec<TextItem> = spans+ .iter()+ .map(|(t, x, font)| TextItem {+ text: (*t).into(),+ x: *x,+ y,+ width: t.chars().count() as f32 * size * 0.5,+ height: size,+ font_size: Some(size),+ font_name: font.map(String::from),+ ..Default::default()+ })+ .collect();+ let joined: String = spans+ .iter()+ .map(|(t, _, _)| *t)+ .collect::<Vec<_>>()+ .join(" ");+ let min_x = items.iter().map(|s| s.x).fold(f32::INFINITY, f32::min);+ let max_x = items+ .iter()+ .map(|s| s.x + s.width)+ .fold(f32::NEG_INFINITY, f32::max);+ ProjectedLine {+ text: joined,+ bbox: Rect {+ x: min_x,+ y,+ width: (max_x - min_x).max(0.0),+ height: size,+ },+ anchor: Anchor::Left,+ indent_x: min_x,+ dominant_font_size: size,+ dominant_font_name: Some("Arial".into()),+ all_bold: false,+ all_italic: false,+ all_mono: false,+ all_strike: false,+ spans: items,+ region_path: Vec::new(),+ mcid: None,+ }+ }++ #[test]+ fn render_line_inline_mid_line_bold() {+ // Plain span, then bold span: should produce a mid-line `**bold**` run.+ let l = styled_line(+ &[+ ("regular text with", 50.0, Some("Arial")),+ ("bold word", 200.0, Some("Arial-Bold")),+ ],+ 100.0,+ 10.0,+ );+ let out = render_line_inline(&l);+ assert!(out.contains("regular text with"), "got: {out}");+ assert!(out.contains("**bold word**"), "got: {out}");+ assert!(+ !out.starts_with("**"),+ "mid-line shouldn't open with bold: {out}"+ );+ }++ #[test]+ fn render_line_inline_uniform_bold_uses_shortcut() {+ // All spans bold → single outer wrap, no per-span noise.+ let l = styled_line(+ &[+ ("first", 50.0, Some("Arial-Bold")),+ ("second", 100.0, Some("Arial-Bold")),+ ],+ 100.0,+ 10.0,+ );+ let out = render_line_inline(&l);+ assert!(out.starts_with("**") && out.ends_with("**"), "got: {out}");+ // Only one bold run, not two — the shortcut should kick in.+ assert_eq!(out.matches("**").count(), 2, "got: {out}");+ }++ #[test]+ fn render_line_inline_escapes_emphasis_chars() {+ let l = styled_line(&[("5*4=20", 50.0, Some("Arial"))], 100.0, 10.0);+ let out = render_line_inline(&l);+ assert_eq!(out, "5\\*4=20");+ }++ #[test]+ fn render_line_inline_italic_then_bold() {+ let l = styled_line(+ &[+ ("italic", 50.0, Some("Arial-Italic")),+ ("plain", 100.0, Some("Arial")),+ ("bold", 150.0, Some("Arial-Bold")),+ ],+ 100.0,+ 10.0,+ );+ let out = render_line_inline(&l);+ assert!(out.contains("*italic*"), "got: {out}");+ assert!(out.contains("plain"), "got: {out}");+ assert!(out.contains("**bold**"), "got: {out}");+ }++ #[test]+ fn render_line_inline_mono_span() {+ let l = styled_line(+ &[+ ("call", 50.0, Some("Arial")),+ ("foo()", 100.0, Some("Courier")),+ ("on it", 150.0, Some("Arial")),+ ],+ 100.0,+ 10.0,+ );+ let out = render_line_inline(&l);+ assert!(out.contains("`foo()`"), "got: {out}");+ // Plain spans stay unwrapped.+ assert!(out.contains("call"));+ assert!(out.contains("on it"));+ }++ #[test]+ fn classify_paragraph_with_mid_line_bold() {+ // First line has a bold word mid-line → not uniformly styled; paragraph+ // should emit baked-in `**bold**` inside the text and `bold=false` at+ // the block level.+ let a = styled_line(+ &[+ ("a sentence with a", 50.0, Some("Arial")),+ ("bold", 180.0, Some("Arial-Bold")),+ ("word in it.", 230.0, Some("Arial")),+ ],+ 50.0,+ 10.0,+ );+ let p = page(vec![a]);+ let pages = vec![p];+ let body = compute_body_size(&pages);+ let map = build_heading_map(&pages, body);+ let blocks = classify_page(&pages[0], &map);+ assert_eq!(blocks.len(), 1, "got: {blocks:?}");+ match &blocks[0] {+ Block::Paragraph { text, bold, italic } => {+ assert!(!*bold, "mixed-style paragraph shouldn't set block bold");+ assert!(!*italic);+ assert!(text.contains("**bold**"), "got: {text}");+ }+ other => panic!("expected paragraph, got {other:?}"),+ }+ }++ #[test]+ fn classify_list_item_strips_marker_under_emphasis() {+ // Whole bullet line is bold (marker + text). Rendered text should be+ // wrapped, with the marker dropped (the renderer prints it).+ let l = styled_line(+ &[+ ("•", 60.0, Some("Arial-Bold")),+ ("important item", 80.0, Some("Arial-Bold")),+ ],+ 50.0,+ 10.0,+ );+ let p = page(vec![l]);+ let pages = vec![p];+ let body = compute_body_size(&pages);+ let map = build_heading_map(&pages, body);+ let blocks = classify_page(&pages[0], &map);+ assert_eq!(blocks.len(), 1);+ match &blocks[0] {+ Block::ListItem { text, .. } => {+ assert_eq!(text, "**important item**");+ }+ other => panic!("expected list item, got {other:?}"),+ }+ }++ fn stroke(x1: f32, y1: f32, x2: f32, y2: f32, width: f32) -> GraphicPrimitive {+ GraphicPrimitive::Stroke {+ x1,+ y1,+ x2,+ y2,+ width,+ color: None,+ }+ }++ fn page_with_graphics(+ lines: Vec<ProjectedLine>,+ graphics: Vec<GraphicPrimitive>,+ ) -> ParsedPage {+ let mut p = page(lines);+ p.graphics = graphics;+ p+ }++ #[test]+ fn hr_long_thin_horizontal_stroke_detected() {+ // 400pt wide stroke on a 612pt page → comfortably above 30% threshold.+ let p = page_with_graphics(vec![], vec![stroke(50.0, 200.0, 450.0, 200.5, 0.5)]);+ let ys = detect_horizontal_rules(&p);+ assert_eq!(ys, vec![200.25]);+ }++ #[test]+ fn hr_short_stroke_rejected() {+ // 50pt wide — table border or list bullet, not an HR.+ let p = page_with_graphics(vec![], vec![stroke(50.0, 200.0, 100.0, 200.0, 0.5)]);+ assert!(detect_horizontal_rules(&p).is_empty());+ }++ #[test]+ fn hr_vertical_stroke_rejected() {+ let p = page_with_graphics(vec![], vec![stroke(50.0, 50.0, 50.0, 500.0, 0.5)]);+ assert!(detect_horizontal_rules(&p).is_empty());+ }++ #[test]+ fn hr_thick_stroke_rejected() {+ // 4pt-thick stroke → a filled bar, not a rule.+ let p = page_with_graphics(vec![], vec![stroke(50.0, 200.0, 450.0, 200.0, 4.0)]);+ assert!(detect_horizontal_rules(&p).is_empty());+ }++ #[test]+ fn hr_underline_at_text_baseline_dropped() {+ // Text line at y=100 height=10 → bottom at y=110. Stroke at y=111 within+ // the line's horizontal extent → underline, not an HR.+ let text_line = line(+ "Some underlined heading text on the page",+ 50.0,+ 100.0,+ 10.0,+ 10.0,+ );+ let bottom = text_line.bbox.y + text_line.bbox.height;+ let p = page_with_graphics(+ vec![text_line.clone()],+ vec![stroke(+ 50.0,+ bottom + 1.0,+ 50.0 + text_line.bbox.width,+ bottom + 1.0,+ 0.5,+ )],+ );+ assert!(detect_horizontal_rules(&p).is_empty());+ }++ /// Helper: build the four borders of a rectangle as four strokes.+ fn rect_borders(x: f32, y: f32, w: f32, h: f32) -> Vec<GraphicPrimitive> {+ vec![+ stroke(x, y, x + w, y, 0.5), // top+ stroke(x, y + h, x + w, y + h, 0.5), // bottom+ stroke(x, y, x, y + h, 0.5), // left+ stroke(x + w, y, x + w, y + h, 0.5), // right+ ]+ }++ #[test]+ fn ruled_table_2x2_detected() {+ // 2 rows × 2 cols grid: 3 H lines (y=100,140,180), 3 V lines (x=50,150,250)+ // Cell text dropped in the centroid of each cell.+ let mut graphics = Vec::new();+ for y in [100.0_f32, 140.0, 180.0] {+ graphics.push(stroke(50.0, y, 250.0, y, 0.5));+ }+ for x in [50.0_f32, 150.0, 250.0] {+ graphics.push(stroke(x, 100.0, x, 180.0, 0.5));+ }++ // Text lines: one per cell, centered.+ let lines = vec![+ line("a", 90.0, 115.0, 10.0, 10.0), // row 0, col 0+ line("b", 190.0, 115.0, 10.0, 10.0), // row 0, col 1+ line("c", 90.0, 155.0, 10.0, 10.0), // row 1, col 0+ line("d", 190.0, 155.0, 10.0, 10.0), // row 1, col 1+ ];++ let runs = detect_ruled_tables(&lines, &graphics, 612.0, 792.0);+ assert_eq!(runs.len(), 1, "expected 1 ruled table, got {runs:?}");+ match &runs[0].block {+ Block::Table { header, rows } => {+ assert!(header.is_none(), "no bold first row → no header");+ assert_eq!(rows.len(), 2);+ assert_eq!(rows[0], vec!["a", "b"]);+ assert_eq!(rows[1], vec!["c", "d"]);+ }+ other => panic!("expected Block::Table, got {other:?}"),+ }+ }++ #[test]+ fn ruled_table_rect_borders_detected() {+ // Same 2×2 table but drawn as 4 individual cell rects (each cell is a+ // stroked rectangle). Each rect contributes 4 strokes via+ // extract_h_v_segments.+ let mut graphics = Vec::new();+ graphics.extend(rect_borders(50.0, 100.0, 100.0, 40.0)); // r0 c0+ graphics.extend(rect_borders(150.0, 100.0, 100.0, 40.0)); // r0 c1+ graphics.extend(rect_borders(50.0, 140.0, 100.0, 40.0)); // r1 c0+ graphics.extend(rect_borders(150.0, 140.0, 100.0, 40.0)); // r1 c1++ let lines = vec![+ line("a", 90.0, 115.0, 10.0, 10.0),+ line("b", 190.0, 115.0, 10.0, 10.0),+ line("c", 90.0, 155.0, 10.0, 10.0),+ line("d", 190.0, 155.0, 10.0, 10.0),+ ];+ let runs = detect_ruled_tables(&lines, &graphics, 612.0, 792.0);+ assert_eq!(runs.len(), 1);+ }++ #[test]+ fn ruled_table_page_border_rejected() {+ // Single big rect covering ~the whole page → should NOT be treated as a+ // table even though it has H+V lines on all four sides.+ let graphics = rect_borders(10.0, 10.0, 590.0, 770.0);+ let lines = vec![line("body text", 50.0, 400.0, 10.0, 10.0)];+ let runs = detect_ruled_tables(&lines, &graphics, 612.0, 792.0);+ assert!(+ runs.is_empty(),+ "page-border rect should not become a table, got {runs:?}"+ );+ }++ #[test]+ fn ruled_table_mostly_empty_rejected() {+ // 3×3 grid with text in only one cell — empty fraction 8/9 ≈ 89% >> 30%.+ let mut graphics = Vec::new();+ for y in [100.0_f32, 130.0, 160.0, 190.0] {+ graphics.push(stroke(50.0, y, 350.0, y, 0.5));+ }+ for x in [50.0_f32, 150.0, 250.0, 350.0] {+ graphics.push(stroke(x, 100.0, x, 190.0, 0.5));+ }+ let lines = vec![line("only", 90.0, 115.0, 10.0, 10.0)];+ let runs = detect_ruled_tables(&lines, &graphics, 612.0, 792.0);+ assert!(runs.is_empty());+ }++ #[test]+ fn ruled_table_first_row_bold_becomes_header() {+ // 2×2 with first row text marked all_bold → header promotion.+ let mut graphics = Vec::new();+ for y in [100.0_f32, 140.0, 180.0] {+ graphics.push(stroke(50.0, y, 250.0, y, 0.5));+ }+ for x in [50.0_f32, 150.0, 250.0] {+ graphics.push(stroke(x, 100.0, x, 180.0, 0.5));+ }+ let mut a = line("Name", 90.0, 115.0, 10.0, 10.0);+ let mut b = line("Score", 190.0, 115.0, 10.0, 10.0);+ a.all_bold = true;+ b.all_bold = true;+ let lines = vec![+ a,+ b,+ line("alice", 90.0, 155.0, 10.0, 10.0),+ line("99", 190.0, 155.0, 10.0, 10.0),+ ];+ let runs = detect_ruled_tables(&lines, &graphics, 612.0, 792.0);+ assert_eq!(runs.len(), 1);+ match &runs[0].block {+ Block::Table { header, rows } => {+ assert_eq!(+ header.as_deref(),+ Some(&["Name".into(), "Score".into()][..])+ );+ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0], vec!["alice", "99"]);+ }+ other => panic!("expected Block::Table, got {other:?}"),+ }+ }++ #[test]+ fn merge_prefers_ruled_when_overlapping() {+ let ruled = vec![TableRun {+ start: 5,+ end: 10,+ block: Block::Table {+ header: None,+ rows: vec![vec!["ruled".into()]],+ },+ }];+ let borderless = vec![TableRun {+ start: 6,+ end: 11,+ block: Block::GridFallback {+ lines: vec!["bl".into()],+ },+ }];+ let merged = merge_table_runs(ruled, borderless);+ assert_eq!(merged.len(), 1);+ assert!(matches!(&merged[0].block, Block::Table { .. }));+ }++ #[test]+ fn hr_emitted_between_lines_by_y_order() {+ let lines = vec![+ line("before the rule", 50.0, 100.0, 10.0, 10.0),+ line("after the rule", 50.0, 300.0, 10.0, 10.0),+ ];+ // Stroke between the two lines, far from either's baseline.+ let p = page_with_graphics(lines, vec![stroke(50.0, 200.0, 450.0, 200.0, 0.5)]);+ let blocks = classify_page(&p, &[]);+ let has_hr = blocks+ .iter()+ .position(|b| matches!(b, Block::HorizontalRule));+ assert!(has_hr.is_some(), "expected an HR block, got {blocks:?}");+ // HR must land between the two paragraphs, not before/after both.+ let pos = has_hr.unwrap();+ assert!(pos > 0 && pos < blocks.len() - 1);+ }+}diff --git a/crates/liteparse/src/output/json.rs b/crates/liteparse/src/output/json.rsindex 98342bd..b6db995 100644--- a/crates/liteparse/src/output/json.rs+++ b/crates/liteparse/src/output/json.rs@@ -91,6 +91,10 @@ mod tests {page_height: 792.0,text: "txt".into(),text_items: items,+ projected_lines: vec![],+ regions: crate::types::Region::default(),+ graphics: vec![],+ figures: vec![],}}diff --git a/crates/liteparse/src/output/markdown.rs b/crates/liteparse/src/output/markdown.rsnew file mode 100644index 0000000..69a8658--- /dev/null+++ b/crates/liteparse/src/output/markdown.rs@@ -0,0 +1,156 @@+use crate::markdown_layout::{+ build_heading_map, classify_page_with_filters, compute_body_size, compute_header_footer_set,+ render_blocks,+};+use crate::types::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.+///+/// Pages are emitted in order, separated by `\n\n-----\n\n` with a+/// `<!-- page N -->` marker. Pages that contain no projected lines (e.g. blank+/// or fully-OCR pages without font-size info) fall back to the projected text+/// wrapped in a fenced block so we never silently drop content.+pub fn format_markdown(pages: &[ParsedPage]) -> String {+ if pages.is_empty() {+ return String::new();+ }++ let body_size = compute_body_size(pages);+ let heading_map = build_heading_map(pages, body_size);+ let header_footer = compute_header_footer_set(pages);++ let mut out = String::new();+ for (i, page) in pages.iter().enumerate() {+ if i > 0 {+ out.push_str("\n\n-----\n\n");+ }+ out.push_str(&format!("<!-- page {} -->\n\n", page.page_number));++ if page.projected_lines.is_empty() {+ // No structural metadata for this page — fall back to the+ // projection text inside a fence so nothing is dropped.+ out.push_str("```text\n");+ out.push_str(&page.text);+ if !page.text.ends_with('\n') {+ out.push('\n');+ }+ out.push_str("```");+ continue;+ }++ let blocks = classify_page_with_filters(page, &heading_map, &header_footer);+ out.push_str(&render_blocks(&blocks));+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::types::{Anchor, ProjectedLine, Rect, TextItem};++ fn line(text: &str, x: f32, y: f32, h: f32, size: f32) -> ProjectedLine {+ ProjectedLine {+ text: text.into(),+ bbox: Rect {+ x,+ y,+ width: text.chars().count() as f32 * (size * 0.5),+ height: h,+ },+ anchor: Anchor::Left,+ indent_x: x,+ dominant_font_size: size,+ dominant_font_name: Some("Arial".into()),+ all_bold: false,+ all_italic: false,+ all_mono: false,+ all_strike: false,+ spans: vec![TextItem::default()],+ region_path: Vec::new(),+ mcid: None,+ }+ }++ fn page_with(n: usize, lines: Vec<ProjectedLine>) -> ParsedPage {+ ParsedPage {+ page_number: n,+ page_width: 612.0,+ page_height: 792.0,+ text: "fallback".into(),+ text_items: vec![],+ projected_lines: lines,+ regions: crate::types::Region::default(),+ graphics: vec![],+ figures: vec![],+ }+ }++ #[test]+ fn test_empty() {+ assert_eq!(format_markdown(&[]), "");+ }++ #[test]+ fn test_fallback_when_no_projected_lines() {+ let p = ParsedPage {+ page_number: 1,+ page_width: 0.0,+ page_height: 0.0,+ text: "hello".into(),+ text_items: vec![],+ projected_lines: vec![],+ regions: crate::types::Region::default(),+ graphics: vec![],+ figures: vec![],+ };+ let out = format_markdown(&[p]);+ assert!(out.contains("```text"));+ assert!(out.contains("hello"));+ assert!(out.contains("<!-- page 1 -->"));+ }++ #[test]+ fn test_heading_and_paragraph() {+ let p = page_with(+ 1,+ vec![+ line("My Title For This Test Document", 50.0, 50.0, 18.0, 18.0),+ // Enough body text to dominate the char-weighted body-size+ // mode so the title at 18pt registers as larger-than-body.+ line("First sentence of body prose here.", 50.0, 80.0, 10.0, 10.0),+ line(+ "Second sentence of body prose here.",+ 50.0,+ 92.0,+ 10.0,+ 10.0,+ ),+ line(+ "Third sentence of body prose here.",+ 50.0,+ 104.0,+ 10.0,+ 10.0,+ ),+ ],+ );+ let out = format_markdown(&[p]);+ assert!(out.contains("# My Title For This Test Document"));+ assert!(out.contains("First sentence of body prose here."));+ }++ #[test]+ fn test_multi_page_separator() {+ let a = page_with(1, vec![line("A page.", 50.0, 80.0, 10.0, 10.0)]);+ let b = page_with(2, vec![line("B page.", 50.0, 80.0, 10.0, 10.0)]);+ let out = format_markdown(&[a, b]);+ assert!(out.contains("-----"));+ assert!(out.find("A page.").unwrap() < out.find("B page.").unwrap());+ }+}diff --git a/crates/liteparse/src/output/mod.rs b/crates/liteparse/src/output/mod.rsindex 1c593c8..c2d2804 100644--- a/crates/liteparse/src/output/mod.rs+++ b/crates/liteparse/src/output/mod.rs@@ -1,2 +1,3 @@pub mod json;+pub mod markdown;pub mod text;diff --git a/crates/liteparse/src/output/text.rs b/crates/liteparse/src/output/text.rsindex d451a7a..82bf1a9 100644--- a/crates/liteparse/src/output/text.rs+++ b/crates/liteparse/src/output/text.rs@@ -20,6 +20,10 @@ mod tests {page_height: 0.0,text: text.into(),text_items: vec![],+ projected_lines: vec![],+ regions: crate::types::Region::default(),+ graphics: vec![],+ figures: vec![],}}diff --git a/crates/liteparse/src/parser.rs b/crates/liteparse/src/parser.rsindex 4a295ae..4fa3512 100644--- a/crates/liteparse/src/parser.rs+++ b/crates/liteparse/src/parser.rs@@ -9,6 +9,7 @@ use crate::ocr::http_simple::HttpOcrEngine;#[cfg(feature = "tesseract")]use crate::ocr::tesseract::TesseractOcrEngine;use crate::ocr_merge;+use crate::output::markdown;use crate::projection;#[cfg(not(target_arch = "wasm32"))]use crate::render;@@ -193,13 +194,23 @@ impl LiteParse {t2.duration_since(t_ocr).as_secs_f64() * 1000.0));- let full_text = parsed_pages- .iter()- .map(|p| p.text.as_str())- .collect::<Vec<_>>()- .join("\n\n");+ let full_text = if self.config.output_format == crate::config::OutputFormat::Markdown {+ let md = markdown::format_markdown(&parsed_pages);+ let t3 = web_time::Instant::now();+ log(&format!(+ "[liteparse] markdown: {:.1}ms",+ t3.duration_since(t2).as_secs_f64() * 1000.0+ ));+ md+ } else {+ parsed_pages+ .iter()+ .map(|p| p.text.as_str())+ .collect::<Vec<_>>()+ .join("\n\n")+ };- let total = t2.duration_since(t0).as_secs_f64() * 1000.0;+ let total = web_time::Instant::now().duration_since(t0).as_secs_f64() * 1000.0;log(&format!("[liteparse] total: {:.1}ms", total));Ok(ParseResult {diff --git a/crates/liteparse/src/projection.rs b/crates/liteparse/src/projection.rsindex b5a3497..3eeffa8 100644--- a/crates/liteparse/src/projection.rs+++ b/crates/liteparse/src/projection.rs@@ -2655,17 +2655,943 @@ pub fn project_pages_to_grid(pages: Vec<Page>) -> Vec<ParsedPage> {.collect();let (projected_items, text) = project_to_grid(&page, projection_boxes);+ // Detect figure regions from the page's vector graphics before+ // XY-cut runs so the layout recursion can treat them as obstacles+ // (partition the page around figures rather than slicing through).+ let figures = crate::figure_cluster::detect_figure_rects(+ &page.graphics,+ &page.text_items,+ page.page_width,+ page.page_height,+ );+ let (projected_lines, regions) = build_projected_lines(+ &projected_items,+ page.page_width,+ page.page_height,+ &figures,+ );ParsedPage {page_number: page.page_number,page_width: page.page_width,page_height: page.page_height,text,text_items: projected_items.into_iter().map(|proj| proj.item).collect(),+ projected_lines,+ regions,+ graphics: page.graphics,+ figures,}}).collect()}+// ── ProjectedLine derivation ────────────────────────────────────────────────+//+// `build_projected_lines` groups already-projected items (in reading order)+// into per-line structural metadata consumed by the markdown emitter. Lines+// are grouped by y-proximity; aggregates (dominant font, all-bold/italic/mono)+// are char-weighted across the line's items. The JSON/text outputs are+// unaffected — `ParsedPage.projected_lines` is `#[serde(skip)]`.++/// PDF font descriptor flag bits we care about.+/// See PDF spec §9.8.2 (table 123).+const PDF_FONT_FLAG_FIXED_PITCH: i32 = 1; // bit 1+const PDF_FONT_FLAG_ITALIC: i32 = 64; // bit 7+const PDF_FONT_FLAG_FORCE_BOLD: i32 = 262144; // bit 19++/// Font-name substrings that indicate bold weight.+const BOLD_NAME_HINTS: &[&str] = &["Bold", "Black", "Heavy", "Semibold", "Demibold"];+/// Font-name substrings that indicate italic / oblique slant.+const ITALIC_NAME_HINTS: &[&str] = &["Italic", "Oblique"];+/// Font-name substrings that indicate a monospaced typeface.+const MONO_NAME_HINTS: &[&str] = &[+ "Courier",+ "Mono",+ "Consolas",+ "Menlo",+ "Source Code",+ "Inconsolata",+ "Hack",+ "Fira Code",+];++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 {+ if flags & PDF_FONT_FLAG_FORCE_BOLD != 0 {+ return true;+ }+ }+ if let Some(w) = item.font_weight {+ if w >= 600 {+ return true;+ }+ }+ if let Some(n) = &item.font_name {+ if 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(n) = &item.font_name {+ if 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(n) = &item.font_name {+ if name_contains_any(n, MONO_NAME_HINTS) {+ return true;+ }+ }+ false+}++// ── XY-cut layout decomposition ─────────────────────────────────────────────+//+// Replaces the prior flat column detector. Recursively splits the page along H+// or V axes at "valleys" — runs of low projection density wider than a minimum+// threshold. Pre-order traversal of the resulting tree gives reading order+// (top→bottom, left→right) including for nested layouts (banded splits with+// sub-columns).+//+// Threshold is min-density relative to the local content's median: a cut is+// valid if the projection density in the valley stays below T_DENS × median+// for at least MIN_VALLEY_PT continuous units. Auto-scales to page content so+// dense vs. sparse pages need no per-doc tuning. Conservative defaults — we'd+// rather under-cut (merge columns) than shred a paragraph with wide+// inter-word gaps.++/// Bucket size for the 1D density projection (points).+const XY_BUCKET_PT: f32 = 2.0;+/// Density threshold for a "valley", expressed as a fraction of the local+/// median non-zero bucket density.+const XY_T_DENS: f32 = 0.10;+/// Minimum vertical-cut (column gutter) valley width.+const XY_MIN_V_VALLEY_PT: f32 = 8.0;+/// Minimum horizontal-cut (row gap) valley width, expressed as a multiple of+/// the median line height.+const XY_MIN_H_VALLEY_FACTOR: f32 = 1.4;+/// Hard recursion cap.+const XY_MAX_DEPTH: u32 = 6;+/// Below this item count we stop trying to cut.+const XY_MIN_ITEMS_TO_CUT: usize = 4;+/// A horizontal cut must leave at least this many distinct text lines on each+/// side; otherwise we don't slice prose into sliver bands.+const XY_MIN_LINES_PER_H_SIDE: usize = 2;+/// Vertical-cut score must beat the horizontal score by this factor to be+/// chosen. Tie-breaks in favor of horizontal so pages are sliced into bands+/// before columns — matches natural reading order.+const XY_V_PREFERENCE_MARGIN: f32 = 1.1;++#[derive(Debug)]+struct CutCandidate {+ axis: CutAxis,+ /// Coordinate of the split (y for horizontal cut, x for vertical).+ position: f32,+ score: f32,+}++/// Character-weighted contribution of an item to the projection. Headings get+/// roughly the same weight as the body text they're competing with, instead of+/// being amplified by their bbox area.+fn xy_item_weight(it: &TextItem) -> f32 {+ it.text.chars().count().max(1) as f32+}++fn xy_root_bbox(items: &[ProjectedTextItem], page_width: f32, page_height: f32) -> Rect {+ let mut min_x = f32::INFINITY;+ let mut min_y = f32::INFINITY;+ let mut max_x = f32::NEG_INFINITY;+ let mut max_y = f32::NEG_INFINITY;+ for it in items {+ if it.item.text.is_empty() {+ continue;+ }+ min_x = min_x.min(it.item.x);+ min_y = min_y.min(it.item.y);+ max_x = max_x.max(it.item.x + it.item.width.max(0.0));+ max_y = max_y.max(it.item.y + it.item.height.max(0.0));+ }+ if !min_x.is_finite() {+ return Rect {+ x: 0.0,+ y: 0.0,+ width: page_width.max(1.0),+ height: page_height.max(1.0),+ };+ }+ let x = min_x.max(0.0);+ let y = min_y.max(0.0);+ let w = (max_x - x).max(1.0);+ let h = (max_y - y).max(1.0);+ let w = if page_width > 0.0 {+ w.min(page_width)+ } else {+ w+ };+ let h = if page_height > 0.0 {+ h.min(page_height)+ } else {+ h+ };+ Rect {+ x,+ y,+ width: w,+ height: h,+ }+}++fn xy_median_line_height(items: &[ProjectedTextItem], idxs: &[usize]) -> f32 {+ let mut heights: Vec<f32> = idxs+ .iter()+ .filter_map(|&i| {+ let h = items[i].item.height;+ if h > 0.5 { Some(h) } else { None }+ })+ .collect();+ if heights.is_empty() {+ return 10.0;+ }+ heights.sort_by(|a, b| a.total_cmp(b));+ heights[heights.len() / 2]+}++/// Approximate distinct-line count by y-banding, used only to enforce+/// `XY_MIN_LINES_PER_H_SIDE`.+fn xy_distinct_lines(items: &[ProjectedTextItem], idxs: &[usize], median_h: f32) -> usize {+ if idxs.is_empty() {+ return 0;+ }+ let band = (median_h * 0.5).max(2.0);+ let mut ys: Vec<f32> = idxs.iter().map(|&i| items[i].item.y).collect();+ ys.sort_by(|a, b| a.total_cmp(b));+ let mut lines = 1usize;+ let mut last = ys[0];+ for &y in &ys[1..] {+ if (y - last).abs() > band {+ lines += 1;+ last = y;+ }+ }+ lines+}++/// Find the best valley along `axis` inside `bbox` for the given items. The+/// returned position is in absolute page coordinates.+///+/// `figures` is the set of figure-region rectangles on the page. Any figure+/// that intersects `bbox` is stamped into the density projection like a giant+/// opaque text block — its perpendicular extent (clipped to `bbox`) is added+/// to each bucket it covers along `axis`. This makes the recursion prefer+/// cuts *around* figures rather than slicing through them (which is the+/// motivating fix for academic-paper page-1 layouts where a figure straddles+/// both columns).+fn xy_find_best_cut(+ items: &[ProjectedTextItem],+ idxs: &[usize],+ bbox: &Rect,+ axis: CutAxis,+ median_h: f32,+ figures: &[Rect],+) -> Option<CutCandidate> {+ let (origin, length) = match axis {+ CutAxis::Horizontal => (bbox.y, bbox.height),+ CutAxis::Vertical => (bbox.x, bbox.width),+ };+ if length <= 0.0 {+ return None;+ }+ let n_buckets = ((length / XY_BUCKET_PT).ceil() as usize).max(1);+ let mut density = vec![0.0f32; n_buckets];++ for &i in idxs {+ let it = &items[i].item;+ let (c0, c1) = match axis {+ CutAxis::Horizontal => (it.y, it.y + it.height.max(0.0)),+ CutAxis::Vertical => (it.x, it.x + it.width.max(0.0)),+ };+ let weight = xy_item_weight(it);+ let b0_f = ((c0 - origin) / XY_BUCKET_PT).floor();+ let b1_f = ((c1 - origin) / XY_BUCKET_PT).ceil();+ let b0 = b0_f.max(0.0) as usize;+ let b1 = (b1_f.max(b0_f + 1.0) as usize).min(n_buckets);+ for b in b0..b1 {+ density[b] += weight;+ }+ }++ // Stamp figures into the projection as opaque obstacles. A figure that+ // intersects `bbox` adds density to each axis-parallel bucket it spans;+ // weight = its perpendicular extent (clipped to bbox) so figures behave+ // like very wide/tall pseudo-items relative to text. The valley search+ // naturally finds cuts adjacent to figures rather than through them.+ for fig in figures {+ let fx0 = fig.x.max(bbox.x);+ let fy0 = fig.y.max(bbox.y);+ let fx1 = (fig.x + fig.width).min(bbox.x + bbox.width);+ let fy1 = (fig.y + fig.height).min(bbox.y + bbox.height);+ if fx1 <= fx0 || fy1 <= fy0 {+ continue;+ }+ let (c0, c1, perp) = match axis {+ CutAxis::Horizontal => (fy0, fy1, fx1 - fx0),+ CutAxis::Vertical => (fx0, fx1, fy1 - fy0),+ };+ let weight = perp.max(1.0);+ let b0_f = ((c0 - origin) / XY_BUCKET_PT).floor();+ let b1_f = ((c1 - origin) / XY_BUCKET_PT).ceil();+ let b0 = b0_f.max(0.0) as usize;+ let b1 = (b1_f.max(b0_f + 1.0) as usize).min(n_buckets);+ for b in b0..b1 {+ density[b] += weight;+ }+ }++ let mut nonzero: Vec<f32> = density.iter().copied().filter(|d| *d > 0.0).collect();+ if nonzero.is_empty() {+ return None;+ }+ nonzero.sort_by(|a, b| a.total_cmp(b));+ let median = nonzero[nonzero.len() / 2];+ if median <= 0.0 {+ return None;+ }+ let threshold = median * XY_T_DENS;++ // Don't cut at leading/trailing whitespace — only consider valleys interior+ // to the content's span on this axis.+ let first_dense = density.iter().position(|d| *d > threshold)?;+ let last_dense = density.iter().rposition(|d| *d > threshold)?;+ if last_dense <= first_dense + 1 {+ return None;+ }++ let min_valley_pt = match axis {+ CutAxis::Vertical => XY_MIN_V_VALLEY_PT,+ CutAxis::Horizontal => median_h * XY_MIN_H_VALLEY_FACTOR,+ };+ let min_valley_buckets = ((min_valley_pt / XY_BUCKET_PT).ceil() as usize).max(1);++ let mut best: Option<CutCandidate> = None;+ let mut i = first_dense + 1;+ while i <= last_dense {+ if density[i] <= threshold {+ let s = i;+ while i <= last_dense && density[i] <= threshold {+ i += 1;+ }+ let e = i; // exclusive+ let width = e - s;+ if width >= min_valley_buckets {+ let mean: f32 = density[s..e].iter().sum::<f32>() / width as f32;+ let depth = (1.0 - mean / median).max(0.0);+ let score = width as f32 * depth;+ let mid = (s as f32 + e as f32) * 0.5;+ let position = origin + mid * XY_BUCKET_PT;+ if best.as_ref().is_none_or(|b| score > b.score) {+ best = Some(CutCandidate {+ axis,+ position,+ score,+ });+ }+ }+ } else {+ i += 1;+ }+ }+ best+}++fn xy_split_bbox(bbox: &Rect, cut: &CutCandidate) -> (Rect, Rect) {+ match cut.axis {+ CutAxis::Horizontal => {+ let top_h = (cut.position - bbox.y).max(0.0);+ let top = Rect {+ x: bbox.x,+ y: bbox.y,+ width: bbox.width,+ height: top_h,+ };+ let bot = Rect {+ x: bbox.x,+ y: cut.position,+ width: bbox.width,+ height: (bbox.height - top_h).max(0.0),+ };+ (top, bot)+ }+ CutAxis::Vertical => {+ let left_w = (cut.position - bbox.x).max(0.0);+ let left = Rect {+ x: bbox.x,+ y: bbox.y,+ width: left_w,+ height: bbox.height,+ };+ let right = Rect {+ x: cut.position,+ y: bbox.y,+ width: (bbox.width - left_w).max(0.0),+ height: bbox.height,+ };+ (left, right)+ }+ }+}++/// Minimum fraction of region width a banner band must cover.+const XY_BANNER_WIDTH_FRACTION: f32 = 0.6;+/// Banner clearance gap above/below in multiples of median line height.+const XY_BANNER_CLEARANCE_FACTOR: f32 = 1.5;++/// Detect a "banner" y-band — one or more vertically-adjacent wide text bands+/// (≥ `XY_BANNER_WIDTH_FRACTION` of bbox width) flanked by a clear vertical+/// gap from the rest of the content. Returns an H-cut that isolates the banner+/// from neighboring content.+///+/// Motivating case: a full-width centered title + authors block above a 2-+/// column body where a figure straddles both columns. Density-based XY-cut+/// can't separate them because the figure prevents any clean V-cut and there's+/// no obvious H-valley between the banner and the body. The banner detector+/// runs first and force-cuts just below the banner stack, freeing the+/// recursion to find normal column gutters in the lower region.+///+/// Also helps mid-document section headings that span the full content width:+/// a wide centered "5 Conclusion" line above a 2-column body would otherwise+/// get pulled into one column.+fn xy_find_banner_cut(+ items: &[ProjectedTextItem],+ idxs: &[usize],+ bbox: &Rect,+ median_h: f32,+) -> Option<CutCandidate> {+ if bbox.width <= 1.0 || idxs.len() < 2 {+ return None;+ }+ let mut sorted: Vec<usize> = idxs.iter().copied().collect();+ 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);+ let width_threshold = XY_BANNER_WIDTH_FRACTION * bbox.width;++ // Group items into y-bands. A new item joins the current band when its top+ // is within `band_tol` of either the band's center or its existing bottom+ // (handles slight baseline variation).+ let mut bands: Vec<(f32, f32, f32, f32)> = Vec::new(); // (y_min, y_max, x_min, x_max)+ for &i in &sorted {+ let it = &items[i].item;+ let y0 = it.y;+ let y1 = it.y + it.height.max(0.0);+ let x0 = it.x;+ let x1 = it.x + it.width.max(0.0);+ let mut merged = false;+ if let Some(last) = bands.last_mut() {+ let center = (last.0 + last.1) * 0.5;+ if (y0 - center).abs() <= band_tol || y0 <= last.1 + band_tol {+ last.0 = last.0.min(y0);+ last.1 = last.1.max(y1);+ last.2 = last.2.min(x0);+ last.3 = last.3.max(x1);+ merged = true;+ }+ }+ if !merged {+ bands.push((y0, y1, x0, x1));+ }+ }+ if bands.is_empty() {+ return None;+ }+ let is_wide = |b: &(f32, f32, f32, f32)| -> bool { (b.3 - b.2) >= width_threshold };++ // Walk top→bottom. For each run of consecutive wide bands (close enough to+ // each other to count as a single banner stack), check above/below clearance+ // and emit a cut if isolated.+ let mut i = 0;+ while i < bands.len() {+ if !is_wide(&bands[i]) {+ i += 1;+ continue;+ }+ let start = i;+ let mut end = i;+ // Extend through consecutive wide bands separated by less than the+ // clearance threshold — multi-line title + authors counts as one+ // banner stack.+ while end + 1 < bands.len()+ && is_wide(&bands[end + 1])+ && bands[end + 1].0 - bands[end].1 < min_clearance+ {+ end += 1;+ }+ let banner_top = bands[start].0;+ let banner_bot = bands[end].1;+ let above_y = if start > 0 {+ Some(bands[start - 1].1)+ } else {+ None+ };+ let below_y = if end + 1 < bands.len() {+ Some(bands[end + 1].0)+ } else {+ None+ };+ let above_clear = above_y.is_none_or(|ay| banner_top - ay >= min_clearance);+ let below_clear = below_y.is_none_or(|by| by - banner_bot >= min_clearance);++ if above_clear && below_clear {+ // Prefer cutting BELOW the banner so it becomes the top region of+ // the split (matches natural reading order). Fall back to cutting+ // above only when there's nothing below to cut against.+ let cut_y = if let Some(by) = below_y {+ (banner_bot + by) * 0.5+ } else if let Some(ay) = above_y {+ (ay + banner_top) * 0.5+ } else {+ // Banner spans the whole region — no productive cut.+ i = end + 1;+ continue;+ };+ // Skip degenerate cuts that would leave one side empty.+ if cut_y > bbox.y + 1.0 && cut_y < bbox.y + bbox.height - 1.0 {+ return Some(CutCandidate {+ axis: CutAxis::Horizontal,+ position: cut_y,+ score: f32::INFINITY,+ });+ }+ }+ i = end + 1;+ }+ None+}++fn xy_cut_rec(+ items: &[ProjectedTextItem],+ idxs: Vec<usize>,+ bbox: Rect,+ depth: u32,+ median_h: f32,+ figures: &[Rect],+) -> Region {+ if idxs.len() <= XY_MIN_ITEMS_TO_CUT || depth >= XY_MAX_DEPTH {+ return Region {+ bbox,+ kind: RegionKind::Leaf { item_indices: idxs },+ };+ }+ // Banner cut wins over density-based valleys. Score is f32::INFINITY so+ // the existing comparison logic naturally selects it.+ let banner = xy_find_banner_cut(items, &idxs, &bbox, median_h);+ let h = xy_find_best_cut(items, &idxs, &bbox, CutAxis::Horizontal, median_h, figures);+ let v = xy_find_best_cut(items, &idxs, &bbox, CutAxis::Vertical, median_h, figures);+ let cut = match (banner, h, v) {+ (Some(bc), _, _) => Some(bc),+ (None, Some(hc), Some(vc)) => {+ if vc.score > hc.score * XY_V_PREFERENCE_MARGIN {+ Some(vc)+ } else {+ Some(hc)+ }+ }+ (None, Some(hc), None) => Some(hc),+ (None, None, Some(vc)) => Some(vc),+ (None, None, None) => None,+ };+ let Some(cut) = cut else {+ return Region {+ bbox,+ kind: RegionKind::Leaf { item_indices: idxs },+ };+ };++ // Partition items by centroid. We use centroids rather than bbox edges so+ // items that straddle the cut don't get arbitrarily assigned — they go to+ // whichever side holds most of their ink.+ let mut left: Vec<usize> = Vec::new();+ let mut right: Vec<usize> = Vec::new();+ for i in idxs {+ let it = &items[i].item;+ let centroid = match cut.axis {+ CutAxis::Horizontal => it.y + it.height.max(0.0) * 0.5,+ CutAxis::Vertical => it.x + it.width.max(0.0) * 0.5,+ };+ if centroid < cut.position {+ left.push(i);+ } else {+ right.push(i);+ }+ }+ if left.is_empty() || right.is_empty() {+ let mut all = left;+ all.extend(right);+ return Region {+ bbox,+ kind: RegionKind::Leaf { item_indices: all },+ };+ }+ // Banner cuts (score = ∞) at the page root are explicitly meant to+ // isolate single-line wide headers like titles, so skip the min-lines+ // guard for them. At deeper recursion levels we keep the guard — an+ // aggressive single-line banner cut mid-recursion fragments paragraphs+ // around emphasized lines (e.g. a centered "Figure N caption" sandwiched+ // between body paragraphs would otherwise carve out its own sliver+ // region and break paragraph continuation).+ let allow_single_line =+ cut.axis == CutAxis::Horizontal && cut.score.is_infinite() && depth == 0;+ if cut.axis == CutAxis::Horizontal && !allow_single_line {+ let lc = xy_distinct_lines(items, &left, median_h);+ let rc = xy_distinct_lines(items, &right, median_h);+ if lc < XY_MIN_LINES_PER_H_SIDE || rc < XY_MIN_LINES_PER_H_SIDE {+ let mut all = left;+ all.extend(right);+ return Region {+ bbox,+ kind: RegionKind::Leaf { item_indices: all },+ };+ }+ }++ let (left_bbox, right_bbox) = xy_split_bbox(&bbox, &cut);+ let left_region = xy_cut_rec(items, left, left_bbox, depth + 1, median_h, figures);+ let right_region = xy_cut_rec(items, right, right_bbox, depth + 1, median_h, figures);+ Region {+ bbox,+ kind: RegionKind::Split {+ axis: cut.axis,+ children: vec![left_region, right_region],+ },+ }+}++/// Build the page's XY-cut region tree.+///+/// `figures` is an optional set of figure-region bounding rectangles (from+/// `figure_cluster::detect_figure_rects`); pass `&[]` to disable obstacle+/// seeding. Figures cause the recursion to favor cuts around them.+pub(crate) fn xy_cut(+ items: &[ProjectedTextItem],+ page_width: f32,+ page_height: f32,+ figures: &[Rect],+) -> Region {+ let all: Vec<usize> = items+ .iter()+ .enumerate()+ .filter(|(_, it)| !it.item.text.is_empty())+ .map(|(i, _)| i)+ .collect();+ if all.is_empty() {+ return Region {+ bbox: Rect {+ x: 0.0,+ y: 0.0,+ width: page_width.max(1.0),+ height: page_height.max(1.0),+ },+ kind: RegionKind::Leaf {+ item_indices: Vec::new(),+ },+ };+ }+ let bbox = xy_root_bbox(items, page_width, page_height);+ let median_h = xy_median_line_height(items, &all);+ xy_cut_rec(items, all, bbox, 0, median_h, figures)+}++/// Pre-order walk of leaves. Each leaf yields its `region_path` (index trail+/// from the root) and item indices. Leaves with no items are skipped.+fn xy_walk_leaves(region: &Region, path: &mut Vec<u16>, out: &mut Vec<(Vec<u16>, Vec<usize>)>) {+ match ®ion.kind {+ RegionKind::Leaf { item_indices } => {+ if !item_indices.is_empty() {+ out.push((path.clone(), item_indices.clone()));+ }+ }+ RegionKind::Split { children, .. } => {+ for (i, child) in children.iter().enumerate() {+ path.push(i as u16);+ xy_walk_leaves(child, path, out);+ path.pop();+ }+ }+ }+}++/// Group `items` into per-leaf lines using the XY-cut region tree, then derive+/// per-line aggregates. Leaves are walked pre-order so reading order follows+/// the layout — top→bottom bands, left→right columns, recursively. Returns+/// the populated lines and the region tree so callers can persist it on+/// `ParsedPage`.+pub(crate) fn build_projected_lines(+ items: &[ProjectedTextItem],+ page_width: f32,+ page_height: f32,+ figures: &[Rect],+) -> (Vec<ProjectedLine>, Region) {+ if items.is_empty() {+ return (Vec::new(), Region::default());+ }++ let region = xy_cut(items, page_width, page_height, figures);+ let mut leaves: Vec<(Vec<u16>, Vec<usize>)> = Vec::new();+ xy_walk_leaves(®ion, &mut Vec::new(), &mut leaves);++ let mut out: Vec<ProjectedLine> = Vec::new();+ for (path, indices) in leaves {+ // Sort within the leaf by y, tie-break by x. `build_one_line` re-sorts+ // by x for left→right concatenation; the y-banding loop here only+ // needs y order.+ let mut sorted = indices;+ sorted.sort_by(|&a, &b| {+ items[a]+ .item+ .y+ .total_cmp(&items[b].item.y)+ .then(items[a].item.x.total_cmp(&items[b].item.x))+ });++ let mut current: Vec<usize> = Vec::new();+ let mut current_y: f32 = 0.0;+ let mut current_h: f32 = 0.0;+ for idx in sorted {+ let y = items[idx].item.y;+ let h = items[idx].item.height.max(1.0);+ if current.is_empty() {+ current.push(idx);+ current_y = y;+ current_h = h;+ continue;+ }+ let same = (y - current_y).abs() < current_h.max(h) * 0.5;+ if same {+ current.push(idx);+ current_y = current_y.min(y);+ current_h = current_h.max(h);+ } else {+ out.push(build_one_line(items, ¤t, path.clone()));+ current = vec![idx];+ current_y = y;+ current_h = h;+ }+ }+ if !current.is_empty() {+ out.push(build_one_line(items, ¤t, path.clone()));+ }+ }++ // Normalize `indent_x` to be leaf-relative: subtract each leaf's minimum+ // line bbox.x from every line in that leaf. This way list-nesting and+ // paragraph-indent comparisons in `markdown_layout.rs` use offsets from+ // the column's left edge rather than absolute page x. Multi-column pages+ // would otherwise see every column-2 line as "indented" relative to+ // column-1 lines.+ {+ use std::collections::HashMap;+ let mut leaf_min: HashMap<Vec<u16>, f32> = HashMap::new();+ for line in &out {+ let e = leaf_min+ .entry(line.region_path.clone())+ .or_insert(f32::INFINITY);+ if line.indent_x < *e {+ *e = line.indent_x;+ }+ }+ for line in &mut out {+ if let Some(min) = leaf_min.get(&line.region_path)+ && min.is_finite()+ {+ line.indent_x -= *min;+ if line.indent_x < 0.0 {+ line.indent_x = 0.0;+ }+ }+ }+ }++ (out, region)+}++fn build_one_line(+ items: &[ProjectedTextItem],+ idxs: &[usize],+ region_path: Vec<u16>,+) -> ProjectedLine {+ // Sort by x so concatenation reads left→right even if reading order had+ // rotated insertions.+ let mut sorted: Vec<usize> = idxs.to_vec();+ sorted.sort_by(|a, b| items[*a].item.x.total_cmp(&items[*b].item.x));++ let mut text = String::new();+ let mut min_x = f32::INFINITY;+ let mut min_y = f32::INFINITY;+ let mut max_x = f32::NEG_INFINITY;+ let mut max_y = f32::NEG_INFINITY;++ let mut size_weights: HashMap<u32, (f32, usize)> = HashMap::new();+ let mut height_weights: HashMap<u32, (f32, usize)> = HashMap::new();+ let mut name_weights: HashMap<String, usize> = HashMap::new();+ let mut bold_chars: usize = 0;+ let mut italic_chars: usize = 0;+ let mut mono_chars: usize = 0;+ let mut total_chars: usize = 0;+ let mut anchor_weights: HashMap<u8, usize> = HashMap::new();+ let mut mcid: Option<i32> = None;+ let mut spans: Vec<TextItem> = Vec::with_capacity(sorted.len());++ for (pos, &i) in sorted.iter().enumerate() {+ let proj = &items[i];+ let it = &proj.item;+ spans.push(it.clone());++ // Concatenate item text. Use existing num_spaces from projection only as+ // a hint — the markdown emitter re-collapses whitespace, so we just+ // ensure there's *some* separation between adjacent items.+ if pos > 0 && !text.ends_with(' ') {+ text.push(' ');+ }+ text.push_str(&it.text);++ min_x = min_x.min(it.x);+ min_y = min_y.min(it.y);+ max_x = max_x.max(it.x + it.width);+ max_y = max_y.max(it.y + it.height);++ 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;+ }+ }+ 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));+ e.1 += n;++ if let Some(name) = &it.font_name {+ *name_weights.entry(name.clone()).or_insert(0) += n;+ }++ if is_bold_item(it) {+ bold_chars += n;+ }+ if is_italic_item(it) {+ italic_chars += n;+ }+ if is_mono_item(it) {+ mono_chars += n;+ }++ let akey = match proj.anchor {+ Anchor::Left => 0u8,+ Anchor::Right => 1,+ Anchor::Center => 2,+ Anchor::Floating => 3,+ };+ *anchor_weights.entry(akey).or_insert(0) += n;++ if mcid.is_none() {+ mcid = it.mcid;+ }+ }++ let dominant_size_from_font = size_weights+ .values()+ .max_by_key(|(_, n)| *n)+ .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+ // something to chew on. Documented in MARKDOWN_PROGRESS.md.+ let dominant_font_size = if dominant_size_from_font > 1.5 {+ dominant_size_from_font+ } else {+ height_weights+ .values()+ .max_by_key(|(_, n)| *n)+ .map(|(h, _)| *h)+ .unwrap_or(0.0)+ };++ let dominant_font_name = name_weights+ .into_iter()+ .max_by_key(|(_, n)| *n)+ .map(|(n, _)| n);++ let majority = |count: usize| total_chars > 0 && count * 2 > total_chars;++ let dominant_anchor_key = anchor_weights+ .iter()+ .max_by_key(|(_, n)| **n)+ .map(|(k, _)| *k)+ .unwrap_or(0);+ let anchor = match dominant_anchor_key {+ 1 => Anchor::Right,+ 2 => Anchor::Center,+ 3 => Anchor::Floating,+ _ => Anchor::Left,+ };++ let bbox = Rect {+ x: if min_x.is_finite() { min_x } else { 0.0 },+ y: if min_y.is_finite() { min_y } else { 0.0 },+ width: if max_x.is_finite() && min_x.is_finite() {+ (max_x - min_x).max(0.0)+ } else {+ 0.0+ },+ height: if max_y.is_finite() && min_y.is_finite() {+ (max_y - min_y).max(0.0)+ } else {+ 0.0+ },+ };++ ProjectedLine {+ text,+ bbox: bbox.clone(),+ anchor,+ // Real column detection is deferred (carry-forward in MARKDOWN_PROGRESS).+ // `indent_x` mirrors bbox.x for now; the markdown emitter relies on+ // this for paragraph/list-indent comparisons within a single column.+ indent_x: bbox.x,+ dominant_font_size,+ dominant_font_name,+ all_bold: majority(bold_chars),+ all_italic: majority(italic_chars),+ all_mono: majority(mono_chars),+ all_strike: false,+ spans,+ region_path,+ mcid,+ }+}+#[cfg(test)]mod tests {use super::*;@@ -2698,6 +3624,7 @@ mod tests {page_number: 1,page_width: 612.0,page_height: 792.0,+ graphics: Vec::new(),text_items: Vec::new(),};let projection_boxes = vec![@@ -2710,6 +3637,211 @@ mod tests {assert!(text.is_empty());}+ fn item_at(text: &str, x: f32, y: f32, w: f32, h: f32) -> ProjectedTextItem {+ ProjectedTextItem {+ item: TextItem {+ text: text.to_string(),+ x,+ y,+ width: w,+ height: h,+ ..Default::default()+ },+ snap: Snap::Left,+ anchor: Anchor::Left,+ is_dup: false,+ rendered: false,+ num_spaces: 0,+ force_unsnapped: false,+ is_margin_line_number: false,+ rotated: false,+ d: 0.0,+ }+ }++ #[test]+ fn xy_cut_finds_column_gutter_on_two_column_layout() {+ // Two columns, 50pt-wide gutter centered at x=300. Each column has+ // five rows of body text. Expect: a single vertical split at the+ // gutter, both children leaves.+ let mut items = Vec::new();+ for row in 0..5 {+ let y = 100.0 + row as f32 * 14.0;+ items.push(item_at("left side text", 50.0, y, 200.0, 10.0));+ items.push(item_at("right side text", 350.0, y, 200.0, 10.0));+ }+ let region = xy_cut(&items, 612.0, 792.0, &[]);+ match region.kind {+ RegionKind::Split { axis, children } => {+ assert_eq!(axis, CutAxis::Vertical);+ assert_eq!(children.len(), 2);+ let l = match &children[0].kind {+ RegionKind::Leaf { item_indices } => item_indices.len(),+ _ => 0,+ };+ let r = match &children[1].kind {+ RegionKind::Leaf { item_indices } => item_indices.len(),+ _ => 0,+ };+ assert_eq!(l, 5, "left col should hold 5 items");+ assert_eq!(r, 5, "right col should hold 5 items");+ }+ _ => panic!("expected a vertical split, got {:?}", region.kind),+ }+ }++ #[test]+ fn xy_cut_returns_leaf_on_single_column_prose() {+ // Tight single-column text — no valley wide enough to cut.+ let items: Vec<_> = (0..8)+ .map(|row| {+ let y = 100.0 + row as f32 * 12.0;+ item_at("the quick brown fox", 60.0, y, 400.0, 10.0)+ })+ .collect();+ let region = xy_cut(&items, 612.0, 792.0, &[]);+ assert!(matches!(region.kind, RegionKind::Leaf { .. }));+ }++ #[test]+ fn xy_cut_walk_assigns_reading_order_paths() {+ // 2-column page: pre-order walk visits left column before right.+ let mut items = Vec::new();+ for row in 0..5 {+ let y = 100.0 + row as f32 * 14.0;+ items.push(item_at("L", 50.0, y, 200.0, 10.0));+ items.push(item_at("R", 350.0, y, 200.0, 10.0));+ }+ let (lines, _region) = build_projected_lines(&items, 612.0, 792.0, &[]);+ // Left col's 5 lines come first (path [0, ...]), then right col's 5+ // (path [1, ...]).+ assert_eq!(lines.len(), 10);+ for line in &lines[..5] {+ assert_eq!(line.region_path.first().copied(), Some(0));+ }+ for line in &lines[5..] {+ assert_eq!(line.region_path.first().copied(), Some(1));+ }+ }++ #[test]+ fn banner_cut_isolates_full_width_title_above_two_columns() {+ // Layout: a centered wide title at the top, clear gap, then 2-column+ // body text. Density-based V-cut at the root would place the title+ // (centroid at page center) inside one of the columns. The banner+ // detector should H-cut just below the title so it ends up as the+ // pre-order first leaf, separate from both columns.+ let mut items = Vec::new();+ items.push(item_at(+ "Wide Centered Title Spanning Full Page",+ 100.0,+ 50.0,+ 412.0,+ 14.0,+ ));+ // Body starts well below the title (clear vertical gap).+ for row in 0..5 {+ let y = 200.0 + row as f32 * 14.0;+ items.push(item_at("left side text", 50.0, y, 200.0, 10.0));+ items.push(item_at("right side text", 350.0, y, 200.0, 10.0));+ }+ let (lines, _region) = build_projected_lines(&items, 612.0, 792.0, &[]);+ // First line (in pre-order) must be the title.+ let first = lines.first().expect("at least one line");+ assert!(+ first.text.contains("Title"),+ "expected title first, got {:?}",+ first.text+ );+ // Title leaf should be different from any column leaf.+ let body_paths: Vec<&Vec<u16>> = lines[1..].iter().map(|l| &l.region_path).collect();+ assert!(+ body_paths.iter().all(|p| **p != first.region_path),+ "title leaf should not share region_path with body lines"+ );+ }++ #[test]+ fn banner_cut_does_not_fire_on_plain_two_column_layout() {+ // Same layout as `xy_cut_finds_column_gutter_on_two_column_layout` —+ // no wide centered element to trigger a banner cut. Regression guard:+ // the V-cut must still be the first cut at the root.+ let mut items = Vec::new();+ for row in 0..5 {+ let y = 100.0 + row as f32 * 14.0;+ items.push(item_at("left side text", 50.0, y, 200.0, 10.0));+ items.push(item_at("right side text", 350.0, y, 200.0, 10.0));+ }+ let region = xy_cut(&items, 612.0, 792.0, &[]);+ match region.kind {+ RegionKind::Split { axis, .. } => {+ assert_eq!(axis, CutAxis::Vertical, "expected V-cut, not H");+ }+ _ => panic!("expected a split at the root"),+ }+ }++ #[test]+ fn figure_obstacle_forces_h_cut_around_straddling_figure() {+ // Two text bands separated by a wide figure that spans both halves of+ // the page. The text alone has no V-gutter and only a modest y-gap;+ // without obstacle seeding the root would either V-cut (bad — the+ // figure straddles both sides) or fail to cut at all. With the figure+ // stamped into density, the H-valleys above/below the figure dominate+ // and the recursion H-cuts into a top band → figure band → bottom band.+ let mut items = Vec::new();+ // Top band: several wide lines of text.+ for row in 0..4 {+ let y = 100.0 + row as f32 * 14.0;+ items.push(item_at(+ "top band line spans full width",+ 50.0,+ y,+ 500.0,+ 12.0,+ ));+ }+ // Bottom band: several wide lines, well below the figure.+ for row in 0..4 {+ let y = 400.0 + row as f32 * 14.0;+ items.push(item_at(+ "bottom band line after the figure",+ 50.0,+ y,+ 500.0,+ 12.0,+ ));+ }+ // Figure: 500×200pt block centered in the page between the bands.+ let figures = vec![Rect {+ x: 60.0,+ y: 160.0,+ width: 490.0,+ height: 200.0,+ }];++ let region_no_fig = xy_cut(&items, 612.0, 792.0, &[]);+ let region_with_fig = xy_cut(&items, 612.0, 792.0, &figures);++ // With figures, the root cut must be horizontal (top vs. bottom band).+ // Drilling through nested splits is fine — we just check the first one.+ match region_with_fig.kind {+ RegionKind::Split { axis, .. } => {+ assert_eq!(+ axis,+ CutAxis::Horizontal,+ "figure obstacle should force an H-cut between bands"+ );+ }+ RegionKind::Leaf { .. } => panic!("expected a split when figure is present"),+ }+ // Without figures, the same layout *might* still find an H-cut (the+ // gap from y≈127 to y≈400 is real), but the cut score with figures+ // should be at least as strong. We mostly just want to confirm both+ // paths return without panicking and the figure path produces a split.+ let _ = region_no_fig;+ }+#[test]fn project_pages_to_grid_handles_page_with_no_text_items() {let pages = vec![Page {@@ -2717,6 +3849,7 @@ mod tests {page_width: 612.0,page_height: 792.0,text_items: Vec::new(),+ graphics: Vec::new(),}];let parsed = project_pages_to_grid(pages);diff --git a/crates/liteparse/src/types.rs b/crates/liteparse/src/types.rsindex 4c34da2..977b731 100644--- a/crates/liteparse/src/types.rs+++ b/crates/liteparse/src/types.rs@@ -62,6 +62,10 @@ pub struct Page {pub page_width: f32,pub page_height: f32,pub text_items: Vec<TextItem>,+ /// Vector graphics on the page, distilled from PDFium path objects.+ /// Not emitted in JSON/text outputs — consumed by the markdown layout pass.+ #[serde(skip)]+ pub graphics: Vec<GraphicPrimitive>,}/// Represents a fully parsed page with projected text layout.@@ -72,6 +76,138 @@ pub struct ParsedPage {pub page_height: f32,pub text: String,pub text_items: Vec<TextItem>,+ /// Per-line structural metadata used by the markdown emitter. Not part of+ /// the JSON/text outputs (consumed internally) so it is `#[serde(skip)]`.+ #[serde(skip)]+ pub projected_lines: Vec<ProjectedLine>,+ /// Root of the XY-cut region tree for this page. Leaves correspond to the+ /// `region_path` on each `ProjectedLine`. Internal-only.+ #[serde(skip)]+ pub regions: Region,+ /// Vector graphics on the page (decomposed paths) used by the markdown+ /// emitter for ruled-table / HR / figure-cluster detection. Not part of+ /// the JSON/text output.+ #[serde(skip)]+ pub graphics: Vec<GraphicPrimitive>,+ /// Figure-region bounding rectangles derived from `graphics`. Pre-computed+ /// in `to_parsed_pages` so the XY-cut layout pass can treat them as+ /// obstacles, and reused downstream for figure classification.+ #[serde(skip)]+ pub figures: Vec<Rect>,+}++#[doc(hidden)]+#[derive(Debug, Clone, Default, Serialize)]+pub struct Rect {+ pub x: f32,+ pub y: f32,+ pub width: f32,+ pub height: f32,+}++/// Lightweight vector-graphic primitive derived from PDFium path objects.+/// Only the shapes useful to the markdown emitter (ruled tables, HRs, figure+/// clusters) are kept — bezier curves and complex paths are decomposed into+/// straight strokes, or dropped.+#[doc(hidden)]+#[derive(Debug, Clone)]+pub enum GraphicPrimitive {+ /// A single straight line segment in viewport coords. Used for HR/table+ /// border detection.+ Stroke {+ x1: f32,+ y1: f32,+ x2: f32,+ y2: f32,+ color: Option<String>,+ width: f32,+ },+ /// An axis-aligned rectangle — typically a filled cell background, banner,+ /// or fully-stroked table border drawn as a single path.+ Rect {+ bbox: Rect,+ fill: Option<String>,+ stroke: Option<String>,+ },+}++impl GraphicPrimitive {+ /// Bbox of the primitive in viewport coords.+ pub fn bbox(&self) -> Rect {+ match self {+ GraphicPrimitive::Stroke { x1, y1, x2, y2, .. } => {+ let x = x1.min(*x2);+ let y = y1.min(*y2);+ Rect {+ x,+ y,+ width: (x2 - x1).abs(),+ height: (y2 - y1).abs(),+ }+ }+ GraphicPrimitive::Rect { bbox, .. } => bbox.clone(),+ }+ }+}++/// Per-line structural metadata derived during grid projection. Used by the+/// markdown emitter; not surfaced in JSON/text output.+#[doc(hidden)]+#[derive(Debug, Clone, Serialize)]+pub struct ProjectedLine {+ pub text: String,+ pub bbox: Rect,+ pub anchor: Anchor,+ pub indent_x: f32,+ pub dominant_font_size: f32,+ pub dominant_font_name: Option<String>,+ pub all_bold: bool,+ pub all_italic: bool,+ pub all_mono: bool,+ pub all_strike: bool,+ pub spans: Vec<TextItem>,+ /// Path from the page's region-tree root to the leaf containing this line.+ /// Equality means "same leaf"; prefix relationship means "one contains the+ /// other". Replaces the prior flat `column_id` scheme so nested layouts+ /// (banded splits with sub-columns) survive paragraph/table grouping.+ pub region_path: Vec<u16>,+ pub mcid: Option<i32>,+}++/// XY-cut region tree node. A page's root region recursively splits along H or+/// V axes until each leaf holds a coherent block of items.+#[doc(hidden)]+#[derive(Debug, Clone, Default)]+pub struct Region {+ pub bbox: Rect,+ pub kind: RegionKind,+}++#[doc(hidden)]+#[derive(Debug, Clone)]+pub enum RegionKind {+ Leaf {+ item_indices: Vec<usize>,+ },+ Split {+ axis: CutAxis,+ children: Vec<Region>,+ },+}++impl Default for RegionKind {+ fn default() -> Self {+ RegionKind::Leaf {+ item_indices: Vec::new(),+ }+ }+}++#[doc(hidden)]+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum CutAxis {+ Horizontal,+ Vertical,}#[doc(hidden)]@@ -83,11 +219,14 @@ pub enum Snap {}#[doc(hidden)]-#[derive(Debug, Serialize)]+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pub enum Anchor {Left,Right,Center,+ /// Inline span that does not snap to a column edge — used by lines whose+ /// dominant items couldn't be classified as Left/Right/Center.+ Floating,}#[doc(hidden)]@@ -150,6 +289,7 @@ mod tests {page_width: 100.0,page_height: 200.0,text_items: vec![sample_item()],+ graphics: vec![],};let s = serde_json::to_string(&p).unwrap();assert!(s.contains("\"page_number\":1"));diff --git a/crates/pdfium-sys/src/dynamic.rs b/crates/pdfium-sys/src/dynamic.rsindex 761ab80..660545d 100644--- a/crates/pdfium-sys/src/dynamic.rs+++ b/crates/pdfium-sys/src/dynamic.rs@@ -72,6 +72,34 @@ pub struct PdfiumBindings {unsafe extern "C" fn(FPDF_PAGEOBJECT) -> std::os::raw::c_int,pub FPDFImageObj_GetRenderedBitmap:unsafe extern "C" fn(FPDF_DOCUMENT, FPDF_PAGE, FPDF_PAGEOBJECT) -> FPDF_BITMAP,+ pub FPDFPageObj_GetMatrix: unsafe extern "C" fn(FPDF_PAGEOBJECT, *mut FS_MATRIX) -> FPDF_BOOL,+ pub FPDFPageObj_GetStrokeColor: unsafe extern "C" fn(+ FPDF_PAGEOBJECT,+ *mut std::os::raw::c_uint,+ *mut std::os::raw::c_uint,+ *mut std::os::raw::c_uint,+ *mut std::os::raw::c_uint,+ ) -> FPDF_BOOL,+ pub FPDFPageObj_GetFillColor: unsafe extern "C" fn(+ FPDF_PAGEOBJECT,+ *mut std::os::raw::c_uint,+ *mut std::os::raw::c_uint,+ *mut std::os::raw::c_uint,+ *mut std::os::raw::c_uint,+ ) -> FPDF_BOOL,+ pub FPDFPageObj_GetStrokeWidth: unsafe extern "C" fn(FPDF_PAGEOBJECT, *mut f32) -> FPDF_BOOL,+ pub FPDFPath_GetDrawMode: unsafe extern "C" fn(+ FPDF_PAGEOBJECT,+ *mut std::os::raw::c_int,+ *mut FPDF_BOOL,+ ) -> FPDF_BOOL,+ pub FPDFPath_CountSegments: unsafe extern "C" fn(FPDF_PAGEOBJECT) -> std::os::raw::c_int,+ pub FPDFPath_GetPathSegment:+ unsafe extern "C" fn(FPDF_PAGEOBJECT, std::os::raw::c_int) -> FPDF_PATHSEGMENT,+ pub FPDFPathSegment_GetPoint:+ unsafe extern "C" fn(FPDF_PATHSEGMENT, *mut f32, *mut f32) -> FPDF_BOOL,+ pub FPDFPathSegment_GetType: unsafe extern "C" fn(FPDF_PATHSEGMENT) -> std::os::raw::c_int,+ pub FPDFPathSegment_GetClose: unsafe extern "C" fn(FPDF_PATHSEGMENT) -> FPDF_BOOL,// -- TextPage --pub FPDFText_LoadPage: unsafe extern "C" fn(FPDF_PAGE) -> FPDF_TEXTPAGE,@@ -232,6 +260,16 @@ impl PdfiumBindings {FPDFPageObj_GetBounds: load_fn!(lib, "FPDFPageObj_GetBounds"),FPDFPageObj_GetMarkedContentID: load_fn!(lib, "FPDFPageObj_GetMarkedContentID"),FPDFImageObj_GetRenderedBitmap: load_fn!(lib, "FPDFImageObj_GetRenderedBitmap"),+ FPDFPageObj_GetMatrix: load_fn!(lib, "FPDFPageObj_GetMatrix"),+ FPDFPageObj_GetStrokeColor: load_fn!(lib, "FPDFPageObj_GetStrokeColor"),+ FPDFPageObj_GetFillColor: load_fn!(lib, "FPDFPageObj_GetFillColor"),+ FPDFPageObj_GetStrokeWidth: load_fn!(lib, "FPDFPageObj_GetStrokeWidth"),+ FPDFPath_GetDrawMode: load_fn!(lib, "FPDFPath_GetDrawMode"),+ FPDFPath_CountSegments: load_fn!(lib, "FPDFPath_CountSegments"),+ FPDFPath_GetPathSegment: load_fn!(lib, "FPDFPath_GetPathSegment"),+ FPDFPathSegment_GetPoint: load_fn!(lib, "FPDFPathSegment_GetPoint"),+ FPDFPathSegment_GetType: load_fn!(lib, "FPDFPathSegment_GetType"),+ FPDFPathSegment_GetClose: load_fn!(lib, "FPDFPathSegment_GetClose"),FPDFText_LoadPage: load_fn!(lib, "FPDFText_LoadPage"),FPDFText_ClosePage: load_fn!(lib, "FPDFText_ClosePage"),FPDFText_CountChars: load_fn!(lib, "FPDFText_CountChars"),diff --git a/crates/pdfium/src/lib.rs b/crates/pdfium/src/lib.rsindex f0219ce..389e9f1 100644--- a/crates/pdfium/src/lib.rs+++ b/crates/pdfium/src/lib.rs@@ -12,7 +12,7 @@ pub use document::Document;pub use error::PdfiumError;pub use font::{Font, FontType};pub use library::Library;-pub use page::{ImageBounds, Page, ViewportTransform};+pub use page::{ImageBounds, Page, PathObject, PathSegment, SegmentKind, ViewportTransform};pub use text_page::{TextChar, TextCharIter, TextPage};pub use types::*;diff --git a/crates/pdfium/src/page.rs b/crates/pdfium/src/page.rsindex 2f36cd1..97777dd 100644--- a/crates/pdfium/src/page.rs+++ b/crates/pdfium/src/page.rs@@ -5,7 +5,7 @@ use crate::document::Document;use crate::error::PdfiumError;use crate::ffi;use crate::text_page::TextPage;-use crate::types::RectF;+use crate::types::{Color, RectF};/// Bounding box of an embedded image object on a page./// Coordinates are in PDF points with top-left origin (Y-down).@@ -17,6 +17,40 @@ pub struct ImageBounds {pub height: f32,}+/// One segment of a vector path. Coordinates are in viewport space+/// (top-left origin, 72 DPI) after the object's matrix has been applied.+#[derive(Debug, Clone, Copy)]+pub struct PathSegment {+ pub kind: SegmentKind,+ pub x: f32,+ pub y: f32,+ /// Whether this segment closes the current subpath back to its MoveTo.+ pub close: bool,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum SegmentKind {+ MoveTo,+ LineTo,+ BezierTo,+}++/// A vector path object extracted from a page. Used by the markdown emitter+/// for ruled-table, horizontal-rule, and figure-cluster detection.+#[derive(Debug, Clone)]+pub struct PathObject {+ /// Object bbox in viewport space (after matrix; from FPDFPageObj_GetBounds).+ pub bbox: RectF,+ pub stroke_color: Option<Color>,+ pub fill_color: Option<Color>,+ pub stroke_width: f32,+ /// True when the path is stroked per its draw mode.+ pub is_stroked: bool,+ /// True when the path is filled (draw-mode fill ≠ NONE).+ pub is_filled: bool,+ pub segments: Vec<PathSegment>,+}+pub struct Page<'doc> {pub(crate) handle: pdfium_sys::FPDF_PAGE,pub(crate) doc_handle: pdfium_sys::FPDF_DOCUMENT,@@ -242,6 +276,152 @@ impl Page<'_> {Err(PdfiumError::OperationFailed)}++ /// Enumerate vector path objects on this page. Segment points are+ /// transformed into viewport space (top-left origin, 72 DPI) by composing+ /// the object's matrix with the page→viewport transform.+ pub fn path_objects(&self, view_box: &RectF) -> Vec<PathObject> {+ let vp = self.viewport_transform(view_box);+ let obj_count = unsafe { ffi!(FPDFPage_CountObjects(self.handle)) };+ let mut out = Vec::new();++ for i in 0..obj_count {+ let obj = unsafe { ffi!(FPDFPage_GetObject(self.handle, i)) };+ if obj.is_null() {+ continue;+ }+ let obj_type = unsafe { ffi!(FPDFPageObj_GetType(obj)) };+ if obj_type != pdfium_sys::FPDF_PAGEOBJ_PATH as i32 {+ continue;+ }++ // Object → page matrix. Defaults to identity when not available.+ let mut m = pdfium_sys::FS_MATRIX {+ a: 1.0,+ b: 0.0,+ c: 0.0,+ d: 1.0,+ e: 0.0,+ f: 0.0,+ };+ unsafe { ffi!(FPDFPageObj_GetMatrix(obj, &mut m)) };++ // Bounds are reported in page space already accounting for the+ // matrix — just lift to viewport.+ let mut left = 0.0f32;+ let mut bottom = 0.0f32;+ let mut right = 0.0f32;+ let mut top = 0.0f32;+ let ok = unsafe {+ ffi!(FPDFPageObj_GetBounds(+ obj,+ &mut left,+ &mut bottom,+ &mut right,+ &mut top+ ))+ };+ if ok == 0 {+ continue;+ }+ let bbox = vp.transform_bounds(&RectF {+ left,+ top,+ right,+ bottom,+ });++ // Draw mode → is_filled / is_stroked.+ let mut fill_mode = 0i32;+ let mut stroke_bool = 0i32;+ let dm_ok =+ unsafe { ffi!(FPDFPath_GetDrawMode(obj, &mut fill_mode, &mut stroke_bool)) };+ let (is_filled, is_stroked) = if dm_ok != 0 {+ (+ fill_mode != pdfium_sys::FPDF_FILLMODE_NONE as i32,+ stroke_bool != 0,+ )+ } else {+ (false, false)+ };++ // Colors are reported as RGBA channels in 0..=255 cuint.+ let stroke_color = read_color(|r, g, b, a| unsafe {+ ffi!(FPDFPageObj_GetStrokeColor(obj, r, g, b, a))+ });+ let fill_color =+ read_color(|r, g, b, a| unsafe { ffi!(FPDFPageObj_GetFillColor(obj, r, g, b, a)) });++ let mut stroke_width = 0.0f32;+ unsafe { ffi!(FPDFPageObj_GetStrokeWidth(obj, &mut stroke_width)) };++ // Walk segments. Points are in the object's local coords; apply+ // matrix → page, then viewport transform.+ let n_segs = unsafe { ffi!(FPDFPath_CountSegments(obj)) };+ let mut segments = Vec::with_capacity(n_segs.max(0) as usize);+ for si in 0..n_segs {+ let seg = unsafe { ffi!(FPDFPath_GetPathSegment(obj, si)) };+ if seg.is_null() {+ continue;+ }+ let mut sx = 0.0f32;+ let mut sy = 0.0f32;+ let pt_ok = unsafe { ffi!(FPDFPathSegment_GetPoint(seg, &mut sx, &mut sy)) };+ if pt_ok == 0 {+ continue;+ }+ let ty = unsafe { ffi!(FPDFPathSegment_GetType(seg)) };+ let close = unsafe { ffi!(FPDFPathSegment_GetClose(seg)) } != 0;+ let kind = match ty as u32 {+ pdfium_sys::FPDF_SEGMENT_MOVETO => SegmentKind::MoveTo,+ pdfium_sys::FPDF_SEGMENT_LINETO => SegmentKind::LineTo,+ pdfium_sys::FPDF_SEGMENT_BEZIERTO => SegmentKind::BezierTo,+ _ => continue,+ };++ // Apply object matrix (FS_MATRIX is column-major a/b/c/d/e/f+ // matching the PDF text-matrix convention used elsewhere).+ let page_x = m.a * sx + m.c * sy + m.e;+ let page_y = m.b * sx + m.d * sy + m.f;+ let (x, y) = vp.transform_point(page_x, page_y);+ segments.push(PathSegment { kind, x, y, close });+ }++ out.push(PathObject {+ bbox,+ stroke_color,+ fill_color,+ stroke_width,+ is_stroked,+ is_filled,+ segments,+ });+ }++ out+ }+}++/// Helper: call a PDFium getter for RGBA color channels and pack into our `Color`.+/// Returns None when the FFI call reports failure.+fn read_color<F>(getter: F) -> Option<Color>+where+ F: FnOnce(*mut u32, *mut u32, *mut u32, *mut u32) -> i32,+{+ let mut r = 0u32;+ let mut g = 0u32;+ let mut b = 0u32;+ let mut a = 0u32;+ let ok = getter(&mut r, &mut g, &mut b, &mut a);+ if ok == 0 {+ return None;+ }+ Some(Color {+ r: r as u8,+ g: g as u8,+ b: b as u8,+ a: a as u8,+ })}/// Pre-computed affine transform from PDF page space to viewport space.diff --git a/packages/node/native.d.ts b/packages/node/native.d.tsindex ef09b26..c8d2d86 100644--- a/packages/node/native.d.ts+++ b/packages/node/native.d.ts@@ -18,7 +18,7 @@ export interface JsLiteParseConfig {targetPages?: string/** DPI for rendering pages (used for OCR and screenshots). */dpi?: number- /** Output format: "json" or "text". */+ /** Output format: "json", "text", or "markdown". */outputFormat?: string/** Keep very small text that would normally be filtered out. */preserveVerySmallText?: boolean@@ -26,6 +26,8 @@ export interface JsLiteParseConfig {password?: string/** Suppress progress output. */quiet?: boolean+ /** Number of concurrent OCR workers (default: CPU cores - 1). */+ numWorkers?: number}export interface JsTextItem {text: string@@ -54,6 +56,8 @@ export interface JsScreenshotResult {height: numberimageBuffer: Buffer}+/** Search text items for phrase matches, returning merged items with combined bounding boxes. */+export declare function searchItems(items: Array<JsTextItem>, phrase: string, caseSensitive?: boolean | undefined | null): Array<JsTextItem>/** Main LiteParse parser class. */export declare class LiteParse {/**@@ -63,7 +67,12 @@ export declare class LiteParse {constructor(config?: JsLiteParseConfig | undefined | null)/** Parse a document. Accepts a file path (string) or raw PDF bytes (Buffer). */parse(input: string | Buffer): Promise<JsParseResult>- /** Take screenshots of document pages. Returns PNG image buffers. */+ /**+ * Take screenshots of document pages. Returns PNG image buffers.+ *+ * Non-PDF files are automatically converted to PDF before rendering when+ * LibreOffice/ImageMagick are available.+ */screenshot(input: string | Buffer, pageNumbers?: Array<number> | undefined | null): Promise<Array<JsScreenshotResult>>/** Get the current configuration. */get config(): JsLiteParseConfigdiff --git a/packages/node/src/cli.ts b/packages/node/src/cli.tsindex e8478da..71c792c 100644--- a/packages/node/src/cli.ts+++ b/packages/node/src/cli.ts@@ -15,7 +15,7 @@ program.description("Parse a document and extract text").argument("<file>", "Path to the document file").option("-o, --output <file>", "Output file path")- .option("--format <format>", 'Output format: json|text (default: "text")')+ .option("--format <format>", 'Output format: json|text|markdown (default: "text")').option("--ocr-server-url <url>", "HTTP OCR server URL").option("--no-ocr", "Disable OCR").option("--ocr-language <lang>", "OCR language (default: eng)")@@ -43,7 +43,7 @@ program}// CLI options override config file- if (opts.format) config.outputFormat = opts.format as "json" | "text";+ if (opts.format) config.outputFormat = opts.format as "json" | "text" | "markdown";if (opts.ocrServerUrl)config.ocrServerUrl = opts.ocrServerUrl as string;if (opts.ocr === false) config.ocrEnabled = false;@@ -160,7 +160,7 @@ program.description("Parse multiple documents in batch mode").argument("<input-dir>", "Input directory").argument("<output-dir>", "Output directory")- .option("--format <format>", 'Output format: json|text (default: "text")')+ .option("--format <format>", 'Output format: json|text|markdown (default: "text")').option("--no-ocr", "Disable OCR").option("--ocr-language <lang>", "OCR language (default: eng)").option("--ocr-server-url <url>", "HTTP OCR server URL")@@ -180,7 +180,7 @@ programtry {const config: Partial<LiteParseConfig> = {};const format = (opts.format as string) ?? "text";- config.outputFormat = format as "json" | "text";+ config.outputFormat = format as "json" | "text" | "markdown";if (opts.ocr === false) config.ocrEnabled = false;if (opts.ocrLanguage) config.ocrLanguage = opts.ocrLanguage as string;if (opts.ocrServerUrl)@@ -192,7 +192,7 @@ programif (opts.numWorkers) config.numWorkers = opts.numWorkers as number;const parser = new LiteParse(config);- const outExt = format === "json" ? ".json" : ".txt";+ const outExt = format === "json" ? ".json" : format === "markdown" ? ".md" : ".txt";mkdirSync(outputDir, { recursive: true });diff --git a/packages/node/src/lib.ts b/packages/node/src/lib.tsindex 6d14c71..e69387b 100644--- a/packages/node/src/lib.ts+++ b/packages/node/src/lib.ts@@ -12,7 +12,7 @@ import {// ---------------------------------------------------------------------------export type LiteParseInput = string | Buffer | Uint8Array;-export type OutputFormat = "json" | "text";+export type OutputFormat = "json" | "text" | "markdown";export interface LiteParseConfig {ocrLanguage: string;diff --git a/packages/python/liteparse/parser.py b/packages/python/liteparse/parser.pyindex 019286a..22dd98d 100644--- a/packages/python/liteparse/parser.py+++ b/packages/python/liteparse/parser.py@@ -88,7 +88,7 @@ class LiteParse:max_pages: Maximum number of pages to parsetarget_pages: Specific pages to parse (e.g., "1-5,10,15-20")dpi: DPI for rendering (affects OCR quality)- output_format: Output format: "json" or "text" (default: "json")+ output_format: Output format: "json", "text", or "markdown" (default: "json")preserve_very_small_text: Whether to preserve very small textpassword: Password for encrypted/protected documentsquiet: Suppress progress output