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