liteparse 2.1.0

Fast, lightweight PDF and document parsing with spatial text extraction
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use crate::projection::{is_bold_item, is_italic_item, is_mono_item, is_strike_item};
use crate::types::{ProjectedLine, TextItem};

use super::paragraphs::{collapse_whitespace, dehyphenate_join};

/// Per-span style flags used by the inline-emphasis renderer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct SpanStyle {
    pub(super) bold: bool,
    pub(super) italic: bool,
    pub(super) mono: bool,
    pub(super) strike: bool,
}

impl SpanStyle {
    pub(super) fn from_item(item: &TextItem) -> Self {
        SpanStyle {
            bold: is_bold_item(item),
            italic: is_italic_item(item),
            mono: is_mono_item(item),
            strike: is_strike_item(item),
        }
    }

    pub(super) fn is_plain(self) -> bool {
        !self.bold && !self.italic && !self.mono && !self.strike
    }
}

/// 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.
pub(super) 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` in a markdown inline link to `url`. Uses the angle-bracket
/// destination form when the URL contains characters that would otherwise
/// terminate or break the `(url)` form (whitespace or parentheses).
fn apply_link(inner: &str, url: &str) -> String {
    if url.contains([' ', '\t', '(', ')']) {
        format!("[{}](<{}>)", inner, url)
    } else {
        format!("[{}]({})", inner, url)
    }
}

/// 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 {
    let styled = 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('`') {
            format!("`` {} ``", inner)
        } else {
            format!("`{}`", inner)
        }
    } else {
        match (style.bold, style.italic) {
            (true, true) => format!("***{}***", inner),
            (true, false) => format!("**{}**", inner),
            (false, true) => format!("*{}*", inner),
            (false, false) => inner.to_string(),
        }
    };
    // Strikethrough (GFM `~~…~~`) wraps outermost so it composes with emphasis
    // and inline code (`~~**foo**~~`, `~~`bar`~~`).
    if style.strike {
        format!("~~{}~~", styled)
    } else {
        styled
    }
}

/// 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
/// (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).
pub(super) 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();
    let links: Vec<Option<&str>> = spans.iter().map(|s| s.link.as_deref()).collect();

    // Per-line shortcut — only when the whole line shares one style AND carries
    // no hyperlinks (a link must wrap only the spans it covers, so link lines
    // always take the per-group path below).
    let uniform = styles.iter().all(|s| *s == styles[0]) && links.iter().all(|l| l.is_none());
    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 link = links[i];
        let mut j = i + 1;
        while j < spans.len() && styles[j] == style && links[j] == link {
            j += 1;
        }
        let mut group_text = String::new();
        for span in &spans[i..j] {
            if !group_text.is_empty() && !group_text.ends_with(' ') {
                group_text.push(' ');
            }
            group_text.push_str(span.text.trim());
        }
        let group_text = collapse_whitespace(&group_text);
        let escaped = escape_inline(&group_text);
        let mut rendered = if style.is_plain() {
            escaped
        } else {
            apply_style(&escaped, style)
        };
        if let Some(url) = link {
            rendered = apply_link(&rendered, url);
        }
        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`.
pub(super) 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.
pub(super) fn append_inline_continuation(
    prev_text: &mut String,
    next_raw: &str,
    next_inline: &str,
) {
    let next_raw = collapse_whitespace(next_raw);
    dehyphenate_join(prev_text, &next_raw, next_inline);
}

/// 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.
pub(super) fn line_uniform_style(line: &ProjectedLine) -> Option<SpanStyle> {
    // A line carrying any hyperlink can't use the uniform fast path: the link
    // wraps only its own spans, so such lines must render via the per-group
    // path in `render_line_inline`.
    if line
        .spans
        .iter()
        .any(|s| !s.text.trim().is_empty() && s.link.is_some())
    {
        return None;
    }
    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)
}

/// True when every non-whitespace span on the line is bold and non-mono.
/// Unlike `line_uniform_style`, this tolerates per-span *italic* variation,
/// so a heading whose spans mix bold and bold-italic (e.g.
/// "**4** ***Foo*** **Bar**") still reads as a single bold line. Returns
/// false for an empty / all-whitespace line.
pub(super) fn line_all_bold(line: &ProjectedLine) -> bool {
    let mut saw_span = false;
    for span in &line.spans {
        if span.text.trim().is_empty() {
            continue;
        }
        if is_mono_item(span) || !is_bold_item(span) {
            return false;
        }
        saw_span = true;
    }
    saw_span
}

#[cfg(test)]
mod tests {
    use super::super::test_helpers::styled_line;
    use super::*;

    #[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_wraps_link_span() {
        // Plain span followed by a linked span → `[anchor](url)` mid-line.
        let mut l = styled_line(
            &[
                ("see", 50.0, Some("Arial")),
                ("the docs", 150.0, Some("Arial")),
            ],
            100.0,
            10.0,
        );
        l.spans[1].link = Some("https://example.com/docs".to_string());
        let out = render_line_inline(&l);
        assert!(out.contains("see"), "got: {out}");
        assert!(
            out.contains("[the docs](https://example.com/docs)"),
            "got: {out}"
        );
    }

    #[test]
    fn render_line_inline_link_wraps_outside_emphasis() {
        // An italic linked span → `[*anchor*](url)` (link outside emphasis).
        let mut l = styled_line(&[("cite", 50.0, Some("Arial-Italic"))], 100.0, 10.0);
        l.spans[0].link = Some("https://example.com/p.pdf".to_string());
        let out = render_line_inline(&l);
        assert_eq!(out, "[*cite*](https://example.com/p.pdf)");
    }

    #[test]
    fn render_line_inline_link_url_with_space_uses_angle_brackets() {
        let mut l = styled_line(&[("link", 50.0, Some("Arial"))], 100.0, 10.0);
        l.spans[0].link = Some("https://example.com/a b".to_string());
        let out = render_line_inline(&l);
        assert_eq!(out, "[link](<https://example.com/a b>)");
    }

    #[test]
    fn render_line_inline_strike_span() {
        // A struck-through span mid-line → `~~word~~`, plain neighbors untouched.
        let mut l = styled_line(
            &[
                ("keep this", 50.0, Some("Arial")),
                ("removed", 150.0, Some("Arial")),
            ],
            100.0,
            10.0,
        );
        l.spans[1].strike = true;
        let out = render_line_inline(&l);
        assert!(out.contains("keep this"), "got: {out}");
        assert!(out.contains("~~removed~~"), "got: {out}");
    }

    #[test]
    fn render_line_inline_strike_composes_with_bold() {
        // Strike wraps outside emphasis: `~~**word**~~`.
        let mut l = styled_line(&[("gone", 50.0, Some("Arial-Bold"))], 100.0, 10.0);
        l.spans[0].strike = true;
        let out = render_line_inline(&l);
        assert_eq!(out, "~~**gone**~~");
    }

    #[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"));
    }
}