rtex 0.1.11

Native TeX to PDF converter written in Rust with zero external LaTeX dependencies
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
//! Simple macro expansion engine for user-defined LaTeX commands.
//!
//! Supports `\newcommand`, `\renewcommand` (with optional parameter count) and `\def`.
//! Macros are extracted from the source in a first pass, then all
//! invocations are expanded before the document is parsed.

use std::collections::HashMap;

/// A single macro definition.
#[derive(Debug, Clone, PartialEq)]
pub struct MacroDef {
    pub name: String,
    pub param_count: usize,
    pub body: String,
}

/// Storage and expansion engine for user-defined macros.
#[derive(Debug, Default)]
pub struct MacroStore {
    defs: HashMap<String, MacroDef>,
    /// `\let\new\old` aliases: `\new` expands to `\old`.
    aliases: HashMap<String, String>,
}

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

    /// Scan `text` for `\newcommand`, `\renewcommand`, `\providecommand`, and `\def` declarations and store them.
    /// The definitions themselves are removed from the returned string.
    pub fn extract_definitions(&mut self, text: &str) -> String {
        let mut result = String::with_capacity(text.len());
        let mut i = 0;

        while i < text.len() {
            let remaining = &text[i..];

            if (remaining.starts_with("\\newcommand")
                || remaining.starts_with("\\renewcommand")
                || remaining.starts_with("\\providecommand"))
                && let Some(skip) = self.parse_newcommand(remaining)
            {
                i += skip;
                continue;
            }

            if remaining.starts_with("\\def")
                && let Some(skip) = self.parse_def(remaining)
            {
                i += skip;
                continue;
            }

            if remaining.starts_with("\\let")
                && let Some(skip) = self.parse_let(remaining)
            {
                i += skip;
                continue;
            }

            let ch = remaining.chars().next().unwrap_or('\0');
            result.push(ch);
            i += ch.len_utf8();
        }

        result
    }

    /// Expand every known macro invocation in `text`.
    pub fn expand_all(&self, text: &str) -> String {
        let mut result = text.to_string();
        // Limit recursion depth to avoid infinite loops.
        for _ in 0..10 {
            let next = self.expand_once(&result);
            if next == result {
                break;
            }
            result = next;
        }
        result
    }

    // ------------------------------------------------------------------
    // Parsing helpers
    // ------------------------------------------------------------------

    /// Parse `\newcommand{\name}[n]{body}`, `\renewcommand{...}`, `\providecommand{...}`,
    /// or `\newcommand\name[n]{body}`. Returns the number of bytes consumed on success.
    /// `\providecommand` only inserts a definition when the name is not already defined.
    fn parse_newcommand(&mut self, text: &str) -> Option<usize> {
        let (start, only_if_absent) = if text.starts_with("\\providecommand") {
            ("\\providecommand".len(), true)
        } else if text.starts_with("\\renewcommand") {
            ("\\renewcommand".len(), false)
        } else {
            ("\\newcommand".len(), false)
        };
        let rest = text.get(start..)?;

        // Skip optional whitespace
        let mut pos = 0;
        while pos < rest.len() && rest[pos..].starts_with(|c: char| c.is_whitespace()) {
            pos += rest[pos..].chars().next()?.len_utf8();
        }

        // Macro name: either {\name} or \name
        let (name, consumed) = if rest.get(pos..).is_some_and(|s| s.starts_with('{')) {
            let (inner, end) = extract_braced(rest, pos)?;
            let trimmed = inner.trim();
            let name = trimmed.strip_prefix('\\').unwrap_or(trimmed).to_string();
            (name, end)
        } else if rest.get(pos..).is_some_and(|s| s.starts_with('\\')) {
            let name_end = rest[pos + 1..]
                .find(|c: char| !c.is_alphabetic() && c != '*')
                .map(|i| pos + 1 + i)
                .unwrap_or(rest.len());
            (rest[pos + 1..name_end].to_string(), name_end)
        } else {
            return None;
        };
        pos = consumed;

        // Skip whitespace
        while pos < rest.len() && rest[pos..].starts_with(|c: char| c.is_whitespace()) {
            pos += rest[pos..].chars().next()?.len_utf8();
        }

        // Optional parameter count [n]
        let mut param_count = 0;
        if rest[pos..].starts_with('[') {
            let close = rest[pos..].find(']')?;
            let num_str = &rest[pos + 1..pos + close];
            param_count = num_str.parse().ok()?;
            pos += close + 1;
        }

        // Skip whitespace
        while pos < rest.len() && rest[pos..].starts_with(|c: char| c.is_whitespace()) {
            pos += rest[pos..].chars().next()?.len_utf8();
        }

        // Body
        let (body, end) = extract_braced(rest, pos)?;
        pos = end;

        // `\providecommand` only defines when the name is not already defined.
        if !only_if_absent || !self.defs.contains_key(&name) {
            self.defs.insert(
                name.clone(),
                MacroDef {
                    name,
                    param_count,
                    body,
                },
            );
        }

        Some(start + pos)
    }

    /// Parse `\def\name#1#2...{body}`.
    /// Returns the number of bytes consumed on success.
    fn parse_def(&mut self, text: &str) -> Option<usize> {
        let start = "\\def".len();
        let rest = text.get(start..)?;

        let mut pos = 0;
        while pos < rest.len() && rest[pos..].starts_with(|c: char| c.is_whitespace()) {
            pos += rest[pos..].chars().next()?.len_utf8();
        }

        if !rest[pos..].starts_with('\\') {
            return None;
        }

        let name_end = rest[pos + 1..]
            .find(|c: char| !c.is_alphabetic() && c != '*')
            .map(|i| pos + 1 + i)
            .unwrap_or(rest.len());
        let name = rest[pos + 1..name_end].to_string();
        pos = name_end;

        // Count parameter tokens #1, #2, ...
        let mut param_count = 0;
        while let Some(digit) = rest
            .get(pos + 1..)
            .and_then(|s| s.chars().next())
            .filter(|c| c.is_ascii_digit())
        {
            let n = digit.to_digit(10).unwrap() as usize;
            param_count = param_count.max(n);
            pos += 1 + digit.len_utf8();
        }

        // Body
        let (body, end) = extract_braced(rest, pos)?;
        pos = end;

        self.defs.insert(
            name.clone(),
            MacroDef {
                name,
                param_count,
                body,
            },
        );

        Some(start + pos)
    }

    /// Parse `\let\new\old` or `\let\new=\old` — alias `\new` to `\old`.
    /// Returns the number of bytes consumed on success.
    fn parse_let(&mut self, text: &str) -> Option<usize> {
        let start = "\\let".len();
        let rest = text.get(start..)?;
        let mut pos = 0;
        while pos < rest.len() && rest[pos..].starts_with(|c: char| c.is_whitespace()) {
            pos += rest[pos..].chars().next()?.len_utf8();
        }
        if !rest[pos..].starts_with('\\') {
            return None;
        }
        let new_end = rest[pos + 1..]
            .find(|c: char| !c.is_alphabetic() && c != '*')
            .map(|i| pos + 1 + i)
            .unwrap_or(rest.len());
        let new_name = rest[pos + 1..new_end].to_string();
        pos = new_end;
        while pos < rest.len() && rest[pos..].starts_with(|c: char| c.is_whitespace()) {
            pos += rest[pos..].chars().next()?.len_utf8();
        }
        if rest[pos..].starts_with('=') {
            pos += 1;
            while pos < rest.len() && rest[pos..].starts_with(|c: char| c.is_whitespace()) {
                pos += rest[pos..].chars().next()?.len_utf8();
            }
        }
        if !rest[pos..].starts_with('\\') {
            return None;
        }
        let old_end = rest[pos + 1..]
            .find(|c: char| !c.is_alphabetic() && c != '*')
            .map(|i| pos + 1 + i)
            .unwrap_or(rest.len());
        let old_name = rest[pos + 1..old_end].to_string();
        pos = old_end;

        self.aliases.insert(new_name, old_name);
        Some(start + pos)
    }

    // ------------------------------------------------------------------
    // Expansion helpers
    // ------------------------------------------------------------------

    fn expand_once(&self, text: &str) -> String {
        let mut result = String::with_capacity(text.len() * 2);
        let mut i = 0;

        while i < text.len() {
            let remaining = &text[i..];

            if remaining.starts_with("\\newcommand")
                || remaining.starts_with("\\renewcommand")
                || remaining.starts_with("\\providecommand")
                || remaining.starts_with("\\def")
                || remaining.starts_with("\\let")
            {
                // Should have been stripped during extraction, but skip just in case.
                let cmd = if remaining.starts_with("\\providecommand") {
                    "\\providecommand"
                } else if remaining.starts_with("\\renewcommand") {
                    "\\renewcommand"
                } else if remaining.starts_with("\\newcommand") {
                    "\\newcommand"
                } else if remaining.starts_with("\\let") {
                    "\\let"
                } else {
                    "\\def"
                };
                result.push_str(cmd);
                i += cmd.len();
                continue;
            }

            if let Some(after_backslash) = remaining.strip_prefix('\\') {
                // Try to match a macro name.
                let name_end = if after_backslash.is_empty() {
                    0
                } else {
                    after_backslash
                        .find(|c: char| !c.is_alphabetic() && c != '*')
                        .unwrap_or(after_backslash.len())
                };
                let name = &after_backslash[..name_end];

                if let Some(def) = self.defs.get(name) {
                    let after = &after_backslash[name_end..];
                    let (args, consumed) = self.collect_args(after, def.param_count);
                    let expanded = self.substitute(&def.body, &args);
                    result.push_str(&expanded);
                    i += 1 + name_end + consumed;
                    continue;
                }

                // `\let` alias: emit the aliased command name so the parser
                // (or a later expansion round) handles it.
                if let Some(target) = self.aliases.get(name) {
                    result.push('\\');
                    result.push_str(target);
                    i += 1 + name_end;
                    continue;
                }
            }

            let ch = remaining.chars().next().unwrap_or('\0');
            result.push(ch);
            i += ch.len_utf8();
        }

        result
    }

    /// Collect `count` braced arguments from the start of `text`.
    /// Returns `(args, bytes_consumed)`.
    fn collect_args(&self, text: &str, count: usize) -> (Vec<String>, usize) {
        let mut args = Vec::with_capacity(count);
        let mut pos = 0;

        for _ in 0..count {
            while pos < text.len() && text[pos..].starts_with(|c: char| c.is_whitespace()) {
                pos += text[pos..].chars().next().unwrap().len_utf8();
            }
            if text.get(pos..).is_some_and(|s| s.starts_with('{'))
                && let Some((inner, end)) = extract_braced(text, pos)
            {
                args.push(inner);
                pos = end;
                continue;
            }
            // Failed to collect expected arg — stop.
            break;
        }

        (args, pos)
    }

    fn substitute(&self, body: &str, args: &[String]) -> String {
        let mut result = String::with_capacity(body.len() * 2);
        let mut i = 0;
        while i < body.len() {
            if body.get(i..).is_some_and(|s| s.starts_with('#'))
                && let Some(ch) = body.get(i + 1..).and_then(|s| s.chars().next())
                && let Some(n) = ch.to_digit(10)
            {
                let idx = n as usize;
                if idx > 0 && idx <= args.len() {
                    result.push_str(&args[idx - 1]);
                }
                i += 1 + ch.len_utf8();
                continue;
            }
            let c = body[i..].chars().next().unwrap();
            result.push(c);
            i += c.len_utf8();
        }
        result
    }
}

// Re-use the local helper for balanced braces.
fn extract_braced(text: &str, start: usize) -> Option<(String, usize)> {
    if start >= text.len() || !text[start..].starts_with('{') {
        return None;
    }
    let mut depth = 0;
    let mut content_start = None;
    for (offset, ch) in text[start..].char_indices() {
        let index = start + offset;
        if ch == '{' {
            depth += 1;
            if depth == 1 {
                content_start = Some(index + ch.len_utf8());
            }
        } else if ch == '}' {
            depth -= 1;
            if depth == 0 {
                let inner_start = content_start?;
                return Some((text[inner_start..index].to_string(), index + ch.len_utf8()));
            }
        }
    }
    None
}

/// Expand user-defined macros in `text` without structured parsing.
///
/// Used for intermediate artifact output and inspection.
pub fn expand_document(text: &str) -> String {
    let mut store = MacroStore::new();
    let stripped = store.extract_definitions(text);
    store.expand_all(&stripped)
}

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

    #[test]
    fn test_newcommand_no_args() {
        let mut store = MacroStore::new();
        let cleaned = store.extract_definitions("\\newcommand{\\hello}{Hello World} begin");
        assert_eq!(cleaned, " begin");
        assert_eq!(store.defs["hello"].body, "Hello World");
        assert_eq!(store.defs["hello"].param_count, 0);
    }

    #[test]
    fn test_newcommand_with_args() {
        let mut store = MacroStore::new();
        let cleaned = store.extract_definitions("\\newcommand{\\greet}[1]{Hello, #1!} text");
        assert_eq!(cleaned, " text");
        assert_eq!(store.defs["greet"].body, "Hello, #1!");
        assert_eq!(store.defs["greet"].param_count, 1);
    }

    #[test]
    fn test_def_with_params() {
        let mut store = MacroStore::new();
        let cleaned = store.extract_definitions("\\def\\foo#1#2{#1 loves #2} end");
        assert_eq!(cleaned, " end");
        assert_eq!(store.defs["foo"].body, "#1 loves #2");
        assert_eq!(store.defs["foo"].param_count, 2);
    }

    #[test]
    fn test_expand_no_args() {
        let mut store = MacroStore::new();
        store.extract_definitions("\\newcommand{\\hi}{Hi}");
        assert_eq!(store.expand_all("Say \\hi."), "Say Hi.");
    }

    #[test]
    fn test_expand_with_args() {
        let mut store = MacroStore::new();
        store.extract_definitions("\\newcommand{\\greet}[1]{Hello, #1!}");
        assert_eq!(store.expand_all("\\greet{World}"), "Hello, World!");
    }

    #[test]
    fn test_expand_def() {
        let mut store = MacroStore::new();
        store.extract_definitions("\\def\\twice#1{#1 #1}");
        assert_eq!(store.expand_all("\\twice{hello}"), "hello hello");
    }

    #[test]
    fn test_multiple_macros() {
        let mut store = MacroStore::new();
        store.extract_definitions("\\newcommand{\\a}{A}\\newcommand{\\b}{B}");
        assert_eq!(store.expand_all("\\a and \\b"), "A and B");
    }

    #[test]
    fn test_unknown_command_preserved() {
        let store = MacroStore::new();
        assert_eq!(store.expand_all("\\unknown{test}"), "\\unknown{test}");
    }

    #[test]
    fn test_renewcommand_overrides_definition() {
        // \renewcommand overrides an existing \newcommand definition
        let mut store = MacroStore::new();
        store.extract_definitions("\\newcommand{\\foo}{old}\\renewcommand{\\foo}{new}");
        assert_eq!(store.defs["foo"].body, "new");
        assert_eq!(store.expand_all("\\foo"), "new");
    }

    #[test]
    fn test_providecommand_defines_when_absent() {
        let mut store = MacroStore::new();
        store.extract_definitions("\\providecommand{\\foo}{bar}");
        assert_eq!(store.defs["foo"].body, "bar");
        assert_eq!(store.expand_all("\\foo"), "bar");
    }

    #[test]
    fn test_providecommand_does_not_override_existing() {
        // \providecommand must not overwrite a prior \newcommand definition.
        let mut store = MacroStore::new();
        store.extract_definitions("\\newcommand{\\foo}{first}\\providecommand{\\foo}{second}");
        assert_eq!(store.defs["foo"].body, "first", "providecommand must keep the existing definition");
        assert_eq!(store.expand_all("\\foo"), "first");
    }

    #[test]
    fn test_let_alias() {
        // \let\new\old makes \new expand to \old
        let mut store = MacroStore::new();
        store.extract_definitions("\\let\\oldsection\\section");
        assert_eq!(store.expand_all("\\oldsection"), "\\section");
    }

    #[test]
    fn test_let_alias_with_equals() {
        let mut store = MacroStore::new();
        store.extract_definitions("\\let\\foo=\\bar");
        assert_eq!(store.expand_all("\\foo"), "\\bar");
    }

    #[test]
    fn test_let_alias_to_macro() {
        // \let\new\old where \old is itself a macro: alias resolves first,
        // then the macro expands in a later round.
        let mut store = MacroStore::new();
        store.extract_definitions("\\newcommand{\\bar}{BAR}\\let\\foo\\bar");
        assert_eq!(store.expand_all("\\foo"), "BAR");
    }

    #[test]
    fn test_expand_multiple_args() {
        let mut store = MacroStore::new();
        store.extract_definitions("\\newcommand{\\add}[2]{#1 + #2}");
        assert_eq!(store.expand_all("\\add{a}{b}"), "a + b");
    }

    #[test]
    fn test_expand_document_helper() {
        let input = "\\newcommand{\\hi}{Hello}\\hi there";
        assert_eq!(expand_document(input), "Hello there");
    }

    #[test]
    fn test_nested_macro_expansion() {
        let mut store = MacroStore::new();
        store.extract_definitions("\\newcommand{\\inner}{X}\\newcommand{\\outer}{\\inner Y}");
        // \outer expands to \inner Y, then \inner expands to X Y
        let result = store.expand_all("\\outer");
        assert!(result.contains('X'), "nested expansion should produce X, got: {result}");
    }

    #[test]
    fn test_macro_with_optional_arg_not_stripped() {
        // Optional args in \newcommand are not currently stripped from source
        let mut store = MacroStore::new();
        store.extract_definitions("\\newcommand{\\foo}[1][default]{value: #1}");
        // The macro definition may or may not be extracted depending on parsing
        // Just verify the store doesn't crash
    }

    #[test]
    fn test_def_no_args() {
        let mut store = MacroStore::new();
        store.extract_definitions("\\def\\bar{BAR}");
        assert_eq!(store.expand_all("\\bar"), "BAR");
    }

    #[test]
    fn test_expand_preserves_non_macro_text() {
        let mut store = MacroStore::new();
        store.extract_definitions("\\newcommand{\\x}{X}");
        assert_eq!(store.expand_all("before \\x after"), "before X after");
    }
}