doxx 0.1.4

Terminal document viewer for .docx files
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
use anyhow::Result;
use crossterm::style::{
    Attribute, Color as CrosstermColor, ResetColor, SetAttribute, SetForegroundColor,
};
use std::fmt::Write;
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;

use crate::{document::*, ColorDepth};

pub struct AnsiOptions {
    pub terminal_width: usize,
    pub color_depth: ColorDepth,
}

impl Default for AnsiOptions {
    fn default() -> Self {
        Self {
            terminal_width: std::env::var("COLUMNS")
                .ok()
                .and_then(|s| s.parse().ok())
                .unwrap_or(80),
            color_depth: ColorDepth::Auto,
        }
    }
}

pub fn export_to_ansi_with_options(document: &Document, options: &AnsiOptions) -> Result<String> {
    let mut output = String::new();

    // Add document title
    write_ansi_heading(&mut output, &document.title, 1, options)?;
    output.push('\n');

    // Add metadata
    writeln!(
        output,
        "{}Document Information{}",
        format_ansi_text("", true, false, false, false, None, options),
        format_ansi_reset()
    )?;
    let prefix = "- File: ";
    let available = options.terminal_width.saturating_sub(prefix.len());
    let path = &document.metadata.file_path;
    let file_str = if UnicodeWidthStr::width(path.as_str()) <= available {
        path.clone()
    } else {
        let truncated: String = path
            .graphemes(true)
            .rev()
            .scan(0usize, |w, g| {
                *w += UnicodeWidthStr::width(g);
                if *w < available {
                    Some(g)
                } else {
                    None
                }
            })
            .collect::<Vec<_>>()
            .into_iter()
            .rev()
            .collect();
        format!("{truncated}")
    };
    writeln!(output, "{prefix}{file_str}")?;
    writeln!(output, "- Pages: {}", document.metadata.page_count)?;
    writeln!(output, "- Words: {}", document.metadata.word_count)?;
    if let Some(author) = &document.metadata.author {
        writeln!(output, "- Author: {author}")?;
    }
    output.push('\n');

    // Separator
    let separator = "=".repeat(std::cmp::min(50, options.terminal_width));
    writeln!(output, "{separator}")?;
    output.push('\n');

    // Convert document content
    for element in &document.elements {
        match element {
            DocumentElement::Heading {
                level,
                text,
                number,
            } => {
                let heading_text = if let Some(number) = number {
                    format!("{number} {text}")
                } else {
                    text.clone()
                };
                write_ansi_heading(&mut output, &heading_text, *level, options)?;
                output.push('\n');
            }
            DocumentElement::Paragraph { runs } => {
                if runs.is_empty() || runs.iter().all(|run| run.text.trim().is_empty()) {
                    continue;
                }
                write_ansi_paragraph(&mut output, runs, options)?;
                output.push('\n');
            }
            DocumentElement::List { items, ordered } => {
                write_ansi_list(&mut output, items, *ordered, options)?;
                output.push('\n');
            }
            DocumentElement::Table { table } => {
                write_ansi_table(&mut output, table, options)?;
                output.push('\n');
            }
            DocumentElement::Image { description, .. } => {
                writeln!(
                    output,
                    "{}🖼️  [Image: {}]{}",
                    format_ansi_color(Some("#FF00FF"), options), // Magenta
                    description,
                    format_ansi_reset()
                )?;
                output.push('\n');
            }
            DocumentElement::Equation { latex, .. } => {
                writeln!(
                    output,
                    "{}📐 {}{}",
                    format_ansi_color(Some("#00AAFF"), options), // Cyan
                    latex,
                    format_ansi_reset()
                )?;
                output.push('\n');
            }
            DocumentElement::CodeBlock { text } => {
                let code_color = format_ansi_color(Some("#AAFFAA"), options);
                let reset = format_ansi_reset();
                for line in text.lines() {
                    writeln!(output, "  {code_color}{line}{reset}")?;
                }
                output.push('\n');
            }
            DocumentElement::TextBox { lines } => {
                let border_color = format_ansi_color(Some("#00FFFF"), options);
                let reset = format_ansi_reset();
                let inner_width = options.terminal_width.saturating_sub(4);
                let bar = "".repeat(options.terminal_width.saturating_sub(2));
                writeln!(output, "{border_color}{bar}{reset}")?;
                for line in lines {
                    let truncated: String = line.chars().take(inner_width).collect();
                    writeln!(
                        output,
                        "{border_color}{reset} {truncated:<inner_width$} {border_color}{reset}",
                        inner_width = inner_width
                    )?;
                }
                writeln!(output, "{border_color}{bar}{reset}")?;
                output.push('\n');
            }
            DocumentElement::PageBreak => {
                let separator = "".repeat(std::cmp::min(60, options.terminal_width));
                writeln!(
                    output,
                    "{}{}{}",
                    format_ansi_color(Some("#666666"), options), // Dark gray
                    separator,
                    format_ansi_reset()
                )?;
                output.push('\n');
            }
        }
    }

    Ok(output)
}

fn write_ansi_heading(
    output: &mut String,
    text: &str,
    level: u8,
    options: &AnsiOptions,
) -> Result<()> {
    let color = match level {
        1 => Some("#FFFF00"), // Yellow
        2 => Some("#00FF00"), // Green
        _ => Some("#00FFFF"), // Cyan
    };

    let prefix = match level {
        1 => "",
        2 => "",
        3 => "",
        _ => "",
    };

    let prefix_width = UnicodeWidthStr::width(prefix);
    let available_width = options.terminal_width.saturating_sub(prefix_width);
    let wrapped = wrap_plain_text(text, available_width);
    let indent = " ".repeat(prefix_width);

    for (i, line) in wrapped.iter().enumerate() {
        let display = if i == 0 {
            format!("{prefix}{line}")
        } else {
            format!("{indent}{line}")
        };
        writeln!(
            output,
            "{}",
            format_ansi_text(&display, true, false, false, false, color, options)
        )?;
    }

    Ok(())
}

fn wrap_plain_text(text: &str, max_width: usize) -> Vec<String> {
    if max_width == 0 {
        return vec![text.to_string()];
    }

    let mut lines = Vec::new();
    let mut current_line = String::new();
    let mut current_width = 0;

    for word in text.split_whitespace() {
        let word_width = UnicodeWidthStr::width(word);
        if current_width == 0 {
            current_line.push_str(word);
            current_width = word_width;
        } else if current_width + 1 + word_width > max_width {
            lines.push(current_line.clone());
            current_line = word.to_string();
            current_width = word_width;
        } else {
            current_line.push(' ');
            current_line.push_str(word);
            current_width += 1 + word_width;
        }
    }

    if !current_line.is_empty() {
        lines.push(current_line);
    }
    if lines.is_empty() {
        lines.push(String::new());
    }

    lines
}

fn write_ansi_paragraph(
    output: &mut String,
    runs: &[FormattedRun],
    options: &AnsiOptions,
) -> Result<()> {
    let wrapped_lines = wrap_formatted_runs(runs, options);
    for line in wrapped_lines {
        writeln!(output, "{}{}", line, format_ansi_reset())?;
    }
    Ok(())
}

/// Wrap formatted text runs to terminal width while preserving formatting
fn wrap_formatted_runs(runs: &[FormattedRun], options: &AnsiOptions) -> Vec<String> {
    if runs.is_empty() {
        return vec![];
    }

    let max_width = options.terminal_width;
    let mut lines = Vec::new();
    let mut current_line = String::new();
    let mut current_width = 0;
    let mut line_needs_formatting = false;

    for run in runs {
        let graphemes: Vec<&str> = run.text.graphemes(true).collect();
        let mut word = String::new();
        let mut word_width = 0;

        // Apply formatting at start of run
        let format_start = get_ansi_format_start(
            run.formatting.bold,
            run.formatting.italic,
            run.formatting.underline,
            run.formatting.strikethrough,
            run.formatting.color.as_deref(),
            options,
        );

        for grapheme in graphemes {
            let grapheme_width = UnicodeWidthStr::width(grapheme);

            if grapheme == " " || grapheme == "\n" {
                // End of word - try to add it to the current line
                if !word.is_empty() {
                    if current_width + word_width > max_width && current_width > 0 {
                        // Word doesn't fit on current line, start new line
                        if line_needs_formatting {
                            current_line.push_str(&format_ansi_reset());
                        }
                        lines.push(current_line.clone());
                        current_line.clear();
                        current_width = 0;
                        line_needs_formatting = false;
                    }

                    // Apply formatting if not already applied on this line
                    if !line_needs_formatting && !format_start.is_empty() {
                        current_line.push_str(&format_start);
                        line_needs_formatting = true;
                    }

                    current_line.push_str(&word);
                    current_width += word_width;

                    word.clear();
                    word_width = 0;
                }

                // Handle space or newline
                if grapheme == "\n" {
                    if line_needs_formatting {
                        current_line.push_str(&format_ansi_reset());
                    }
                    lines.push(current_line.clone());
                    current_line.clear();
                    current_width = 0;
                    line_needs_formatting = false;
                } else if current_width < max_width {
                    current_line.push(' ');
                    current_width += 1;
                }
            } else {
                // Building a word
                word.push_str(grapheme);
                word_width += grapheme_width;
            }
        }

        // Handle remaining word at end of run
        if !word.is_empty() {
            if current_width + word_width > max_width && current_width > 0 {
                if line_needs_formatting {
                    current_line.push_str(&format_ansi_reset());
                }
                lines.push(current_line.clone());
                current_line.clear();
                current_width = 0;
                line_needs_formatting = false;
            }

            // Apply formatting if not already applied on this line
            if !line_needs_formatting && !format_start.is_empty() {
                current_line.push_str(&format_start);
                line_needs_formatting = true;
            }

            current_line.push_str(&word);
            current_width += word_width;
        }

        // Reset formatting at end of run if it was applied
        if line_needs_formatting && !current_line.is_empty() {
            current_line.push_str(&format_ansi_reset());
            line_needs_formatting = false;
        }
    }

    // Add final line if not empty
    if !current_line.is_empty() {
        lines.push(current_line);
    }

    lines
}

/// Get ANSI formatting codes for start of formatted text
fn get_ansi_format_start(
    bold: bool,
    italic: bool,
    underline: bool,
    strikethrough: bool,
    color: Option<&str>,
    options: &AnsiOptions,
) -> String {
    let mut result = String::new();

    if bold {
        result.push_str(&format!("{}", SetAttribute(Attribute::Bold)));
    }
    if italic {
        result.push_str(&format!("{}", SetAttribute(Attribute::Italic)));
    }
    if underline {
        result.push_str(&format!("{}", SetAttribute(Attribute::Underlined)));
    }
    if strikethrough {
        result.push_str(&format!("{}", SetAttribute(Attribute::CrossedOut)));
    }
    if let Some(color_hex) = color {
        result.push_str(&format_ansi_color(Some(color_hex), options));
    }

    result
}

fn write_ansi_list(
    output: &mut String,
    items: &[ListItem],
    ordered: bool,
    options: &AnsiOptions,
) -> Result<()> {
    for (i, item) in items.iter().enumerate() {
        let bullet = if ordered {
            format!("{}. ", i + 1)
        } else {
            "".to_string()
        };

        let indent = "  ".repeat(item.level as usize);
        let bullet_color = format_ansi_color(Some("#0066FF"), options); // Blue
        let prefix = format!("{}{}{}", bullet_color, indent, bullet);
        let prefix_visual_width = indent.len() + bullet.len();

        // Wrap item text with proper indentation
        let available_width = options.terminal_width.saturating_sub(prefix_visual_width);
        let wrapped_lines = wrap_formatted_runs_with_width(&item.runs, available_width, options);

        for (line_idx, line) in wrapped_lines.iter().enumerate() {
            if line_idx == 0 {
                // First line: include bullet
                writeln!(output, "{}{}{}", prefix, format_ansi_reset(), line)?;
            } else {
                // Continuation lines: indent to align with first line
                writeln!(output, "{}{}", " ".repeat(prefix_visual_width), line)?;
            }
        }
    }
    Ok(())
}

/// Wrap formatted text runs to a specific width
fn wrap_formatted_runs_with_width(
    runs: &[FormattedRun],
    max_width: usize,
    options: &AnsiOptions,
) -> Vec<String> {
    if runs.is_empty() || max_width == 0 {
        return vec![String::new()];
    }

    let mut lines = Vec::new();
    let mut current_line = String::new();
    let mut current_width = 0;
    let mut line_needs_formatting = false;

    for run in runs {
        let graphemes: Vec<&str> = run.text.graphemes(true).collect();
        let mut word = String::new();
        let mut word_width = 0;

        // Get formatting codes for this run
        let format_start = get_ansi_format_start(
            run.formatting.bold,
            run.formatting.italic,
            run.formatting.underline,
            run.formatting.strikethrough,
            run.formatting.color.as_deref(),
            options,
        );

        for grapheme in graphemes {
            let grapheme_width = UnicodeWidthStr::width(grapheme);

            if grapheme == " " || grapheme == "\n" {
                // End of word - try to add it to the current line
                if !word.is_empty() {
                    if current_width + word_width > max_width && current_width > 0 {
                        // Word doesn't fit on current line, start new line
                        if line_needs_formatting {
                            current_line.push_str(&format_ansi_reset());
                        }
                        lines.push(current_line.clone());
                        current_line.clear();
                        current_width = 0;
                        line_needs_formatting = false;
                    }

                    // Apply formatting if not already applied on this line
                    if !line_needs_formatting && !format_start.is_empty() {
                        current_line.push_str(&format_start);
                        line_needs_formatting = true;
                    }

                    current_line.push_str(&word);
                    current_width += word_width;

                    word.clear();
                    word_width = 0;
                }

                // Handle space or newline
                if grapheme == "\n" {
                    if line_needs_formatting {
                        current_line.push_str(&format_ansi_reset());
                    }
                    lines.push(current_line.clone());
                    current_line.clear();
                    current_width = 0;
                    line_needs_formatting = false;
                } else if current_width < max_width {
                    current_line.push(' ');
                    current_width += 1;
                }
            } else {
                // Building a word
                word.push_str(grapheme);
                word_width += grapheme_width;
            }
        }

        // Handle remaining word at end of run
        if !word.is_empty() {
            if current_width + word_width > max_width && current_width > 0 {
                if line_needs_formatting {
                    current_line.push_str(&format_ansi_reset());
                }
                lines.push(current_line.clone());
                current_line.clear();
                current_width = 0;
                line_needs_formatting = false;
            }

            // Apply formatting if not already applied on this line
            if !line_needs_formatting && !format_start.is_empty() {
                current_line.push_str(&format_start);
                line_needs_formatting = true;
            }

            current_line.push_str(&word);
            current_width += word_width;
        }

        // Reset formatting at end of run if it was applied
        if line_needs_formatting && !current_line.is_empty() {
            current_line.push_str(&format_ansi_reset());
            line_needs_formatting = false;
        }
    }

    // Add final line if not empty
    if !current_line.is_empty() {
        lines.push(current_line);
    }

    // Return at least one line even if empty
    if lines.is_empty() {
        lines.push(String::new());
    }

    lines
}

fn write_ansi_table(output: &mut String, table: &TableData, options: &AnsiOptions) -> Result<()> {
    // Add table title if present
    if let Some(title) = &table.metadata.title {
        let formatted_title = format_ansi_text(
            &format!("📊 {title}"),
            true,
            false,
            false,
            false,
            Some("#0066FF"), // Blue
            options,
        );
        writeln!(output, "{}{}", formatted_title, format_ansi_reset())?;
        output.push('\n');
    }

    // Simple table rendering for ANSI
    if !table.headers.is_empty() {
        // Headers
        write!(output, "")?;
        for header in &table.headers {
            write!(
                output,
                " {}{}{}",
                format_ansi_text("", true, false, false, false, None, options),
                header.content,
                format_ansi_reset()
            )?;
        }
        writeln!(output)?;

        // Separator
        write!(output, "")?;
        for _ in &table.headers {
            write!(output, "─────┼")?;
        }
        writeln!(output, "")?;

        // Rows
        for row in &table.rows {
            write!(output, "")?;
            for cell in row {
                write!(output, " {}", cell.content)?;
            }
            writeln!(output)?;
        }
    }

    Ok(())
}

fn format_ansi_text(
    text: &str,
    bold: bool,
    italic: bool,
    underline: bool,
    strikethrough: bool,
    color: Option<&str>,
    options: &AnsiOptions,
) -> String {
    let mut result = String::new();

    // Apply formatting attributes
    if bold {
        result.push_str(&format!("{}", SetAttribute(Attribute::Bold)));
    }
    if italic {
        result.push_str(&format!("{}", SetAttribute(Attribute::Italic)));
    }
    if underline {
        result.push_str(&format!("{}", SetAttribute(Attribute::Underlined)));
    }
    if strikethrough {
        result.push_str(&format!("{}", SetAttribute(Attribute::CrossedOut)));
    }

    // Apply color
    if let Some(color_hex) = color {
        result.push_str(&format_ansi_color(Some(color_hex), options));
    }

    result.push_str(text);

    // Reset formatting after this run to prevent bleeding into subsequent runs
    result.push_str(&format_ansi_reset());

    result
}

fn format_ansi_color(color_hex: Option<&str>, options: &AnsiOptions) -> String {
    let Some(hex) = color_hex else {
        return String::new();
    };

    match convert_hex_to_crossterm_color(hex, &options.color_depth) {
        Some(color) => format!("{}", SetForegroundColor(color)),
        None => String::new(),
    }
}

fn format_ansi_reset() -> String {
    format!("{ResetColor}")
}

fn convert_hex_to_crossterm_color(hex: &str, color_depth: &ColorDepth) -> Option<CrosstermColor> {
    // Remove # if present and ensure we have 6 characters
    let hex = hex.trim_start_matches('#');
    if hex.len() != 6 {
        return None;
    }

    // Parse RGB components
    let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
    let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
    let b = u8::from_str_radix(&hex[4..6], 16).ok()?;

    match color_depth {
        ColorDepth::Monochrome => None,
        ColorDepth::Standard => {
            // Convert to 16 colors (approximation)
            let color_index = rgb_to_ansi_16(r, g, b);
            Some(CrosstermColor::AnsiValue(color_index))
        }
        ColorDepth::Extended => {
            // Convert to 256 colors
            let color_index = rgb_to_ansi_256(r, g, b);
            Some(CrosstermColor::AnsiValue(color_index))
        }
        ColorDepth::TrueColor | ColorDepth::Auto => {
            // Use full RGB
            Some(CrosstermColor::Rgb { r, g, b })
        }
    }
}

fn rgb_to_ansi_16(r: u8, g: u8, b: u8) -> u8 {
    // Simple mapping to 16 colors
    let r_bright = r > 127;
    let g_bright = g > 127;
    let b_bright = b > 127;

    let base = match (r > 64, g > 64, b > 64) {
        (false, false, false) => 0, // Black
        (false, false, true) => 4,  // Blue
        (false, true, false) => 2,  // Green
        (false, true, true) => 6,   // Cyan
        (true, false, false) => 1,  // Red
        (true, false, true) => 5,   // Magenta
        (true, true, false) => 3,   // Yellow
        (true, true, true) => 7,    // White
    };

    // Add 8 for bright colors if any component is very bright
    if r_bright || g_bright || b_bright {
        base + 8
    } else {
        base
    }
}

fn rgb_to_ansi_256(r: u8, g: u8, b: u8) -> u8 {
    // 256-color conversion
    if r == g && g == b {
        // Grayscale
        if r < 8 {
            16
        } else if r > 247 {
            231
        } else {
            232 + (r - 8) / 10
        }
    } else {
        // Color cube: 16 + 36*r + 6*g + b
        let r_index = (r as f32 / 255.0 * 5.0) as u8;
        let g_index = (g as f32 / 255.0 * 5.0) as u8;
        let b_index = (b as f32 / 255.0 * 5.0) as u8;
        16 + 36 * r_index + 6 * g_index + b_index
    }
}