tylax 0.3.6

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
//! Conversion context and options for Typst to LaTeX conversion
//!
//! This module handles state management, output buffering, and conversion options.

use std::collections::HashMap;

/// Controls how the document wrapper (`\documentclass` + `\usepackage`s +
/// `\begin{document}` ... `\end{document}`) is emitted around the body
/// when `T2LOptions::full_document` is `true`.
///
/// Has no effect when `full_document` is `false` (math-only / fragment mode).
#[derive(Debug, Clone, Default)]
pub enum DocumentWrapperMode {
    /// Emit the default LaTeX wrapper (article class, common packages,
    /// geometry, `\begin{document}` / `\end{document}`).
    #[default]
    Default,
    /// Emit only the converted body. No `\documentclass`, no packages,
    /// no `\begin{document}` / `\end{document}`.
    BodyOnly,
    /// Emit `before_body` + body + `after_body`. The caller is responsible
    /// for any `\documentclass`, `\begin{document}` / `\end{document}`,
    /// and package setup.
    Custom {
        before_body: String,
        after_body: String,
    },
}

impl DocumentWrapperMode {
    /// Build a [`DocumentWrapperMode::Custom`] from a single template
    /// string containing the literal placeholder `{body}`.
    ///
    /// Returns an error if the placeholder is missing — silently appending
    /// the body would mask user mistakes.
    pub fn from_template(template: &str) -> Result<Self, &'static str> {
        match template.split_once("{body}") {
            Some((before, after)) => Ok(DocumentWrapperMode::Custom {
                before_body: before.to_string(),
                after_body: after.to_string(),
            }),
            None => Err("wrapper template must contain `{body}` placeholder"),
        }
    }
}

/// Options for Typst to LaTeX conversion
#[derive(Debug, Clone)]
pub struct T2LOptions {
    /// Whether to wrap output in a complete LaTeX document
    pub full_document: bool,
    /// Document class to use (default: "article")
    pub document_class: String,
    /// Document title (optional)
    pub title: Option<String>,
    /// Document author (optional)
    pub author: Option<String>,
    /// Whether this is math-only input
    pub math_only: bool,
    /// Whether we're in block math mode (affects display/inline conversion)
    /// true = block math mode (default), false = inline math mode
    pub block_math_mode: bool,
    /// Controls the LaTeX document wrapper when `full_document` is true.
    /// Default: [`DocumentWrapperMode::Default`].
    pub wrapper: DocumentWrapperMode,
}

impl Default for T2LOptions {
    fn default() -> Self {
        Self {
            full_document: false,
            document_class: "article".to_string(),
            title: None,
            author: None,
            math_only: false,
            block_math_mode: true,
            wrapper: DocumentWrapperMode::Default,
        }
    }
}

/// Environment context for Typst to LaTeX conversion
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum EnvironmentContext {
    #[default]
    None,
    Document,
    Figure,
    Table,
    Tabular,
    Itemize,
    Enumerate,
    Description,
    Equation,
    Align,
    Matrix(String), // Matrix type: matrix, pmatrix, bmatrix, etc.
    Cases,
    Theorem(String), // Theorem-like environment with name
    Center,
    Quote,
    Verbatim,
}

impl T2LOptions {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn math_only() -> Self {
        Self {
            math_only: true,
            ..Default::default()
        }
    }

    pub fn full_document() -> Self {
        Self {
            full_document: true,
            ..Default::default()
        }
    }

    /// Create options for inline math mode
    pub fn inline_math() -> Self {
        Self {
            math_only: true,
            block_math_mode: false,
            ..Default::default()
        }
    }

    /// Create options for block math mode
    pub fn block_math() -> Self {
        Self {
            math_only: true,
            block_math_mode: true,
            ..Default::default()
        }
    }
}

/// Token type for smart spacing decisions
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum TokenType {
    None,
    Operator,
    Punctuation,
    Letter,
    Number,
    OpenParen,
    CloseParen,
    Command,
    Text,
    Newline,
}

/// Conversion context for tracking state during conversion
pub struct ConvertContext {
    /// Output buffer
    pub output: String,
    /// Whether we're inside a matrix/aligned environment
    pub in_environment: bool,
    /// Last token type for spacing decisions
    pub last_token: TokenType,
    /// Current indentation level
    pub indent_level: usize,
    /// Whether we're in math mode
    pub in_math: bool,
    /// Conversion options
    pub options: T2LOptions,
    /// Stack of environment contexts (for nested environments)
    pub env_stack: Vec<EnvironmentContext>,
    /// List nesting level (for itemize/enumerate)
    pub list_depth: usize,
    /// Collected labels for cross-references
    pub labels: Vec<String>,
    /// Collected warnings during conversion
    pub warnings: Vec<String>,
    /// User-defined variables (from #let)
    pub variables: HashMap<String, String>,
    /// Pending label to be attached to the next figure/table environment
    pub pending_label: Option<String>,
}

/// Initial capacity for output buffer (reduces reallocations)
const INITIAL_BUFFER_CAPACITY: usize = 1024;

impl ConvertContext {
    /// Create a new context with pre-allocated buffer
    pub fn new() -> Self {
        Self {
            output: String::with_capacity(INITIAL_BUFFER_CAPACITY),
            in_environment: false,
            last_token: TokenType::None,
            indent_level: 0,
            in_math: false,
            options: T2LOptions::default(),
            env_stack: Vec::new(),
            list_depth: 0,
            labels: Vec::new(),
            warnings: Vec::new(),
            variables: HashMap::new(),
            pending_label: None,
        }
    }

    /// Create a new context with custom buffer capacity
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            output: String::with_capacity(capacity),
            in_environment: false,
            last_token: TokenType::None,
            indent_level: 0,
            in_math: false,
            options: T2LOptions::default(),
            env_stack: Vec::new(),
            list_depth: 0,
            labels: Vec::new(),
            warnings: Vec::new(),
            variables: HashMap::new(),
            pending_label: None,
        }
    }

    // =========================================================================
    // Environment Management
    // =========================================================================

    /// Push a new environment onto the stack
    pub fn push_env(&mut self, env: EnvironmentContext) {
        if matches!(
            env,
            EnvironmentContext::Itemize | EnvironmentContext::Enumerate
        ) {
            self.list_depth += 1;
        }
        self.env_stack.push(env);
    }

    /// Pop the current environment from the stack
    pub fn pop_env(&mut self) -> Option<EnvironmentContext> {
        let env = self.env_stack.pop();
        if let Some(ref e) = env {
            if matches!(
                e,
                EnvironmentContext::Itemize | EnvironmentContext::Enumerate
            ) {
                self.list_depth = self.list_depth.saturating_sub(1);
            }
        }
        env
    }

    /// Get current environment
    pub fn current_env(&self) -> &EnvironmentContext {
        self.env_stack.last().unwrap_or(&EnvironmentContext::None)
    }

    /// Check if we're in any list environment
    pub fn in_list(&self) -> bool {
        self.env_stack.iter().any(|e| {
            matches!(
                e,
                EnvironmentContext::Itemize | EnvironmentContext::Enumerate
            )
        })
    }

    /// Check if we're in a specific environment
    pub fn is_in_env(&self, env: &EnvironmentContext) -> bool {
        self.env_stack.contains(env)
    }

    /// Add a warning
    pub fn add_warning(&mut self, msg: impl Into<String>) {
        self.warnings.push(msg.into());
    }

    /// Get list indentation string
    pub fn list_indent(&self) -> String {
        "  ".repeat(self.list_depth)
    }

    /// Push a string to the output buffer
    pub fn push(&mut self, s: &str) {
        self.output.push_str(s);
    }

    /// Push a line with current indentation
    pub fn push_line(&mut self, s: &str) {
        self.push_indent();
        self.push(s);
        self.push("\n");
        self.last_token = TokenType::Newline;
    }

    /// Push current indentation
    pub fn push_indent(&mut self) {
        for _ in 0..self.indent_level {
            self.output.push_str("  ");
        }
    }

    /// Add a newline if not already at one
    pub fn newline(&mut self) {
        if !self.output.ends_with('\n') {
            self.push("\n");
        }
        self.last_token = TokenType::Newline;
    }

    /// Ensure there's a paragraph break (double newline)
    pub fn ensure_paragraph_break(&mut self) {
        if !self.output.ends_with("\n\n") && !self.output.is_empty() {
            if self.output.ends_with('\n') {
                self.push("\n");
            } else {
                self.push("\n\n");
            }
        }
    }

    /// Add smart spacing based on context
    pub fn push_with_spacing(&mut self, s: &str, token_type: TokenType) {
        // Add space before if needed
        let needs_space = matches!(
            (self.last_token, token_type),
            (TokenType::Letter, TokenType::Letter)
                | (TokenType::Command, TokenType::Letter)
                | (TokenType::Command, TokenType::Number)
                | (TokenType::Number, TokenType::Letter)
        );

        if needs_space && !self.output.ends_with(' ') && !self.output.ends_with('{') {
            self.push(" ");
        }

        self.push(s);
        self.last_token = token_type;
    }

    /// Remove a single trailing plain space if present.
    pub fn trim_trailing_space(&mut self) {
        if self.output.ends_with(' ') {
            self.output.pop();
        }
    }

    /// Finalize and clean up the output
    pub fn finalize(self) -> String {
        // Clean up the output in-place where possible
        let trimmed = self.output.trim();

        // Estimate final capacity (usually slightly smaller than input)
        let mut result = String::with_capacity(trimmed.len());

        let mut prev_char = None;

        for ch in trimmed.chars() {
            // Handle double spaces
            if ch == ' ' && prev_char == Some(' ') {
                continue;
            }

            // Handle spacing around braces in math mode
            if self.options.math_only {
                if ch == ' ' && prev_char == Some('{') {
                    continue; // Skip space after {
                }
                if ch == '}' && prev_char == Some(' ') {
                    // Remove trailing space before }
                    if result.ends_with(' ') {
                        result.pop();
                    }
                }
            }

            result.push(ch);
            prev_char = Some(ch);
        }

        result
    }

    /// Get approximate output size (useful for pre-allocation)
    pub fn output_len(&self) -> usize {
        self.output.len()
    }
}

impl Default for ConvertContext {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_options_default() {
        let opts = T2LOptions::new();
        assert!(!opts.full_document);
        assert!(!opts.math_only);
        assert_eq!(opts.document_class, "article");
    }

    #[test]
    fn test_options_math_only() {
        let opts = T2LOptions::math_only();
        assert!(opts.math_only);
        assert!(!opts.full_document);
    }

    #[test]
    fn test_context_push() {
        let mut ctx = ConvertContext::new();
        ctx.push("hello");
        ctx.push(" world");
        assert_eq!(ctx.output, "hello world");
    }

    #[test]
    fn test_context_indent() {
        let mut ctx = ConvertContext::new();
        ctx.indent_level = 2;
        ctx.push_line("test");
        assert_eq!(ctx.output, "    test\n");
    }

    #[test]
    fn test_context_finalize() {
        let mut ctx = ConvertContext::new();
        ctx.push("  hello  world  ");
        let result = ctx.finalize();
        assert_eq!(result, "hello world");
    }
}