tylax 0.3.5

Tylax - High-performance bidirectional LaTeX ↔ Typst converter
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
//! Tylax CLI - High-performance bidirectional LaTeX ↔ Typst converter

#[cfg(feature = "cli")]
use clap::{Parser, Subcommand, ValueEnum};
use std::fs;
use std::io::{self, Read, Write};
use std::path::Path;
use tylax::{
    convert_auto, convert_auto_document, detect_format,
    diagnostics::{check_latex, format_diagnostics},
    latex_document_to_typst, latex_to_typst, latex_to_typst_with_diagnostics,
    tikz::{convert_cetz_to_tikz, convert_tikz_to_cetz, is_cetz_code},
    typst_document_to_latex, typst_to_latex, typst_to_latex_with_diagnostics, CliDiagnostic,
    T2LOptions,
};

#[cfg(feature = "cli")]
#[derive(Parser)]
#[command(name = "t2l")]
#[command(author = "SciPenAI")]
#[command(version)]
#[command(about = "Tylax - High-performance bidirectional LaTeX ↔ Typst converter", long_about = None)]
struct Cli {
    /// Subcommand to run
    #[command(subcommand)]
    command: Option<Commands>,

    /// Input file path (reads from stdin if not provided)
    input_file: Option<String>,

    /// Output file path (writes to stdout if not provided)
    #[arg(short, long)]
    output: Option<String>,

    /// Conversion direction
    #[arg(short, long, value_enum, default_value_t = Direction::Auto)]
    direction: Direction,

    /// Full document mode (convert entire document, not just math)
    #[arg(short = 'f', long)]
    full_document: bool,

    /// Pretty print the output
    #[arg(short, long)]
    pretty: bool,

    /// Detect and print the input format without converting
    #[arg(long)]
    detect: bool,

    /// Check mode - analyze LaTeX for potential issues without converting
    #[arg(long)]
    check: bool,

    /// Use colored output (for check mode)
    #[arg(long, default_value_t = true)]
    color: bool,

    /// Disable MiniEval preprocessing for Typst scripting features (loops, functions)
    /// By default, MiniEval is enabled for T2L conversions to expand #let, #for, #if, etc.
    #[arg(long)]
    no_eval: bool,

    /// Strict mode: exit with error if any conversion warnings occur
    #[arg(long)]
    strict: bool,

    /// Quiet mode: suppress warning output to stderr
    #[arg(short, long)]
    quiet: bool,

    /// Embed warnings as comments in the output file
    #[arg(long)]
    embed_warnings: bool,
}

#[cfg(feature = "cli")]
#[derive(Subcommand)]
enum Commands {
    /// Check LaTeX for potential conversion issues
    Check {
        /// Input file to check
        input: Option<String>,

        /// Disable colored output
        #[arg(long)]
        no_color: bool,
    },

    /// Convert a file (default action)
    Convert {
        /// Input file path
        input: Option<String>,

        /// Output file path
        #[arg(short, long)]
        output: Option<String>,

        /// Conversion direction
        #[arg(short, long, value_enum, default_value_t = Direction::Auto)]
        direction: Direction,

        /// Full document mode
        #[arg(short = 'f', long)]
        full_document: bool,
    },

    /// Convert TikZ to CeTZ or vice versa
    Tikz {
        /// Input file containing TikZ or CeTZ code
        input: Option<String>,

        /// Output file path
        #[arg(short, long)]
        output: Option<String>,

        /// Direction (auto-detected by default)
        #[arg(short, long, value_enum, default_value_t = TikzDirection::Auto)]
        direction: TikzDirection,
    },

    /// Batch convert multiple files
    Batch {
        /// Input directory or glob pattern
        input: String,

        /// Output directory
        #[arg(short, long)]
        output_dir: String,

        /// Conversion direction
        #[arg(short, long, value_enum, default_value_t = Direction::L2t)]
        direction: Direction,

        /// Full document mode
        #[arg(short = 'f', long)]
        full_document: bool,

        /// File extension for output files
        #[arg(short, long)]
        extension: Option<String>,
    },

    /// Show version and feature info
    Info,
}

#[cfg(feature = "cli")]
#[derive(Clone, ValueEnum)]
enum TikzDirection {
    /// Auto-detect based on content
    Auto,
    /// TikZ to CeTZ
    TikzToCetz,
    /// CeTZ to TikZ
    CetzToTikz,
}

#[cfg(feature = "cli")]
#[derive(Clone, ValueEnum)]
enum Direction {
    /// Auto-detect based on file extension or content
    Auto,
    /// LaTeX to Typst
    L2t,
    /// Typst to LaTeX
    T2l,
}

#[cfg(feature = "cli")]
fn main() -> io::Result<()> {
    let cli = Cli::parse();

    // Handle subcommands first
    if let Some(cmd) = cli.command {
        return handle_subcommand(cmd);
    }

    // Read input
    let (input, filename) = match cli.input_file {
        Some(ref path) => (fs::read_to_string(path)?, Some(path.clone())),
        None => {
            let mut buffer = String::new();
            io::stdin().read_to_string(&mut buffer)?;
            (buffer, None)
        }
    };

    // If detect mode, just print format and exit
    if cli.detect {
        let format = detect_format(&input);
        println!("{}", format);
        return Ok(());
    }

    // If check mode, analyze and report issues
    if cli.check {
        let result = check_latex(&input);
        let output = format_diagnostics(&result, cli.color);
        println!("{}", output);

        // Exit with error code if there are errors
        if result.has_errors() {
            std::process::exit(1);
        }
        return Ok(());
    }

    // Determine direction
    let direction = match cli.direction {
        Direction::Auto => {
            if let Some(ref name) = filename {
                if name.ends_with(".typ") {
                    Direction::T2l
                } else if name.ends_with(".tex") {
                    Direction::L2t
                } else {
                    // Use content-based detection
                    let format = detect_format(&input);
                    if format == "latex" {
                        Direction::L2t
                    } else {
                        Direction::T2l
                    }
                }
            } else {
                // Use content-based detection
                let format = detect_format(&input);
                if format == "latex" {
                    Direction::L2t
                } else {
                    Direction::T2l
                }
            }
        }
        d => d,
    };

    // Determine if this is a full document based on content or flag
    let is_full_document = cli.full_document || is_latex_document(&input);

    // Convert with diagnostics - collect warnings as unified CliDiagnostic
    let (result, diagnostics): (String, Vec<CliDiagnostic>) = match direction {
        Direction::L2t => {
            let conv_result = latex_to_typst_with_diagnostics(&input);
            let diags = conv_result
                .warnings
                .into_iter()
                .map(CliDiagnostic::from)
                .collect();
            (conv_result.output, diags)
        }
        Direction::T2l => {
            let options = if is_full_document {
                T2LOptions::full_document()
            } else {
                T2LOptions::default()
            };
            if !cli.no_eval {
                let conv_result = typst_to_latex_with_diagnostics(&input, &options);
                let diags = conv_result
                    .warnings
                    .into_iter()
                    .map(CliDiagnostic::from)
                    .collect();
                (conv_result.output, diags)
            } else {
                let output = if is_full_document {
                    typst_document_to_latex(&input)
                } else {
                    typst_to_latex(&input)
                };
                (output, Vec::new())
            }
        }
        Direction::Auto => {
            let (output, _) = if is_full_document {
                convert_auto_document(&input)
            } else {
                convert_auto(&input)
            };
            (output, Vec::new())
        }
    };

    // Print diagnostics to stderr (unless quiet mode)
    if !cli.quiet && !diagnostics.is_empty() {
        print_diagnostics_to_stderr(&diagnostics, cli.color);
    }

    // Check strict mode
    if cli.strict && !diagnostics.is_empty() {
        eprintln!(
            "Error: {} conversion warning(s) in strict mode",
            diagnostics.len()
        );
        std::process::exit(1);
    }

    // Embed diagnostics as comments if requested
    let result = if cli.embed_warnings && !diagnostics.is_empty() {
        embed_diagnostics_as_comments(&result, &diagnostics)
    } else {
        result
    };

    // Pretty print if requested
    let result = if cli.pretty {
        pretty_print(&result)
    } else {
        result
    };

    // Output
    match cli.output {
        Some(path) => {
            let mut file = fs::File::create(&path)?;
            writeln!(file, "{}", result)?;
            if diagnostics.is_empty() {
                eprintln!("✓ Output written to: {}", path);
            } else {
                eprintln!(
                    "⚠ Output written to: {} ({} warning(s))",
                    path,
                    diagnostics.len()
                );
            }
        }
        None => {
            println!("{}", result);
        }
    }

    Ok(())
}

#[cfg(feature = "cli")]
fn handle_subcommand(cmd: Commands) -> io::Result<()> {
    match cmd {
        Commands::Check { input, no_color } => {
            let content = match input {
                Some(path) => fs::read_to_string(&path)?,
                None => {
                    let mut buffer = String::new();
                    io::stdin().read_to_string(&mut buffer)?;
                    buffer
                }
            };

            let result = check_latex(&content);
            let output = format_diagnostics(&result, !no_color);
            println!("{}", output);

            if result.has_errors() {
                std::process::exit(1);
            }
        }

        Commands::Convert {
            input,
            output,
            direction,
            full_document,
        } => {
            let (content, filename) = match input {
                Some(ref path) => (fs::read_to_string(path)?, Some(path.clone())),
                None => {
                    let mut buffer = String::new();
                    io::stdin().read_to_string(&mut buffer)?;
                    (buffer, None)
                }
            };

            let direction = match direction {
                Direction::Auto => {
                    if let Some(ref name) = filename {
                        if name.ends_with(".typ") {
                            Direction::T2l
                        } else if name.ends_with(".tex") {
                            Direction::L2t
                        } else {
                            let format = detect_format(&content);
                            if format == "latex" {
                                Direction::L2t
                            } else {
                                Direction::T2l
                            }
                        }
                    } else {
                        let format = detect_format(&content);
                        if format == "latex" {
                            Direction::L2t
                        } else {
                            Direction::T2l
                        }
                    }
                }
                d => d,
            };

            let result = if full_document {
                match direction {
                    Direction::L2t => latex_document_to_typst(&content),
                    Direction::T2l => typst_document_to_latex(&content),
                    Direction::Auto => convert_auto_document(&content).0,
                }
            } else {
                match direction {
                    Direction::L2t => latex_to_typst(&content),
                    Direction::T2l => typst_to_latex(&content),
                    Direction::Auto => convert_auto(&content).0,
                }
            };

            match output {
                Some(path) => {
                    let mut file = fs::File::create(&path)?;
                    writeln!(file, "{}", result)?;
                    eprintln!("✓ Output written to: {}", path);
                }
                None => {
                    println!("{}", result);
                }
            }
        }

        Commands::Tikz {
            input,
            output,
            direction,
        } => {
            let content = match input {
                Some(path) => fs::read_to_string(&path)?,
                None => {
                    let mut buffer = String::new();
                    io::stdin().read_to_string(&mut buffer)?;
                    buffer
                }
            };

            let direction = match direction {
                TikzDirection::Auto => {
                    if is_cetz_code(&content) {
                        TikzDirection::CetzToTikz
                    } else {
                        TikzDirection::TikzToCetz
                    }
                }
                d => d,
            };

            let result = match direction {
                TikzDirection::TikzToCetz => convert_tikz_to_cetz(&content),
                TikzDirection::CetzToTikz => convert_cetz_to_tikz(&content),
                TikzDirection::Auto => unreachable!(),
            };

            match output {
                Some(path) => {
                    let mut file = fs::File::create(&path)?;
                    writeln!(file, "{}", result)?;
                    eprintln!("✓ TikZ/CeTZ conversion written to: {}", path);
                }
                None => {
                    println!("{}", result);
                }
            }
        }

        Commands::Batch {
            input,
            output_dir,
            direction,
            full_document,
            extension,
        } => {
            // Create output directory if it doesn't exist
            fs::create_dir_all(&output_dir)?;

            // Determine output extension
            let out_ext = extension.unwrap_or_else(|| match direction {
                Direction::L2t => "typ".to_string(),
                Direction::T2l => "tex".to_string(),
                Direction::Auto => "out".to_string(),
            });

            // Find input files
            let input_path = Path::new(&input);
            let files: Vec<_> = if input_path.is_dir() {
                // Read all .tex or .typ files from directory
                fs::read_dir(input_path)?
                    .filter_map(|e| e.ok())
                    .filter(|e| {
                        let path = e.path();
                        let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("");
                        matches!(direction, Direction::L2t) && ext == "tex"
                            || matches!(direction, Direction::T2l) && ext == "typ"
                            || matches!(direction, Direction::Auto)
                    })
                    .map(|e| e.path())
                    .collect()
            } else {
                // Single file
                vec![input_path.to_path_buf()]
            };

            let mut success_count = 0;
            let mut error_count = 0;

            for file_path in files {
                let filename = file_path
                    .file_stem()
                    .and_then(|s| s.to_str())
                    .unwrap_or("output");

                let output_path = Path::new(&output_dir).join(format!("{}.{}", filename, out_ext));

                match fs::read_to_string(&file_path) {
                    Ok(content) => {
                        let result = if full_document {
                            match direction {
                                Direction::L2t => latex_document_to_typst(&content),
                                Direction::T2l => typst_document_to_latex(&content),
                                Direction::Auto => convert_auto_document(&content).0,
                            }
                        } else {
                            match direction {
                                Direction::L2t => latex_to_typst(&content),
                                Direction::T2l => typst_to_latex(&content),
                                Direction::Auto => convert_auto(&content).0,
                            }
                        };

                        match fs::write(&output_path, &result) {
                            Ok(_) => {
                                eprintln!("{}", output_path.display());
                                success_count += 1;
                            }
                            Err(e) => {
                                eprintln!("{} - write error: {}", output_path.display(), e);
                                error_count += 1;
                            }
                        }
                    }
                    Err(e) => {
                        eprintln!("{} - read error: {}", file_path.display(), e);
                        error_count += 1;
                    }
                }
            }

            eprintln!(
                "\nBatch conversion complete: {} succeeded, {} failed",
                success_count, error_count
            );

            if error_count > 0 {
                std::process::exit(1);
            }
        }

        Commands::Info => {
            println!("Tylax - High-performance bidirectional LaTeX ↔ Typst converter");
            println!("Version: {}", env!("CARGO_PKG_VERSION"));
            println!();
            println!("Features:");
            println!("  ✓ LaTeX → Typst conversion (math + documents)");
            println!("  ✓ Typst → LaTeX conversion (math + documents)");
            println!("  ✓ TikZ ↔ CeTZ graphics conversion");
            println!("  ✓ Batch file processing");
            println!("  ✓ LaTeX diagnostics and checking");
            println!("  ✓ Auto-detection of input format");
            println!();
            println!("Supported packages:");
            println!("  - amsmath, amssymb, mathtools");
            println!("  - graphicx, hyperref, biblatex");
            println!("  - tikz, pgf (basic features)");
            println!("  - siunitx, mhchem");
            println!();
            println!("Repository: https://github.com/scipenai/tylax");
            println!();
        }
    }

    Ok(())
}

/// Detect if input is a full LaTeX document (vs math snippet)
#[cfg(feature = "cli")]
fn is_latex_document(input: &str) -> bool {
    // Check for document structure indicators
    input.contains("\\documentclass")
        || input.contains("\\begin{document}")
        || input.contains("\\section")
        || input.contains("\\chapter")
        || input.contains("\\title")
        || input.contains("\\maketitle")
        || input.contains("\\usepackage")
}

#[cfg(feature = "cli")]
fn pretty_print(input: &str) -> String {
    // Simple pretty printing: normalize indentation and spacing
    let mut result = String::new();
    let mut indent_level: usize = 0;

    for line in input.lines() {
        let trimmed = line.trim();

        // Decrease indent before closing braces/brackets
        if trimmed.starts_with('}') || trimmed.starts_with(']') || trimmed.starts_with(')') {
            indent_level = indent_level.saturating_sub(1);
        }
        if trimmed.starts_with("\\end{") {
            indent_level = indent_level.saturating_sub(1);
        }

        // Add indentation
        for _ in 0..indent_level {
            result.push_str("  ");
        }
        result.push_str(trimmed);
        result.push('\n');

        // Increase indent after opening braces/brackets
        if trimmed.ends_with('{') || trimmed.ends_with('[') {
            indent_level += 1;
        }
        if trimmed.starts_with("\\begin{") {
            indent_level += 1;
        }
    }

    result.trim().to_string()
}

/// Print diagnostics to stderr with optional color coding (unified for L2T and T2L).
#[cfg(feature = "cli")]
fn print_diagnostics_to_stderr(diagnostics: &[CliDiagnostic], use_color: bool) {
    eprintln!();
    eprintln!(
        "{}Conversion Warnings ({}):{}",
        if use_color { "\x1b[33m" } else { "" },
        diagnostics.len(),
        if use_color { "\x1b[0m" } else { "" }
    );
    eprintln!();

    for diag in diagnostics {
        let color = if use_color { diag.color_code() } else { "" };
        let reset = if use_color { "\x1b[0m" } else { "" };

        if let Some(ref loc) = diag.location {
            eprintln!(
                "  {}[{}]{} {}: {}",
                color, diag.kind, reset, loc, diag.message
            );
        } else {
            eprintln!("  {}[{}]{} {}", color, diag.kind, reset, diag.message);
        }
    }
    eprintln!();
}

/// Embed diagnostics as comments at the end of the output (unified for L2T and T2L).
#[cfg(feature = "cli")]
fn embed_diagnostics_as_comments(output: &str, diagnostics: &[CliDiagnostic]) -> String {
    let mut result = output.to_string();
    result.push_str("\n\n// ═══════════════════════════════════════════════════════════════\n");
    result.push_str("// Conversion Warnings\n");
    result.push_str("// ═══════════════════════════════════════════════════════════════\n");

    for diag in diagnostics {
        if let Some(ref loc) = diag.location {
            result.push_str(&format!("// [{}] {}: {}\n", diag.kind, loc, diag.message));
        } else {
            result.push_str(&format!("// [{}] {}\n", diag.kind, diag.message));
        }
    }

    result
}

#[cfg(not(feature = "cli"))]
fn main() {
    eprintln!("CLI feature not enabled. Build with --features cli");
    eprintln!();
    eprintln!("Usage:");
    eprintln!("  cargo install tylax --features cli");
    eprintln!("  t2l [OPTIONS] [INPUT_FILE]");
}