Skip to main content

rtf_parser_tt/
tokens.rs

1use std::any::type_name;
2use std::convert::TryFrom;
3use std::fmt;
4
5use crate::lexer::LexerError;
6use crate::parser::ParserError;
7
8/// Parser representation of an RTF token
9#[allow(dead_code)]
10#[derive(PartialEq, Eq, Clone)]
11#[non_exhaustive]
12pub enum Token<'a> {
13    PlainText(&'a str),
14    OpeningBracket,
15    ClosingBracket,
16    CRLF,                 // Line-return \n
17    IgnorableDestination, // \*\ <destination-name>
18    ControlSymbol(ControlSymbol<'a>),
19    Empty, // Used by the parser for optimization
20}
21
22#[allow(dead_code)]
23impl<'a> fmt::Debug for Token<'a> {
24    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
25        #[rustfmt::skip]
26        return match self {
27            Token::PlainText(text)        => write!(f, r"PlainText : {:?}", *text),
28            Token::OpeningBracket         => write!(f, "OpeningBracket"),
29            Token::ClosingBracket         => write!(f, "ClosingBracket"),
30            Token::CRLF                   => write!(f, "CRLF"),
31            Token::IgnorableDestination   => write!(f, "IgnorableDestination"),
32            Token::ControlSymbol(symbol)  => write!(f, "ControlSymbol : {:?}", symbol),
33            Token::Empty                  => write!(f, "Empty"),
34        };
35    }
36}
37
38/// A control symbol is a pair (control_word, property)
39/// In the RTF specification, it refers to 'control word entity'
40pub type ControlSymbol<'a> = (ControlWord<'a>, Property);
41
42/// Parameters for a control word
43#[allow(dead_code)]
44#[derive(Copy, Clone, Debug, PartialEq, Eq)]
45#[non_exhaustive]
46pub enum Property {
47    On,         // 1
48    Off,        // 0
49    Value(i32), // Specified as i16 in the spec 1.5 but some softwre use i32 (ex: TextEdit for unicode)
50    None,       // No parameter
51}
52
53impl Property {
54    pub fn as_bool(&self) -> bool {
55        match self {
56            Property::On => true,
57            Property::Off => false,
58            Property::None => true,
59            Property::Value(val) => *val != 0,
60        }
61    }
62
63    // Retrieve and cast the i32 value to a specific numeric type
64    pub fn get_value_as<T: TryFrom<i32>>(&self) -> Result<T, ParserError> {
65        let error: Result<T, ParserError> = Err(ParserError::ValueCastError(type_name::<T>().to_string()));
66        if let Property::Value(value) = &self {
67            return T::try_from(*value).or(error);
68        }
69        // If no value, returns 0
70        T::try_from(0).or(error)
71    }
72
73    // Default variant
74    pub fn get_value(&self) -> i32 {
75        self.get_value_as::<i32>().expect("i32 to i32 conversion should never fail")
76    }
77
78    /// Return the u16 corresponding value of the unicode
79    pub fn get_unicode_value(&self) -> Result<u16, ParserError> {
80        // RTF control words generally accept signed 16-bit numbers as arguments.
81        // For this reason, Unicode values greater than 32767 must be expressed as negative numbers.
82        let mut offset = 0;
83        if let Property::Value(value) = &self {
84            if *value < 0 {
85                offset = 65_536;
86            }
87            return u16::try_from(value + offset).or(Err(ParserError::UnicodeParsingError(*value)));
88        }
89        Err(ParserError::UnicodeParsingError(0))
90    }
91}
92
93#[derive(Copy, Clone, Debug, PartialEq, Eq)]
94#[non_exhaustive]
95pub enum ControlWord<'a> {
96    Rtf,
97    Ansi,
98
99    Unicode,
100    UnicodeIgnoreCount,
101
102    FontTable,
103    FontCharset,
104    FontNumber,
105    FontSize, // Expressed in half point
106    ColorNumber,
107
108    ColorTable,
109    FileTable,
110    StyleSheet,
111
112    Italic,
113    Bold,
114    Underline,
115    UnderlineNone,
116    Superscript, // 5th
117    Subscript,   // H20
118    Smallcaps,
119    Strikethrough,
120
121    Par,  // New paragraph
122    Pard, // Resets to default paragraph properties
123    Sectd,
124    Plain,
125    ParStyle,  // Designates paragraph style. If a paragraph style is specified, style properties must be specified with the paragraph. N references an entry in the stylesheet.
126    ParDefTab, // Tab width
127    // Paragraph indent
128    FirstLineIdent,
129    LeftIndent,
130    RightIndent,
131    // Paragraph alignment
132    LeftAligned,
133    RightAligned,
134    Center,
135    Justify,
136    // Paragraph spacing
137    SpaceBefore,
138    SpaceAfter,
139    SpaceBetweenLine,
140    SpaceLineMul, // Line spacing multiple. Indicates that the current line spacing is a multiple of "Single" line spacing. This control word can follow only the \sl control word and works in conjunction with it.
141
142    ColorRed,
143    ColorGreen,
144    ColorBlue,
145
146    // Special characters
147    Emdash,
148    Endash,
149    Bullet,
150    LeftSingleQuote,
151    RightSingleQuote,
152    LeftDoubleQuote,
153    RightDoubleQuote,
154    Tab,
155    Line,
156
157    Page,
158    Sect,
159    Cell,
160    Row,
161    NestCell,
162    NestRow,
163
164    Hidden,
165    HexChar,
166    NonBreakingSpace,
167    OptionalHyphen,
168    NonBreakingHyphen,
169    FormulaCharacter,
170    IndexSubentry,
171
172    AnsiCodePage,
173    Mac,
174    Pc,
175    Pca,
176    DefaultFont,
177
178    Bin,
179    Info,
180    Upr,
181    Ud,
182
183    Unknown(&'a str),
184}
185
186const SKIPPED_DESTINATIONS: &[&str] = &[
187    "bkmkend", "bkmkstart", "colorschememapping", "datafield", "datastore", "do", "docvar", "fldinst", "generator", "latentstyles",
188    "listoverridetable", "listtable", "mmathPr", "nonshppict", "objclass", "objdata", "pgdsctbl", "pict", "pntxta", "pntxtb", "revtbl",
189    "rsidtbl", "sp", "tc", "template", "themedata", "userprops", "xe", "xmlnstbl",
190];
191
192impl<'a> ControlWord<'a> {
193    // https://www.biblioscape.com/rtf15_spec.htm
194    // version 1.5 should be compatible with 1.9
195    pub fn from(input: &str) -> Result<ControlSymbol<'_>, LexerError> {
196        let digits = input.bytes().rev().take_while(|b| b.is_ascii_digit() || *b == b'-').count();
197        let (prefix, suffix) = input.split_at(input.len() - digits);
198
199        let property = if suffix.is_empty() {
200            Property::None
201        } else {
202            let Ok(value) = suffix.parse::<i32>() else {
203                return Err(LexerError::Error(format!("[Lexer] Unable to parse {} as integer", &suffix)));
204            };
205            Property::Value(value)
206        };
207
208        let control_word = ControlWord::lookup(prefix);
209        Ok((control_word, property))
210    }
211
212    pub(crate) fn lookup<'w>(name: &'w str) -> ControlWord<'w> {
213        #[rustfmt::skip]
214        let word = match name.as_bytes().get(1) {
215            Some(b'a') => match name {
216                r"\ansi" => ControlWord::Ansi,
217                r"\ansicpg" => ControlWord::AnsiCodePage,
218                _ => ControlWord::Unknown(name),
219            },
220            Some(b'b') => match name {
221                r"\b" => ControlWord::Bold,
222                r"\bin" => ControlWord::Bin,
223                r"\blue" => ControlWord::ColorBlue,
224                r"\bullet" => ControlWord::Bullet,
225                _ => ControlWord::Unknown(name),
226            },
227            Some(b'c') => match name {
228                r"\cf" => ControlWord::ColorNumber,
229                r"\cell" => ControlWord::Cell,
230                r"\colortbl" => ControlWord::ColorTable,
231                _ => ControlWord::Unknown(name),
232            },
233            Some(b'd') => match name {
234                r"\deff" => ControlWord::DefaultFont,
235                _ => ControlWord::Unknown(name),
236            },
237            Some(b'e') => match name {
238                r"\emdash" => ControlWord::Emdash,
239                r"\endash" => ControlWord::Endash,
240                _ => ControlWord::Unknown(name),
241            },
242            Some(b'f') => match name {
243                r"\f" => ControlWord::FontNumber,
244                r"\fi" => ControlWord::FirstLineIdent,
245                r"\fs" => ControlWord::FontSize,
246                r"\filetbl" => ControlWord::FileTable,
247                r"\fonttbl" => ControlWord::FontTable,
248                r"\fcharset" => ControlWord::FontCharset,
249                _ => ControlWord::Unknown(name),
250            },
251            Some(b'g') => match name {
252                r"\green" => ControlWord::ColorGreen,
253                _ => ControlWord::Unknown(name),
254            },
255            Some(b'i') => match name {
256                r"\i" => ControlWord::Italic,
257                r"\info" => ControlWord::Info,
258                _ => ControlWord::Unknown(name),
259            },
260            Some(b'l') => match name {
261                r"\li" => ControlWord::LeftIndent,
262                r"\line" => ControlWord::Line,
263                r"\lquote" => ControlWord::LeftSingleQuote,
264                r"\ldblquote" => ControlWord::LeftDoubleQuote,
265                _ => ControlWord::Unknown(name),
266            },
267            Some(b'm') => match name {
268                r"\mac" => ControlWord::Mac,
269                _ => ControlWord::Unknown(name),
270            },
271            Some(b'n') => match name {
272                r"\nestrow" => ControlWord::NestRow,
273                r"\nestcell" => ControlWord::NestCell,
274                _ => ControlWord::Unknown(name),
275            },
276            Some(b'p') => match name {
277                r"\pc" => ControlWord::Pc,
278                r"\par" => ControlWord::Par,
279                r"\pca" => ControlWord::Pca,
280                r"\page" => ControlWord::Page,
281                r"\pard" => ControlWord::Pard,
282                r"\plain" => ControlWord::Plain,
283                r"\pardeftab" => ControlWord::ParDefTab,
284                _ => ControlWord::Unknown(name),
285            },
286            Some(b'q') => match name {
287                r"\qc" => ControlWord::Center,
288                r"\qj" => ControlWord::Justify,
289                r"\ql" => ControlWord::LeftAligned,
290                r"\qr" => ControlWord::RightAligned,
291                _ => ControlWord::Unknown(name),
292            },
293            Some(b'r') => match name {
294                r"\ri" => ControlWord::RightIndent,
295                r"\red" => ControlWord::ColorRed,
296                r"\row" => ControlWord::Row,
297                r"\rtf" => ControlWord::Rtf,
298                r"\rquote" => ControlWord::RightSingleQuote,
299                r"\rdblquote" => ControlWord::RightDoubleQuote,
300                _ => ControlWord::Unknown(name),
301            },
302            Some(b's') => match name {
303                r"\s" => ControlWord::ParStyle,
304                r"\sa" => ControlWord::SpaceAfter,
305                r"\sb" => ControlWord::SpaceBefore,
306                r"\sl" => ControlWord::SpaceBetweenLine,
307                r"\sub" => ControlWord::Subscript,
308                r"\sect" => ControlWord::Sect,
309                r"\scaps" => ControlWord::Smallcaps,
310                r"\sectd" => ControlWord::Sectd,
311                r"\slmul" => ControlWord::SpaceLineMul,
312                r"\super" => ControlWord::Superscript,
313                r"\slmult" => ControlWord::SpaceLineMul,
314                r"\strike" => ControlWord::Strikethrough,
315                r"\stylesheet" => ControlWord::StyleSheet,
316                _ => ControlWord::Unknown(name),
317            },
318            Some(b't') => match name {
319                r"\tab" => ControlWord::Tab,
320                _ => ControlWord::Unknown(name),
321            },
322            Some(b'u') => match name {
323                r"\u" => ControlWord::Unicode,
324                r"\uc" => ControlWord::UnicodeIgnoreCount,
325                r"\ud" => ControlWord::Ud,
326                r"\ul" => ControlWord::Underline,
327                r"\upr" => ControlWord::Upr,
328                r"\ulnone" => ControlWord::UnderlineNone,
329                _ => ControlWord::Unknown(name),
330            },
331            Some(b'v') => match name {
332                r"\v" => ControlWord::Hidden,
333                _ => ControlWord::Unknown(name),
334            },
335            _ => ControlWord::Unknown(name),
336        };
337        word
338    }
339
340    pub(crate) fn skips_group(&self) -> bool {
341        match self {
342            ControlWord::FontTable | ControlWord::ColorTable | ControlWord::StyleSheet | ControlWord::FileTable => true,
343            ControlWord::Unknown(name) => SKIPPED_DESTINATIONS.contains(&name.trim_start_matches('\\')),
344            _ => false,
345        }
346    }
347}
348
349#[cfg(test)]
350mod tests {
351    use crate::tokens::{ControlWord, Property};
352
353    #[test]
354    fn control_word_from_input_test() {
355        let input = r"\rtf1";
356        assert_eq!(ControlWord::from(input).unwrap(), (ControlWord::Rtf, Property::Value(1)))
357    }
358
359    #[test]
360    fn lookup_finds_known_and_unknown_words() {
361        assert_eq!(ControlWord::from(r"\pard").unwrap(), (ControlWord::Pard, Property::None));
362        assert_eq!(ControlWord::from(r"\fs24").unwrap(), (ControlWord::FontSize, Property::Value(24)));
363        assert_eq!(ControlWord::from(r"\af3").unwrap(), (ControlWord::Unknown(r"\af"), Property::Value(3)));
364        assert_eq!(ControlWord::from(r"\zzz").unwrap(), (ControlWord::Unknown(r"\zzz"), Property::None));
365    }
366
367    #[test]
368    fn control_word_with_negative_parameter() {
369        let input = r"\rtf-1";
370        assert_eq!(ControlWord::from(input).unwrap(), (ControlWord::Rtf, Property::Value(-1)))
371    }
372}