ppt-rs 0.2.27

Create, read, and update PowerPoint 2007+ (.pptx) files with rich formatting, bullet styles, themes, and templates.
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
//! Markdown export module
//!
//! Provides functionality to export presentations to Markdown format.
//! Supports GitHub Flavored Markdown with extensions for slides.

use crate::api::Presentation;
use crate::exc::Result;

/// Export options for Markdown generation
#[derive(Debug, Clone)]
pub struct MarkdownOptions {
    /// Include slide numbers as headers
    pub include_slide_numbers: bool,
    /// Format for slide separators (--- or horizontal rule)
    pub slide_separator: String,
    /// Include speaker notes
    pub include_notes: bool,
    /// Use GFM tables for table export
    pub use_gfm_tables: bool,
    /// Include image references
    pub include_images: bool,
    /// Add YAML frontmatter with presentation metadata
    pub include_frontmatter: bool,
    /// Group slides under `## Section` headings (slide headers become `###`)
    pub group_by_sections: bool,
}

impl Default for MarkdownOptions {
    fn default() -> Self {
        Self {
            include_slide_numbers: true,
            slide_separator: "---".to_string(),
            include_notes: true,
            use_gfm_tables: true,
            include_images: true,
            include_frontmatter: true,
            group_by_sections: false,
        }
    }
}

impl MarkdownOptions {
    /// Create new options with defaults
    pub fn new() -> Self {
        Self::default()
    }

    /// Set slide number inclusion
    pub fn with_slide_numbers(mut self, include: bool) -> Self {
        self.include_slide_numbers = include;
        self
    }

    /// Set slide separator
    pub fn with_separator(mut self, sep: &str) -> Self {
        self.slide_separator = sep.to_string();
        self
    }

    /// Set notes inclusion
    pub fn with_notes(mut self, include: bool) -> Self {
        self.include_notes = include;
        self
    }

    /// Set GFM table usage
    pub fn with_gfm_tables(mut self, use_gfm: bool) -> Self {
        self.use_gfm_tables = use_gfm;
        self
    }

    /// Set image inclusion
    pub fn with_images(mut self, include: bool) -> Self {
        self.include_images = include;
        self
    }

    /// Set frontmatter inclusion
    pub fn with_frontmatter(mut self, include: bool) -> Self {
        self.include_frontmatter = include;
        self
    }

    /// Group slides under section headings (when the presentation has sections)
    pub fn with_section_grouping(mut self, group: bool) -> Self {
        self.group_by_sections = group;
        self
    }
}

/// Export a presentation to Markdown format
pub fn export_to_markdown(presentation: &Presentation) -> Result<String> {
    export_to_markdown_with_options(presentation, &MarkdownOptions::default())
}

/// Export a presentation to Markdown with custom options
pub fn export_to_markdown_with_options(
    presentation: &Presentation,
    options: &MarkdownOptions,
) -> Result<String> {
    let mut md = String::new();

    // YAML frontmatter
    if options.include_frontmatter {
        md.push_str("---\n");
        md.push_str(&format!(
            "title: \"{}\"\n",
            escape_yaml(presentation.get_title())
        ));
        md.push_str(&format!("slides: {}\n", presentation.slide_count()));
        md.push_str("generator: ppt-rs\n");
        md.push_str("---\n\n");
    }

    // Presentation title as main heading
    md.push_str(&format!("# {}\n\n", presentation.get_title()));

    // Export each slide
    let sections = presentation.sections();
    let mut current_section: Option<String> = None;
    for (i, slide) in presentation.slides().iter().enumerate() {
        let slide_num = i + 1;

        // Slide separator
        if i > 0 || options.include_slide_numbers {
            md.push_str(&format!("\n{}\n\n", options.slide_separator));
        }

        // Section heading on section change (opt-in)
        if options.group_by_sections {
            let section_name = sections.section_for_slide(i).map(|s| s.name.clone());
            if section_name != current_section {
                if let Some(name) = &section_name {
                    md.push_str(&format!("## {}\n\n", escape_markdown(name)));
                }
                current_section = section_name;
            }
        }

        // Slide number header (demoted to ### when section grouping is on)
        let header_level = if options.group_by_sections {
            "###"
        } else {
            "##"
        };
        if options.include_slide_numbers {
            md.push_str(&format!(
                "{} Slide {}: {}\n\n",
                header_level,
                slide_num,
                escape_markdown(&slide.title)
            ));
        } else {
            md.push_str(&format!(
                "{} {}\n\n",
                header_level,
                escape_markdown(&slide.title)
            ));
        }

        // Bullet content
        if !slide.content.is_empty() {
            for item in &slide.content {
                md.push_str(&format!("- {}\n", escape_markdown(item)));
            }
            md.push('\n');
        }

        // Table export (GFM format)
        if options.use_gfm_tables
            && slide.has_table
            && let Some(table) = &slide.table
        {
            md.push_str(&export_table_to_gfm(table));
            md.push('\n');
        }

        // Images
        if options.include_images && !slide.images.is_empty() {
            for (img_idx, image) in slide.images.iter().enumerate() {
                let alt_text = format!("Image {} on slide {}", img_idx + 1, slide_num);
                // Note: Actual image data would need to be saved separately
                md.push_str(&format!(
                    "![{}](images/slide{}_image{}{})\n\n",
                    alt_text,
                    slide_num,
                    img_idx + 1,
                    image
                        .format
                        .to_lowercase()
                        .replace("jpeg", ".jpg")
                        .replace("png", ".png")
                ));
            }
        }

        // Code blocks
        if !slide.code_blocks.is_empty() {
            for code_block in &slide.code_blocks {
                md.push_str(&format!(
                    "```{lang}\n{code}\n```\n\n",
                    lang = &code_block.language,
                    code = &code_block.code
                ));
            }
        }

        // Speaker notes
        let has_notes = slide.notes.as_ref().is_some_and(|n| !n.is_empty());
        if options.include_notes && has_notes {
            md.push_str("**Notes:**\n\n");
            if let Some(notes) = &slide.notes {
                md.push_str(&format!("> {}\n\n", escape_markdown(notes)));
            }
        }
    }

    Ok(md)
}

/// Export a table to GitHub Flavored Markdown format
fn export_table_to_gfm(table: &crate::generator::Table) -> String {
    let mut md = String::new();

    // Header row
    if let Some(first_row) = table.rows.first() {
        md.push_str("| ");
        for cell in &first_row.cells {
            md.push_str(&escape_markdown(&cell.text));
            md.push_str(" | ");
        }
        md.push('\n');

        // Separator
        md.push('|');
        for _ in &first_row.cells {
            md.push_str(" --- |");
        }
        md.push('\n');

        // Data rows
        for row in table.rows.iter().skip(1) {
            md.push_str("| ");
            for cell in &row.cells {
                md.push_str(&escape_markdown(&cell.text));
                md.push_str(" | ");
            }
            md.push('\n');
        }
    }

    md
}

/// Escape special Markdown characters
fn escape_markdown(text: &str) -> String {
    text.replace('\\', "\\\\")
        .replace('*', "\\*")
        .replace('_', "\\_")
        .replace('[', "\\[")
        .replace(']', "\\]")
        .replace('`', "\\`")
        .replace('#', "\\#")
        .replace('<', "\\<")
        .replace('>', "\\>")
}

/// Escape special YAML characters in frontmatter
fn escape_yaml(text: &str) -> String {
    if text.contains('\n') || text.contains('"') || text.contains('\\') {
        // Use literal block scalar for multiline or complex strings
        format!("|\n  {}", text.replace('\n', "\n  "))
    } else {
        text.replace('"', "\\\"").replace('\\', "\\\\")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::generator::{CodeBlock, SlideContent, TableBuilder, TableCell, TableRow};

    #[test]
    fn test_export_simple_presentation() {
        let mut presentation = Presentation::with_title("Test Presentation");
        presentation = presentation.add_slide(SlideContent::new("Slide 1").add_bullet("Point 1"));
        presentation = presentation.add_slide(SlideContent::new("Slide 2").add_bullet("Point 2"));

        let md = export_to_markdown(&presentation).unwrap();

        assert!(md.contains("# Test Presentation"));
        assert!(md.contains("## Slide 1: Slide 1"));
        assert!(md.contains("- Point 1"));
        assert!(md.contains("---"));
    }

    #[test]
    fn test_markdown_options() {
        let mut presentation = Presentation::with_title("Test");
        presentation = presentation.add_slide(SlideContent::new("Slide").add_bullet("Point"));

        let options = MarkdownOptions::new()
            .with_slide_numbers(false)
            .with_frontmatter(false);

        let md = export_to_markdown_with_options(&presentation, &options).unwrap();

        assert!(!md.contains("## Slide 1:"));
        assert!(md.contains("## Slide"));
        assert!(!md.contains("---\ntitle:"));
    }

    #[test]
    fn test_escape_markdown() {
        assert_eq!(escape_markdown("*bold*"), "\\*bold\\*");
        assert_eq!(escape_markdown("[link]"), "\\[link\\]");
        assert_eq!(escape_markdown("`code`"), "\\`code\\`");
    }

    #[test]
    fn test_export_table_to_gfm() {
        let cells1 = vec![TableCell::new("Header 1"), TableCell::new("Header 2")];
        let cells2 = vec![TableCell::new("Row 1 Col 1"), TableCell::new("Row 1 Col 2")];
        let table = TableBuilder::new(vec![100, 100])
            .add_row(TableRow::new(cells1))
            .add_row(TableRow::new(cells2))
            .build();

        let md = export_table_to_gfm(&table);

        assert!(md.contains("| Header 1 | Header 2 |"));
        assert!(md.contains("| --- | --- |"));
        assert!(md.contains("| Row 1 Col 1 | Row 1 Col 2 |"));
    }

    #[test]
    fn test_export_with_code_blocks() {
        let mut presentation = Presentation::with_title("Code Test");
        let mut slide = SlideContent::new("Code Slide");
        slide
            .code_blocks
            .push(CodeBlock::new("println!(\"Hello\");", "rust"));
        presentation = presentation.add_slide(slide);

        let md = export_to_markdown(&presentation).unwrap();

        assert!(md.contains("```rust"));
        assert!(md.contains("println!(\"Hello\");"));
        assert!(md.contains("```"));
    }

    #[test]
    fn test_export_with_speaker_notes() {
        let mut presentation = Presentation::with_title("Notes Test");
        let mut slide = SlideContent::new("Notes Slide");
        slide.notes = Some("This is a speaker note".to_string());
        presentation = presentation.add_slide(slide);

        let md = export_to_markdown(&presentation).unwrap();

        assert!(md.contains("**Notes:**"));
        assert!(md.contains("> This is a speaker note"));
    }

    #[test]
    fn test_yaml_escape_multiline() {
        let multiline = "Line 1\nLine 2";
        let escaped = escape_yaml(multiline);
        assert!(escaped.starts_with("|"));
        assert!(escaped.contains("Line 1"));
        assert!(escaped.contains("Line 2"));
    }

    #[test]
    fn test_yaml_escape_quotes() {
        let with_quotes = r#"Title with "quotes""#;
        let escaped = escape_yaml(with_quotes);
        // Single line with quotes gets escaped or uses literal block
        assert!(escaped.contains("quotes") || escaped.contains("\\\""));
    }

    #[test]
    fn test_markdown_all_options_disabled() {
        let mut presentation = Presentation::with_title("Minimal");
        let mut slide = SlideContent::new("Slide");
        slide.notes = Some("Note".to_string());
        presentation = presentation.add_slide(slide);

        let options = MarkdownOptions::new()
            .with_frontmatter(false)
            .with_slide_numbers(false)
            .with_notes(false)
            .with_images(false);

        let md = export_to_markdown_with_options(&presentation, &options).unwrap();

        assert!(!md.contains("---\ntitle:"));
        assert!(!md.contains("Slide 1:"));
        assert!(!md.contains("**Notes:**"));
    }

    #[test]
    fn test_empty_presentation() {
        let presentation = Presentation::with_title("Empty");
        let md = export_to_markdown(&presentation).unwrap();

        assert!(md.contains("# Empty"));
        assert!(!md.contains("## Slide")); // No slides
    }

    #[test]
    fn test_markdown_escape_various_chars() {
        let text = r#"Special chars: * _ [ ] ` # < > \ "#;
        let escaped = escape_markdown(text);
        assert!(escaped.contains("\\*"));
        assert!(escaped.contains("\\_"));
        assert!(escaped.contains("\\["));
        assert!(escaped.contains("\\]"));
        assert!(escaped.contains("\\`"));
        assert!(escaped.contains("\\#"));
        assert!(escaped.contains("\\<"));
        assert!(escaped.contains("\\>"));
    }
}