undoc 0.2.2

High-performance Microsoft Office document extraction to Markdown
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
//! Rendering options configuration.

use std::path::PathBuf;

use super::heading_analyzer::HeadingConfig;

/// How to render complex tables.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum TableFallback {
    /// Use Markdown pipe tables (may break with merged cells)
    #[default]
    Markdown,
    /// Fall back to HTML tables for complex layouts
    Html,
    /// Use ASCII art tables
    Ascii,
}

/// Cleanup preset for LLM training data preparation.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum CleanupPreset {
    /// Minimal cleanup: only essential normalization
    Minimal,
    /// Default: balanced normalization
    #[default]
    Default,
    /// Aggressive: maximum purification
    Aggressive,
}

/// Cleanup options for post-processing.
#[derive(Debug, Clone, Default)]
pub struct CleanupOptions {
    /// Normalize Unicode strings (NFC), standardize bullets
    pub normalize_strings: bool,

    /// Remove headers, footers, page numbers, TOC markers
    pub clean_lines: bool,

    /// Filter empty paragraphs, orphaned elements
    pub filter_structure: bool,

    /// Final whitespace normalization
    pub final_normalize: bool,

    /// Remove Private Use Area characters
    pub remove_pua: bool,

    /// Detect and flag potential mojibake
    pub detect_mojibake: bool,

    /// Preserve YAML frontmatter during cleanup
    pub preserve_frontmatter: bool,
}

impl CleanupOptions {
    /// Create cleanup options from a preset.
    pub fn from_preset(preset: CleanupPreset) -> Self {
        match preset {
            CleanupPreset::Minimal => Self {
                normalize_strings: true,
                final_normalize: true,
                ..Default::default()
            },
            CleanupPreset::Default => Self {
                normalize_strings: true,
                clean_lines: true,
                final_normalize: true,
                preserve_frontmatter: true,
                ..Default::default()
            },
            CleanupPreset::Aggressive => Self {
                normalize_strings: true,
                clean_lines: true,
                filter_structure: true,
                final_normalize: true,
                remove_pua: true,
                detect_mojibake: true,
                preserve_frontmatter: true,
            },
        }
    }

    /// Create minimal cleanup options.
    pub fn minimal() -> Self {
        Self::from_preset(CleanupPreset::Minimal)
    }

    /// Create default cleanup options.
    pub fn standard() -> Self {
        Self::from_preset(CleanupPreset::Default)
    }

    /// Create aggressive cleanup options.
    pub fn aggressive() -> Self {
        Self::from_preset(CleanupPreset::Aggressive)
    }
}

/// Options for rendering documents.
#[derive(Debug, Clone)]
pub struct RenderOptions {
    /// Directory to save extracted images
    pub image_dir: Option<PathBuf>,

    /// Prefix for image paths in markdown (e.g., "assets/")
    pub image_path_prefix: String,

    /// How to handle complex tables
    pub table_fallback: TableFallback,

    /// Maximum heading level (1-6).
    /// Default: 4 (Office documents often misuse deep heading levels for visual styling)
    pub max_heading_level: u8,

    /// Include YAML frontmatter with metadata
    pub include_frontmatter: bool,

    /// Preserve line breaks within paragraphs
    pub preserve_line_breaks: bool,

    /// Include empty paragraphs in output
    pub include_empty_paragraphs: bool,

    /// Character for unordered list markers
    pub list_marker: char,

    /// Use ATX-style headers (# instead of underlines)
    pub use_atx_headers: bool,

    /// Add blank line between paragraphs
    pub paragraph_spacing: bool,

    /// Escape special Markdown characters
    pub escape_special_chars: bool,

    /// Cleanup options (None = no cleanup)
    pub cleanup: Option<CleanupOptions>,

    /// Heading analysis configuration.
    /// When set, enables sophisticated heading detection with multi-priority analysis.
    pub heading_config: Option<HeadingConfig>,

    /// How to handle tracked changes (insertions and deletions).
    pub revision_handling: RevisionHandling,

    /// Strip redundant `**bold**`/`*italic*` from heading text and table
    /// header cells when the *entire* paragraph is uniformly emphasized
    /// (i.e. the emphasis is a styling artifact, not author intent).
    ///
    /// Partial emphasis (e.g. `Section 2: **Required**`) is always preserved.
    pub strip_redundant_emphasis_in_headings: bool,

    /// Emit `\n\n---\n\n` for hard page breaks (`<w:br w:type="page"/>` and
    /// `Block::PageBreak`). Disabled by default — markdown has no page
    /// concept and these break visual flow.
    ///
    /// `Block::SectionBreak` is *not* affected; it remains emitted as a
    /// horizontal rule because it carries a semantic boundary.
    pub emit_page_breaks: bool,

    /// Render DOCX section headers/footers as blockquoted lines around the
    /// document body. Disabled by default because they are typically
    /// page-chrome and add noise to LLM training data.
    pub include_headers_footers: bool,

    /// Convert single-row, single-column tables whose entire content is
    /// emphasized into `> **...**` blockquotes (a callout fallback).
    /// Off by default — only enable if the corpus is known to use 1×1
    /// tables exclusively for callouts.
    pub callout_blockquote: bool,

    /// Style for PPTX slide / XLSX sheet boundary markers.
    /// DOCX is unaffected regardless of this setting.
    pub section_markers: SectionMarkerStyle,
}

/// How to handle tracked changes in the output.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum RevisionHandling {
    /// Accept all changes - show final text (default)
    #[default]
    AcceptAll,
    /// Reject all changes - show original text
    RejectAll,
    /// Show both insertions and deletions with markup
    ShowMarkup,
}

/// Style for section boundary markers in Markdown output.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SectionMarkerStyle {
    /// No markers (default — preserves existing output unchanged).
    #[default]
    None,
    /// HTML comment inserted before each PPTX slide or XLSX sheet:
    /// `<!-- slide N: Name -->` / `<!-- sheet N: Name -->`.
    Comment,
}

impl Default for RenderOptions {
    fn default() -> Self {
        Self {
            image_dir: None,
            image_path_prefix: String::new(),
            table_fallback: TableFallback::Markdown,
            max_heading_level: 4,
            include_frontmatter: false,
            preserve_line_breaks: false,
            include_empty_paragraphs: false,
            list_marker: '-',
            use_atx_headers: true,
            paragraph_spacing: true,
            escape_special_chars: true,
            cleanup: None,
            heading_config: None,
            revision_handling: RevisionHandling::AcceptAll,
            strip_redundant_emphasis_in_headings: true,
            emit_page_breaks: false,
            include_headers_footers: false,
            callout_blockquote: false,
            section_markers: SectionMarkerStyle::None,
        }
    }
}

impl RenderOptions {
    /// Create new render options.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the image output directory.
    pub fn with_image_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.image_dir = Some(dir.into());
        self
    }

    /// Set the image path prefix for markdown references.
    pub fn with_image_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.image_path_prefix = prefix.into();
        self
    }

    /// Set table fallback mode.
    pub fn with_table_fallback(mut self, fallback: TableFallback) -> Self {
        self.table_fallback = fallback;
        self
    }

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

    /// Enable cleanup with default options.
    pub fn with_cleanup(mut self) -> Self {
        self.cleanup = Some(CleanupOptions::standard());
        self
    }

    /// Enable cleanup with specific preset.
    pub fn with_cleanup_preset(mut self, preset: CleanupPreset) -> Self {
        self.cleanup = Some(CleanupOptions::from_preset(preset));
        self
    }

    /// Enable cleanup with custom options.
    pub fn with_cleanup_options(mut self, options: CleanupOptions) -> Self {
        self.cleanup = Some(options);
        self
    }

    /// Set maximum heading level.
    pub fn with_max_heading(mut self, level: u8) -> Self {
        self.max_heading_level = level.clamp(1, 6);
        self
    }

    /// Preserve line breaks within paragraphs.
    pub fn with_preserve_breaks(mut self, preserve: bool) -> Self {
        self.preserve_line_breaks = preserve;
        self
    }

    /// Enable sophisticated heading analysis with default config.
    pub fn with_heading_analysis(mut self) -> Self {
        self.heading_config = Some(HeadingConfig::default());
        self
    }

    /// Enable sophisticated heading analysis with custom config.
    pub fn with_heading_config(mut self, config: HeadingConfig) -> Self {
        self.heading_config = Some(config);
        self
    }

    /// Set how to handle tracked changes (revisions).
    pub fn with_revision_handling(mut self, handling: RevisionHandling) -> Self {
        self.revision_handling = handling;
        self
    }

    /// Show tracked changes with markup (insertions and deletions visible).
    pub fn with_show_revisions(mut self) -> Self {
        self.revision_handling = RevisionHandling::ShowMarkup;
        self
    }

    /// Restore the lossless rendering behavior: emit hard page breaks and
    /// include section headers/footers in the output. Use this when round-
    /// tripping document layout matters more than reading flow.
    pub fn lossless() -> Self {
        Self {
            emit_page_breaks: true,
            include_headers_footers: true,
            ..Self::default()
        }
    }

    /// Toggle whether hard page breaks emit a horizontal rule.
    pub fn with_emit_page_breaks(mut self, enabled: bool) -> Self {
        self.emit_page_breaks = enabled;
        self
    }

    /// Toggle whether DOCX section headers/footers appear in the output.
    pub fn with_include_headers_footers(mut self, enabled: bool) -> Self {
        self.include_headers_footers = enabled;
        self
    }

    /// Toggle conversion of 1×1 emphasized tables into blockquoted callouts.
    pub fn with_callout_blockquote(mut self, enabled: bool) -> Self {
        self.callout_blockquote = enabled;
        self
    }

    /// Set the section boundary marker style.
    pub fn with_section_markers(mut self, style: SectionMarkerStyle) -> Self {
        self.section_markers = style;
        self
    }

    /// Toggle stripping of styling-artifact emphasis in heading text and
    /// table header cells.
    pub fn with_strip_redundant_emphasis_in_headings(mut self, enabled: bool) -> Self {
        self.strip_redundant_emphasis_in_headings = enabled;
        self
    }
}

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

    #[test]
    fn test_default_options() {
        let opts = RenderOptions::default();
        assert!(opts.image_dir.is_none());
        assert!(!opts.include_frontmatter);
        assert_eq!(opts.table_fallback, TableFallback::Markdown);
        // Default max_heading_level is 4 (not 6) because Office documents
        // often misuse deep heading levels for visual styling
        assert_eq!(opts.max_heading_level, 4);
    }

    #[test]
    fn test_builder_pattern() {
        let opts = RenderOptions::new()
            .with_image_dir("assets")
            .with_frontmatter(true)
            .with_cleanup();

        assert_eq!(opts.image_dir, Some(PathBuf::from("assets")));
        assert!(opts.include_frontmatter);
        assert!(opts.cleanup.is_some());
    }

    #[test]
    fn test_cleanup_presets() {
        let minimal = CleanupOptions::minimal();
        assert!(minimal.normalize_strings);
        assert!(!minimal.clean_lines);

        let aggressive = CleanupOptions::aggressive();
        assert!(aggressive.normalize_strings);
        assert!(aggressive.clean_lines);
        assert!(aggressive.filter_structure);
        assert!(aggressive.remove_pua);
    }

    #[test]
    fn test_max_heading_clamp() {
        let opts = RenderOptions::new().with_max_heading(10);
        assert_eq!(opts.max_heading_level, 6);

        let opts = RenderOptions::new().with_max_heading(0);
        assert_eq!(opts.max_heading_level, 1);
    }

    #[test]
    fn test_section_marker_style_default_is_none() {
        let opts = RenderOptions::new();
        assert_eq!(opts.section_markers, SectionMarkerStyle::None);
    }

    #[test]
    fn test_section_marker_style_builder() {
        let opts = RenderOptions::new().with_section_markers(SectionMarkerStyle::Comment);
        assert_eq!(opts.section_markers, SectionMarkerStyle::Comment);
    }
}