Skip to main content

deepdoc_core/extract/
rtf.rs

1//! RTF extractor — a small reader for the parts of RTF that carry text.
2//!
3//! Why not the `rtf-parser` crate: as of 0.4.3 it never handles the `\par`
4//! control word, so every paragraph boundary is lost and a document collapses
5//! into one blob — the one thing a Markdown extractor cannot afford. Its default
6//! features also pull `wasm-bindgen` into the binary. RTF's grammar is small
7//! enough that reading it directly is both cheaper and more accurate.
8//!
9//! Scope: groups, destinations, character escapes, `\uN` unicode, bold/italic,
10//! and the breaks (`\par`, `\line`, `\cell`, `\row`). Formatting we cannot
11//! represent — fonts, colours, sizes — is skipped, and headings are not guessed
12//! from point sizes.
13
14use std::path::Path;
15
16use crate::detect::{Format, Sniff};
17use crate::error::{Error, Result};
18use crate::extract::{ExtractOpts, Extractor};
19use crate::model::{Block, Document, Inline, Metadata, Span};
20
21pub struct RtfExtractor;
22
23impl Extractor for RtfExtractor {
24    fn name(&self) -> &'static str {
25        "rtf"
26    }
27
28    fn supports(&self, _path: &Path, sniff: &Sniff) -> bool {
29        crate::detect::detect(sniff) == Some(Format::Rtf)
30    }
31
32    fn extract(&self, path: &Path, _opts: &ExtractOpts) -> Result<Document> {
33        let raw = std::fs::read(path).map_err(|e| Error::io(path, e))?;
34        // RTF is 7-bit ASCII with escapes, but files in the wild carry raw high
35        // bytes; lossy decoding keeps those documents usable.
36        let text = String::from_utf8_lossy(&raw);
37        let parsed = parse(&text).map_err(|message| Error::parse(path, message))?;
38
39        let mut meta = parsed.meta;
40        meta.source_format = Some(Format::Rtf);
41        meta.source_path = Some(path.display().to_string());
42
43        Ok(Document {
44            meta,
45            blocks: parsed.blocks,
46        })
47    }
48}
49
50/// Group state — inherited by nested groups, restored when a group closes.
51#[derive(Debug, Clone)]
52struct State {
53    bold: bool,
54    italic: bool,
55    /// Inside a destination whose content is not document text.
56    skip: bool,
57    /// Inside an `\info` field whose text is metadata.
58    capture: Option<Field>,
59    /// How many characters follow a `\uN` as its non-unicode fallback.
60    unicode_fallback: usize,
61}
62
63/// A metadata field of the `\info` group.
64#[derive(Debug, Clone, Copy, PartialEq)]
65enum Field {
66    Title,
67    Author,
68}
69
70impl Default for State {
71    fn default() -> Self {
72        Self {
73            bold: false,
74            italic: false,
75            skip: false,
76            capture: None,
77            unicode_fallback: 1,
78        }
79    }
80}
81
82/// Destinations that hold metadata or binary payloads rather than text.
83fn is_skipped_destination(word: &str) -> bool {
84    matches!(
85        word,
86        "fonttbl"
87            | "colortbl"
88            | "stylesheet"
89            | "listtable"
90            | "listoverridetable"
91            | "filetbl"
92            | "rsidtbl"
93            | "generator"
94            | "pict"
95            | "object"
96            | "themedata"
97            | "datastore"
98            | "latentstyles"
99            | "xmlnstbl"
100            | "fldinst"
101            | "revtbl"
102            | "upr"
103    )
104}
105
106/// What a parsed RTF document yields.
107#[derive(Debug, Default, PartialEq)]
108pub struct Parsed {
109    pub meta: Metadata,
110    pub blocks: Vec<Block>,
111}
112
113/// Parse RTF source. Pure.
114pub fn parse(source: &str) -> std::result::Result<Parsed, String> {
115    if !source.trim_start().starts_with("{\\rtf") {
116        return Err("not an RTF document (no {\\rtf header)".to_string());
117    }
118
119    let mut reader = Reader::new(source);
120    reader.run();
121    Ok(reader.finish())
122}
123
124struct Reader<'a> {
125    chars: Vec<char>,
126    position: usize,
127    stack: Vec<State>,
128    /// Text of the run being accumulated, under the current styling.
129    run: String,
130    /// Spans of the paragraph being accumulated.
131    spans: Vec<Span>,
132    blocks: Vec<Block>,
133    meta: Metadata,
134    /// Creation date parts collected from `\creatim`.
135    created: [Option<i32>; 3],
136    /// Characters still to swallow as a `\uN` fallback.
137    pending_fallback: usize,
138    source: std::marker::PhantomData<&'a str>,
139}
140
141impl Reader<'_> {
142    fn new(source: &str) -> Reader<'_> {
143        Reader {
144            chars: source.chars().collect(),
145            position: 0,
146            stack: vec![State::default()],
147            run: String::new(),
148            spans: Vec::new(),
149            blocks: Vec::new(),
150            meta: Metadata::default(),
151            created: [None; 3],
152            pending_fallback: 0,
153            source: std::marker::PhantomData,
154        }
155    }
156
157    fn state(&self) -> &State {
158        self.stack.last().expect("the stack is never empty")
159    }
160
161    fn state_mut(&mut self) -> &mut State {
162        self.stack.last_mut().expect("the stack is never empty")
163    }
164
165    fn run(&mut self) {
166        while let Some(ch) = self.chars.get(self.position).copied() {
167            self.position += 1;
168            match ch {
169                '{' => {
170                    self.flush_run();
171                    let state = self.state().clone();
172                    self.stack.push(state);
173                }
174                '}' => {
175                    self.flush_run();
176                    if self.stack.len() > 1 {
177                        self.stack.pop();
178                    }
179                }
180                '\\' => self.control(),
181                // Raw line endings are formatting in the source file, not text.
182                '\r' | '\n' => {}
183                _ => self.push_char(ch),
184            }
185        }
186    }
187
188    /// Read one control word or control symbol, starting after the backslash.
189    fn control(&mut self) {
190        let Some(&first) = self.chars.get(self.position) else {
191            return;
192        };
193
194        if !first.is_ascii_alphabetic() {
195            self.position += 1;
196            self.control_symbol(first);
197            return;
198        }
199
200        let start = self.position;
201        while self
202            .chars
203            .get(self.position)
204            .is_some_and(|c| c.is_ascii_alphabetic())
205        {
206            self.position += 1;
207        }
208        let word: String = self.chars[start..self.position].iter().collect();
209
210        // Optional numeric parameter, possibly negative.
211        let mut parameter: Option<i32> = None;
212        let number_start = self.position;
213        if self.chars.get(self.position) == Some(&'-') {
214            self.position += 1;
215        }
216        while self
217            .chars
218            .get(self.position)
219            .is_some_and(char::is_ascii_digit)
220        {
221            self.position += 1;
222        }
223        if self.position > number_start {
224            let digits: String = self.chars[number_start..self.position].iter().collect();
225            parameter = digits.parse().ok();
226        }
227
228        // A single space after a control word is a delimiter, not text.
229        if self.chars.get(self.position) == Some(&' ') {
230            self.position += 1;
231        }
232
233        self.control_word(&word, parameter);
234    }
235
236    fn control_word(&mut self, word: &str, parameter: Option<i32>) {
237        let on = parameter != Some(0);
238
239        match word {
240            "par" | "sect" => self.end_paragraph(),
241            "line" => {
242                self.flush_run();
243                self.spans.push(Span::LineBreak);
244            }
245            // Table cells become tab-separated text; RTF table structure is a
246            // later phase, and mangled pipes would be worse than plain columns.
247            "cell" | "tab" => self.push_char('\t'),
248            "row" => self.end_paragraph(),
249            // Styling changes end the current run — otherwise the text before
250            // and after `\b0` would share one span.
251            "b" => {
252                self.flush_run();
253                self.state_mut().bold = on;
254            }
255            "i" => {
256                self.flush_run();
257                self.state_mut().italic = on;
258            }
259            "plain" => {
260                self.flush_run();
261                let state = self.state_mut();
262                state.bold = false;
263                state.italic = false;
264            }
265            "uc" => {
266                if let Some(count) = parameter {
267                    self.state_mut().unicode_fallback = count.max(0) as usize;
268                }
269            }
270            "u" => {
271                if let Some(code) = parameter {
272                    // Word writes codepoints above 0x7FFF as negative numbers.
273                    let code = if code < 0 {
274                        (code + 65536) as u32
275                    } else {
276                        code as u32
277                    };
278                    if let Some(ch) = char::from_u32(code) {
279                        self.push_char(ch);
280                    }
281                }
282                self.pending_fallback = self.state().unicode_fallback;
283            }
284            "emdash" => self.push_char('—'),
285            "endash" => self.push_char('–'),
286            "bullet" => self.push_char('•'),
287            "lquote" => self.push_char('‘'),
288            "rquote" => self.push_char('’'),
289            "ldblquote" => self.push_char('“'),
290            "rdblquote" => self.push_char('”'),
291            // `{\info{\title …}{\author …}{\creatim\yr…\mo…\dy…}}`
292            "info" => self.state_mut().skip = true,
293            "title" => self.start_field(Field::Title),
294            "author" => self.start_field(Field::Author),
295            "creatim" => self.state_mut().skip = true,
296            "yr" | "mo" | "dy" => {
297                let index = match word {
298                    "yr" => 0,
299                    "mo" => 1,
300                    _ => 2,
301                };
302                if let Some(value) = parameter {
303                    self.created[index] = Some(value);
304                }
305            }
306            word if is_skipped_destination(word) => self.state_mut().skip = true,
307            // Everything else is formatting we do not model.
308            _ => {}
309        }
310    }
311
312    fn control_symbol(&mut self, symbol: char) {
313        match symbol {
314            '\\' | '{' | '}' => self.push_char(symbol),
315            // `{\*\foo …}` marks a destination the reader may ignore wholesale.
316            '*' => self.state_mut().skip = true,
317            '~' => self.push_char('\u{00a0}'),
318            '_' => self.push_char('-'),
319            '\r' | '\n' => self.end_paragraph(),
320            '\'' => {
321                let hex: String = self
322                    .chars
323                    .get(self.position..self.position + 2)
324                    .map(|slice| slice.iter().collect())
325                    .unwrap_or_default();
326                self.position += hex.len();
327                if let Ok(byte) = u8::from_str_radix(&hex, 16) {
328                    self.push_char(cp1252(byte));
329                }
330            }
331            // `\-` (optional hyphen) and friends leave no text behind.
332            _ => {}
333        }
334    }
335
336    /// Open an `\info` field: its text is metadata, not document text.
337    fn start_field(&mut self, field: Field) {
338        self.flush_run();
339        let state = self.state_mut();
340        state.capture = Some(field);
341        state.skip = false;
342    }
343
344    fn push_char(&mut self, ch: char) {
345        if self.pending_fallback > 0 {
346            self.pending_fallback -= 1;
347            return;
348        }
349        if let Some(field) = self.state().capture {
350            let target = match field {
351                Field::Title => &mut self.meta.title,
352                Field::Author => &mut self.meta.author,
353            };
354            target.get_or_insert_with(String::new).push(ch);
355            return;
356        }
357        if self.state().skip {
358            return;
359        }
360        self.run.push(ch);
361    }
362
363    /// Close the current styled run.
364    fn flush_run(&mut self) {
365        if self.run.is_empty() || self.state().capture.is_some() {
366            self.run.clear();
367            return;
368        }
369        let text = std::mem::take(&mut self.run);
370        let state = self.state();
371        self.spans.push(style(&text, state.bold, state.italic));
372    }
373
374    fn end_paragraph(&mut self) {
375        self.flush_run();
376        let inline = Inline::new(std::mem::take(&mut self.spans));
377        if !inline.plain_text().trim().is_empty() {
378            self.blocks.push(Block::Paragraph { text: inline });
379        }
380    }
381
382    fn finish(mut self) -> Parsed {
383        self.end_paragraph();
384
385        if let [Some(year), Some(month), Some(day)] = self.created {
386            self.meta.created = Some(format!("{year:04}-{month:02}-{day:02}"));
387        }
388        for field in [&mut self.meta.title, &mut self.meta.author] {
389            if let Some(value) = field {
390                *value = value.trim().to_string();
391            }
392            field.take_if(|value| value.is_empty());
393        }
394
395        Parsed {
396            meta: self.meta,
397            blocks: self.blocks,
398        }
399    }
400}
401
402/// Wrap a run of text in the character styling RTF reported for it.
403fn style(text: &str, bold: bool, italic: bool) -> Span {
404    let span = Span::Text(text.to_string());
405    match (bold, italic) {
406        (false, false) => span,
407        (true, false) => Span::Bold(vec![span]),
408        (false, true) => Span::Italic(vec![span]),
409        (true, true) => Span::Bold(vec![Span::Italic(vec![span])]),
410    }
411}
412
413/// Decode a `\'hh` byte as Windows-1252, the codepage almost every RTF uses.
414fn cp1252(byte: u8) -> char {
415    const HIGH: [char; 32] = [
416        '€', '\u{81}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{8d}', 'Ž',
417        '\u{8f}', '\u{90}', '‘', '’', '“', '”', '•', '–', '—', '˜', '™', 'š', '›', 'œ', '\u{9d}',
418        'ž', 'Ÿ',
419    ];
420    match byte {
421        0x80..=0x9f => HIGH[(byte - 0x80) as usize],
422        // Everything else matches Latin-1, which is Unicode's first block.
423        _ => char::from(byte),
424    }
425}
426
427#[cfg(test)]
428mod tests {
429    use super::*;
430
431    const HEADER: &str = r"{\rtf1\ansi\deff0{\fonttbl{\f0 Helvetica;}}\pard ";
432
433    fn parse_body(body: &str) -> Vec<Block> {
434        parse(&format!("{HEADER}{body}}}"))
435            .expect("valid rtf")
436            .blocks
437    }
438
439    #[test]
440    fn paragraphs_split_on_par() {
441        assert_eq!(
442            parse_body(r"first\par second\par "),
443            vec![Block::paragraph("first"), Block::paragraph("second")]
444        );
445    }
446
447    #[test]
448    fn bold_and_italic_runs_survive() {
449        let blocks = parse_body(r"plain {\b bold} {\i italic}\par ");
450        let Block::Paragraph { text } = &blocks[0] else {
451            panic!("expected a paragraph, got {blocks:?}");
452        };
453        assert_eq!(
454            text.spans,
455            vec![
456                Span::Text("plain ".into()),
457                Span::Bold(vec![Span::Text("bold".into())]),
458                Span::Text(" ".into()),
459                Span::Italic(vec![Span::Text("italic".into())]),
460            ]
461        );
462    }
463
464    #[test]
465    fn styling_switches_off_with_a_zero_parameter() {
466        let blocks = parse_body(r"\b bold\b0  plain\par ");
467        let Block::Paragraph { text } = &blocks[0] else {
468            panic!("expected a paragraph");
469        };
470        assert_eq!(
471            text.spans,
472            vec![
473                Span::Bold(vec![Span::Text("bold".into())]),
474                Span::Text(" plain".into()),
475            ]
476        );
477    }
478
479    #[test]
480    fn font_and_colour_tables_are_not_text() {
481        let blocks = parse_body(r"{\colortbl;\red255\green0\blue0;}visible\par ");
482        assert_eq!(blocks, vec![Block::paragraph("visible")]);
483    }
484
485    #[test]
486    fn ignorable_destinations_are_skipped() {
487        assert_eq!(
488            parse_body(r"{\*\generator Riched20 10.0}kept\par "),
489            vec![Block::paragraph("kept")]
490        );
491    }
492
493    #[test]
494    fn escapes_and_unicode_are_decoded() {
495        // `\'e9` is a Windows-1252 byte; `႐?` is a codepoint followed by
496        // the ASCII fallback character, which must be swallowed.
497        assert_eq!(
498            parse_body(r"caf\'e9 \u1090? \\ \{ \} \emdash\par "),
499            vec![Block::paragraph("café т \\ { } —")]
500        );
501    }
502
503    #[test]
504    fn line_breaks_stay_inside_a_paragraph() {
505        let blocks = parse_body(r"first\line second\par ");
506        let Block::Paragraph { text } = &blocks[0] else {
507            panic!("expected a paragraph");
508        };
509        assert_eq!(
510            text.spans,
511            vec![
512                Span::Text("first".into()),
513                Span::LineBreak,
514                Span::Text("second".into()),
515            ]
516        );
517    }
518
519    #[test]
520    fn table_cells_become_tab_separated_lines() {
521        assert_eq!(
522            parse_body(r"a\cell b\cell \row "),
523            vec![Block::paragraph("a\tb\t")]
524        );
525    }
526
527    #[test]
528    fn trailing_text_without_a_final_par_is_kept() {
529        assert_eq!(
530            parse_body("no trailing par"),
531            vec![Block::paragraph("no trailing par")]
532        );
533    }
534
535    #[test]
536    fn blank_paragraphs_are_dropped() {
537        assert_eq!(
538            parse_body(r"text\par \par \par "),
539            vec![Block::paragraph("text")]
540        );
541    }
542
543    #[test]
544    fn the_info_group_becomes_metadata_not_text() {
545        let parsed = parse(&format!(
546            r"{HEADER}{{\info{{\title Quarterly Report}}{{\author Ada Lovelace}}{{\creatim\yr2026\mo7\dy24\hr10}}}}Body text.\par }}"
547        ))
548        .expect("valid rtf");
549
550        assert_eq!(parsed.meta.title.as_deref(), Some("Quarterly Report"));
551        assert_eq!(parsed.meta.author.as_deref(), Some("Ada Lovelace"));
552        assert_eq!(parsed.meta.created.as_deref(), Some("2026-07-24"));
553        assert_eq!(
554            parsed.blocks,
555            vec![Block::paragraph("Body text.")],
556            "info fields must not leak into the document"
557        );
558    }
559
560    #[test]
561    fn a_document_without_an_info_group_has_no_metadata() {
562        let parsed = parse(&format!(r"{HEADER}just text\par }}")).expect("valid rtf");
563        assert_eq!(parsed.meta, Metadata::default());
564    }
565
566    #[test]
567    fn malformed_input_is_an_error_not_a_panic() {
568        assert!(parse("not rtf at all").is_err());
569    }
570}