litchi 0.0.1

High-performance parser for Microsoft Office, OpenDocument, and Apple iWork file formats with unified API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
/// Paragraph and Run structures for Word documents.
use crate::ooxml::error::{OoxmlError, Result};
use quick_xml::events::Event;
use quick_xml::Reader;
use smallvec::SmallVec;
use std::borrow::Cow;

/// A paragraph in a Word document.
///
/// Represents a `<w:p>` element. Paragraphs contain runs which in turn
/// contain the actual text and formatting.
///
/// # Example
///
/// ```rust,ignore
/// for para in document.paragraphs()? {
///     println!("Paragraph text: {}", para.text());
///     for run in para.runs()? {
///         println!("  Run: {} (bold: {:?})", run.text(), run.bold());
///     }
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Paragraph {
    /// The raw XML bytes for this paragraph
    xml_bytes: Vec<u8>,
}

impl Paragraph {
    /// Create a new Paragraph from XML bytes.
    ///
    /// # Arguments
    ///
    /// * `xml_bytes` - The XML content of the `<w:p>` element
    pub fn new(xml_bytes: Vec<u8>) -> Self {
        Self { xml_bytes }
    }

    /// Get the text content of this paragraph.
    ///
    /// Concatenates all text from all runs in the paragraph.
    ///
    /// # Performance
    ///
    /// Uses streaming XML parsing with pre-allocated buffer to extract text efficiently.
    pub fn text(&self) -> Result<String> {
        let mut reader = Reader::from_reader(&self.xml_bytes[..]);
        reader.config_mut().trim_text(true);

        // Pre-allocate string with estimated capacity to reduce reallocations
        let estimated_capacity = self.xml_bytes.len() / 4; // Rough estimate
        let mut result = String::with_capacity(estimated_capacity);
        let mut in_text_element = false;
        let mut buf = Vec::with_capacity(512); // Reusable buffer

        loop {
            buf.clear();
            match reader.read_event_into(&mut buf) {
                Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
                    if e.local_name().as_ref() == b"t" {
                        in_text_element = true;
                    }
                }
                Ok(Event::Text(e)) if in_text_element => {
                    // Use unsafe conversion for better performance (safe since we validate XML)
                    let text = unsafe { std::str::from_utf8_unchecked(e.as_ref()) };
                    result.push_str(text);
                }
                Ok(Event::End(e)) => {
                    if e.local_name().as_ref() == b"t" {
                        in_text_element = false;
                    }
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(OoxmlError::Xml(e.to_string())),
                _ => {}
            }
        }

        // Shrink to fit to release unused capacity
        result.shrink_to_fit();
        Ok(result)
    }

    /// Get an iterator over the runs in this paragraph.
    ///
    /// Each run represents a `<w:r>` element and may have different formatting.
    pub fn runs(&self) -> Result<SmallVec<[Run; 8]>> {
        let mut reader = Reader::from_reader(&self.xml_bytes[..]);
        reader.config_mut().trim_text(true);

        // Use SmallVec for efficient storage of typically small run collections
        let mut runs = SmallVec::new();
        let mut current_run_xml = Vec::with_capacity(1024); // Pre-allocate for XML fragments
        let mut in_run = false;
        let mut depth = 0;
        let mut buf = Vec::with_capacity(512); // Reusable buffer

        loop {
            match reader.read_event_into(&mut buf) {
                Ok(Event::Start(e)) => {
                    if e.local_name().as_ref() == b"r" && !in_run {
                        in_run = true;
                        depth = 1;
                        current_run_xml.clear();
                        // Pre-allocate with estimated size for run XML
                        current_run_xml.reserve(512);

                        // Build opening tag more efficiently
                        current_run_xml.extend_from_slice(b"<w:r");
                        for attr in e.attributes().flatten() {
                            current_run_xml.push(b' ');
                            current_run_xml.extend_from_slice(attr.key.as_ref());
                            current_run_xml.extend_from_slice(b"=\"");
                            current_run_xml.extend_from_slice(&attr.value);
                            current_run_xml.push(b'"');
                        }
                        current_run_xml.push(b'>');
                    } else if in_run {
                        depth += 1;
                        current_run_xml.push(b'<');
                        current_run_xml.extend_from_slice(e.name().as_ref());
                        for attr in e.attributes().flatten() {
                            current_run_xml.push(b' ');
                            current_run_xml.extend_from_slice(attr.key.as_ref());
                            current_run_xml.extend_from_slice(b"=\"");
                            current_run_xml.extend_from_slice(&attr.value);
                            current_run_xml.push(b'"');
                        }
                        current_run_xml.push(b'>');
                    }
                }
                Ok(Event::End(e)) => {
                    if in_run {
                        current_run_xml.extend_from_slice(b"</");
                        current_run_xml.extend_from_slice(e.name().as_ref());
                        current_run_xml.push(b'>');

                        depth -= 1;
                        if depth == 0 && e.local_name().as_ref() == b"r" {
                            runs.push(Run::new(current_run_xml.clone()));
                            in_run = false;
                        }
                    }
                }
                Ok(Event::Text(e)) if in_run => {
                    current_run_xml.extend_from_slice(e.as_ref());
                }
                Ok(Event::Empty(e)) if in_run => {
                    current_run_xml.push(b'<');
                    current_run_xml.extend_from_slice(e.name().as_ref());
                    for attr in e.attributes().flatten() {
                        current_run_xml.push(b' ');
                        current_run_xml.extend_from_slice(attr.key.as_ref());
                        current_run_xml.extend_from_slice(b"=\"");
                        current_run_xml.extend_from_slice(&attr.value);
                        current_run_xml.push(b'"');
                    }
                    current_run_xml.extend_from_slice(b"/>");
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(OoxmlError::Xml(e.to_string())),
                _ => {}
            }
            buf.clear();
        }

        Ok(runs)
    }

    /// Extract all OMML formulas from this paragraph.
    ///
    /// Returns a vector of OMML formula strings found in any run within this paragraph.
    pub fn omml_formulas(&self) -> Result<Vec<String>> {
        let mut formulas = Vec::new();
        for run in self.runs()? {
            if let Some(formula) = run.omml_formula()? {
                formulas.push(formula);
            }
        }
        Ok(formulas)
    }
}

/// Vertical text position (superscript/subscript).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VerticalPosition {
    /// Normal position
    Normal,
    /// Superscript
    Superscript,
    /// Subscript
    Subscript,
}

/// A run within a paragraph.
///
/// Represents a `<w:r>` element. A run is a region of text with a single
/// set of formatting properties.
///
/// # Example
///
/// ```rust,ignore
/// let run = runs[0];
/// println!("Text: {}", run.text()?);
/// println!("Bold: {:?}", run.bold()?);
/// println!("Italic: {:?}", run.italic()?);
///
/// // Check for embedded formulas
/// if let Some(omml) = run.omml_formula()? {
///     println!("OMML formula: {}", omml);
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Run {
    /// The raw XML bytes for this run
    xml_bytes: Vec<u8>,
}

impl Run {
    /// Create a new Run from XML bytes.
    pub fn new(xml_bytes: Vec<u8>) -> Self {
        Self { xml_bytes }
    }

    /// Get the text content of this run.
    ///
    /// Extracts text from `<w:t>` elements and converts special characters:
    /// - `<w:tab/>` → tab character
    /// - `<w:br/>` → newline character
    pub fn text(&self) -> Result<String> {
        let mut reader = Reader::from_reader(&self.xml_bytes[..]);
        reader.config_mut().trim_text(true);

        // Pre-allocate with estimated capacity
        let estimated_capacity = self.xml_bytes.len() / 8; // Rough estimate for text content
        let mut result = String::with_capacity(estimated_capacity);
        let mut in_text_element = false;
        let mut buf = Vec::with_capacity(256); // Reusable buffer

        loop {
            match reader.read_event_into(&mut buf) {
                Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
                    let name = e.local_name();
                    if name.as_ref() == b"t" {
                        in_text_element = true;
                    } else if name.as_ref() == b"tab" {
                        result.push('\t');
                    } else if name.as_ref() == b"br" {
                        result.push('\n');
                    }
                }
                Ok(Event::Text(e)) if in_text_element => {
                    // Use unsafe conversion for better performance (safe since we validate XML)
                    let text = unsafe { std::str::from_utf8_unchecked(e.as_ref()) };
                    result.push_str(text);
                }
                Ok(Event::End(e)) => {
                    if e.local_name().as_ref() == b"t" {
                        in_text_element = false;
                    }
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(OoxmlError::Xml(e.to_string())),
                _ => {}
            }
            buf.clear();
        }

        Ok(result)
    }

    /// Check if this run is bold.
    ///
    /// Returns `Some(true)` if bold is explicitly enabled,
    /// `Some(false)` if explicitly disabled,
    /// `None` if not specified (inherits from style).
    pub fn bold(&self) -> Result<Option<bool>> {
        self.get_bool_property(b"b")
    }

    /// Check if this run is italic.
    ///
    /// Returns `Some(true)` if italic is explicitly enabled,
    /// `Some(false)` if explicitly disabled,
    /// `None` if not specified (inherits from style).
    pub fn italic(&self) -> Result<Option<bool>> {
        self.get_bool_property(b"i")
    }

    /// Check if this run is underlined.
    ///
    /// Returns `Some(true)` if underline is present,
    /// `None` if not specified.
    ///
    /// Note: This is simplified. Full implementation would return
    /// the underline style (single, double, wavy, etc.).
    pub fn underline(&self) -> Result<Option<bool>> {
        let mut reader = Reader::from_reader(&self.xml_bytes[..]);
        reader.config_mut().trim_text(true);

        let mut in_r_pr = false;
        let mut buf = Vec::new();

        loop {
            match reader.read_event_into(&mut buf) {
                Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
                    let name = e.local_name();
                    if name.as_ref() == b"rPr" {
                        in_r_pr = true;
                    } else if in_r_pr && name.as_ref() == b"u" {
                        return Ok(Some(true));
                    }
                }
                Ok(Event::End(e)) => {
                    if e.local_name().as_ref() == b"rPr" {
                        in_r_pr = false;
                    }
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(OoxmlError::Xml(e.to_string())),
                _ => {}
            }
            buf.clear();
        }

        Ok(None)
    }

    /// Check if this run is strikethrough.
    ///
    /// Returns `Some(true)` if strikethrough is present,
    /// `None` if not specified.
    pub fn strikethrough(&self) -> Result<Option<bool>> {
        self.get_bool_property(b"strike")
    }

    /// Get the vertical position of this run (superscript/subscript).
    ///
    /// Returns the vertical positioning if specified, None if normal.
    pub fn vertical_position(&self) -> Result<Option<VerticalPosition>> {
        let mut reader = Reader::from_reader(&self.xml_bytes[..]);
        reader.config_mut().trim_text(true);

        let mut in_r_pr = false;
        let mut buf = Vec::new();

        loop {
            match reader.read_event_into(&mut buf) {
                Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
                    let name = e.local_name();
                    if name.as_ref() == b"rPr" {
                        in_r_pr = true;
                    } else if in_r_pr && name.as_ref() == b"vertAlign" {
                        for attr in e.attributes().flatten() {
                            if attr.key.as_ref() == b"val" {
                                let value = attr.value.as_ref();
                                match value {
                                    b"superscript" => return Ok(Some(VerticalPosition::Superscript)),
                                    b"subscript" => return Ok(Some(VerticalPosition::Subscript)),
                                    _ => {}
                                }
                            }
                        }
                    }
                }
                Ok(Event::End(e)) => {
                    if e.local_name().as_ref() == b"rPr" {
                        in_r_pr = false;
                    }
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(OoxmlError::Xml(e.to_string())),
                _ => {}
            }
            buf.clear();
        }

        Ok(None)
    }

    /// Get the font name for this run.
    ///
    /// Returns the typeface name if specified, None if inherited.
    pub fn font_name(&self) -> Result<Option<String>> {
        let mut reader = Reader::from_reader(&self.xml_bytes[..]);
        reader.config_mut().trim_text(true);

        let mut in_r_pr = false;
        let mut buf = Vec::new();

        loop {
            match reader.read_event_into(&mut buf) {
                Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
                    let name = e.local_name();
                    if name.as_ref() == b"rPr" {
                        in_r_pr = true;
                    } else if in_r_pr && name.as_ref() == b"rFonts" {
                        for attr in e.attributes().flatten() {
                            if attr.key.as_ref() == b"ascii" {
                                let value = attr.unescape_value().unwrap_or(Cow::Borrowed(""));
                                return Ok(Some(value.to_string()));
                            }
                        }
                    }
                }
                Ok(Event::End(e)) => {
                    if e.local_name().as_ref() == b"rPr" {
                        break;
                    }
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(OoxmlError::Xml(e.to_string())),
                _ => {}
            }
            buf.clear();
        }

        Ok(None)
    }

    /// Get the font size for this run in half-points.
    ///
    /// Returns the size if specified, None if inherited.
    /// Note: Word stores font size in half-points (e.g., 24 = 12pt).
    pub fn font_size(&self) -> Result<Option<u32>> {
        let mut reader = Reader::from_reader(&self.xml_bytes[..]);
        reader.config_mut().trim_text(true);

        let mut in_r_pr = false;
        let mut buf = Vec::new();

        loop {
            match reader.read_event_into(&mut buf) {
                Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
                    let name = e.local_name();
                    if name.as_ref() == b"rPr" {
                        in_r_pr = true;
                    } else if in_r_pr && name.as_ref() == b"sz" {
                        for attr in e.attributes().flatten() {
                            if attr.key.as_ref() == b"val"
                                && let Ok(value) = std::str::from_utf8(&attr.value)
                                    && let Ok(size) = value.parse::<u32>() {
                                        return Ok(Some(size));
                                    }
                        }
                    }
                }
                Ok(Event::End(e)) => {
                    if e.local_name().as_ref() == b"rPr" {
                        break;
                    }
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(OoxmlError::Xml(e.to_string())),
                _ => {}
            }
            buf.clear();
        }

        Ok(None)
    }

    /// Check if this run contains an OMML formula.
    ///
    /// Returns the OMML XML content if this run contains a mathematical formula,
    /// None otherwise. This method looks for `<m:oMath>` elements embedded in the run.
    pub fn omml_formula(&self) -> Result<Option<String>> {
        let mut reader = Reader::from_reader(&self.xml_bytes[..]);
        reader.config_mut().trim_text(true);

        let mut in_omath = false;
        let mut omml_content = String::new();
        let mut buf = Vec::new();

        loop {
            match reader.read_event_into(&mut buf) {
                Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
                    let name = e.local_name();
                    if name.as_ref() == b"oMath" {
                        in_omath = true;
                        omml_content.push('<');
                        omml_content.push_str(std::str::from_utf8(name.as_ref()).unwrap());
                        for attr in e.attributes().flatten() {
                            omml_content.push(' ');
                            omml_content.push_str(std::str::from_utf8(attr.key.as_ref()).unwrap());
                            omml_content.push_str("=\"");
                            omml_content.push_str(&attr.unescape_value().unwrap_or(Cow::Borrowed("")));
                            omml_content.push('"');
                        }
                        omml_content.push('>');
                    } else if in_omath {
                        // Include nested elements in the OMML content
                        omml_content.push('<');
                        omml_content.push_str(std::str::from_utf8(name.as_ref()).unwrap());
                        for attr in e.attributes().flatten() {
                            omml_content.push(' ');
                            omml_content.push_str(std::str::from_utf8(attr.key.as_ref()).unwrap());
                            omml_content.push_str("=\"");
                            omml_content.push_str(&attr.unescape_value().unwrap_or(Cow::Borrowed("")));
                            omml_content.push('"');
                        }
                        if name.as_ref() == b"oMath" {
                            omml_content.push('/');
                            in_omath = false;
                        }
                        omml_content.push('>');
                    }
                }
                Ok(Event::Text(e)) if in_omath => {
                    // Extract text content - OMML doesn't typically use entities that need unescaping
                    let text = std::str::from_utf8(e.as_ref())
                        .map_err(|_| OoxmlError::Xml("Invalid UTF-8 in OMML text".to_string()))?;
                    omml_content.push_str(text);
                }
                Ok(Event::End(e)) if in_omath => {
                    omml_content.push_str("</");
                    omml_content.push_str(std::str::from_utf8(e.name().as_ref()).unwrap());
                    omml_content.push('>');
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(OoxmlError::Xml(e.to_string())),
                _ => {}
            }
            buf.clear();
        }

        if omml_content.is_empty() {
            Ok(None)
        } else {
            Ok(Some(omml_content))
        }
    }

    /// Helper to extract boolean properties from run properties.
    ///
    /// Handles the tri-state logic where w:val can be "true", "false", "1", "0"
    /// or the element can be present without a val attribute (implies true).
    fn get_bool_property(&self, property_name: &[u8]) -> Result<Option<bool>> {
        let mut reader = Reader::from_reader(&self.xml_bytes[..]);
        reader.config_mut().trim_text(true);

        let mut in_r_pr = false;
        let mut buf = Vec::new();

        loop {
            match reader.read_event_into(&mut buf) {
                Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
                    let name = e.local_name();
                    if name.as_ref() == b"rPr" {
                        in_r_pr = true;
                    } else if in_r_pr && name.as_ref() == property_name {
                        // Check for w:val attribute
                        for attr in e.attributes().flatten() {
                            if attr.key.as_ref() == b"val" {
                                let value = attr.value.as_ref();
                                return Ok(Some(value == b"true" || value == b"1"));
                            }
                        }
                        // Element present without val attribute means true
                        return Ok(Some(true));
                    }
                }
                Ok(Event::End(e)) => {
                    if e.local_name().as_ref() == b"rPr" {
                        in_r_pr = false;
                    }
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(OoxmlError::Xml(e.to_string())),
                _ => {}
            }
            buf.clear();
        }

        Ok(None)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_run_text_extraction() {
        let xml = br#"<w:r xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
            <w:t>Hello, World!</w:t>
        </w:r>"#;

        let run = Run::new(xml.to_vec());
        let text = run.text().unwrap();
        assert_eq!(text, "Hello, World!");
    }

    #[test]
    fn test_run_bold() {
        let xml = br#"<w:r xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
            <w:rPr><w:b/></w:rPr>
            <w:t>Bold text</w:t>
        </w:r>"#;

        let run = Run::new(xml.to_vec());
        assert!(run.bold().unwrap().unwrap_or(false));
    }

    #[test]
    fn test_run_italic() {
        let xml = br#"<w:r xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
            <w:rPr><w:i/></w:rPr>
            <w:t>Italic text</w:t>
        </w:r>"#;

        let run = Run::new(xml.to_vec());
        assert!(run.italic().unwrap().unwrap_or(false));
    }
}