fix(bookmarks): report every way a suggested outline can miss headings

bookmark_suggest's pages_read counted a page whose text could not be
read (its content past the page decode allowance) as read, and the
layout cap of 10,000 bookmarks dropped headings without setting
truncated. read_lines now counts the pages it read; the suggestion
carries truncated when pages were not read or more headings than the
cap were found, and the tool returns that. Caption leads (Figure, Fig.,
Table, Chart, Exhibit, Plate) now match in any case, so "FIGURE 3:" is
not suggested as a heading.

Tests: captions_match_in_any_case,
more_headings_than_the_cap_are_reported,
a_page_whose_text_cant_be_read_is_not_counted; each fails with its fix
reverted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
KenM76andClaude Opus 5.5 committed 2026-11-18 18:01:56 -05:00
1 parent 3a8fbb8c62
commit 2980cfca6a
5 files changed
+92 -22

No files matched your search

+1 -1
View File
@@ -76,7 +76,7 @@ impl Automation {
"headings": s.entries.len(),
"pages": s.pages,
"pages_read": s.pages_read,
"truncated": s.pages_read < s.pages,
"truncated": s.truncated,
});
if s.entries.is_empty() {
out["note"] = json!(
+1 -1
View File
@@ -490,7 +490,7 @@ pub fn tools() -> Vec<ToolDef> {
t(
"bookmark_suggest",
"Suggest bookmarks",
"Propose a bookmark tree for the whole document, for review: its tagged headings (H, H1-H6) when it has them (source \"structure\"), or else headings found from how its text looks (source \"layout\"): short blocks set larger than the body text, or bold where the body is not, levelled by size without skipping a level, a heading set on several lines as one bookmark that goes to its top; captions such as \"Figure 3\" are left out. Reads the first 5000 pages for a layout suggestion (pages_read; truncated is true when the document has more). Changes nothing: bookmarks is in bookmark_export's form, so edit titles, levels or remove entries, then apply it with bookmark_import (with replace to drop the existing outline), one undoable step. headings counts the suggested bookmarks; note says what to try when there are none. Needs the document to allow copying, as its text is returned.",
"Propose a bookmark tree for the whole document, for review: its tagged headings (H, H1-H6) when it has them (source \"structure\"), or else headings found from how its text looks (source \"layout\"): short blocks set larger than the body text, or bold where the body is not, levelled by size without skipping a level, a heading set on several lines as one bookmark that goes to its top; captions such as \"Figure 3\" are left out. Reads the first 5000 pages for a layout suggestion; pages_read counts the pages whose text was read. truncated is true when headings may be missing: the document has more pages, a page's text could not be read, or there were more than 10000 headings (the first 10000 are given). Changes nothing: bookmarks is in bookmark_export's form, so edit titles, levels or remove entries, then apply it with bookmark_import (with replace to drop the existing outline), one undoable step. headings counts the suggested bookmarks; note says what to try when there are none. Needs the document to allow copying, as its text is returned.",
)
.ro()
.with(schema(json!({ "doc": doc() }), &["doc"])),
+80 -18
View File
@@ -12,7 +12,7 @@ use pdfcraft_a11y::TextBlock;
use pdfcraft_cos::Document;
use pdfcraft_organize::{OutlineEntry, OutlineNode};
use crate::text_style_bookmarks::{Line, MAX_BOOKMARKS, MAX_PAGES, MAX_TITLE_CHARS, lines};
use crate::text_style_bookmarks::{Line, MAX_BOOKMARKS, MAX_TITLE_CHARS, read_lines};
/// Blocks looked back over for one a line continues: a heading's next line can come after lines
/// of other columns on the same row.
@@ -37,8 +37,11 @@ pub struct OutlineSuggestion {
pub entries: Vec<OutlineEntry>,
/// Pages in the document.
pub pages: usize,
/// Pages whose text was read: at most [`MAX_PAGES`] for a suggestion from layout.
/// Pages whose text was read: at most [`MAX_PAGES`](crate::text_style_bookmarks::MAX_PAGES)
/// for a suggestion from layout, fewer when a page's text can't be read.
pub pages_read: usize,
/// Headings were left out: pages weren't read, or layout found more than [`MAX_BOOKMARKS`].
pub truncated: bool,
}
impl OutlineSuggestion {
@@ -81,14 +84,17 @@ pub(crate) fn structure_entries(doc: &Document) -> Vec<OutlineEntry> {
}
/// The outline suggested for `doc`: its tagged headings, or else headings inferred from the
/// first [`MAX_PAGES`] pages' text. Empty when neither finds a heading.
/// first [`MAX_PAGES`](crate::text_style_bookmarks::MAX_PAGES) pages' text. Empty when neither
/// finds a heading.
pub fn suggest(doc: &Document) -> OutlineSuggestion {
let pages = pdfcraft_organize::page_count(doc).unwrap_or(0);
let tagged = structure_entries(doc);
if !tagged.is_empty() {
return OutlineSuggestion { source: OutlineSource::Structure, entries: tagged, pages, pages_read: pages };
return OutlineSuggestion { source: OutlineSource::Structure, entries: tagged, pages, pages_read: pages, truncated: false };
}
OutlineSuggestion { source: OutlineSource::Layout, entries: inferred(lines(doc)), pages, pages_read: pages.min(MAX_PAGES) }
let (lines, pages_read) = read_lines(doc);
let (entries, capped) = inferred(lines);
OutlineSuggestion { source: OutlineSource::Layout, entries, pages, pages_read, truncated: capped || pages_read < pages }
}
/// Lines in one style, one after another down a page.
@@ -147,27 +153,33 @@ fn blocks(lines: Vec<Line>) -> Vec<Block> {
out
}
/// A caption's lead: `Figure`, `Fig.`, `Table`, `Chart`, `Exhibit` or `Plate`, then a number.
/// A caption's lead in any case: `Figure`, `Fig.`, `Table`, `Chart`, `Exhibit` or `Plate`, then a
/// number.
fn is_caption(text: &str) -> bool {
let t = text.trim_start();
["Figure", "Fig.", "Table", "Chart", "Exhibit", "Plate"]
.iter()
.any(|lead| t.strip_prefix(lead).is_some_and(|rest| rest.trim_start().chars().next().is_some_and(|c| c.is_ascii_digit())))
["Figure", "Fig.", "Table", "Chart", "Exhibit", "Plate"].iter().any(|lead| {
let rest = t.get(..lead.len()).filter(|head| head.eq_ignore_ascii_case(lead)).and_then(|_| t.get(lead.len()..));
rest.is_some_and(|rest| rest.trim_start().chars().next().is_some_and(|c| c.is_ascii_digit()))
})
}
/// The headings among `lines`, as outline entries.
fn inferred(lines: Vec<Line>) -> Vec<OutlineEntry> {
/// The headings among `lines`, as outline entries: the first [`MAX_BOOKMARKS`], and whether there
/// were more.
fn inferred(lines: Vec<Line>) -> (Vec<OutlineEntry>, bool) {
let blocks: Vec<Block> = blocks(lines).into_iter().filter(|b| !is_caption(&b.title)).collect();
let evidence: Vec<TextBlock> = blocks.iter().map(Block::evidence).collect();
blocks
let mut entries: Vec<OutlineEntry> = blocks
.iter()
.zip(pdfcraft_a11y::heading_levels(&evidence))
.filter_map(|(b, level)| {
let [left, top] = b.first.anchor;
Some(OutlineEntry { level: level?, title: b.title.clone(), page: b.first.page, element: None, left, top })
})
.take(MAX_BOOKMARKS)
.collect()
.take(MAX_BOOKMARKS.saturating_add(1))
.collect();
let capped = entries.len() > MAX_BOOKMARKS;
entries.truncate(MAX_BOOKMARKS);
(entries, capped)
}
#[cfg(test)]
@@ -205,7 +217,8 @@ mod tests {
body(1, 730.0),
body(1, 716.0),
];
let found = inferred(lines);
let (found, capped) = inferred(lines);
assert!(!capped);
assert_eq!(titles(&found), [(1, "Getting started with the toolkit", 0), (2, "Installing", 0), (1, "Reference", 1)]);
assert_eq!((found[0].left, found[0].top), (None, Some(760.0)), "a bookmark goes to the top of its first line");
}
@@ -215,21 +228,70 @@ mod tests {
let mut right = body(0, 760.0);
(right.left, right.right) = (420.0, 560.0);
let lines = vec![line(0, 760.0, 20.0, true, "Two column"), right, line(0, 738.0, 20.0, true, "heading"), body(0, 700.0), body(0, 686.0)];
assert_eq!(titles(&inferred(lines)), [(1, "Two column heading", 0)]);
assert_eq!(titles(&inferred(lines).0), [(1, "Two column heading", 0)]);
}
#[test]
fn captions_and_numbers_are_not_headings() {
let lines = vec![line(0, 760.0, 16.0, true, "Figure 3: The toolkit"), line(0, 730.0, 16.0, true, "42"), body(0, 700.0), body(0, 686.0)];
assert!(inferred(lines).is_empty());
assert!(inferred(lines).0.is_empty());
assert!(is_caption("Table 12 Results") && is_caption("Fig. 2") && !is_caption("Tables are useful"));
}
#[test]
fn captions_match_in_any_case() {
let lines = vec![line(0, 760.0, 16.0, true, "FIGURE 3: Architecture"), body(0, 700.0), body(0, 686.0)];
assert!(inferred(lines).0.is_empty(), "an upper-case caption was suggested as a heading");
assert!(is_caption("table 2") && is_caption("FIG. 4") && !is_caption("TABLES are useful") && !is_caption("Figé 3"));
}
#[test]
fn more_headings_than_the_cap_are_reported() {
// Each heading on a page of its own, with a line of body text under it.
let pages = |n: usize| (0..n).flat_map(|p| [line(p, 760.0, 20.0, true, "Heading"), body(p, 700.0)]).collect::<Vec<_>>();
let (at_cap, capped) = inferred(pages(MAX_BOOKMARKS));
assert_eq!((at_cap.len(), capped), (MAX_BOOKMARKS, false));
let (over, capped) = inferred(pages(MAX_BOOKMARKS + 1));
assert_eq!((over.len(), capped), (MAX_BOOKMARKS, true), "a heading past the cap was dropped unreported");
}
/// A page past the page decode allowance (two compressed streams of spaces, each just over
/// half of it) can't be read: it doesn't count as read, and the suggestion says headings
/// may be missing.
#[test]
fn a_page_whose_text_cant_be_read_is_not_counted() {
let packed = pdfcraft_filters::encode_flate(&vec![b' '; pdfcraft_cos::MAX_PAGE_DECODED / 2 + 1]);
let stream = |dict: &str, data: &[u8]| [format!("<< /Length {} {dict} >>\nstream\n", data.len()).as_bytes(), data, b"\nendstream"].concat();
let objs: Vec<Vec<u8>> = vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] /Resources << /Font << /F 7 0 R >> >> >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /Contents 5 0 R >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /Contents [6 0 R 6 0 R] >>".to_vec(),
stream("", b"BT /F 11 Tf 72 700 Td (Body) Tj ET"),
stream("/Filter /FlateDecode", &packed),
b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec(),
];
let mut bytes = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (i, o) in objs.iter().enumerate() {
offsets.push(bytes.len());
bytes.extend_from_slice(&[format!("{} 0 obj\n", i + 1).as_bytes(), o, b"\nendobj\n"].concat());
}
let xref = bytes.len();
bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
for o in offsets {
bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
}
bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
let s = suggest(&Document::open(std::sync::Arc::new(bytes)).unwrap());
assert_eq!((s.pages, s.pages_read, s.truncated), (2, 1, true), "the unread page counted as read");
}
#[test]
fn the_tree_nests_by_level_and_caps_the_depth() {
let entry = |level: u8, title: &str| OutlineEntry { level, title: title.into(), page: 0, element: None, left: None, top: Some(700.0) };
let mut entries = vec![entry(1, "A"), entry(2, "A.1"), entry(3, "A.1.a"), entry(2, "A.2"), entry(1, "B")];
let s = OutlineSuggestion { source: OutlineSource::Layout, entries: entries.clone(), pages: 1, pages_read: 1 };
let s = OutlineSuggestion { source: OutlineSource::Layout, entries: entries.clone(), pages: 1, pages_read: 1, truncated: false };
let tree = s.tree();
assert_eq!(tree.iter().map(|n| n.title.as_str()).collect::<Vec<_>>(), ["A", "B"]);
assert_eq!(tree[0].children.iter().map(|n| n.title.as_str()).collect::<Vec<_>>(), ["A.1", "A.2"]);
+9 -1
View File
@@ -109,12 +109,20 @@ fn without_subset_tag(name: &str) -> &str {
/// The text lines of `doc`'s first [`MAX_PAGES`] pages, each page's in reading order. Text that
/// is only whitespace, or whose size can't be read, is left out.
pub(crate) fn lines(doc: &Document) -> Vec<Line> {
read_lines(doc).0
}
/// [`lines`], and how many pages' text was read: a page whose text can't be read (its content
/// past the page's decode allowance, say) is skipped and not counted.
pub(crate) fn read_lines(doc: &Document) -> (Vec<Line>, usize) {
let pages = pdfcraft_organize::page_count(doc).unwrap_or(0).min(MAX_PAGES);
let rotations = pdfcraft_organize::page_rotations(doc).unwrap_or_default();
let mut out = Vec::new();
let mut read = 0usize;
for page in 0..pages {
let rotation = rotations.get(page).copied().unwrap_or(0);
let Ok(found) = pdfcraft_edit::text_lines(doc, page) else { continue };
read = read.saturating_add(1);
let mut on_page: Vec<Line> = found
.into_iter()
.filter_map(|l| {
@@ -147,7 +155,7 @@ pub(crate) fn lines(doc: &Document) -> Vec<Line> {
on_page.sort_by(|a, b| (b.top * 10.0).round().total_cmp(&(a.top * 10.0).round()).then(a.left.total_cmp(&b.left)));
out.extend(on_page);
}
out
(out, read)
}
/// The styles `doc`'s text is set in, the largest size first (then the most used): headings
+1 -1
View File
@@ -3442,7 +3442,7 @@ milestone = "M4"
status = "partial"
commands = []
tools = ["bookmark_suggest"]
evidence = ["crates/automation/tests/it/suggest_outline.rs::suggest_from_layout_then_import_and_undo", "crates/automation/tests/it/suggest_outline.rs::suggest_uses_the_tags_once_there_are_some", "crates/engine/src/suggest_outline.rs::headings_take_levels_by_size_and_weight_and_wrapped_lines_join", "crates/engine/src/suggest_outline.rs::a_wrapped_heading_joins_across_a_line_of_another_column", "crates/engine/src/suggest_outline.rs::captions_and_numbers_are_not_headings", "crates/engine/src/suggest_outline.rs::the_tree_nests_by_level_and_caps_the_depth", "crates/a11y/src/heading_levels.rs::blocks_take_the_levels_auto_tag_gives_text_objects"]
evidence = ["crates/automation/tests/it/suggest_outline.rs::suggest_from_layout_then_import_and_undo", "crates/automation/tests/it/suggest_outline.rs::suggest_uses_the_tags_once_there_are_some", "crates/engine/src/suggest_outline.rs::headings_take_levels_by_size_and_weight_and_wrapped_lines_join", "crates/engine/src/suggest_outline.rs::a_wrapped_heading_joins_across_a_line_of_another_column", "crates/engine/src/suggest_outline.rs::captions_and_numbers_are_not_headings", "crates/engine/src/suggest_outline.rs::captions_match_in_any_case", "crates/engine/src/suggest_outline.rs::more_headings_than_the_cap_are_reported", "crates/engine/src/suggest_outline.rs::a_page_whose_text_cant_be_read_is_not_counted", "crates/engine/src/suggest_outline.rs::the_tree_nests_by_level_and_caps_the_depth", "crates/a11y/src/heading_levels.rs::blocks_take_the_levels_auto_tag_gives_text_objects"]
notes = "#6020, headless only: bookmark_suggest proposes a bookmark tree without changing the document, from its tagged headings when it has them, or else from how its text looks, by the heading rules Auto-tag uses (a short block larger than the body text, or bold where the body is not, levelled by size without skipping a level). A heading set on several lines is one bookmark going to its top (/XYZ); captions (Figure 3, Table 2) are left out. The proposal is in bookmark_export's form, so it is reviewed and edited as data and applied with bookmark_import in one undoable step. Not yet: the review dialog in the app, leaving out running headers and footers, multi-column reading order (lines are read down the page, then across), and the first 5000 pages only. Acrobat makes bookmarks from structure only; this is beyond it"
[[feature]]