deepdoc-core 0.1.0

Extract clean Markdown, JSON or text from documents — the DeepDoc engine.
Documentation
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
//! RTF extractor — a small reader for the parts of RTF that carry text.
//!
//! Why not the `rtf-parser` crate: as of 0.4.3 it never handles the `\par`
//! control word, so every paragraph boundary is lost and a document collapses
//! into one blob — the one thing a Markdown extractor cannot afford. Its default
//! features also pull `wasm-bindgen` into the binary. RTF's grammar is small
//! enough that reading it directly is both cheaper and more accurate.
//!
//! Scope: groups, destinations, character escapes, `\uN` unicode, bold/italic,
//! and the breaks (`\par`, `\line`, `\cell`, `\row`). Formatting we cannot
//! represent — fonts, colours, sizes — is skipped, and headings are not guessed
//! from point sizes.

use std::path::Path;

use crate::detect::{Format, Sniff};
use crate::error::{Error, Result};
use crate::extract::{ExtractOpts, Extractor};
use crate::model::{Block, Document, Inline, Metadata, Span};

pub struct RtfExtractor;

impl Extractor for RtfExtractor {
    fn name(&self) -> &'static str {
        "rtf"
    }

    fn supports(&self, _path: &Path, sniff: &Sniff) -> bool {
        crate::detect::detect(sniff) == Some(Format::Rtf)
    }

    fn extract(&self, path: &Path, _opts: &ExtractOpts) -> Result<Document> {
        let raw = std::fs::read(path).map_err(|e| Error::io(path, e))?;
        // RTF is 7-bit ASCII with escapes, but files in the wild carry raw high
        // bytes; lossy decoding keeps those documents usable.
        let text = String::from_utf8_lossy(&raw);
        let parsed = parse(&text).map_err(|message| Error::parse(path, message))?;

        let mut meta = parsed.meta;
        meta.source_format = Some(Format::Rtf);
        meta.source_path = Some(path.display().to_string());

        Ok(Document {
            meta,
            blocks: parsed.blocks,
        })
    }
}

/// Group state — inherited by nested groups, restored when a group closes.
#[derive(Debug, Clone)]
struct State {
    bold: bool,
    italic: bool,
    /// Inside a destination whose content is not document text.
    skip: bool,
    /// Inside an `\info` field whose text is metadata.
    capture: Option<Field>,
    /// How many characters follow a `\uN` as its non-unicode fallback.
    unicode_fallback: usize,
}

/// A metadata field of the `\info` group.
#[derive(Debug, Clone, Copy, PartialEq)]
enum Field {
    Title,
    Author,
}

impl Default for State {
    fn default() -> Self {
        Self {
            bold: false,
            italic: false,
            skip: false,
            capture: None,
            unicode_fallback: 1,
        }
    }
}

/// Destinations that hold metadata or binary payloads rather than text.
fn is_skipped_destination(word: &str) -> bool {
    matches!(
        word,
        "fonttbl"
            | "colortbl"
            | "stylesheet"
            | "listtable"
            | "listoverridetable"
            | "filetbl"
            | "rsidtbl"
            | "generator"
            | "pict"
            | "object"
            | "themedata"
            | "datastore"
            | "latentstyles"
            | "xmlnstbl"
            | "fldinst"
            | "revtbl"
            | "upr"
    )
}

/// What a parsed RTF document yields.
#[derive(Debug, Default, PartialEq)]
pub struct Parsed {
    pub meta: Metadata,
    pub blocks: Vec<Block>,
}

/// Parse RTF source. Pure.
pub fn parse(source: &str) -> std::result::Result<Parsed, String> {
    if !source.trim_start().starts_with("{\\rtf") {
        return Err("not an RTF document (no {\\rtf header)".to_string());
    }

    let mut reader = Reader::new(source);
    reader.run();
    Ok(reader.finish())
}

struct Reader<'a> {
    chars: Vec<char>,
    position: usize,
    stack: Vec<State>,
    /// Text of the run being accumulated, under the current styling.
    run: String,
    /// Spans of the paragraph being accumulated.
    spans: Vec<Span>,
    blocks: Vec<Block>,
    meta: Metadata,
    /// Creation date parts collected from `\creatim`.
    created: [Option<i32>; 3],
    /// Characters still to swallow as a `\uN` fallback.
    pending_fallback: usize,
    source: std::marker::PhantomData<&'a str>,
}

impl Reader<'_> {
    fn new(source: &str) -> Reader<'_> {
        Reader {
            chars: source.chars().collect(),
            position: 0,
            stack: vec![State::default()],
            run: String::new(),
            spans: Vec::new(),
            blocks: Vec::new(),
            meta: Metadata::default(),
            created: [None; 3],
            pending_fallback: 0,
            source: std::marker::PhantomData,
        }
    }

    fn state(&self) -> &State {
        self.stack.last().expect("the stack is never empty")
    }

    fn state_mut(&mut self) -> &mut State {
        self.stack.last_mut().expect("the stack is never empty")
    }

    fn run(&mut self) {
        while let Some(ch) = self.chars.get(self.position).copied() {
            self.position += 1;
            match ch {
                '{' => {
                    self.flush_run();
                    let state = self.state().clone();
                    self.stack.push(state);
                }
                '}' => {
                    self.flush_run();
                    if self.stack.len() > 1 {
                        self.stack.pop();
                    }
                }
                '\\' => self.control(),
                // Raw line endings are formatting in the source file, not text.
                '\r' | '\n' => {}
                _ => self.push_char(ch),
            }
        }
    }

    /// Read one control word or control symbol, starting after the backslash.
    fn control(&mut self) {
        let Some(&first) = self.chars.get(self.position) else {
            return;
        };

        if !first.is_ascii_alphabetic() {
            self.position += 1;
            self.control_symbol(first);
            return;
        }

        let start = self.position;
        while self
            .chars
            .get(self.position)
            .is_some_and(|c| c.is_ascii_alphabetic())
        {
            self.position += 1;
        }
        let word: String = self.chars[start..self.position].iter().collect();

        // Optional numeric parameter, possibly negative.
        let mut parameter: Option<i32> = None;
        let number_start = self.position;
        if self.chars.get(self.position) == Some(&'-') {
            self.position += 1;
        }
        while self
            .chars
            .get(self.position)
            .is_some_and(char::is_ascii_digit)
        {
            self.position += 1;
        }
        if self.position > number_start {
            let digits: String = self.chars[number_start..self.position].iter().collect();
            parameter = digits.parse().ok();
        }

        // A single space after a control word is a delimiter, not text.
        if self.chars.get(self.position) == Some(&' ') {
            self.position += 1;
        }

        self.control_word(&word, parameter);
    }

    fn control_word(&mut self, word: &str, parameter: Option<i32>) {
        let on = parameter != Some(0);

        match word {
            "par" | "sect" => self.end_paragraph(),
            "line" => {
                self.flush_run();
                self.spans.push(Span::LineBreak);
            }
            // Table cells become tab-separated text; RTF table structure is a
            // later phase, and mangled pipes would be worse than plain columns.
            "cell" | "tab" => self.push_char('\t'),
            "row" => self.end_paragraph(),
            // Styling changes end the current run — otherwise the text before
            // and after `\b0` would share one span.
            "b" => {
                self.flush_run();
                self.state_mut().bold = on;
            }
            "i" => {
                self.flush_run();
                self.state_mut().italic = on;
            }
            "plain" => {
                self.flush_run();
                let state = self.state_mut();
                state.bold = false;
                state.italic = false;
            }
            "uc" => {
                if let Some(count) = parameter {
                    self.state_mut().unicode_fallback = count.max(0) as usize;
                }
            }
            "u" => {
                if let Some(code) = parameter {
                    // Word writes codepoints above 0x7FFF as negative numbers.
                    let code = if code < 0 {
                        (code + 65536) as u32
                    } else {
                        code as u32
                    };
                    if let Some(ch) = char::from_u32(code) {
                        self.push_char(ch);
                    }
                }
                self.pending_fallback = self.state().unicode_fallback;
            }
            "emdash" => self.push_char('—'),
            "endash" => self.push_char('–'),
            "bullet" => self.push_char('•'),
            "lquote" => self.push_char('‘'),
            "rquote" => self.push_char('’'),
            "ldblquote" => self.push_char('“'),
            "rdblquote" => self.push_char('”'),
            // `{\info{\title …}{\author …}{\creatim\yr…\mo…\dy…}}`
            "info" => self.state_mut().skip = true,
            "title" => self.start_field(Field::Title),
            "author" => self.start_field(Field::Author),
            "creatim" => self.state_mut().skip = true,
            "yr" | "mo" | "dy" => {
                let index = match word {
                    "yr" => 0,
                    "mo" => 1,
                    _ => 2,
                };
                if let Some(value) = parameter {
                    self.created[index] = Some(value);
                }
            }
            word if is_skipped_destination(word) => self.state_mut().skip = true,
            // Everything else is formatting we do not model.
            _ => {}
        }
    }

    fn control_symbol(&mut self, symbol: char) {
        match symbol {
            '\\' | '{' | '}' => self.push_char(symbol),
            // `{\*\foo …}` marks a destination the reader may ignore wholesale.
            '*' => self.state_mut().skip = true,
            '~' => self.push_char('\u{00a0}'),
            '_' => self.push_char('-'),
            '\r' | '\n' => self.end_paragraph(),
            '\'' => {
                let hex: String = self
                    .chars
                    .get(self.position..self.position + 2)
                    .map(|slice| slice.iter().collect())
                    .unwrap_or_default();
                self.position += hex.len();
                if let Ok(byte) = u8::from_str_radix(&hex, 16) {
                    self.push_char(cp1252(byte));
                }
            }
            // `\-` (optional hyphen) and friends leave no text behind.
            _ => {}
        }
    }

    /// Open an `\info` field: its text is metadata, not document text.
    fn start_field(&mut self, field: Field) {
        self.flush_run();
        let state = self.state_mut();
        state.capture = Some(field);
        state.skip = false;
    }

    fn push_char(&mut self, ch: char) {
        if self.pending_fallback > 0 {
            self.pending_fallback -= 1;
            return;
        }
        if let Some(field) = self.state().capture {
            let target = match field {
                Field::Title => &mut self.meta.title,
                Field::Author => &mut self.meta.author,
            };
            target.get_or_insert_with(String::new).push(ch);
            return;
        }
        if self.state().skip {
            return;
        }
        self.run.push(ch);
    }

    /// Close the current styled run.
    fn flush_run(&mut self) {
        if self.run.is_empty() || self.state().capture.is_some() {
            self.run.clear();
            return;
        }
        let text = std::mem::take(&mut self.run);
        let state = self.state();
        self.spans.push(style(&text, state.bold, state.italic));
    }

    fn end_paragraph(&mut self) {
        self.flush_run();
        let inline = Inline::new(std::mem::take(&mut self.spans));
        if !inline.plain_text().trim().is_empty() {
            self.blocks.push(Block::Paragraph { text: inline });
        }
    }

    fn finish(mut self) -> Parsed {
        self.end_paragraph();

        if let [Some(year), Some(month), Some(day)] = self.created {
            self.meta.created = Some(format!("{year:04}-{month:02}-{day:02}"));
        }
        for field in [&mut self.meta.title, &mut self.meta.author] {
            if let Some(value) = field {
                *value = value.trim().to_string();
            }
            field.take_if(|value| value.is_empty());
        }

        Parsed {
            meta: self.meta,
            blocks: self.blocks,
        }
    }
}

/// Wrap a run of text in the character styling RTF reported for it.
fn style(text: &str, bold: bool, italic: bool) -> Span {
    let span = Span::Text(text.to_string());
    match (bold, italic) {
        (false, false) => span,
        (true, false) => Span::Bold(vec![span]),
        (false, true) => Span::Italic(vec![span]),
        (true, true) => Span::Bold(vec![Span::Italic(vec![span])]),
    }
}

/// Decode a `\'hh` byte as Windows-1252, the codepage almost every RTF uses.
fn cp1252(byte: u8) -> char {
    const HIGH: [char; 32] = [
        '€', '\u{81}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{8d}', 'Ž',
        '\u{8f}', '\u{90}', '‘', '’', '“', '”', '•', '–', '—', '˜', '™', 'š', '›', 'œ', '\u{9d}',
        'ž', 'Ÿ',
    ];
    match byte {
        0x80..=0x9f => HIGH[(byte - 0x80) as usize],
        // Everything else matches Latin-1, which is Unicode's first block.
        _ => char::from(byte),
    }
}

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

    const HEADER: &str = r"{\rtf1\ansi\deff0{\fonttbl{\f0 Helvetica;}}\pard ";

    fn parse_body(body: &str) -> Vec<Block> {
        parse(&format!("{HEADER}{body}}}"))
            .expect("valid rtf")
            .blocks
    }

    #[test]
    fn paragraphs_split_on_par() {
        assert_eq!(
            parse_body(r"first\par second\par "),
            vec![Block::paragraph("first"), Block::paragraph("second")]
        );
    }

    #[test]
    fn bold_and_italic_runs_survive() {
        let blocks = parse_body(r"plain {\b bold} {\i italic}\par ");
        let Block::Paragraph { text } = &blocks[0] else {
            panic!("expected a paragraph, got {blocks:?}");
        };
        assert_eq!(
            text.spans,
            vec![
                Span::Text("plain ".into()),
                Span::Bold(vec![Span::Text("bold".into())]),
                Span::Text(" ".into()),
                Span::Italic(vec![Span::Text("italic".into())]),
            ]
        );
    }

    #[test]
    fn styling_switches_off_with_a_zero_parameter() {
        let blocks = parse_body(r"\b bold\b0  plain\par ");
        let Block::Paragraph { text } = &blocks[0] else {
            panic!("expected a paragraph");
        };
        assert_eq!(
            text.spans,
            vec![
                Span::Bold(vec![Span::Text("bold".into())]),
                Span::Text(" plain".into()),
            ]
        );
    }

    #[test]
    fn font_and_colour_tables_are_not_text() {
        let blocks = parse_body(r"{\colortbl;\red255\green0\blue0;}visible\par ");
        assert_eq!(blocks, vec![Block::paragraph("visible")]);
    }

    #[test]
    fn ignorable_destinations_are_skipped() {
        assert_eq!(
            parse_body(r"{\*\generator Riched20 10.0}kept\par "),
            vec![Block::paragraph("kept")]
        );
    }

    #[test]
    fn escapes_and_unicode_are_decoded() {
        // `\'e9` is a Windows-1252 byte; `႐?` is a codepoint followed by
        // the ASCII fallback character, which must be swallowed.
        assert_eq!(
            parse_body(r"caf\'e9 \u1090? \\ \{ \} \emdash\par "),
            vec![Block::paragraph("café т \\ { } —")]
        );
    }

    #[test]
    fn line_breaks_stay_inside_a_paragraph() {
        let blocks = parse_body(r"first\line second\par ");
        let Block::Paragraph { text } = &blocks[0] else {
            panic!("expected a paragraph");
        };
        assert_eq!(
            text.spans,
            vec![
                Span::Text("first".into()),
                Span::LineBreak,
                Span::Text("second".into()),
            ]
        );
    }

    #[test]
    fn table_cells_become_tab_separated_lines() {
        assert_eq!(
            parse_body(r"a\cell b\cell \row "),
            vec![Block::paragraph("a\tb\t")]
        );
    }

    #[test]
    fn trailing_text_without_a_final_par_is_kept() {
        assert_eq!(
            parse_body("no trailing par"),
            vec![Block::paragraph("no trailing par")]
        );
    }

    #[test]
    fn blank_paragraphs_are_dropped() {
        assert_eq!(
            parse_body(r"text\par \par \par "),
            vec![Block::paragraph("text")]
        );
    }

    #[test]
    fn the_info_group_becomes_metadata_not_text() {
        let parsed = parse(&format!(
            r"{HEADER}{{\info{{\title Quarterly Report}}{{\author Ada Lovelace}}{{\creatim\yr2026\mo7\dy24\hr10}}}}Body text.\par }}"
        ))
        .expect("valid rtf");

        assert_eq!(parsed.meta.title.as_deref(), Some("Quarterly Report"));
        assert_eq!(parsed.meta.author.as_deref(), Some("Ada Lovelace"));
        assert_eq!(parsed.meta.created.as_deref(), Some("2026-07-24"));
        assert_eq!(
            parsed.blocks,
            vec![Block::paragraph("Body text.")],
            "info fields must not leak into the document"
        );
    }

    #[test]
    fn a_document_without_an_info_group_has_no_metadata() {
        let parsed = parse(&format!(r"{HEADER}just text\par }}")).expect("valid rtf");
        assert_eq!(parsed.meta, Metadata::default());
    }

    #[test]
    fn malformed_input_is_an_error_not_a_panic() {
        assert!(parse("not rtf at all").is_err());
    }
}