Skip to main content

rtf_parser_tt/
parser.rs

1use std::collections::HashMap;
2use std::{fmt, mem};
3
4use serde::{Deserialize, Serialize};
5#[cfg(feature = "jsbindings")]
6use tsify::Tsify;
7#[cfg(feature = "jsbindings")]
8use wasm_bindgen::prelude::wasm_bindgen;
9
10use crate::document::{DocumentInfo, RtfDocument};
11use crate::encoding::{code_page_for_charset, code_page_for_document, code_page_for_font, decode_into, needs_trail_byte, symbol_font_char, SYMBOL_CODE_PAGE};
12use crate::header::{CharacterSet, Color, ColorRef, ColorTable, Font, FontFamily, FontRef, FontTable, RtfHeader, Style, StyleRef, StyleSheet};
13use crate::paragraph::{Alignment, Paragraph, SpaceBetweenLine};
14use crate::tokens::{ControlWord, Property, Token};
15
16macro_rules! header_control_word {
17    ($cw:ident) => {
18        &Token::ControlSymbol((ControlWord::$cw, _))
19    };
20    ($cw:ident, $prop:ident) => {
21        &Token::ControlSymbol((ControlWord::$cw, Property::$prop))
22    };
23}
24
25#[derive(Debug, Default, PartialEq, Clone, Deserialize, Serialize)]
26#[cfg_attr(feature = "jsbindings", wasm_bindgen(getter_with_clone))]
27#[non_exhaustive]
28pub struct StyleBlock {
29    pub painter: Painter,
30    pub paragraph: Paragraph,
31    #[serde(default)]
32    pub part: Part,
33    pub text: String,
34}
35
36#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
37#[cfg_attr(feature = "jsbindings", derive(Tsify), tsify(into_wasm_abi, from_wasm_abi))]
38#[non_exhaustive]
39pub enum Part {
40    #[default]
41    Body,
42    NoteReference(u32),
43    Note(u32),
44    Header,
45    Footer,
46}
47
48#[derive(Debug, Clone, PartialEq, Hash, Deserialize, Serialize)]
49#[cfg_attr(feature = "jsbindings", wasm_bindgen)]
50#[non_exhaustive]
51pub struct Painter {
52    pub color_ref: ColorRef,
53    pub font_ref: FontRef,
54    pub font_size: u16,
55    pub bold: bool,
56    pub italic: bool,
57    pub underline: bool,
58    pub superscript: bool,
59    pub subscript: bool,
60    pub smallcaps: bool,
61    pub strike: bool,
62    pub hidden: bool,
63}
64
65impl Default for Painter {
66    fn default() -> Self {
67        Self {
68            color_ref: Default::default(),
69            font_ref: Default::default(),
70            font_size: 12,
71            bold: Default::default(),
72            italic: Default::default(),
73            underline: Default::default(),
74            superscript: Default::default(),
75            subscript: Default::default(),
76            smallcaps: Default::default(),
77            strike: Default::default(),
78            hidden: Default::default(),
79        }
80    }
81}
82
83#[derive(Debug, Clone)]
84#[non_exhaustive]
85pub enum ParserError {
86    InvalidToken(String),
87    IgnorableDestinationParsingError,
88    MalformedPainterStack,
89    InvalidFontIdentifier(Property),
90    InvalidColorIdentifier(Property),
91    NoMoreToken,
92    ValueCastError(String),
93    UnicodeParsingError(i32),
94    ParseEmptyToken,
95}
96
97impl std::error::Error for ParserError {}
98
99impl fmt::Display for ParserError {
100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101        write!(f, "[RTF Parser] : ")?;
102        match self {
103            ParserError::InvalidToken(msg) => write!(f, "{}", msg),
104            ParserError::IgnorableDestinationParsingError => write!(f, "No ignorable destination should be left"),
105            ParserError::MalformedPainterStack => write!(f, "Malformed painter stack : Unbalanced number of brackets"),
106            ParserError::InvalidFontIdentifier(property) => write!(f, "Invalid font identifier : {:?}", property),
107            ParserError::InvalidColorIdentifier(property) => write!(f, "Invalid color identifier : {:?}", property),
108            ParserError::NoMoreToken => write!(f, "No more token to parse"),
109            ParserError::ValueCastError(_type) => write!(f, "Unable to cast i32 to {_type}"),
110            ParserError::UnicodeParsingError(value) => write!(f, "Unable to parse {value} value to unicode"),
111            ParserError::ParseEmptyToken => write!(f, "Try to parse an empty token, this should never happen. If so, please open an issue in the github repository"),
112        }
113    }
114}
115
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
117enum InfoField {
118    Title,
119    Subject,
120    Author,
121    Manager,
122    Company,
123    Operator,
124    Category,
125    Keywords,
126    Comment,
127}
128
129impl InfoField {
130    fn from_word(word: &ControlWord) -> Option<Self> {
131        let ControlWord::Unknown(name) = word else {
132            return None;
133        };
134        match name.trim_start_matches('\\') {
135            "title" => Some(Self::Title),
136            "subject" => Some(Self::Subject),
137            "author" => Some(Self::Author),
138            "manager" => Some(Self::Manager),
139            "company" => Some(Self::Company),
140            "operator" => Some(Self::Operator),
141            "category" => Some(Self::Category),
142            "keywords" => Some(Self::Keywords),
143            "doccomm" | "comment" => Some(Self::Comment),
144            _ => None,
145        }
146    }
147
148    fn slot(self, info: &mut DocumentInfo) -> &mut Option<String> {
149        match self {
150            Self::Title => &mut info.title,
151            Self::Subject => &mut info.subject,
152            Self::Author => &mut info.author,
153            Self::Manager => &mut info.manager,
154            Self::Company => &mut info.company,
155            Self::Operator => &mut info.operator,
156            Self::Category => &mut info.category,
157            Self::Keywords => &mut info.keywords,
158            Self::Comment => &mut info.comment,
159        }
160    }
161}
162
163#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
164enum Deferred {
165    Note,
166    Header,
167    Footer,
168}
169
170impl Deferred {
171    fn from_word(word: &ControlWord) -> Option<Self> {
172        let ControlWord::Unknown(name) = word else {
173            return None;
174        };
175        match name.trim_start_matches('\\') {
176            "footnote" => Some(Self::Note),
177            "header" | "headerl" | "headerr" | "headerf" => Some(Self::Header),
178            "footer" | "footerl" | "footerr" | "footerf" => Some(Self::Footer),
179            _ => None,
180        }
181    }
182}
183
184#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
185enum Destination {
186    #[default]
187    Body,
188    Skip,
189    InfoRoot,
190    Info(InfoField),
191    Deferred(Deferred),
192}
193
194#[derive(Debug, Clone, PartialEq, Hash)]
195struct ParserState {
196    pub painter: Painter,
197    pub paragraph: Paragraph,
198    pub unicode_ignore_count: i32,
199    destination: Destination,
200    upr_resume: Option<Destination>,
201}
202
203impl Default for ParserState {
204    fn default() -> Self {
205        Self {
206            painter: Default::default(),
207            paragraph: Default::default(),
208            unicode_ignore_count: 1,
209            destination: Destination::Body,
210            upr_resume: None,
211        }
212    }
213}
214
215impl ParserState {
216    fn open_group(&mut self, token: &Token, ignorable: bool) {
217        let parent = self.destination;
218        let resume = self.upr_resume.take();
219        let word = match token {
220            Token::ControlSymbol((word, _)) => Some(word),
221            _ => None,
222        };
223        self.destination = match (parent, word) {
224            (_, Some(ControlWord::Ud)) if resume.is_some() => resume.unwrap_or(Destination::Skip),
225            (Destination::Skip, _) => Destination::Skip,
226            (Destination::InfoRoot, Some(ControlWord::Upr)) => {
227                self.upr_resume = Some(Destination::InfoRoot);
228                Destination::Skip
229            }
230            (Destination::InfoRoot, Some(word)) => InfoField::from_word(word).map_or(Destination::Skip, Destination::Info),
231            (Destination::InfoRoot, None) => Destination::Skip,
232            (_, Some(ControlWord::Info)) => Destination::InfoRoot,
233            (Destination::Body | Destination::Deferred(_), Some(word)) if !ignorable && Deferred::from_word(word).is_some() => {
234                Deferred::from_word(word).map_or(parent, Destination::Deferred)
235            }
236            (_, Some(ControlWord::Upr)) => {
237                self.upr_resume = Some(parent);
238                Destination::Skip
239            }
240            (_, Some(word)) if ignorable || word.skips_group() => Destination::Skip,
241            (_, None) if ignorable => Destination::Skip,
242            _ => parent,
243        };
244    }
245
246    fn apply(&mut self, control_word: &ControlWord, property: &Property) -> Result<(), ParserError> {
247        let painter = &mut self.painter;
248        let paragraph = &mut self.paragraph;
249        #[rustfmt::skip]
250        match control_word {
251            ControlWord::ColorNumber        => painter.color_ref = property.get_value_as::<ColorRef>()?,
252            ControlWord::FontNumber         => painter.font_ref = property.get_value_as::<FontRef>()?,
253            ControlWord::DefaultFont        => painter.font_ref = property.get_value_as::<FontRef>()?,
254            ControlWord::FontSize           => painter.font_size = property.get_value_as::<u16>()?,
255            ControlWord::Bold               => painter.bold = property.as_bool(),
256            ControlWord::Italic             => painter.italic = property.as_bool(),
257            ControlWord::Underline          => painter.underline = property.as_bool(),
258            ControlWord::UnderlineNone      => painter.underline = false,
259            ControlWord::Superscript        => painter.superscript = property.as_bool(),
260            ControlWord::Subscript          => painter.subscript = property.as_bool(),
261            ControlWord::Smallcaps          => painter.smallcaps = property.as_bool(),
262            ControlWord::Strikethrough      => painter.strike = property.as_bool(),
263            ControlWord::Hidden             => painter.hidden = property.as_bool(),
264            ControlWord::Pard               => *paragraph = Paragraph::default(),
265            ControlWord::Plain              => *painter = Painter::default(),
266            ControlWord::ParDefTab          => paragraph.tab_width = property.get_value(),
267            ControlWord::LeftAligned
268                | ControlWord::RightAligned
269                | ControlWord::Center
270                | ControlWord::Justify      => paragraph.alignment = Alignment::from(control_word),
271            ControlWord::SpaceBefore        => paragraph.spacing.before = property.get_value(),
272            ControlWord::SpaceAfter         => paragraph.spacing.after = property.get_value(),
273            ControlWord::SpaceBetweenLine   => paragraph.spacing.between_line = SpaceBetweenLine::from(property.get_value()),
274            ControlWord::SpaceLineMul       => paragraph.spacing.line_multiplier = property.get_value(),
275            ControlWord::LeftIndent         => paragraph.indent.left = property.get_value(),
276            ControlWord::RightIndent        => paragraph.indent.right = property.get_value(),
277            ControlWord::FirstLineIdent     => paragraph.indent.first_line = property.get_value(),
278            ControlWord::UnicodeIgnoreCount => self.unicode_ignore_count = property.get_value(),
279            _ => {}
280        };
281        Ok(())
282    }
283}
284
285enum Emit {
286    Nothing,
287    Text(&'static str),
288    Unicode(i32),
289    Cell,
290    Row,
291    NoteNumber,
292}
293
294struct TextSink {
295    document_code_page: u16,
296    hex: Vec<u8>,
297    high_surrogate: Option<u16>,
298    pending_cell: bool,
299    fallback: usize,
300    notes: Vec<StyleBlock>,
301    header_footer: Vec<StyleBlock>,
302    note_count: u32,
303}
304
305impl TextSink {
306    fn new(document_code_page: u16) -> Self {
307        Self {
308            document_code_page,
309            hex: Vec::new(),
310            high_surrogate: None,
311            pending_cell: false,
312            fallback: 0,
313            notes: Vec::new(),
314            header_footer: Vec::new(),
315            note_count: 0,
316        }
317    }
318
319    fn emit(&mut self, text: &str, states: &[ParserState], document: &mut RtfDocument) -> Result<(), ParserError> {
320        self.emit_as(text, None, states, document)
321    }
322
323    fn emit_as(&mut self, text: &str, reference: Option<u32>, states: &[ParserState], document: &mut RtfDocument) -> Result<(), ParserError> {
324        if self.high_surrogate.take().is_some() {
325            self.route("\u{FFFD}", None, states, document)?;
326        }
327        if mem::take(&mut self.pending_cell) {
328            self.route("\t", None, states, document)?;
329        }
330        self.route(text, reference, states, document)
331    }
332
333    fn route(&mut self, text: &str, reference: Option<u32>, states: &[ParserState], document: &mut RtfDocument) -> Result<(), ParserError> {
334        let Some(state) = states.last() else {
335            return Err(ParserError::MalformedPainterStack);
336        };
337        match state.destination {
338            Destination::Body => Parser::add_text_to_blocks(text, state, reference.map_or(Part::Body, Part::NoteReference), &mut document.body),
339            Destination::Deferred(Deferred::Note) => Parser::add_text_to_blocks(text, state, Part::Note(self.note_count), &mut self.notes),
340            Destination::Deferred(Deferred::Header) => Parser::add_text_to_blocks(text, state, Part::Header, &mut self.header_footer),
341            Destination::Deferred(Deferred::Footer) => Parser::add_text_to_blocks(text, state, Part::Footer, &mut self.header_footer),
342            Destination::Info(field) => field.slot(&mut document.info).get_or_insert_with(String::new).push_str(text),
343            Destination::Skip | Destination::InfoRoot => {}
344        }
345        Ok(())
346    }
347
348    fn begin_deferred(&mut self, kind: Deferred) {
349        let blocks = match kind {
350            Deferred::Note => {
351                self.note_count = self.note_count.saturating_add(1);
352                &mut self.notes
353            }
354            Deferred::Header | Deferred::Footer => &mut self.header_footer,
355        };
356        if let Some(last) = blocks.last_mut() {
357            if !last.text.ends_with('\n') {
358                last.text.push('\n');
359            }
360        }
361    }
362
363    fn note_number(&self, state: &ParserState) -> (u32, Option<u32>) {
364        match state.destination {
365            Destination::Deferred(Deferred::Note) => (self.note_count, None),
366            Destination::Body => {
367                let number = self.note_count.saturating_add(1);
368                (number, Some(number))
369            }
370            _ => (self.note_count.saturating_add(1), None),
371        }
372    }
373
374    fn take_trail_byte(&mut self, text: &str, states: &[ParserState], header: &RtfHeader) -> bool {
375        match text.as_bytes().first() {
376            Some(&byte) if !self.hex.is_empty() && (0x40..=0x7E).contains(&byte) && needs_trail_byte(self.code_page(states, header), &self.hex) => {
377                self.hex.push(byte);
378                true
379            }
380            _ => false,
381        }
382    }
383
384    fn code_page(&self, states: &[ParserState], header: &RtfHeader) -> u16 {
385        states
386            .last()
387            .and_then(|state| header.font_table.get(&state.painter.font_ref))
388            .and_then(code_page_for_font)
389            .unwrap_or(self.document_code_page)
390    }
391
392    fn flush_hex(&mut self, states: &[ParserState], document: &mut RtfDocument) -> Result<(), ParserError> {
393        if self.hex.is_empty() {
394            return Ok(());
395        }
396        let mut decoded = String::with_capacity(self.hex.len());
397        decode_into(self.code_page(states, &document.header), &self.hex, &mut decoded);
398        self.hex.clear();
399        self.emit(&decoded, states, document)
400    }
401
402    fn unicode(&mut self, value: i32, states: &[ParserState], document: &mut RtfDocument) -> Result<(), ParserError> {
403        let code = if value < 0 { value.checked_add(65_536).filter(|code| *code >= 0) } else { Some(value) };
404        let code = code.and_then(|code| u32::try_from(code).ok()).unwrap_or(0xFFFD);
405        match code {
406            0xD800..=0xDBFF => {
407                if self.high_surrogate.take().is_some() {
408                    self.emit("\u{FFFD}", states, document)?;
409                }
410                self.high_surrogate = Some(code as u16);
411                Ok(())
412            }
413            0xDC00..=0xDFFF => match self.high_surrogate.take() {
414                Some(high) => self.emit(&String::from_utf16_lossy(&[high, code as u16]), states, document),
415                None => self.emit("\u{FFFD}", states, document),
416            },
417            _ => {
418                let symbol = (0xF020..=0xF0FF).contains(&code) && self.code_page(states, &document.header) == SYMBOL_CODE_PAGE;
419                let character = if symbol { symbol_font_char((code - 0xF000) as u8) } else { char::from_u32(code) };
420                let mut buffer = [0; 4];
421                self.emit(character.unwrap_or('\u{FFFD}').encode_utf8(&mut buffer), states, document)
422            }
423        }
424    }
425
426    fn finish(&mut self, states: &[ParserState], document: &mut RtfDocument) -> Result<(), ParserError> {
427        if !states.is_empty() {
428            self.flush_hex(states, document)?;
429            if self.high_surrogate.take().is_some() {
430                self.route("\u{FFFD}", None, states, document)?;
431            }
432        }
433        for deferred in [mem::take(&mut self.notes), mem::take(&mut self.header_footer)] {
434            if deferred.is_empty() {
435                continue;
436            }
437            match document.body.last_mut() {
438                Some(last) if last.text.ends_with('\n') => {}
439                Some(last) if matches!(last.part, Part::NoteReference(_)) => {
440                    let paragraph = last.paragraph;
441                    document.body.push(StyleBlock {
442                        paragraph,
443                        text: String::from("\n"),
444                        ..StyleBlock::default()
445                    });
446                }
447                Some(last) => last.text.push('\n'),
448                None => {}
449            }
450            document.body.extend(deferred);
451        }
452        Ok(())
453    }
454}
455
456pub struct Parser<'a> {
457    tokens: Vec<Token<'a>>,
458    parsed_item: Vec<bool>,
459    cursor: usize,
460}
461
462impl<'a> Parser<'a> {
463    pub fn new(tokens: Vec<Token<'a>>) -> Self {
464        Self {
465            parsed_item: vec![false; tokens.len()],
466            tokens,
467            cursor: 0,
468        }
469    }
470
471    pub fn get_tokens(&self) -> Vec<&Token<'_>> {
472        self.tokens.iter().filter(|t| *t != &Token::Empty).collect()
473    }
474
475    fn check_document_validity(&self) -> Result<(), ParserError> {
476        if let Some(token) = self.tokens.first() {
477            if token != &Token::OpeningBracket {
478                return Err(ParserError::InvalidToken(format!("Invalid first token : {:?} not a '{{'", token)));
479            }
480        } else {
481            return Err(ParserError::NoMoreToken);
482        }
483        if let Some(token) = self.tokens.last() {
484            if token != &Token::ClosingBracket {
485                return Err(ParserError::InvalidToken(format!("Invalid last token : {:?} not a '}}'", token)));
486            }
487        } else {
488            return Err(ParserError::NoMoreToken);
489        }
490        Ok(())
491    }
492
493    pub fn parse(&mut self) -> Result<RtfDocument, ParserError> {
494        self.check_document_validity()?;
495        let mut document = RtfDocument {
496            header: self.parse_header()?,
497            ..RtfDocument::default()
498        };
499        let mut states: Vec<ParserState> = vec![ParserState::default()];
500        let mut sink = TextSink::new(code_page_for_document(&document.header.character_set));
501        let mut group_start = false;
502        let mut ignorable = false;
503        let mut seen_rtf = false;
504        for index in 0..self.tokens.len() {
505            if self.parsed_item[index] {
506                continue;
507            }
508            let token = &self.tokens[index];
509            let is_hex = matches!(token, Token::ControlSymbol((ControlWord::HexChar, _)));
510            let mut trail_taken = false;
511            if !is_hex && !sink.hex.is_empty() {
512                if let Token::PlainText(text) = token {
513                    trail_taken = sink.take_trail_byte(text, &states, &document.header);
514                }
515                sink.flush_hex(&states, &mut document)?;
516            }
517            match token {
518                Token::OpeningBracket => {
519                    let state = states.last().cloned().unwrap_or_default();
520                    states.push(state);
521                    group_start = true;
522                    ignorable = false;
523                    sink.fallback = 0;
524                    continue;
525                }
526                Token::ClosingBracket => {
527                    if states.pop().is_none() {
528                        return Err(ParserError::MalformedPainterStack);
529                    }
530                    group_start = false;
531                    ignorable = false;
532                    sink.fallback = 0;
533                    continue;
534                }
535                Token::IgnorableDestination => {
536                    ignorable |= group_start;
537                    continue;
538                }
539                Token::Empty => continue,
540                _ => {}
541            }
542            let Some(state) = states.last_mut() else {
543                return Err(ParserError::MalformedPainterStack);
544            };
545            if mem::take(&mut group_start) {
546                let parent = state.destination;
547                state.open_group(token, mem::take(&mut ignorable));
548                if let Destination::Deferred(kind) = state.destination {
549                    if parent != state.destination {
550                        sink.begin_deferred(kind);
551                    }
552                }
553                if let (Destination::Info(field), Destination::InfoRoot) = (state.destination, parent) {
554                    *field.slot(&mut document.info) = None;
555                }
556            }
557            match token {
558                Token::PlainText(text) => {
559                    let mut text = if trail_taken { &text[1..] } else { *text };
560                    if sink.fallback > 0 {
561                        let cut = text.char_indices().nth(sink.fallback).map_or(text.len(), |(at, _)| at);
562                        sink.fallback -= text[..cut].chars().count();
563                        text = &text[cut..];
564                    }
565                    if !text.is_empty() && (seen_rtf || !text.trim().is_empty()) {
566                        sink.emit(text, &states, &mut document)?;
567                    }
568                }
569                Token::CRLF => sink.emit("\n", &states, &mut document)?,
570                Token::ControlSymbol((control_word, property)) => {
571                    state.apply(control_word, property)?;
572                    let unicode_ignore_count = state.unicode_ignore_count;
573                    #[rustfmt::skip]
574                    let emit = match control_word {
575                        ControlWord::Rtf               => { seen_rtf = true; Emit::Nothing }
576                        ControlWord::HexChar           => {
577                            if sink.fallback > 0 {
578                                sink.fallback -= 1;
579                            } else if let Property::Value(byte) = property {
580                                sink.hex.push(*byte as u8);
581                            }
582                            Emit::Nothing
583                        }
584                        ControlWord::Unicode           => match property {
585                            Property::Value(value) => {
586                                sink.fallback = usize::try_from(unicode_ignore_count).unwrap_or(0);
587                                Emit::Unicode(*value)
588                            }
589                            _ => Emit::Nothing,
590                        },
591                        ControlWord::Par
592                            | ControlWord::Sect
593                            | ControlWord::Page
594                            | ControlWord::Line        => Emit::Text("\n"),
595                        ControlWord::Tab               => Emit::Text("\t"),
596                        ControlWord::Cell
597                            | ControlWord::NestCell    => Emit::Cell,
598                        ControlWord::Row
599                            | ControlWord::NestRow     => Emit::Row,
600                        ControlWord::Emdash            => Emit::Text("\u{2014}"),
601                        ControlWord::Endash            => Emit::Text("\u{2013}"),
602                        ControlWord::Bullet            => Emit::Text("\u{2022}"),
603                        ControlWord::LeftSingleQuote   => Emit::Text("\u{2018}"),
604                        ControlWord::RightSingleQuote  => Emit::Text("\u{2019}"),
605                        ControlWord::LeftDoubleQuote   => Emit::Text("\u{201C}"),
606                        ControlWord::RightDoubleQuote  => Emit::Text("\u{201D}"),
607                        ControlWord::NonBreakingSpace  => Emit::Text("\u{A0}"),
608                        ControlWord::OptionalHyphen    => Emit::Text("\u{AD}"),
609                        ControlWord::NonBreakingHyphen => Emit::Text("\u{2011}"),
610                        ControlWord::Unknown(r"\chftn") => Emit::NoteNumber,
611                        _                              => Emit::Nothing,
612                    };
613                    match emit {
614                        Emit::Nothing => {}
615                        Emit::Text(text) => sink.emit(text, &states, &mut document)?,
616                        Emit::Unicode(value) => sink.unicode(value, &states, &mut document)?,
617                        Emit::Cell => {
618                            if mem::replace(&mut sink.pending_cell, true) {
619                                sink.pending_cell = false;
620                                sink.emit("\t", &states, &mut document)?;
621                                sink.pending_cell = true;
622                            }
623                        }
624                        Emit::Row => {
625                            sink.pending_cell = false;
626                            sink.emit("\n", &states, &mut document)?;
627                        }
628                        Emit::NoteNumber => {
629                            if let Some((number, reference)) = states.last().map(|state| sink.note_number(state)) {
630                                sink.emit_as(&number.to_string(), reference, &states, &mut document)?;
631                            }
632                        }
633                    }
634                }
635                _ => {}
636            }
637        }
638        sink.finish(&states, &mut document)?;
639        Ok(document)
640    }
641
642    fn add_text_to_blocks(text: &str, state: &ParserState, part: Part, blocks: &mut Vec<StyleBlock>) {
643        if let Some(group) = blocks.last_mut() {
644            if group.part == part && group.painter == state.painter && group.paragraph == state.paragraph {
645                group.text.push_str(text);
646                return;
647            }
648        }
649        blocks.push(StyleBlock {
650            painter: state.painter.clone(),
651            paragraph: state.paragraph,
652            part,
653            text: String::from(text),
654        });
655    }
656
657    fn get_token_at(&'a self, index: usize) -> Option<&'a Token<'a>> {
658        self.tokens.get(index)
659    }
660
661    #[inline]
662    fn consume_token_at(&mut self, index: usize) -> Option<Token<'a>> {
663        if self.tokens.is_empty() || index >= self.tokens.len() {
664            return None;
665        }
666        self.cursor += 1;
667        self.parsed_item[index] = true;
668        Some(mem::replace(&mut self.tokens[index], Token::Empty))
669    }
670
671    fn consume_next_token(&mut self) -> Option<Token<'a>> {
672        self.consume_token_at(self.cursor)
673    }
674
675    fn consume_tokens_until_matching_bracket(&mut self) -> Vec<Token<'a>> {
676        let mut ret = vec![];
677        let mut count = 0;
678        while let Some(token) = self.consume_next_token() {
679            match token {
680                Token::OpeningBracket => count += 1,
681                Token::ClosingBracket => count -= 1,
682                _ => {}
683            }
684            ret.push(token);
685            if count < 0 {
686                break;
687            }
688        }
689        ret
690    }
691
692    fn consume_group(&mut self) -> Vec<Token<'a>> {
693        self.consume_token_at(self.cursor);
694        self.consume_tokens_until_matching_bracket()
695    }
696
697    fn parse_header(&mut self) -> Result<RtfHeader, ParserError> {
698        self.cursor = 0;
699        let mut header = RtfHeader::default();
700        while let (Some(token), Some(mut next_token)) = (self.get_token_at(self.cursor), self.get_token_at(self.cursor + 1)) {
701            let mut i = 0;
702            while *next_token == Token::CRLF {
703                if let Some(next_token_not_crlf) = self.get_token_at(self.cursor + 1 + i) {
704                    next_token = next_token_not_crlf;
705                    i += 1;
706                } else {
707                    break;
708                }
709            }
710            match (token, next_token) {
711                (Token::OpeningBracket, header_control_word!(FontTable, None)) => {
712                    let font_table_tokens = self.consume_group();
713                    header.font_table = Self::parse_font_table(&font_table_tokens, code_page_for_document(&header.character_set))?;
714                }
715                (Token::OpeningBracket, header_control_word!(ColorTable, None)) => {
716                    let color_table_tokens = self.consume_group();
717                    header.color_table = Self::parse_color_table(&color_table_tokens)?;
718                }
719                (Token::OpeningBracket, header_control_word!(StyleSheet, None)) => {
720                    let stylesheet_tokens = self.consume_group();
721                    header.stylesheet = Self::parse_stylesheet(&stylesheet_tokens)?;
722                }
723                (token, _) => {
724                    if let Some(charset) = CharacterSet::from(token) {
725                        header.character_set = charset;
726                    }
727                    self.cursor += 1;
728                }
729            }
730        }
731        Ok(header)
732    }
733
734    fn skip_ignorable_group(tokens: &[Token<'a>], index: usize) -> Option<usize> {
735        if tokens.get(index) != Some(&Token::OpeningBracket) || tokens.get(index + 1) != Some(&Token::IgnorableDestination) {
736            return None;
737        }
738        let mut depth = 0;
739        for (offset, token) in tokens[index..].iter().enumerate() {
740            match token {
741                Token::OpeningBracket => depth += 1,
742                Token::ClosingBracket => {
743                    depth -= 1;
744                    if depth == 0 {
745                        return Some(index + offset + 1);
746                    }
747                }
748                _ => {}
749            }
750        }
751        Some(tokens.len())
752    }
753
754    fn parse_font_table(font_tables_tokens: &[Token<'a>], document_code_page: u16) -> Result<FontTable, ParserError> {
755        let Some(font_table_first_token) = font_tables_tokens.first() else {
756            return Err(ParserError::NoMoreToken);
757        };
758        if font_table_first_token != header_control_word!(FontTable, None) {
759            return Err(ParserError::InvalidToken(format!("{:?} is not a FontTable token", font_table_first_token)));
760        }
761        let mut table = HashMap::new();
762        let mut current: Option<(FontRef, Font)> = None;
763        let mut name_bytes: Vec<u8> = Vec::new();
764        let mut name_done = false;
765        let mut index = 0;
766        while index < font_tables_tokens.len() {
767            if let Some(next) = Self::skip_ignorable_group(font_tables_tokens, index) {
768                index = next;
769                continue;
770            }
771            match &font_tables_tokens[index] {
772                Token::ControlSymbol((ControlWord::FontNumber, property)) => {
773                    Self::insert_font(&mut table, current.take(), &mut name_bytes, document_code_page);
774                    let Property::Value(key) = property else {
775                        return Err(ParserError::InvalidFontIdentifier(*property));
776                    };
777                    let key = FontRef::try_from(*key).map_err(|_| ParserError::InvalidFontIdentifier(*property))?;
778                    current = Some((key, Font::default()));
779                    name_done = false;
780                }
781                Token::ControlSymbol((ControlWord::FontCharset, property)) => {
782                    if let Some((_, font)) = current.as_mut() {
783                        font.character_set = u8::try_from(property.get_value()).unwrap_or(0);
784                    }
785                }
786                Token::ControlSymbol((ControlWord::Unknown(name), _)) => {
787                    if let (Some((_, font)), Some(font_family)) = (current.as_mut(), FontFamily::from(name)) {
788                        font.font_family = font_family;
789                    }
790                }
791                Token::ControlSymbol((ControlWord::HexChar, Property::Value(byte))) if !name_done => name_bytes.push(*byte as u8),
792                Token::PlainText(text) if !name_done => match text.split_once(';') {
793                    Some((before, _)) => {
794                        name_bytes.extend_from_slice(before.as_bytes());
795                        name_done = true;
796                    }
797                    None => name_bytes.extend_from_slice(text.as_bytes()),
798                },
799                _ => {}
800            }
801            index += 1;
802        }
803        Self::insert_font(&mut table, current, &mut name_bytes, document_code_page);
804        Ok(table)
805    }
806
807    fn insert_font(table: &mut FontTable, entry: Option<(FontRef, Font)>, name_bytes: &mut Vec<u8>, document_code_page: u16) {
808        let Some((key, mut font)) = entry else {
809            name_bytes.clear();
810            return;
811        };
812        let code_page = code_page_for_charset(font.character_set).unwrap_or(document_code_page);
813        let mut name = String::new();
814        match std::str::from_utf8(name_bytes) {
815            Ok(text) if text.is_ascii() || !name_bytes.iter().any(|b| *b >= 0x80 && !text.is_char_boundary(0)) => name.push_str(text),
816            _ => decode_into(code_page, name_bytes, &mut name),
817        }
818        name_bytes.clear();
819        font.name = name.trim().to_string();
820        table.insert(key, font);
821    }
822
823    fn parse_color_table(color_table_tokens: &[Token<'a>]) -> Result<ColorTable, ParserError> {
824        let Some(color_table_first_token) = color_table_tokens.first() else {
825            return Err(ParserError::NoMoreToken);
826        };
827        if color_table_first_token != header_control_word!(ColorTable, None) {
828            return Err(ParserError::InvalidToken(format!("ParserError: {:?} is not a ColorTable token", color_table_first_token)));
829        }
830        let mut table = HashMap::new();
831        let mut current_key: ColorRef = 0;
832        let mut current_color = Color::default();
833        let mut has_color = false;
834        for token in color_table_tokens.iter() {
835            match token {
836                Token::ControlSymbol((control_word, property)) => match control_word {
837                    ControlWord::ColorRed => {
838                        current_color.red = property.get_value_as::<u8>()?;
839                        has_color = true;
840                    }
841                    ControlWord::ColorGreen => {
842                        current_color.green = property.get_value_as::<u8>()?;
843                        has_color = true;
844                    }
845                    ControlWord::ColorBlue => {
846                        current_color.blue = property.get_value_as::<u8>()?;
847                        has_color = true;
848                    }
849                    _ => {}
850                },
851                Token::PlainText(text) => {
852                    for _ in text.matches(';') {
853                        if mem::take(&mut has_color) {
854                            table.insert(current_key, mem::take(&mut current_color));
855                        }
856                        current_key = current_key.saturating_add(1);
857                    }
858                }
859                _ => {}
860            }
861        }
862        if has_color {
863            table.insert(current_key, current_color);
864        }
865        Ok(table)
866    }
867
868    fn parse_stylesheet(stylesheet_tokens: &[Token<'a>]) -> Result<StyleSheet, ParserError> {
869        let mut stylesheet = StyleSheet::new();
870        let mut depth = 0;
871        let mut index = 0;
872        let mut entry: Option<(StyleRef, ParserState, String, bool)> = None;
873        while index < stylesheet_tokens.len() {
874            let token = &stylesheet_tokens[index];
875            if depth == 1 {
876                if let Some(next) = Self::skip_ignorable_group(stylesheet_tokens, index) {
877                    index = next;
878                    continue;
879                }
880            }
881            match token {
882                Token::OpeningBracket => {
883                    depth += 1;
884                    if depth == 1 {
885                        let paragraph_style = stylesheet_tokens.get(index + 1) != Some(&Token::IgnorableDestination);
886                        entry = Some((0, ParserState::default(), String::new(), paragraph_style));
887                    }
888                }
889                Token::ClosingBracket => {
890                    if depth == 1 {
891                        if let Some((key, state, name, true)) = entry.take() {
892                            let name = name.split(';').next().unwrap_or("").trim().to_string();
893                            stylesheet.insert(
894                                key,
895                                Style {
896                                    name,
897                                    painter: state.painter,
898                                    paragraph: state.paragraph,
899                                },
900                            );
901                        }
902                    }
903                    depth -= 1;
904                }
905                Token::ControlSymbol((ControlWord::ParStyle, property)) if depth == 1 => {
906                    if let Some((key, ..)) = entry.as_mut() {
907                        *key = property.get_value_as::<StyleRef>()?;
908                    }
909                }
910                Token::ControlSymbol((control_word, property)) if depth == 1 => {
911                    if let Some((_, state, ..)) = entry.as_mut() {
912                        state.apply(control_word, property)?;
913                    }
914                }
915                Token::PlainText(text) if depth == 1 => {
916                    if let Some((_, _, name, _)) = entry.as_mut() {
917                        name.push_str(text);
918                    }
919                }
920                _ => {}
921            }
922            index += 1;
923        }
924        Ok(stylesheet)
925    }
926}
927
928#[cfg(test)]
929pub mod tests {
930    use super::*;
931    use crate::header::CharacterSet::*;
932    use crate::header::FontFamily::*;
933    use crate::header::RtfHeader;
934    use crate::include_test_file;
935    use crate::lexer::Lexer;
936
937    fn text_blocks(document: &RtfDocument) -> Vec<&StyleBlock> {
938        document.body.iter().filter(|block| !block.text.trim().is_empty()).collect()
939    }
940
941    #[test]
942    fn parser_header() {
943        let tokens = Lexer::scan(r#"{ \rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard Voici du texte en {\b gras}.\par }"#).unwrap();
944        let doc = Parser::new(tokens).parse().unwrap();
945        assert_eq!(
946            doc.header,
947            RtfHeader {
948                character_set: Ansi,
949                font_table: FontTable::from([(
950                    0,
951                    Font {
952                        name: "Helvetica".into(),
953                        character_set: 0,
954                        font_family: Swiss
955                    }
956                )]),
957                ..RtfHeader::default()
958            }
959        );
960        assert_eq!(
961            doc.body,
962            [
963                StyleBlock {
964                    painter: Painter::default(),
965                    paragraph: Default::default(),
966                    part: Part::Body,
967                    text: "Voici du texte en ".into(),
968                },
969                StyleBlock {
970                    painter: Painter { bold: true, ..Painter::default() },
971                    paragraph: Default::default(),
972                    part: Part::Body,
973                    text: "gras".into(),
974                },
975                StyleBlock {
976                    painter: Painter::default(),
977                    paragraph: Default::default(),
978                    part: Part::Body,
979                    text: ".\n".into(),
980                },
981            ]
982        );
983    }
984
985    #[test]
986    fn parse_multiline_document() {
987        let document = r"{\rtf1\ansi\deff0 {\fonttbl {\f0 Courier;}{\f1 ProFontWindows;}}
988{\colortbl;\red0\green0\blue0;\red255\green0\blue0;\red255\green255\blue0;}
989This line is font 0 which is courier\line
990\f1
991This line is font 1\line
992\f0
993This line is font 0 again\line
994This line has a \cf2 red \cf1 word\line
995\highlight3 while this line has a \cf2 red \cf1 word and is highlighted in yellow\highlight0\line
996Finally, back to the default color.\line
997}";
998        let doc = RtfDocument::try_from(document).unwrap();
999        assert_eq!(
1000            doc.get_text(),
1001            "This line is font 0 which is courier\nThis line is font 1\nThis line is font 0 again\nThis line has a red word\nwhile this line has a red word and is highlighted in yellow\nFinally, back to the default color.\n"
1002        );
1003        assert_eq!(doc.header.font_table.get(&1).unwrap().name, "ProFontWindows");
1004    }
1005
1006    #[test]
1007    fn parse_entire_file_header() {
1008        let file_content = include_test_file!("test-file.rtf");
1009        let tokens = Lexer::scan(file_content).unwrap();
1010        let doc = Parser::new(tokens).parse().unwrap();
1011        assert_eq!(
1012            doc.header,
1013            RtfHeader {
1014                character_set: Ansicpg(1252),
1015                font_table: FontTable::from([
1016                    (
1017                        0,
1018                        Font {
1019                            name: "Helvetica".into(),
1020                            character_set: 0,
1021                            font_family: Swiss,
1022                        }
1023                    ),
1024                    (
1025                        1,
1026                        Font {
1027                            name: "Helvetica-Bold".into(),
1028                            character_set: 0,
1029                            font_family: Swiss,
1030                        }
1031                    )
1032                ]),
1033                color_table: ColorTable::from([(1, Color { red: 255, green: 255, blue: 255 }),]),
1034                ..RtfHeader::default()
1035            }
1036        );
1037    }
1038
1039    #[test]
1040    fn parse_ignore_group() {
1041        let rtf = r"{\*\expandedcolortbl;;}";
1042        let tokens = Lexer::scan(rtf).unwrap();
1043        let document = Parser::new(tokens).parse().unwrap();
1044        assert_eq!(document.get_text(), "");
1045        assert_eq!(document.header, RtfHeader::default());
1046    }
1047
1048    #[test]
1049    fn parse_ignore_group_after_line_breaks() {
1050        let rtf = "{\n\n\\*\\expandedcolortbl;;}";
1051        let tokens = Lexer::scan(rtf).unwrap();
1052        let document = Parser::new(tokens).parse().unwrap();
1053        assert_eq!(document.get_text(), "");
1054        assert_eq!(document.header, RtfHeader::default());
1055    }
1056
1057    #[test]
1058    fn parse_list_item_whitespace() {
1059        let file_content = include_test_file!("list-item.rtf");
1060        let tokens = Lexer::scan(file_content).unwrap();
1061        let document = Parser::new(tokens).parse().unwrap();
1062        assert_eq!(
1063            document.body,
1064            vec![StyleBlock {
1065                painter: Painter { font_size: 24, ..Painter::default() },
1066                paragraph: Default::default(),
1067                part: Part::Body,
1068                text: "\nEmpty start\n\nList test : \n - item 1\n - item 2\n - item 3\n - item 4".into(),
1069            },]
1070        );
1071    }
1072
1073    #[test]
1074    fn parse_image_data() {
1075        let rtf_content = include_test_file!("file-with-image.rtf");
1076        let document = RtfDocument::try_from(rtf_content).unwrap();
1077        assert!(document.get_text().len() < 1000, "image data leaked into the text: {} characters", document.get_text().len());
1078    }
1079
1080    #[test]
1081    fn parse_header_and_body() {
1082        let rtf = r#"{\rtf1\ansi\ansicpg1252\cocoartf2639
1083\cocoatextscaling0\cocoaplatform0{\fonttbl\f0\froman\fcharset0 Times-Bold;\f1\froman\fcharset0 Times-Roman;\f2\froman\fcharset0 Times-Italic;
1084\f3\fswiss\fcharset0 Helvetica;}
1085{\colortbl;\red255\green255\blue255;\red0\green0\blue10;\red0\green0\blue1;\red191\green191\blue191;
1086}
1087\f0\b\fs21 \cf2 Lorem ipsum
1088\fs56 \
1089\pard\pardeftab709\sl288\slmult1\sa225\qj\partightenfactor0
1090
1091\f1\b0\fs21 \cf0 \
1092\pard\pardeftab709\fi-432\ri-1\sb240\sa120\partightenfactor0
1093\ls1\ilvl0
1094\f0\b\fs36\cf2\plain Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc ac faucibus odio. \
1095\pard\pardeftab709\sl288\slmult1\sa225\qj\partightenfactor0
1096}"#;
1097        let tokens = Lexer::scan(rtf).unwrap();
1098        let document = Parser::new(tokens).parse().unwrap();
1099        assert_eq!(document.body[0].text, "Lorem ipsum");
1100        assert_eq!(document.body[1].text, "\n");
1101        assert_eq!(document.body[2].text, "\n");
1102        assert_eq!(document.body[3].text, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc ac faucibus odio. \n");
1103        assert_eq!(document.header.font_table.get(&3).unwrap().name, "Helvetica");
1104    }
1105
1106    #[test]
1107    fn parse_paragraph_aligment() {
1108        let rtf = r#"{\rtf1\ansi\deff0 {\fonttbl {\f0 Times;}}
1109        \fs34
1110        {\pard \qc \fs60 Annalium Romae\par}
1111        {\pard \qj
1112            Urbem Romam a principio reges habuere; libertatem et
1113            \par}
1114        {\pard \ql
1115            Non Cinnae, non Sullae longa dominatio; et Pompei Crassique potentia
1116            \par}"#;
1117        let tokens = Lexer::scan(rtf).unwrap();
1118        let document = Parser::new(tokens).parse().unwrap();
1119        let blocks = text_blocks(&document);
1120        assert_eq!(blocks[0].paragraph.alignment, Alignment::Center);
1121        assert_eq!(blocks[1].paragraph.alignment, Alignment::Justify);
1122        assert_eq!(blocks[2].paragraph.alignment, Alignment::LeftAligned);
1123    }
1124
1125    #[test]
1126    fn should_parse_escaped_char() {
1127        let rtf = r"{\rtf1\ansi\deff0 {\fonttbl {\f0 Times;}}je suis une b\'eate}";
1128        let tokens = Lexer::scan(rtf).unwrap();
1129        let document = Parser::new(tokens).parse().unwrap();
1130        assert_eq!(document.body[0].text, "je suis une b\u{EA}te");
1131    }
1132
1133    #[test]
1134    fn parse_plain_directive() {
1135        let rtf = r"{\rtf1{\fonttbl {\f0 Times;}}\f0\b\fs36\u\cf2\plain Plain text}";
1136        let tokens = Lexer::scan(rtf).unwrap();
1137        let document = Parser::new(tokens).parse().unwrap();
1138        assert_eq!(document.body[0].painter, Painter::default());
1139    }
1140
1141    #[test]
1142    fn parse_color_table() {
1143        let rtf = r#"{\rtf1\ansi\ansicpg936\cocoartf2761
1144\cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fswiss\fcharset0 Helvetica;\f1\fnil\fcharset134 PingFangSC-Regular;}
1145{\colortbl;\red255\green255\blue255;\red251\green2\blue7;\red114\green44\blue253;}
1146{\*\expandedcolortbl;;\cssrgb\c100000\c14913\c0;\cssrgb\c52799\c30710\c99498;}
1147\f0\fs24 \cf2 A
1148\f1 \cf3 B}"#;
1149        let tokens = Lexer::scan(rtf).unwrap();
1150        let document = Parser::new(tokens).parse().unwrap();
1151        assert_eq!(document.header.color_table.get(&document.body[0].painter.color_ref).unwrap(), &Color { red: 251, green: 2, blue: 7 });
1152        assert_eq!(document.header.color_table.get(&3).unwrap(), &Color { red: 114, green: 44, blue: 253 });
1153    }
1154
1155    #[test]
1156    fn parse_underline() {
1157        let rtf = r#"{\rtf1\ansi\ansicpg936\cocoartf2761
1158\cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
1159{\colortbl;\red255\green255\blue255;}
1160{\*\expandedcolortbl;;}
1161\paperw11900\paperh16840\margl1440\margr1440\vieww11520\viewh8400\viewkind0
1162\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural\partightenfactor0
1163
1164\f0\fs24 \cf0 \ul \ulc0 a\ulnone A}"#;
1165        let tokens = Lexer::scan(rtf).unwrap();
1166        let document = Parser::new(tokens).parse().unwrap();
1167        assert_eq!(&document.body[0].painter.underline, &true);
1168        assert_eq!(&document.body[1].painter.underline, &false);
1169    }
1170
1171    #[test]
1172    fn parse_unicode() {
1173        let rtf = r#"{\rtf1\ansi\ansicpg936\cocoartf2761
1174\cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
1175\f0\fs24 \cf0 \uc0\u21834  \u21834 }"#;
1176        let tokens = Lexer::scan(rtf).unwrap();
1177        let document = Parser::new(tokens).parse().unwrap();
1178        assert_eq!(&document.body[0].text, "\u{554A} \u{554A}");
1179    }
1180
1181    #[test]
1182    fn surrogate_pair_without_fallback_text() {
1183        let rtf = r#"{\rtf1\ansi\uc0 a\u55357 \u56447 1 \u21834}"#;
1184        let document = RtfDocument::try_from(rtf).unwrap();
1185        assert_eq!(document.get_text(), "a\u{1F47F}1 \u{554A}");
1186    }
1187
1188    #[test]
1189    fn unicode_fallback_is_skipped_by_count() {
1190        let rtf = r#"{\rtf1\ansi a\u55357 \u56447 1 \u21834}"#;
1191        let document = RtfDocument::try_from(rtf).unwrap();
1192        assert_eq!(document.get_text(), "a\u{1F47F} \u{554A}");
1193    }
1194
1195    #[test]
1196    fn parse_unicode_with_fallback() {
1197        let rtf = r#"{\rtf1\ansi
1198{\f0 \u-10179\'5f\u-9089\'5f}
1199{\f1 \uc2\u32767\'c2\'52}
1200{\f2 \uc2\u26789\'97\'73}
1201{\f3 b\'eate}
1202{\f4 \uc0 b\'ea\'eate}
1203}"#;
1204        let tokens = Lexer::scan(rtf).unwrap();
1205        let document = Parser::new(tokens).parse().unwrap();
1206        assert_eq!(&document.body[0].text, "\u{1F47F}");
1207        assert_eq!(&document.body[1].text, "\u{7FFF}");
1208        assert_eq!(&document.body[2].text, "\u{68A5}");
1209        assert_eq!(&document.body[3].text, "b\u{EA}te");
1210        assert_eq!(&document.body[4].text, "b\u{EA}\u{EA}te");
1211    }
1212
1213    #[test]
1214    fn body_starts_with_a_group() {
1215        let rtf = r"{\rtf1\ansi\deff0{\fonttbl {\f0\fnil\fcharset0 Calibri;}{\f1\fnil\fcharset2 Symbol;}}{\colortbl ;}{\pard \u21435  \sb70\par}}";
1216        let tokens = Lexer::scan(rtf).unwrap();
1217        let _document = Parser::new(tokens).parse().unwrap();
1218    }
1219
1220    #[test]
1221    fn rtf_different_semantic() {
1222        let rtf1 = r"{\rtf1 \b bold \i Bold Italic \i0 Bold again}";
1223        let rtf2 = r"{\rtf1 \b bold {\i Bold Italic }Bold again}";
1224        let rtf3 = r"{\rtf1 \b bold \i Bold Italic \plain\b Bold again}";
1225        let doc1 = RtfDocument::try_from(rtf1).unwrap();
1226        let doc2 = RtfDocument::try_from(rtf2).unwrap();
1227        let doc3 = RtfDocument::try_from(rtf3).unwrap();
1228        assert_eq!(doc1.body, doc2.body);
1229        assert_eq!(doc3.body, doc2.body);
1230    }
1231
1232    #[test]
1233    fn parse_emdash() {
1234        let rtf = r"{\rtf1\ansi hello\emdash world}";
1235        let doc = RtfDocument::try_from(rtf).unwrap();
1236        let text: String = doc.body.iter().map(|b| b.text.as_str()).collect();
1237        assert!(text.contains("\u{2014}"), "Em-dash not found in: {}", text);
1238        assert!(text.contains("hello\u{2014}world"), "Expected 'hello\u{2014}world', got: {}", text);
1239    }
1240
1241    #[test]
1242    fn parse_endash() {
1243        let rtf = r"{\rtf1\ansi 2020\endash 2025}";
1244        let doc = RtfDocument::try_from(rtf).unwrap();
1245        let text: String = doc.body.iter().map(|b| b.text.as_str()).collect();
1246        assert!(text.contains("\u{2013}"), "En-dash not found in: {}", text);
1247    }
1248
1249    #[test]
1250    fn parse_smart_quotes() {
1251        let rtf = r"{\rtf1\ansi \ldblquote Hello\rdblquote  and \lquote hi\rquote}";
1252        let doc = RtfDocument::try_from(rtf).unwrap();
1253        let text: String = doc.body.iter().map(|b| b.text.as_str()).collect();
1254        assert!(text.contains("\u{201C}"), "Left double quote not found");
1255        assert!(text.contains("\u{201D}"), "Right double quote not found");
1256        assert!(text.contains("\u{2018}"), "Left single quote not found");
1257        assert!(text.contains("\u{2019}"), "Right single quote not found");
1258    }
1259
1260    #[test]
1261    fn parse_bullet() {
1262        let rtf = r"{\rtf1\ansi \bullet Item one}";
1263        let doc = RtfDocument::try_from(rtf).unwrap();
1264        let text: String = doc.body.iter().map(|b| b.text.as_str()).collect();
1265        assert!(text.contains("\u{2022}"), "Bullet not found in: {}", text);
1266    }
1267
1268    #[test]
1269    fn parse_tab_and_line() {
1270        let rtf = r"{\rtf1\ansi col1\tab col2\line next}";
1271        let doc = RtfDocument::try_from(rtf).unwrap();
1272        assert_eq!(doc.get_text(), "col1\tcol2\nnext");
1273    }
1274
1275    #[test]
1276    fn parse_special_chars_in_scrivener_style() {
1277        let rtf = r"{\rtf1\ansi\ansicpg1252\deff0
1278{\fonttbl{\f0\fnil\fcharset0 TimesNewRomanPSMT;}}
1279\f0\fs24 The transformation in reverse\emdash confident expert to tired father.\par
1280He said, \ldblquote Hello.\rdblquote\par}";
1281        let doc = RtfDocument::try_from(rtf).unwrap();
1282        assert_eq!(doc.get_text(), "The transformation in reverse\u{2014}confident expert to tired father.\nHe said, \u{201C}Hello.\u{201D}\n");
1283    }
1284
1285    #[test]
1286    fn info_fields_become_metadata() {
1287        let rtf = r"{\rtf1\ansi{\info{\title Secret Title}{\author Bob}{\*\company Acme}{\creatim\yr2026}}Body}";
1288        let doc = RtfDocument::try_from(rtf).unwrap();
1289        assert_eq!(doc.get_text(), "Body");
1290        assert_eq!(doc.info.title.as_deref(), Some("Secret Title"));
1291        assert_eq!(doc.info.author.as_deref(), Some("Bob"));
1292        assert_eq!(doc.info.company.as_deref(), Some("Acme"));
1293    }
1294
1295    #[test]
1296    fn upr_uses_the_unicode_version() {
1297        let rtf = r"{\rtf1\ansi{\info{\upr{\title A?}{\*\ud{\title A\u945?}}}}Text {\upr{plain?}{\*\ud{uni\u945?}}}}";
1298        let doc = RtfDocument::try_from(rtf).unwrap();
1299        assert_eq!(doc.info.title.as_deref(), Some("A\u{3B1}"));
1300        assert_eq!(doc.get_text(), "Text uni\u{3B1}");
1301    }
1302
1303    #[test]
1304    fn font_names_skip_alternates_and_decode_hex() {
1305        let rtf = r"{\rtf1\ansi\ansicpg1251{\fonttbl{\f0\froman\fcharset0{\*\panose 02020603050405020304}Times New Roman{\*\falt Times};}{\f1\fnil\fcharset204 \'d2\'e5\'f1\'f2;}}x}";
1306        let doc = RtfDocument::try_from(rtf).unwrap();
1307        assert_eq!(doc.header.font_table.get(&0).unwrap().name, "Times New Roman");
1308        assert_eq!(doc.header.font_table.get(&1).unwrap().name, "\u{422}\u{435}\u{441}\u{442}");
1309        assert_eq!(doc.header.font_table.get(&1).unwrap().character_set, 204);
1310    }
1311
1312    #[test]
1313    fn font_charset_selects_the_code_page() {
1314        let rtf = r"{\rtf1\ansi\ansicpg1252{\fonttbl{\f0\fnil\fcharset0 Arial;}{\f1\fnil\fcharset204 Arial Cyr;}}\f0\'e9 \f1\'e9}";
1315        let doc = RtfDocument::try_from(rtf).unwrap();
1316        assert_eq!(doc.get_text(), "\u{E9} \u{439}");
1317    }
1318
1319    #[test]
1320    fn stylesheet_entries_are_parsed() {
1321        let rtf = r"{\rtf1\ansi{\stylesheet{\ql \fs24 Normal;}{\s1\qc\b\fs32 \sbasedon0 heading 1;}{\*\cs10 \additive Default Paragraph Font;}}x}";
1322        let doc = RtfDocument::try_from(rtf).unwrap();
1323        let normal = doc.header.stylesheet.get(&0).unwrap();
1324        assert_eq!(normal.name, "Normal");
1325        assert_eq!(normal.painter.font_size, 24);
1326        let heading = doc.header.stylesheet.get(&1).unwrap();
1327        assert_eq!(heading.name, "heading 1");
1328        assert!(heading.painter.bold);
1329        assert_eq!(heading.paragraph.alignment, Alignment::Center);
1330        assert_eq!(doc.header.stylesheet.len(), 2);
1331    }
1332
1333    #[test]
1334    fn table_rows_and_cells() {
1335        let rtf = r"{\rtf1\ansi\trowd\cellx1000\cellx2000\pard\intbl A\cell B\cell\row\trowd\cellx1000\cellx2000\pard\intbl C\cell D\cell\row}";
1336        assert_eq!(RtfDocument::try_from(rtf).unwrap().get_text(), "A\tB\nC\tD\n");
1337    }
1338
1339    #[test]
1340    fn hidden_text_is_marked() {
1341        let doc = RtfDocument::try_from(r"{\rtf1\ansi Shown{\v Hidden}}").unwrap();
1342        assert!(!doc.body[0].painter.hidden);
1343        assert!(doc.body[1].painter.hidden);
1344    }
1345
1346    #[test]
1347    fn bold_zero_turns_bold_off() {
1348        let doc = RtfDocument::try_from(r"{\rtf1\ansi \b2 a\b0 b}").unwrap();
1349        assert!(doc.body[0].painter.bold);
1350        assert!(!doc.body[1].painter.bold);
1351    }
1352
1353    #[test]
1354    fn notes_and_headers_follow_the_body() {
1355        let rtf = r"{\rtf1\ansi{\header Page head\par}Body one{\super\chftn{\footnote{\super\chftn} First note.}}.\par Body two{\super\chftn{\footnote{\super\chftn} Second note.}}\par}";
1356        assert_eq!(RtfDocument::try_from(rtf).unwrap().get_text(), "Body one1.\nBody two2\n1 First note.\n2 Second note.\nPage head\n");
1357    }
1358
1359    #[test]
1360    fn blocks_are_marked_with_their_part() {
1361        let rtf = r"{\rtf1\ansi{\header Head\par}{\footer Foot\par}Body{\super\chftn}{\footnote\pard\plain{\super\chftn} Note.} end.\par}";
1362        let doc = RtfDocument::try_from(rtf).unwrap();
1363        let parts: Vec<(Part, &str)> = doc.body.iter().map(|block| (block.part, block.text.as_str())).collect();
1364        assert_eq!(
1365            parts,
1366            [
1367                (Part::Body, "Body"),
1368                (Part::NoteReference(1), "1"),
1369                (Part::Body, " end.\n"),
1370                (Part::Note(1), "1"),
1371                (Part::Note(1), " Note.\n"),
1372                (Part::Header, "Head\n"),
1373                (Part::Footer, "Foot\n"),
1374            ]
1375        );
1376    }
1377
1378    #[test]
1379    fn notes_are_numbered_and_separated() {
1380        let rtf = r"{\rtf1\ansi A{\super\chftn}{\footnote\pard\plain{\super\chftn} One.} B{\super\chftn}{\footnote\pard\plain{\super\chftn} Two.}}";
1381        let doc = RtfDocument::try_from(rtf).unwrap();
1382        let parts: Vec<(Part, &str)> = doc.body.iter().map(|block| (block.part, block.text.as_str())).collect();
1383        assert_eq!(
1384            parts,
1385            [
1386                (Part::Body, "A"),
1387                (Part::NoteReference(1), "1"),
1388                (Part::Body, " B"),
1389                (Part::NoteReference(2), "2"),
1390                (Part::Body, "\n"),
1391                (Part::Note(1), "1"),
1392                (Part::Note(1), " One.\n"),
1393                (Part::Note(2), "2"),
1394                (Part::Note(2), " Two."),
1395            ]
1396        );
1397        assert!(!doc.body[4].painter.superscript);
1398    }
1399
1400    #[test]
1401    fn note_references_do_not_merge_with_body_text() {
1402        let doc = RtfDocument::try_from(r"{\rtf1\ansi A\chftn{\footnote N}B}").unwrap();
1403        let parts: Vec<(Part, &str)> = doc.body.iter().map(|block| (block.part, block.text.as_str())).collect();
1404        assert_eq!(parts, [(Part::Body, "A"), (Part::NoteReference(1), "1"), (Part::Body, "B\n"), (Part::Note(1), "N")]);
1405    }
1406
1407    #[test]
1408    fn symbol_font_bullets() {
1409        let rtf = r"{\rtf1\ansi{\fonttbl{\f0\fswiss Arial;}{\f3\fbidi\froman\fcharset2\fprq2 Symbol;}}{\listtext\f3\'b7\tab}Item{\f3 \u-3913\'b7}}";
1410        assert_eq!(RtfDocument::try_from(rtf).unwrap().get_text(), "\u{2022}\tItem\u{2022}");
1411    }
1412
1413    #[test]
1414    fn whitespace_before_rtf_is_ignored() {
1415        assert_eq!(RtfDocument::try_from("{ \n \\rtf1 text}").unwrap().get_text(), "text");
1416    }
1417}