use std::collections::BTreeSet;
use crate::layout::group::{ALIGN_TOL, BASELINE_TOL, LINE_SPLIT_GAP, SIZE_TOL, is_marker};
use crate::layout::hyphen::{self, Candidate, Decision, DocEvidence, HyphenSignals};
use crate::layout::table::{self, Align, Body};
use crate::layout::{Block, CharKind, Page, Word};
#[derive(Clone, Debug, PartialEq)]
pub struct OutlineEntry {
pub title: String,
pub level: usize,
pub page: usize,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum HeadingSource {
#[default]
Auto,
Outline,
Tags,
Typography,
}
#[derive(Clone, Debug, Default)]
pub struct Options {
pub source_name: String,
pub pages: Option<BTreeSet<usize>>,
pub page_markers: bool,
pub heading_source: HeadingSource,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Output {
pub markdown: String,
pub warnings: Vec<String>,
pub heading_source: Option<HeadingSource>,
}
const HEADING_SIZE_RATIO: f32 = 1.15;
const MAX_HEADING_LINES: usize = 3;
const MAX_TITLE_LINES: usize = 5;
const MAX_HEADING_CHARS: usize = 200;
const TITLE_VS_HEADING: f32 = 0.95;
const FOOTNOTE_RATIO: f32 = 0.95;
#[derive(Clone, Copy, Debug, PartialEq)]
enum Kind {
Paragraph,
Heading(u8),
ListItem,
Code,
Figure((usize, u32)),
}
fn figure_of(b: &Block) -> Option<u32> {
let mut words = b.lines.iter().flat_map(|l| &l.words);
let first = words.next()?.figure?;
words
.all(|w| w.figure.is_some_and(|f| f.object == first.object))
.then_some(first.object)
}
type BlockId = (usize, usize);
fn block_text(b: &Block) -> String {
b.lines
.iter()
.map(|l| l.text())
.collect::<Vec<_>>()
.join(" ")
}
fn norm(s: &str) -> String {
s.chars()
.filter(|c| c.is_alphanumeric())
.flat_map(char::to_lowercase)
.collect()
}
fn norm_unnumbered(s: &str) -> String {
let t = s.trim_start();
let rest = t.trim_start_matches(|c: char| c.is_ascii_digit() || c == '.');
if rest.len() < t.len() && rest.starts_with(char::is_whitespace) {
norm(rest)
} else {
norm(t)
}
}
fn starts_with_list_marker(b: &Block) -> bool {
b.lines
.first()
.is_some_and(|l| l.words.len() >= 2 && l.words.first().is_some_and(|w| is_marker(&w.text)))
}
fn body_size(pages: &[Page]) -> f32 {
let mut sizes: Vec<(f32, usize)> = Vec::new();
for w in pages
.iter()
.flat_map(|p| &p.blocks)
.flat_map(|b| &b.lines)
.flat_map(|l| &l.words)
{
match sizes
.iter_mut()
.find(|(s, _)| (s - w.size).abs() <= SIZE_TOL * s.max(w.size))
{
Some((_, n)) => *n += w.len,
None => sizes.push((w.size, w.len)),
}
}
sizes
.into_iter()
.max_by(|a, b| a.1.cmp(&b.1).then(b.0.total_cmp(&a.0)))
.map_or(0.0, |(s, _)| s)
}
fn tag_level(page: &Page, b: &Block) -> Option<u8> {
let mut counts = [0usize; 7];
let mut total = 0;
for w in b.lines.iter().flat_map(|l| &l.words) {
for c in page.chars.get(w.chars.clone()).unwrap_or(&[]) {
if c.ch.is_whitespace() {
continue;
}
total += 1;
if let Some(l) = c.source.struct_heading {
counts[usize::from(l.min(6))] += 1;
}
}
}
let (level, n) = counts
.iter()
.enumerate()
.skip(1)
.max_by_key(|(i, n)| (**n, std::cmp::Reverse(*i)))?;
(*n * 2 > total).then(|| u8::try_from(level).unwrap_or(6))
}
fn heading_shaped(b: &Block, max_lines: usize) -> bool {
let text = block_text(b);
let ends_like_sentence = text.trim_end().ends_with(['.', ',', ';', ':']);
!b.style.mono
&& b.lines.len() <= max_lines
&& text.chars().count() <= MAX_HEADING_CHARS
&& text.chars().any(char::is_alphabetic)
&& !ends_like_sentence
&& !starts_with_list_marker(b)
}
fn isolated(page: &Page, i: usize) -> bool {
let b = &page.blocks[i];
page.blocks.iter().enumerate().all(|(j, o)| {
j == i || o.region != b.region || o.bbox.bottom <= b.bbox.top || o.bbox.top >= b.bbox.bottom
})
}
#[derive(Clone, Copy, Debug)]
struct TypoCand {
id: BlockId,
size: Option<f32>,
lines: usize,
}
fn typo_candidates(pages: &[Page], body: f32) -> Vec<TypoCand> {
let mut out = Vec::new();
for (pi, p) in pages.iter().enumerate() {
for (bi, b) in p.blocks.iter().enumerate() {
if !heading_shaped(b, MAX_TITLE_LINES) || !isolated(p, bi) {
continue;
}
let lines = b.lines.len();
if b.size >= HEADING_SIZE_RATIO * body {
out.push(TypoCand {
id: (pi, bi),
size: Some(b.size),
lines,
});
} else if b.style.bold && lines == 1 && (b.size - body).abs() <= SIZE_TOL * body {
out.push(TypoCand {
id: (pi, bi),
size: None,
lines,
});
}
}
}
out
}
fn size_class(classes: &mut Vec<Option<f32>>, s: Option<f32>) -> usize {
let same = |x: &Option<f32>| match (x, s) {
(Some(x), Some(s)) => (x - s).abs() <= SIZE_TOL * x.max(s),
(None, None) => true,
_ => false,
};
match classes.iter().position(same) {
Some(i) => i,
None => {
classes.push(s);
classes.len() - 1
}
}
}
fn typo_levels(cands: &[TypoCand]) -> Vec<(BlockId, u8)> {
let mut classes: Vec<Option<f32>> = Vec::new();
let class: Vec<usize> = cands
.iter()
.map(|c| size_class(&mut classes, c.size))
.collect();
let mut counts = vec![0usize; classes.len()];
for &k in &class {
counts[k] += 1;
}
let first_repeated = class
.iter()
.position(|&k| counts[k] >= 2)
.unwrap_or(cands.len());
let front: Vec<usize> = (0..first_repeated)
.filter(|&i| cands[i].id.0 == 0)
.collect();
let title = front
.iter()
.copied()
.filter(|&i| cands[i].size.is_some())
.max_by(|&a, &b| {
let (sa, sb) = (cands[a].size.unwrap_or(0.0), cands[b].size.unwrap_or(0.0));
sa.total_cmp(&sb).then(b.cmp(&a))
});
let kept: Vec<usize> = (0..cands.len())
.filter(|i| !front.contains(i) && cands[*i].lines <= MAX_HEADING_LINES)
.collect();
let mut sizes: Vec<f32> = kept.iter().filter_map(|&i| cands[i].size).collect();
sizes.sort_by(|a, b| b.total_cmp(a));
sizes.dedup_by(|a, b| (*a - *b).abs() <= SIZE_TOL * a.max(*b));
let mut out: Vec<(BlockId, u8)> = title.map(|t| (cands[t].id, 1)).into_iter().collect();
for i in kept {
let rank = match cands[i].size {
Some(s) => sizes
.iter()
.position(|x| (x - s).abs() <= SIZE_TOL * x.max(s))
.unwrap_or(0),
None => sizes.len(),
};
out.push((cands[i].id, u8::try_from(rank + 1).unwrap_or(6).min(6)));
}
out
}
fn outline_levels(pages: &[Page], outline: &[OutlineEntry], body: f32) -> Vec<(BlockId, u8)> {
let mut taken: BTreeSet<BlockId> = BTreeSet::new();
let mut out = Vec::new();
for e in outline {
let want = norm(&e.title);
if want.is_empty() {
continue;
}
let want_unnumbered = norm_unnumbered(&e.title);
let found = [e.page, e.page + 1, e.page.saturating_sub(1)]
.into_iter()
.find_map(|n| {
let pi = n.checked_sub(1)?;
let p = pages.get(pi)?;
p.blocks.iter().enumerate().find_map(|(bi, b)| {
if taken.contains(&(pi, bi))
|| b.lines.len() > MAX_HEADING_LINES
|| b.size < FOOTNOTE_RATIO * body
{
return None;
}
let t = block_text(b);
let hit = norm(&t) == want || norm_unnumbered(&t) == want_unnumbered;
hit.then_some((pi, bi))
})
});
if let Some(id) = found {
taken.insert(id);
out.push((id, u8::try_from(e.level.clamp(1, 6)).unwrap_or(6)));
}
}
out
}
fn title(pages: &[Page], body: f32, headings: &[(BlockId, u8)]) -> Option<BlockId> {
let p = pages.first()?;
let first_heading = headings
.iter()
.filter(|((pi, _), _)| *pi == 0)
.map(|((_, bi), _)| *bi)
.min()
.unwrap_or(p.blocks.len());
let max_heading = headings
.iter()
.filter_map(|((pi, bi), _)| pages.get(*pi)?.blocks.get(*bi).map(|b| b.size))
.fold(0.0f32, f32::max);
let min = (HEADING_SIZE_RATIO * body).max(TITLE_VS_HEADING * max_heading);
p.blocks[..first_heading]
.iter()
.enumerate()
.filter(|(_, b)| b.size >= min && heading_shaped(b, MAX_TITLE_LINES))
.max_by(|a, b| a.1.size.total_cmp(&b.1.size).then(b.0.cmp(&a.0)))
.map(|(bi, _)| (0, bi))
}
fn headings(
pages: &[Page],
outline: &[OutlineEntry],
body: f32,
source: HeadingSource,
) -> (Vec<(BlockId, u8)>, HeadingSource) {
let use_outline = |found: &[(BlockId, u8)]| {
!found.is_empty() && found.len() * 2 >= outline.len()
};
let tagged = || -> Vec<(BlockId, u8)> {
pages
.iter()
.enumerate()
.flat_map(|(pi, p)| {
p.blocks
.iter()
.enumerate()
.filter_map(move |(bi, b)| tag_level(p, b).map(|l| ((pi, bi), l)))
})
.collect()
};
let with_title = |mut hs: Vec<(BlockId, u8)>| {
if let Some(t) = title(pages, body, &hs) {
hs.push((t, 1));
}
hs
};
match source {
HeadingSource::Outline => (
with_title(outline_levels(pages, outline, body)),
HeadingSource::Outline,
),
HeadingSource::Tags => (with_title(tagged()), HeadingSource::Tags),
HeadingSource::Typography => (
typo_levels(&typo_candidates(pages, body)),
HeadingSource::Typography,
),
HeadingSource::Auto => {
let o = outline_levels(pages, outline, body);
if use_outline(&o) {
return (with_title(o), HeadingSource::Outline);
}
let t = tagged();
if !t.is_empty() {
return (with_title(t), HeadingSource::Tags);
}
(
typo_levels(&typo_candidates(pages, body)),
HeadingSource::Typography,
)
}
}
}
#[derive(Clone, Copy)]
struct Seg<'a> {
page: &'a Page,
words: &'a [Word],
}
fn words_text(ws: &[Word]) -> String {
let mut s = String::new();
for (i, w) in ws.iter().enumerate() {
if i > 0 && !w.glued {
s.push(' ');
}
s.push_str(&w.text);
}
s
}
#[derive(Debug, PartialEq)]
enum Join {
Space,
DropHyphen,
Glue,
}
fn line_join(prev: &Seg, next: &Seg, ev: &DocEvidence) -> Join {
let (Some(w), Some(n)) = (prev.words.last(), next.words.first()) else {
return Join::Space;
};
let chars = &prev.page.chars;
if w.text.ends_with('\u{AD}') {
return Join::DropHyphen;
}
let Some(last) = w.chars.end.checked_sub(1).and_then(|i| chars.get(i)) else {
return Join::Space;
};
let before_hyphen = w.text.strip_suffix('-').unwrap_or("");
if w.text == "-" {
return Join::Glue;
}
if last.kind != CharKind::LineEndHyphen || w.text.chars().count() < 2 {
if before_hyphen.ends_with(|c: char| c.is_ascii_digit()) {
return Join::Glue;
}
return Join::Space;
}
let own_object = (|| {
let prev_char = chars.get(w.chars.end.checked_sub(2)?)?;
let (po, ho) = (prev_char.source.object?, last.source.object?);
if po == ho {
return Some(false);
}
let run = chars.iter().filter(|c| c.source.object == Some(po)).count();
(run >= 2).then_some(true)
})();
let next_first = next.page.chars.get(n.chars.start);
let cand = Candidate {
before: before_hyphen
.trim_start_matches(|c: char| !c.is_alphanumeric())
.to_string(),
after: n
.text
.trim_end_matches(|c: char| !c.is_alphanumeric())
.to_string(),
signals: HyphenSignals {
actual_text: last.source.actual_text.clone(),
struct_actual_text: last.source.struct_actual_text.clone(),
hidden_before: last.source.hidden_text_before.clone(),
next_hidden_before: next_first.and_then(|c| c.source.hidden_text_before.clone()),
own_object,
},
};
match hyphen::decide(&cand, ev).0 {
Decision::Join => Join::DropHyphen,
Decision::Keep => Join::Glue,
}
}
fn join_lines(segs: &[Seg], ev: &DocEvidence) -> String {
let mut out = String::new();
for (i, s) in segs.iter().enumerate() {
let t = words_text(s.words);
if i > 0 {
match line_join(&segs[i - 1], s, ev) {
Join::Space => out.push(' '),
Join::DropHyphen => {
out.pop();
}
Join::Glue => {}
}
}
out.push_str(&t);
}
out.retain(|c| c != '\u{AD}');
out
}
fn escape_inline(s: &str) -> String {
let chars: Vec<char> = s.chars().collect();
let mut out = String::with_capacity(s.len());
for (i, &c) in chars.iter().enumerate() {
let escape = match c {
'\\' | '*' | '`' => true,
'[' => false,
']' => chars
.get(i + 1)
.is_some_and(|n| matches!(n, '(' | '[' | ':')),
'<' => chars
.get(i + 1)
.is_some_and(|n| n.is_ascii_alphabetic() || matches!(n, '/' | '!' | '?')),
'_' => {
let prev = i.checked_sub(1).and_then(|j| chars.get(j));
let next = chars.get(i + 1);
!(prev.is_some_and(|c| c.is_alphanumeric())
&& next.is_some_and(|c| c.is_alphanumeric()))
}
_ => false,
};
if escape {
out.push('\\');
}
out.push(c);
}
out
}
fn escape_block_start(s: &str) -> String {
let t = escape_inline(s);
if t.starts_with(['#', '>', '-', '+', '=', '~', '|']) {
return format!("\\{t}");
}
let digits = t.chars().take_while(char::is_ascii_digit).count();
if digits > 0 && digits <= 9 {
let rest = &t[digits..];
if let Some(r) = rest.strip_prefix(['.', ')']) {
if r.is_empty() || r.starts_with(' ') {
let (n, d) = t.split_at(digits);
return format!("{n}\\{d}");
}
}
}
t
}
fn comment_safe(s: &str) -> String {
let mut out = s.replace("--", "- -");
while out.contains("--") {
out = out.replace("--", "- -");
}
out
}
enum Item<'a> {
PageMarker(usize),
NoText(usize),
Heading(u8, Vec<Seg<'a>>, (usize, f32, f32)),
Paragraph {
segs: Vec<Seg<'a>>,
size: f32,
full_last: bool,
},
List {
marker: String,
x: f32,
size: f32,
segs: Vec<Seg<'a>>,
},
Code(String),
Table(&'a Page, table::Body),
FigureText((usize, u32), Vec<String>),
}
fn open_ended(segs: &[Seg]) -> bool {
let Some(w) = segs.last().and_then(|s| s.words.last()) else {
return false;
};
let t = w
.text
.trim_end_matches(['"', '\'', '”', '’', '»', ')', ']', '*']);
!t.ends_with(['.', '!', '?', ';', '…'])
}
fn ends_with_colon(segs: &[Seg]) -> bool {
segs.last()
.and_then(|s| s.words.last())
.is_some_and(|w| w.text.ends_with(':'))
}
const FULL_LINE_TOL: f32 = 1.0;
fn full_last_line(b: &Block) -> bool {
b.lines.len() >= 2
&& b.lines
.last()
.is_some_and(|l| l.bbox.right >= b.bbox.right - FULL_LINE_TOL * b.size)
}
fn starts_lowercase(b: &Block) -> bool {
b.lines
.first()
.and_then(|l| l.words.first())
.and_then(|w| w.text.chars().next())
.is_some_and(char::is_lowercase)
}
fn code_text(b: &Block) -> String {
let words = || b.lines.iter().flat_map(|l| &l.words);
let mut adv: Vec<f32> = words()
.filter(|w| w.len > 0)
.map(|w| w.bbox.width() / w.len as f32)
.filter(|a| *a > 0.0)
.collect();
adv.sort_by(f32::total_cmp);
let Some(&cw) = adv.get(adv.len() / 2) else {
return String::new();
};
let mut lines = Vec::new();
for l in &b.lines {
let mut s = String::new();
let mut col = 0usize;
for (i, w) in l.words.iter().enumerate() {
let at = ((w.bbox.left - b.bbox.left) / cw).round().max(0.0) as usize;
let at = at.min(col + 200);
if i > 0 && !w.glued && at <= col {
s.push(' ');
col += 1;
}
while col < at {
s.push(' ');
col += 1;
}
s.push_str(&w.text);
col += w.text.chars().count();
}
lines.push(s.trim_end().to_string());
}
lines.join("\n")
}
fn list_number(marker: &str) -> Option<u64> {
let body = marker.strip_suffix(['.', ')'])?;
if body.is_empty() || !body.chars().all(|c| c.is_ascii_digit()) {
return None;
}
body.parse().ok()
}
fn is_portuguese(pages: &[Page]) -> bool {
const PT: &[&str] = &[
"de", "que", "não", "uma", "com", "para", "os", "as", "da", "do", "em", "é", "um",
];
const EN: &[&str] = &[
"the", "of", "and", "to", "is", "in", "that", "with", "for", "a",
];
let (mut pt, mut en) = (0usize, 0usize);
for w in pages
.iter()
.flat_map(|p| &p.blocks)
.flat_map(|b| &b.lines)
.flat_map(|l| &l.words)
{
let t = w.text.to_lowercase();
pt += usize::from(PT.contains(&t.as_str()));
en += usize::from(EN.contains(&t.as_str()));
}
pt > en
}
pub fn render(pages: &[Page], outline: &[OutlineEntry], opts: &Options) -> Output {
let body = body_size(pages);
let (heads, used) = headings(pages, outline, body, opts.heading_source);
let level_of = |id: BlockId| heads.iter().find(|(h, _)| *h == id).map(|(_, l)| *l);
let chars: Vec<Vec<crate::layout::Char>> = pages.iter().map(|p| p.chars.clone()).collect();
let ev = DocEvidence::from_pages(&chars, is_portuguese(pages));
let selected = |n: usize| opts.pages.as_ref().is_none_or(|s| s.contains(&n));
let mut warnings = Vec::new();
let mut items: Vec<Item> = Vec::new();
for (pi, p) in pages.iter().enumerate() {
if !selected(p.number) {
continue;
}
if opts.page_markers {
items.push(Item::PageMarker(p.number));
}
if p.blocks.is_empty() {
items.push(Item::NoText(p.number));
warnings.push(format!(
"page {} has no text layer (scanned?); run OCR if its text is needed",
p.number
));
continue;
}
let tables = table::detect(p, |bi| {
let b = &p.blocks[bi];
figure_of(b).is_none() && level_of((pi, bi)).is_none() && !b.style.mono
});
let mut in_table = vec![None; p.blocks.len()];
for (ti, t) in tables.iter().enumerate() {
for &bi in &t.blocks {
if let Some(x) = in_table.get_mut(bi) {
*x = Some(ti);
}
}
}
let mut emitted = vec![false; tables.len()];
for (bi, b) in p.blocks.iter().enumerate() {
if let Some(ti) = in_table[bi] {
if !emitted[ti] {
emitted[ti] = true;
items.push(Item::Table(p, tables[ti].body.clone()));
}
continue;
}
let segs = |skip: bool| -> Vec<Seg> {
b.lines
.iter()
.enumerate()
.map(|(k, l)| Seg {
page: p,
words: if skip && k == 0 {
l.words.get(1..).unwrap_or(&[])
} else {
&l.words
},
})
.collect()
};
let kind = match (figure_of(b), level_of((pi, bi))) {
(Some(f), _) => Kind::Figure((p.number, f)),
(None, Some(l)) => Kind::Heading(l),
(None, None) if b.style.mono => Kind::Code,
(None, None) if starts_with_list_marker(b) => Kind::ListItem,
(None, None) => Kind::Paragraph,
};
match kind {
Kind::Heading(l) => {
let base = b.lines.first().map_or(0.0, |l| l.baseline);
let end = b.lines.last().map_or(0.0, |l| l.baseline);
if let Some(Item::Heading(pl, ps, (pp, pb, psize))) = items.last_mut()
&& *pl == l
&& *pp == p.number
&& (base - *pb).abs() <= BASELINE_TOL * psize.max(b.size)
{
ps.extend(segs(false));
*pb = end;
continue;
}
items.push(Item::Heading(l, segs(false), (p.number, end, b.size)));
}
Kind::Code => items.push(Item::Code(code_text(b))),
Kind::Figure(f) => {
let t = block_text(b);
match items.last_mut() {
Some(Item::FigureText(g, texts)) if *g == f => texts.push(t),
_ => items.push(Item::FigureText(f, vec![t])),
}
}
Kind::ListItem => {
let m = &b.lines[0].words[0];
items.push(Item::List {
marker: m.text.clone(),
x: m.bbox.left,
size: b.size,
segs: segs(true),
});
}
Kind::Paragraph => {
let new_region = bi == 0 || p.blocks[bi - 1].region != b.region;
if continue_paragraph(&items, b, new_region) {
if let Some(Item::Paragraph {
segs: s, full_last, ..
}) = items.iter_mut().rev().find(|it| is_target(it, b.size))
{
s.extend(segs(false));
*full_last = full_last_line(b);
}
continue;
}
items.push(Item::Paragraph {
segs: segs(false),
size: b.size,
full_last: full_last_line(b),
});
}
}
}
}
let mut out = String::new();
let total = pages.len();
let shown: Vec<usize> = pages
.iter()
.map(|p| p.number)
.filter(|&n| selected(n))
.collect();
out.push_str(&format!(
"<!-- pdfsift: source={} pages={}/{total} -->\n",
comment_safe(&opts.source_name),
ranges(&shown)
));
let mut stack: Vec<(f32, usize)> = Vec::new();
let mut prev_list = false;
let mut prev_marker = true;
for it in &items {
let is_list = matches!(it, Item::List { .. });
let is_marker = matches!(it, Item::PageMarker(_));
if !is_list && !is_marker {
stack.clear();
}
if !(prev_marker || is_list && prev_list) {
out.push('\n');
}
match it {
Item::PageMarker(n) => out.push_str(&format!("<!-- page: {n} -->\n")),
Item::NoText(n) => {
out.push_str(&format!("<!-- pdfsift: page {n} has no text layer -->\n"))
}
Item::Heading(l, segs, _) => {
let mut t = escape_inline(&join_lines(segs, &ev));
if t.ends_with('#') {
t.insert(t.len() - 1, '\\');
}
out.push_str(&"#".repeat(usize::from(*l)));
out.push(' ');
out.push_str(&t);
out.push('\n');
}
Item::Paragraph { segs, .. } => {
out.push_str(&escape_block_start(&join_lines(segs, &ev)));
out.push('\n');
}
Item::FigureText(_, texts) => {
let t = comment_safe(&texts.join(" | "));
out.push_str(&format!("<!-- figure text: {t} -->\n"));
}
Item::Table(page, body) => out.push_str(&table_text(page, body, &ev)),
Item::Code(t) => {
let fence = if t.contains("```") { "````" } else { "```" };
out.push_str(&format!("{fence}\n{t}\n{fence}\n"));
}
Item::List {
marker,
x,
size,
segs,
} => {
let tol = ALIGN_TOL * size;
while stack.last().is_some_and(|(sx, _)| *x < sx - tol) {
stack.pop();
}
let same = stack.last().is_some_and(|(sx, _)| (x - sx).abs() <= tol);
if same {
stack.pop();
}
let indent = stack.last().map_or(0, |(_, i)| *i);
let prefix = match list_number(marker) {
Some(n) => format!("{n}. "),
None if group_bullet(marker) => "- ".to_string(),
None => format!("- {} ", escape_inline(marker)),
};
let content_indent = indent + prefix.chars().count().min(prefix.len());
stack.push((*x, content_indent));
out.push_str(&" ".repeat(indent));
out.push_str(&prefix);
out.push_str(&escape_block_start(&join_lines(segs, &ev)));
out.push('\n');
}
}
prev_list = is_list;
prev_marker = is_marker || matches!(it, Item::NoText(_));
}
if !out.ends_with('\n') {
out.push('\n');
}
Output {
markdown: out,
warnings,
heading_source: Some(used),
}
}
fn table_text(page: &Page, body: &Body, ev: &DocEvidence) -> String {
match body {
Body::Grid { align, rows } => {
let mut out = String::new();
for (ri, row) in rows.iter().enumerate() {
out.push('|');
for cell in row {
let segs: Vec<Seg> = cell
.iter()
.map(|l| Seg {
page,
words: l.as_slice(),
})
.collect();
let t = escape_inline(&join_lines(&segs, ev)).replace('|', "\\|");
out.push(' ');
out.push_str(&t);
out.push_str(if t.is_empty() { "|" } else { " |" });
}
out.push('\n');
if ri == 0 {
out.push('|');
for a in align {
out.push_str(match a {
Align::Left => "---|",
Align::Right => "---:|",
Align::Center => ":---:|",
});
}
out.push('\n');
}
}
out
}
Body::Layout { rows } => {
let t = layout_text(rows);
let fence = if t.contains("```") { "````" } else { "```" };
format!("{fence}\n{t}\n{fence}\n")
}
}
}
fn layout_text(rows: &[Vec<Word>]) -> String {
let words = || rows.iter().flatten().filter(|w| w.len > 0);
let mut adv: Vec<f32> = words()
.map(|w| w.bbox.width() / w.len as f32)
.filter(|a| *a > 0.0)
.collect();
adv.sort_by(f32::total_cmp);
let (Some(&cw), Some(left)) = (
adv.get(adv.len() / 2),
words().map(|w| w.bbox.left).reduce(f32::min),
) else {
return String::new();
};
let mut lines = Vec::new();
for row in rows {
let mut s = String::new();
let mut col = 0usize;
let mut prev: Option<&Word> = None;
for w in row {
let at = (((w.bbox.left - left) / cw).round().max(0.0) as usize).min(col + 200);
match prev {
None => {}
Some(p) if w.bbox.left - p.bbox.right <= LINE_SPLIT_GAP * w.size.max(p.size) => {
if !w.glued {
s.push(' ');
col += 1;
}
}
Some(_) => {
let to = at.max(col + 2);
s.push_str(&" ".repeat(to - col));
col = to;
}
}
if prev.is_none() {
s.push_str(&" ".repeat(at));
col = at;
}
s.push_str(&w.text);
col += w.text.chars().count();
prev = Some(w);
}
lines.push(s.trim_end().to_string());
}
lines.join("\n")
}
fn group_bullet(marker: &str) -> bool {
!marker.ends_with(['.', ')'])
}
fn is_target(it: &Item, size: f32) -> bool {
matches!(it, Item::Paragraph { size: s, .. } if (s - size).abs() <= SIZE_TOL * s.max(size))
}
fn continue_paragraph(items: &[Item], b: &Block, new_region: bool) -> bool {
for it in items.iter().rev() {
match it {
Item::PageMarker(_) => {}
Item::Paragraph {
segs,
size,
full_last,
} => {
if is_target(it, b.size) {
return open_ended(segs)
&& (starts_lowercase(b)
|| new_region && *full_last && !ends_with_colon(segs));
}
if !new_region || *size >= FOOTNOTE_RATIO * b.size {
return false;
}
}
_ => return false,
}
}
false
}
fn ranges(ns: &[usize]) -> String {
let mut parts: Vec<String> = Vec::new();
let mut i = 0;
while i < ns.len() {
let mut j = i;
while j + 1 < ns.len() && ns[j + 1] == ns[j] + 1 {
j += 1;
}
parts.push(if i == j {
ns[i].to_string()
} else {
format!("{}-{}", ns[i], ns[j])
});
i = j + 1;
}
if parts.is_empty() {
"none".into()
} else {
parts.join(",")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::layout::group::{PagePrimitives, layout_document};
use crate::layout::{Char, Rect, Style};
const R: Style = Style {
bold: false,
italic: false,
mono: false,
};
const BOLD: Style = Style {
bold: true,
italic: false,
mono: false,
};
fn line(text: &str, x: f32, base: f32, size: f32, style: Style) -> Vec<Char> {
let font = if style.bold { "Serif-Bold" } else { "Serif" };
let n = text.chars().count();
let mut out = Vec::new();
let mut x = x;
for (i, ch) in text.chars().enumerate() {
let space = ch == ' ';
let w = if space { 0.0 } else { 0.5 * size };
let hyphen = ch == '-' && i + 1 == n && i > 0;
out.push(Char {
ch,
bbox: if space {
Rect::new(x, base, x, base)
} else {
Rect::new(x, base - 0.9 * size, x + w, base + 0.25 * size)
},
baseline: base,
size,
font: font.into(),
style,
generated: space,
kind: if hyphen {
CharKind::LineEndHyphen
} else {
CharKind::Text
},
source: Default::default(),
});
x += if space { 0.25 * size } else { w };
}
out
}
type L<'a> = (&'a str, f32, Style, f32);
fn doc(pages: &[&[L]]) -> Vec<Page> {
let prims = pages
.iter()
.map(|lines| {
let mut chars = Vec::new();
let mut base = 50.0;
for (t, size, style, gap) in lines.iter() {
base += gap;
chars.extend(line(t, 50.0, base, *size, *style));
}
PagePrimitives {
width: 600.0,
height: 800.0,
chars,
path_marks: Vec::new(),
rules: Vec::new(),
}
})
.collect();
layout_document(prims)
}
fn opts(pages: Option<BTreeSet<usize>>, page_markers: bool) -> Options {
Options {
source_name: "x.pdf".into(),
pages,
page_markers,
heading_source: HeadingSource::Auto,
}
}
fn md(pages: &[Page], outline: &[OutlineEntry]) -> String {
render(pages, outline, &opts(None, true)).markdown
}
fn body(s: &str) -> Vec<String> {
s.split("\n\n")
.filter_map(|b| {
let lines: Vec<&str> = b.lines().filter(|l| !l.starts_with("<!--")).collect();
(!lines.is_empty()).then(|| lines.join("\n"))
})
.collect()
}
#[test]
fn paragraph_lines_are_joined_and_dehyphenated() {
let pages = doc(&[&[
(
"Uma palavra longa que se quebra no fim da li-",
10.0,
R,
0.0,
),
(
"nha mas segunda-feira continua com o hífen e",
10.0,
R,
12.0,
),
("depois vem outra segunda-", 10.0, R, 12.0),
("feira no texto.", 10.0, R, 12.0),
]]);
assert_eq!(
body(&md(&pages, &[])),
[
"Uma palavra longa que se quebra no fim da linha mas segunda-feira continua com o \
hífen e depois vem outra segunda-feira no texto."
]
);
}
#[test]
fn outline_headings_and_title() {
let pages = doc(&[&[
("Um Título", 20.0, BOLD, 0.0),
("Introdução", 14.0, BOLD, 40.0),
("Texto do corpo, uma frase.", 10.0, R, 25.0),
("Detalhe", 12.0, BOLD, 25.0),
("Mais texto.", 10.0, R, 25.0),
]]);
let outline = [
OutlineEntry {
title: "Introdução".into(),
level: 1,
page: 1,
},
OutlineEntry {
title: " Detalhe".into(),
level: 2,
page: 1,
},
];
assert_eq!(
body(&md(&pages, &outline)),
[
"# Um Título",
"# Introdução",
"Texto do corpo, uma frase.",
"## Detalhe",
"Mais texto."
]
);
}
#[test]
fn typography_ranks_sizes_and_skips_front_matter() {
let pages = doc(&[&[
("Um Título", 20.0, BOLD, 0.0),
("Autor Fulano", 12.0, R, 30.0),
("Primeira", 14.0, BOLD, 30.0),
("Texto do corpo, uma frase.", 10.0, R, 25.0),
("Subseção", 10.0, BOLD, 25.0),
("Texto do corpo, outra frase.", 10.0, R, 25.0),
("Segunda", 14.0, BOLD, 25.0),
("Texto final do corpo.", 10.0, R, 25.0),
("Outra subseção", 10.0, BOLD, 25.0),
("Mais texto do corpo.", 10.0, R, 25.0),
]]);
assert_eq!(
body(&md(&pages, &[])),
[
"# Um Título",
"Autor Fulano",
"# Primeira",
"Texto do corpo, uma frase.",
"## Subseção",
"Texto do corpo, outra frase.",
"# Segunda",
"Texto final do corpo.",
"## Outra subseção",
"Mais texto do corpo."
]
);
}
#[test]
fn a_bold_sentence_is_not_a_heading() {
let pages = doc(&[&[
("Texto do corpo, uma frase.", 10.0, R, 0.0),
("Atenção: isto é importante.", 10.0, BOLD, 25.0),
("Mais texto.", 10.0, R, 25.0),
]]);
assert!(!md(&pages, &[]).contains('#'));
}
#[test]
fn lists_with_markers_and_numbers() {
let pages = doc(&[&[
("Uma lista:", 10.0, R, 0.0),
("• primeiro item", 10.0, R, 25.0),
("• segundo item", 10.0, R, 12.0),
("1. passo um", 10.0, R, 25.0),
("2. passo dois", 10.0, R, 12.0),
]]);
assert_eq!(
body(&md(&pages, &[])),
[
"Uma lista:",
"- primeiro item\n- segundo item\n1. passo um\n2. passo dois"
]
);
}
#[test]
fn continuation_across_a_page_break() {
let pages = doc(&[
&[("Um parágrafo que não termina na página", 10.0, R, 0.0)],
&[
("e continua aqui.", 10.0, R, 0.0),
("Outro.", 10.0, R, 25.0),
],
]);
assert_eq!(
md(&pages, &[]),
"<!-- pdfsift: source=x.pdf pages=1-2/2 -->\n<!-- page: 1 -->\n\
Um parágrafo que não termina na página e continua aqui.\n\n\
<!-- page: 2 -->\nOutro.\n"
);
let pages = doc(&[
&[("Um parágrafo que termina.", 10.0, R, 0.0)],
&[("e outro.", 10.0, R, 0.0)],
]);
assert_eq!(body(&md(&pages, &[])).len(), 2);
}
#[test]
fn escaping() {
assert_eq!(
escape_inline("a*b* [c](d) [14] <d> a < b `e` x_y _z_"),
"a\\*b\\* [c\\](d) [14] \\<d> a < b \\`e\\` x_y \\_z\\_"
);
assert_eq!(escape_block_start("# não é título"), "\\# não é título");
assert_eq!(escape_block_start("- não é lista"), "\\- não é lista");
assert_eq!(escape_block_start("1. não é lista"), "1\\. não é lista");
assert_eq!(escape_block_start("1990 foi um ano"), "1990 foi um ano");
assert_eq!(comment_safe("a--b---c"), "a- -b- - -c");
}
#[test]
fn page_ranges_and_selection() {
assert_eq!(ranges(&[1, 2, 3, 5, 7, 8]), "1-3,5,7-8");
assert_eq!(ranges(&[]), "none");
let pages = doc(&[&[("Um.", 10.0, R, 0.0)], &[("Dois.", 10.0, R, 0.0)]]);
assert_eq!(
render(&pages, &[], &opts(Some([2].into_iter().collect()), false)).markdown,
"<!-- pdfsift: source=x.pdf pages=2/2 -->\nDois.\n"
);
}
#[test]
fn empty_page_is_reported_and_output_is_deterministic() {
let pages = doc(&[&[], &[("Texto.", 10.0, R, 0.0)]]);
let o = opts(None, true);
let a = render(&pages, &[], &o);
assert_eq!(a, render(&pages, &[], &o));
assert!(
a.markdown
.contains("<!-- pdfsift: page 1 has no text layer -->")
);
assert_eq!(a.warnings.len(), 1);
assert!(a.markdown.ends_with("Texto.\n"));
let none = render(&[], &[], &o);
assert_eq!(
none.markdown,
"<!-- pdfsift: source=x.pdf pages=none/0 -->\n"
);
}
fn word(t: &str, x: f32, base: f32) -> Word {
Word {
text: t.into(),
bbox: crate::layout::Rect::new(
x,
base - 9.0,
x + 5.0 * t.chars().count() as f32,
base + 2.5,
),
baseline: base,
size: 10.0,
font: "Serif".into(),
style: R,
glued: false,
len: t.chars().count(),
chars: 0..0,
figure: None,
}
}
#[test]
fn tables_as_pipe_tables_and_layout_blocks() {
let p = &doc(&[&[("x", 10.0, R, 0.0)]])[0];
let ev = DocEvidence::from_pages(&[], true);
let cell = |t: &str| vec![vec![word(t, 0.0, 0.0)]];
let grid = Body::Grid {
align: vec![Align::Left, Align::Right],
rows: vec![
vec![cell("Nome"), cell("Valor")],
vec![cell("a|b"), Vec::new()],
vec![
vec![
vec![word("dois", 0.0, 0.0)],
vec![word("linhas", 0.0, 12.0)],
],
cell("*3*"),
],
],
};
assert_eq!(
table_text(p, &grid, &ev),
r"| Nome | Valor |
|---|---:|
| a\|b | |
| dois linhas | \*3\* |
"
);
let layout = Body::Layout {
rows: vec![
vec![word("Ano", 50.0, 100.0), word("Total", 150.0, 100.0)],
vec![word("2023", 50.0, 112.0), word("12", 160.0, 112.0)],
],
};
assert_eq!(
table_text(p, &layout, &ev),
"```
Ano Total
2023 12
```
"
);
}
}