ascfix 0.7.1

Automatic ASCII diagram repair tool for Markdown 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
# Using ascfix as a Library

ascfix can be integrated into your Rust projects as a library for programmatic ASCII diagram and Markdown table fixing.

## Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
ascfix = "0.5"
```

## Basic Usage

### Simple Example: Process Text with Default Settings

```rust
use ascfix::modes::process_by_mode;
use ascfix::cli::Mode;
use ascfix::config::Config;

fn main() {
    let markdown = r#"
┌──────┐
│ Box  │
└──────┘
"#;

    let fixed = process_by_mode(
        &Mode::Diagram,      // Processing mode
        markdown,            // Input text
        false,               // repair_fences
        &Config::default()   // Configuration
    );

    println!("{}", fixed);
}
```

### Processing Modes

ascfix provides three processing modes:

```rust
use ascfix::cli::Mode;

// Safe mode: Fix tables only
let result = process_by_mode(&Mode::Safe, text, false, &config);

// Diagram mode: Fix tables and ASCII diagrams (recommended)
let result = process_by_mode(&Mode::Diagram, text, false, &config);

// Check mode: Validate without making changes
let result = process_by_mode(&Mode::Check, text, false, &config);
```

## Custom Configuration

### Creating a Custom Config

```rust
use ascfix::config::Config;
use ascfix::modes::process_by_mode;
use ascfix::cli::Mode;

let mut config = Config::default();
config.max_file_size = Some(50_000_000); // 50MB
config.respect_gitignore = true;

let text = r#"
│ Table │ Cell │
│ Data  │ Here │
"#;

let fixed = process_by_mode(&Mode::Diagram, text, false, &config);
```

### Config Options

```rust
pub struct Config {
    /// Maximum file size in bytes (None = unlimited)
    pub max_file_size: Option<usize>,

    /// Respect .gitignore files when processing
    pub respect_gitignore: bool,

    /// Additional configuration options...
}
```

## Advanced Usage

### Quality Validation

Validate the quality of transformations:

```rust
use ascfix::quality::{validate_quality, QualityConfig};

let input = "┌───┐\n│box│\n└───┘";
let output = process_by_mode(
    &Mode::Diagram,
    input,
    false,
    &Config::default()
);

// Validate quality
let report = validate_quality(input, &output);

let quality_config = QualityConfig {
    min_text_preservation: 0.85,
    min_structure_preservation: 0.80,
    max_line_count_delta: 2,
    allow_text_corruption: false,
    allow_data_loss: false,
};

if report.is_acceptable(&quality_config) {
    println!("Transformation passed quality checks");
} else {
    println!("Transformation did not meet quality standards");
    println!("Issues: {:?}", report.issues);
}
```

### Working with Diagram Blocks

Extract and process only diagram blocks:

```rust
use ascfix::scanner::extract_diagram_blocks;
use ascfix::modes::process_diagram_block;

let text = r#"
# My Document

Some intro text

┌──────────┐
│ Diagram  │
└──────────┘

Some conclusion
"#;

// Extract diagram blocks
let blocks = extract_diagram_blocks(text);

for block in blocks {
    println!("Found diagram at line {}", block.start_line);
    println!("Block: {}", block.content);
}
```

### Table Processing

Process tables specifically:

```rust
use ascfix::tables::process_wrapped_tables;

let markdown = r#"
| Column 1 | Column 2     |
|----------|--------------|
| Short    | This is a ve |
|          | ry long cell |
"#;

let fixed = process_wrapped_tables(markdown);
println!("{}", fixed);
```

### Fence Repair

Repair unmatched code fence markers:

```rust
use ascfix::fences::repair_code_fences;

let markdown = r#"
```rust
fn main() {
    println!("Hello");
}
```rust  // Mismatched fence marker
"#;

let repaired = repair_code_fences(markdown);
```

## Error Handling

ascfix is designed to be safe - it won't panic on malformed input:

```rust
use ascfix::modes::process_by_mode;
use ascfix::cli::Mode;
use ascfix::config::Config;

let potentially_bad_input = "???";

// This won't panic - it returns the input unchanged if issues occur
let result = process_by_mode(
    &Mode::Diagram,
    potentially_bad_input,
    false,
    &Config::default()
);

assert_eq!(result, "???");
```

## Full Example: Building a Custom Tool

Here's a complete example of building a simple diagram fixer tool:

```rust
use ascfix::cli::Mode;
use ascfix::config::Config;
use ascfix::modes::process_by_mode;
use ascfix::quality::{validate_quality, QualityConfig};
use std::fs;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Read a markdown file
    let input = fs::read_to_string("document.md")?;

    // Create configuration
    let config = Config {
        max_file_size: Some(100_000_000),
        respect_gitignore: false,
    };

    // Process with diagram mode
    let output = process_by_mode(
        &Mode::Diagram,
        &input,
        false,
        &config
    );

    // Validate quality
    let report = validate_quality(&input, &output);

    let quality_config = QualityConfig {
        min_text_preservation: 0.85,
        min_structure_preservation: 0.80,
        max_line_count_delta: 2,
        allow_text_corruption: false,
        allow_data_loss: false,
    };

    if report.is_acceptable(&quality_config) {
        // Write fixed file
        fs::write("document.fixed.md", &output)?;
        println!("✓ Document fixed successfully");
        println!("Quality score: {:.2}", report.score);
    } else {
        println!("✗ Transformation did not meet quality standards");
        println!("Issues found: {}", report.issues.len());
        for issue in &report.issues {
            println!("  - {:?}", issue);
        }
    }

    Ok(())
}
```

## Type Reference

### Key Types

```rust
// Main processing function
pub fn process_by_mode(
    mode: &Mode,
    text: &str,
    repair_fences: bool,
    config: &Config,
) -> String

// Processing modes
pub enum Mode {
    Safe,
    Diagram,
    Check,
}

// Quality validation
pub struct QualityReport {
    pub score: f32,
    pub issues: Vec<QualityIssue>,
    pub metrics: QualityMetrics,
}

// Configuration
pub struct Config {
    pub max_file_size: Option<usize>,
    pub respect_gitignore: bool,
    // ... other options
}
```

## Performance Tips

1. **Batch Processing:** Process multiple files concurrently if needed
2. **Size Limits:** Use `max_file_size` to skip large files
3. **Mode Selection:** Use `Safe` mode for performance-critical scenarios
4. **Caching:** Cache config objects if processing many files

## Troubleshooting

**Q: Output is unchanged from input**
- Check the Mode - `Safe` mode only fixes tables
- Use `Diagram` mode for ASCII diagram fixes

**Q: Getting unexpected transformations**
- Review `QualityConfig` thresholds
- Use quality validation to understand what's changing

**Q: Performance is slow**
- Set a reasonable `max_file_size`
- Consider using `Safe` mode for large batches
- Process files concurrently

## Integration Examples

### With structopt CLI

```rust
use structopt::StructOpt;
use ascfix::modes::process_by_mode;
use ascfix::cli::Mode;
use ascfix::config::Config;

#[derive(StructOpt)]
struct Args {
    #[structopt(short, long)]
    input: String,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args = Args::from_args();
    let text = std::fs::read_to_string(&args.input)?;

    let fixed = process_by_mode(
        &Mode::Diagram,
        &text,
        false,
        &Config::default()
    );

    println!("{}", fixed);
    Ok(())
}
```

### With Tokio for Async Processing

```rust
use std::fs;
use ascfix::modes::process_by_mode;
use ascfix::cli::Mode;
use ascfix::config::Config;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let files = vec!["file1.md", "file2.md"];

    let futures = files.into_iter().map(|file| {
        async move {
            let text = fs::read_to_string(file).ok()?;
            let fixed = process_by_mode(
                &Mode::Diagram,
                &text,
                false,
                &Config::default()
            );
            Some(fixed)
        }
    });

    // Process concurrently
    let results = futures::future::join_all(futures).await;

    Ok(())
}
```

## Known Limitations

### Idempotence Constraints

**ascfix** aims to be idempotent (processing the same input multiple times produces identical output), but there are known edge cases where this doesn't hold for complex diagrams.

#### What Works (Fully Idempotent)

These cases are guaranteed to be idempotent:

```rust
use ascfix::modes::process_by_mode;
use ascfix::cli::Mode;
use ascfix::config::Config;

// ✅ Simple boxes
let simple = "┌───┐\n│ A │\n└───┘";
let pass1 = process_by_mode(&Mode::Diagram, simple, false, &Config::default());
let pass2 = process_by_mode(&Mode::Diagram, &pass1, false, &Config::default());
assert_eq!(pass1, pass2); // Always passes

// ✅ Tables in Safe mode
let table = "| A | B |\n|---|---|\n| 1 | 2 |";
let pass1 = process_by_mode(&Mode::Safe, table, false, &Config::default());
let pass2 = process_by_mode(&Mode::Safe, &pass1, false, &Config::default());
assert_eq!(pass1, pass2); // Always passes

// ✅ Single-level nested boxes
let nested_simple = "┌────────┐\n│ Parent │\n│ ┌────┐ │\n│ │ Ch │ │\n│ └────┘ │\n└────────┘";
let pass1 = process_by_mode(&Mode::Diagram, nested_simple, false, &Config::default());
let pass2 = process_by_mode(&Mode::Diagram, &pass1, false, &Config::default());
assert_eq!(pass1, pass2); // Usually passes
```

#### Known Issues

**Deeply Nested Hierarchies (3+ levels):**

For diagrams with 3 or more levels of nesting, idempotence may not hold:

```rust
// ⚠️ May not be idempotent
let complex = "┌──────────────┐\n│ Grandparent  │\n│ ┌──────────┐ │\n│ │ Parent   │ │\n│ │ ┌──────┐ │ │\n│ │ │Child │ │ │\n│ │ └──────┘ │ │\n│ └──────────┘ │\n└──────────────┘";

let pass1 = process_by_mode(&Mode::Diagram, complex, false, &Config::default());
let pass2 = process_by_mode(&Mode::Diagram, &pass1, false, &Config::default());
// pass1 != pass2 in some cases
```

**Why:** After the first pass expands the parent box to fit children, the detection phase on the second pass sees different spatial relationships and may recalculate box boundaries.

#### Technical Details

The root cause is in the detection phase:

1. **First Pass:**
   - Detector finds boxes at original positions
   - Normalizer expands parent to fit child
   - Renderer outputs expanded diagram

2. **Second Pass:**
   - Detector sees expanded parent box
   - Calculates new parent-child relationships
   - May identify different nesting levels
   - Can trigger different normalization

For complex diagrams with overlapping elements or tight spacing, this detection difference can cascade through nested levels.

See [ARCHITECTURE.md](./ARCHITECTURE.md) for details on the detection algorithm and spatial relationship calculations.

#### Workarounds

**1. Use Safe Mode for Tables:**
```rust
// Always idempotent
let fixed = process_by_mode(&Mode::Safe, content, false, &Config::default());
```

**2. Process Once and Commit:**
```rust
// Run once, review output, commit
let fixed = process_by_mode(&Mode::Diagram, content, false, &Config::default());
std::fs::write("output.md", fixed)?;
// Don't run again on the output
```

**3. Test Idempotence Before Production:**
```rust
fn verify_idempotence(content: &str) -> bool {
    let pass1 = process_by_mode(&Mode::Diagram, content, false, &Config::default());
    let pass2 = process_by_mode(&Mode::Diagram, &pass1, false, &Config::default());
    pass1 == pass2
}

if !verify_idempotence(&my_diagram) {
    eprintln!("Warning: This diagram may not be fully idempotent");
    // Decide whether to proceed
}
```

**4. Use Ignore Markers:**
```markdown
<!-- ascfix:ignore -->
Complex nested diagram here
<!-- /ascfix:ignore -->
```

#### Testing Strategy

If you're processing diagrams programmatically, consider:

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

    #[test]
    fn test_my_diagram_is_idempotent() {
        let diagram = include_str!("../fixtures/my_diagram.md");

        let pass1 = process_by_mode(&Mode::Diagram, diagram, false, &Config::default());
        let pass2 = process_by_mode(&Mode::Diagram, &pass1, false, &Config::default());

        assert_eq!(
            pass1, pass2,
            "Diagram should be idempotent after first normalization"
        );
    }
}
```

This allows you to verify idempotence for your specific diagrams and catch regressions.

---

## Support

For issues or questions about using ascfix as a library, please refer to:
- [ARCHITECTURE.md]./ARCHITECTURE.md - Design and module overview
- [README.md]./README.md - General usage and capabilities
- GitHub Issues - Report bugs or suggest improvements