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    FontCodePage,
105    FontNumber,
106    FontSize, // Expressed in half point
107    ColorNumber,
108
109    ColorTable,
110    FileTable,
111    StyleSheet,
112
113    Italic,
114    Bold,
115    Underline,
116    UnderlineNone,
117    Superscript, // 5th
118    Subscript,   // H20
119    Smallcaps,
120    Strikethrough,
121
122    Par,  // New paragraph
123    Pard, // Resets to default paragraph properties
124    Sectd,
125    Plain,
126    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.
127    ParDefTab, // Tab width
128    // Paragraph indent
129    FirstLineIdent,
130    LeftIndent,
131    RightIndent,
132    // Paragraph alignment
133    LeftAligned,
134    RightAligned,
135    Center,
136    Justify,
137    // Paragraph spacing
138    SpaceBefore,
139    SpaceAfter,
140    SpaceBetweenLine,
141    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.
142
143    ColorRed,
144    ColorGreen,
145    ColorBlue,
146
147    // Special characters
148    Emdash,
149    Endash,
150    Bullet,
151    LeftSingleQuote,
152    RightSingleQuote,
153    LeftDoubleQuote,
154    RightDoubleQuote,
155    Tab,
156    Line,
157
158    Page,
159    Sect,
160    Cell,
161    Row,
162    NestCell,
163    NestRow,
164
165    Hidden,
166    HexChar,
167    NonBreakingSpace,
168    OptionalHyphen,
169    NonBreakingHyphen,
170    FormulaCharacter,
171    IndexSubentry,
172
173    AnsiCodePage,
174    Mac,
175    Pc,
176    Pca,
177    DefaultFont,
178
179    Bin,
180    Info,
181    Upr,
182    Ud,
183
184    Unknown(&'a str),
185}
186
187const SKIPPED_DESTINATIONS: &[&str] = &[
188    "bkmkend", "bkmkstart", "colorschememapping", "datafield", "datastore", "do", "docvar", "fldinst", "generator", "latentstyles",
189    "listoverridetable", "listtable", "mmathPr", "nonshppict", "objclass", "objdata", "pgdsctbl", "pict", "pntxta", "pntxtb", "revtbl",
190    "rsidtbl", "sp", "tc", "template", "themedata", "userprops", "xe", "xmlnstbl",
191];
192
193impl<'a> ControlWord<'a> {
194    // https://www.biblioscape.com/rtf15_spec.htm
195    // version 1.5 should be compatible with 1.9
196    pub fn from(input: &str) -> Result<ControlSymbol<'_>, LexerError> {
197        let digits = input.bytes().rev().take_while(|b| b.is_ascii_digit() || *b == b'-').count();
198        let (prefix, suffix) = input.split_at(input.len() - digits);
199
200        let property = if suffix.is_empty() {
201            Property::None
202        } else {
203            let Ok(value) = suffix.parse::<i32>() else {
204                return Err(LexerError::Error(format!("[Lexer] Unable to parse {} as integer", &suffix)));
205            };
206            Property::Value(value)
207        };
208
209        let control_word = ControlWord::lookup(prefix);
210        Ok((control_word, property))
211    }
212
213    pub(crate) fn lookup<'w>(name: &'w str) -> ControlWord<'w> {
214        #[rustfmt::skip]
215        let word = match name.as_bytes().get(1) {
216            Some(b'a') => match name {
217                r"\ansi" => ControlWord::Ansi,
218                r"\ansicpg" => ControlWord::AnsiCodePage,
219                _ => ControlWord::Unknown(name),
220            },
221            Some(b'b') => match name {
222                r"\b" => ControlWord::Bold,
223                r"\bin" => ControlWord::Bin,
224                r"\blue" => ControlWord::ColorBlue,
225                r"\bullet" => ControlWord::Bullet,
226                _ => ControlWord::Unknown(name),
227            },
228            Some(b'c') => match name {
229                r"\cf" => ControlWord::ColorNumber,
230                r"\cpg" => ControlWord::FontCodePage,
231                r"\cell" => ControlWord::Cell,
232                r"\colortbl" => ControlWord::ColorTable,
233                _ => ControlWord::Unknown(name),
234            },
235            Some(b'd') => match name {
236                r"\deff" => ControlWord::DefaultFont,
237                _ => ControlWord::Unknown(name),
238            },
239            Some(b'e') => match name {
240                r"\emdash" => ControlWord::Emdash,
241                r"\endash" => ControlWord::Endash,
242                _ => ControlWord::Unknown(name),
243            },
244            Some(b'f') => match name {
245                r"\f" => ControlWord::FontNumber,
246                r"\fi" => ControlWord::FirstLineIdent,
247                r"\fs" => ControlWord::FontSize,
248                r"\filetbl" => ControlWord::FileTable,
249                r"\fonttbl" => ControlWord::FontTable,
250                r"\fcharset" => ControlWord::FontCharset,
251                _ => ControlWord::Unknown(name),
252            },
253            Some(b'g') => match name {
254                r"\green" => ControlWord::ColorGreen,
255                _ => ControlWord::Unknown(name),
256            },
257            Some(b'i') => match name {
258                r"\i" => ControlWord::Italic,
259                r"\info" => ControlWord::Info,
260                _ => ControlWord::Unknown(name),
261            },
262            Some(b'l') => match name {
263                r"\li" => ControlWord::LeftIndent,
264                r"\line" => ControlWord::Line,
265                r"\lquote" => ControlWord::LeftSingleQuote,
266                r"\ldblquote" => ControlWord::LeftDoubleQuote,
267                _ => ControlWord::Unknown(name),
268            },
269            Some(b'm') => match name {
270                r"\mac" => ControlWord::Mac,
271                _ => ControlWord::Unknown(name),
272            },
273            Some(b'n') => match name {
274                r"\nestrow" => ControlWord::NestRow,
275                r"\nestcell" => ControlWord::NestCell,
276                _ => ControlWord::Unknown(name),
277            },
278            Some(b'p') => match name {
279                r"\pc" => ControlWord::Pc,
280                r"\par" => ControlWord::Par,
281                r"\pca" => ControlWord::Pca,
282                r"\page" => ControlWord::Page,
283                r"\pard" => ControlWord::Pard,
284                r"\plain" => ControlWord::Plain,
285                r"\pardeftab" => ControlWord::ParDefTab,
286                _ => ControlWord::Unknown(name),
287            },
288            Some(b'q') => match name {
289                r"\qc" => ControlWord::Center,
290                r"\qj" => ControlWord::Justify,
291                r"\ql" => ControlWord::LeftAligned,
292                r"\qr" => ControlWord::RightAligned,
293                _ => ControlWord::Unknown(name),
294            },
295            Some(b'r') => match name {
296                r"\ri" => ControlWord::RightIndent,
297                r"\red" => ControlWord::ColorRed,
298                r"\row" => ControlWord::Row,
299                r"\rtf" => ControlWord::Rtf,
300                r"\rquote" => ControlWord::RightSingleQuote,
301                r"\rdblquote" => ControlWord::RightDoubleQuote,
302                _ => ControlWord::Unknown(name),
303            },
304            Some(b's') => match name {
305                r"\s" => ControlWord::ParStyle,
306                r"\sa" => ControlWord::SpaceAfter,
307                r"\sb" => ControlWord::SpaceBefore,
308                r"\sl" => ControlWord::SpaceBetweenLine,
309                r"\sub" => ControlWord::Subscript,
310                r"\sect" => ControlWord::Sect,
311                r"\scaps" => ControlWord::Smallcaps,
312                r"\sectd" => ControlWord::Sectd,
313                r"\slmul" => ControlWord::SpaceLineMul,
314                r"\super" => ControlWord::Superscript,
315                r"\slmult" => ControlWord::SpaceLineMul,
316                r"\strike" => ControlWord::Strikethrough,
317                r"\stylesheet" => ControlWord::StyleSheet,
318                _ => ControlWord::Unknown(name),
319            },
320            Some(b't') => match name {
321                r"\tab" => ControlWord::Tab,
322                _ => ControlWord::Unknown(name),
323            },
324            Some(b'u') => match name {
325                r"\u" => ControlWord::Unicode,
326                r"\uc" => ControlWord::UnicodeIgnoreCount,
327                r"\ud" => ControlWord::Ud,
328                r"\ul" => ControlWord::Underline,
329                r"\upr" => ControlWord::Upr,
330                r"\ulnone" => ControlWord::UnderlineNone,
331                _ => ControlWord::Unknown(name),
332            },
333            Some(b'v') => match name {
334                r"\v" => ControlWord::Hidden,
335                _ => ControlWord::Unknown(name),
336            },
337            _ => ControlWord::Unknown(name),
338        };
339        word
340    }
341
342    pub(crate) fn skips_group(&self) -> bool {
343        match self {
344            ControlWord::FontTable | ControlWord::ColorTable | ControlWord::StyleSheet | ControlWord::FileTable => true,
345            ControlWord::Unknown(name) => SKIPPED_DESTINATIONS.contains(&name.trim_start_matches('\\')),
346            _ => false,
347        }
348    }
349}
350
351#[cfg(test)]
352mod tests {
353    use crate::tokens::{ControlWord, Property};
354
355    #[test]
356    fn control_word_from_input_test() {
357        let input = r"\rtf1";
358        assert_eq!(ControlWord::from(input).unwrap(), (ControlWord::Rtf, Property::Value(1)))
359    }
360
361    #[test]
362    fn lookup_finds_known_and_unknown_words() {
363        assert_eq!(ControlWord::from(r"\pard").unwrap(), (ControlWord::Pard, Property::None));
364        assert_eq!(ControlWord::from(r"\fs24").unwrap(), (ControlWord::FontSize, Property::Value(24)));
365        assert_eq!(ControlWord::from(r"\af3").unwrap(), (ControlWord::Unknown(r"\af"), Property::Value(3)));
366        assert_eq!(ControlWord::from(r"\zzz").unwrap(), (ControlWord::Unknown(r"\zzz"), Property::None));
367    }
368
369    #[test]
370    fn control_word_with_negative_parameter() {
371        let input = r"\rtf-1";
372        assert_eq!(ControlWord::from(input).unwrap(), (ControlWord::Rtf, Property::Value(-1)))
373    }
374}