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
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
//! Command parsing — backslash commands and their arguments.

use super::{TexElement, TexParser};
use std::path::PathBuf;

impl TexParser {
    /// Parse a sectioning command (\part, \chapter, \section, \subsection, …, \subparagraph).
    ///
    /// A trailing `*` (e.g. `\section*{Title}`) is consumed and ignored,
    /// producing the same `TexElement::Section` as the numbered variant.
    /// Our renderer doesn't emit section numbers, so the star is a no-op
    /// but must not break parsing.
    pub(super) fn parse_section(&mut self, level: u8) -> Option<TexElement> {
        let cmd = match level {
            0 => "\\part",
            1 => "\\section",
            2 => "\\subsection",
            3 => "\\subsubsection",
            4 => "\\paragraph",
            5 => "\\subparagraph",
            6 => "\\chapter",
            _ => "\\section",
        };
        self.position += cmd.len();

        // Optional starred variant.
        if self.content[self.position..].starts_with('*') {
            self.position += 1;
        }

        self.skip_whitespace_and_comments();

        self.parse_braced_content().map(|title| TexElement::Section {
            level: level as usize,
            title: clean_title(&title),
        })
    }

    /// Parse a generic one-argument command (\title, \author, \date, …).
    pub(super) fn parse_command(&mut self, name: &str) -> Option<TexElement> {
        self.position += name.len() + 1;

        self.skip_whitespace_and_comments();

        self.parse_braced_content().map(|arg| TexElement::Command {
            name: name.to_string(),
            args: vec![arg],
        })
    }

    /// Parse `\texttt{arg}`, `\textbf{arg}`, `\textit{arg}`, or `\emph{arg}`.
    pub(super) fn parse_text_command(&mut self) -> Option<TexElement> {
        let remaining = &self.content[self.position..];

        let (cmd_name, cmd_len) = if remaining.starts_with("\\texttt{") {
            ("texttt", 7)
        } else if remaining.starts_with("\\textbf{") {
            ("textbf", 7)
        } else if remaining.starts_with("\\textit{") {
            ("textit", 7)
        } else if remaining.starts_with("\\emph{") {
            ("emph", 5)
        } else {
            return None;
        };

        self.position += cmd_len;

        self.parse_braced_content().map(|arg| TexElement::Command {
            name: cmd_name.to_string(),
            args: vec![arg],
        })
    }

    /// Parse `\includegraphics[…]{path}` with optional width/height.
    pub(super) fn parse_includegraphics(&mut self) -> Option<TexElement> {
        self.position += "\\includegraphics".len();
        self.skip_whitespace_and_comments();

        let mut width = None;
        let mut height = None;

        // Optional [width=...,height=...] arguments
        if self.position < self.content.len() && self.content[self.position..].starts_with('[') {
            self.position += 1;
            let opts = self.read_until(']');
            self.position += 1;

            for part in opts.split(',') {
                let part = part.trim();
                if let Some(val) = part.strip_prefix("width=") {
                    width = Some(val.trim().to_string());
                } else if let Some(val) = part.strip_prefix("height=") {
                    height = Some(val.trim().to_string());
                }
            }
        }

        self.skip_whitespace_and_comments();

        let path = self.parse_braced_content()?;
        Some(TexElement::Image {
            path,
            width,
            height,
        })
    }

    pub(super) fn parse_textcolor(&mut self) -> Option<TexElement> {
        self.position += "\\textcolor".len();
        self.skip_whitespace_and_comments();

        let color = self.parse_braced_content()?;
        self.skip_whitespace_and_comments();

        let text = self.parse_braced_content()?;
        Some(TexElement::ColoredText { color, text })
    }

    /// Parse `\cite{key1,key2}` into a citation element.
    pub(super) fn parse_cite(&mut self) -> Option<TexElement> {
        self.position += "\\cite".len();
        self.skip_whitespace_and_comments();

        let keys_str = self.parse_braced_content()?;
        let keys: Vec<String> = keys_str
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect();
        Some(TexElement::Citation { keys, kind: "cite".to_string() })
    }

    /// Parse `\nocite{key1,key2}` — adds entries to bibliography without printing text.
    pub(super) fn parse_nocite(&mut self) -> Option<TexElement> {
        self.position += "\\nocite".len();
        self.skip_whitespace_and_comments();
        let keys_str = self.parse_braced_content()?;
        let keys: Vec<String> = keys_str
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect();
        Some(TexElement::Citation { keys, kind: "nocite".to_string() })
    }

    /// Parse biblatex citation variants: `\textcite`, `\parencite`, `\footcite`,
    /// `\citeauthor`, `\citeyear`, `\citetitle`, `\fullcite`.
    pub(super) fn parse_cite_variant(&mut self, cmd_name: &str) -> Option<TexElement> {
        self.position += cmd_name.len();
        self.skip_whitespace_and_comments();
        let keys_str = self.parse_braced_content()?;
        let keys: Vec<String> = keys_str
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect();
        Some(TexElement::Citation { keys, kind: cmd_name[1..].to_string() })
    }

    /// Parse `\label{key}`.
    pub(super) fn parse_label(&mut self) -> Option<TexElement> {
        self.position += "\\label".len();
        self.skip_whitespace_and_comments();
        let key = self.parse_braced_content()?;
        Some(TexElement::Label { key })
    }

    /// Parse `\ref{key}`, `\eqref{key}`, `\autoref{key}`, `\nameref{key}`, `\cref{key}`, `\Cref{key}`.
    pub(super) fn parse_ref(&mut self) -> Option<TexElement> {
        let remaining = &self.content[self.position..];
        let cmd_len = [
            "\\eqref", "\\autoref", "\\nameref", "\\cref", "\\Cref", "\\ref",
        ]
        .iter()
        .find_map(|cmd| {
            if remaining.starts_with(cmd) {
                Some(cmd.len())
            } else {
                None
            }
        })
        .unwrap_or("\\ref".len());
        self.position += cmd_len;
        self.skip_whitespace_and_comments();
        let key = self.parse_braced_content()?;
        Some(TexElement::Ref { key })
    }

    /// Parse `\pageref{key}`.
    pub(super) fn parse_pageref(&mut self) -> Option<TexElement> {
        self.position += "\\pageref".len();
        self.skip_whitespace_and_comments();
        let key = self.parse_braced_content()?;
        Some(TexElement::PageRef { key })
    }

    /// Parse page-break commands: `\newpage`, `\clearpage`, `\pagebreak`.
    pub(super) fn parse_pagebreak(&mut self) -> Option<TexElement> {
        let name = if self.content[self.position..].starts_with("\\newpage") {
            self.position += "\\newpage".len();
            "newpage"
        } else if self.content[self.position..].starts_with("\\clearpage") {
            self.position += "\\clearpage".len();
            "clearpage"
        } else if self.content[self.position..].starts_with("\\pagebreak") {
            self.position += "\\pagebreak".len();
            "pagebreak"
        } else {
            "newpage"
        };
        Some(TexElement::Command {
            name: name.to_string(),
            args: vec![],
        })
    }

    /// Parse `\input{filename}` or `\input filename` and splice the
    /// referenced file inline.
    pub(super) fn parse_input(&mut self) -> Option<TexElement> {
        self.position += "\\input".len();
        let filename = if self.content[self.position..].starts_with('{') {
            self.position += 1;
            let name = self.read_until('}');
            self.position += 1; // skip closing brace
            name
        } else {
            self.skip_whitespace_and_comments();
            let start = self.position;
            let rest = &self.content[self.position..];
            let end = rest
                .find(|c: char| c.is_whitespace() || c == '\\' || c == '%' || c == '{')
                .unwrap_or(rest.len());
            self.position += end;
            self.content[start..self.position].to_string()
        };

        self.splice_file(&filename);
        None
    }

    /// Parse `\include{filename}` — like `\input` but with a page break
    /// before and after the included content (LaTeX semantics).
    pub(super) fn parse_include(&mut self) -> Option<TexElement> {
        self.position += "\\include{".len();
        let filename = self.read_until('}');
        self.position += 1; // skip closing brace

        let before = self.content[..self.position].to_string();
        let after = self.content[self.position..].to_string();
        self.content = format!("{}\\clearpage\n", before);
        let insert_pos = self.content.len();
        self.content = format!("{}\n\\clearpage\n{}", self.content, after);
        let saved = self.position;
        self.position = insert_pos;
        self.splice_file(&filename);
        self.position = saved + "\\clearpage\n".len();
        None
    }

    /// Resolve `filename` against base_dir, search_paths, and bare path,
    /// then splice its contents into `self.content` at the current position.
    fn splice_file(&mut self, filename: &str) {
        let mut candidates = Vec::new();
        if let Some(ref base) = self.base_dir {
            candidates.push(base.join(filename));
        }
        for dir in &self.search_paths {
            candidates.push(dir.join(filename));
        }
        candidates.push(PathBuf::from(filename));

        for mut path in candidates {
            if path.extension().is_none() {
                path.set_extension("tex");
            }
            if let Ok(content) = std::fs::read_to_string(&path) {
                let before = &self.content[..self.position];
                let after = &self.content[self.position..];
                self.content = format!("{}{}\n{}", before, content, after);
                break;
            }
        }
    }

    /// Parse `\vspace{length}`.
    pub(super) fn parse_vspace(&mut self) -> Option<TexElement> {
        self.position += "\\vspace{".len();
        let length = self.read_until('}');
        self.position += 1; // skip closing brace
        Some(TexElement::Command {
            name: "vspace".to_string(),
            args: vec![length],
        })
    }

    /// Parse `\underline{text}`.
    pub(super) fn parse_underline(&mut self) -> Option<TexElement> {
        self.position += "\\underline{".len();
        let text = self.read_until('}');
        self.position += 1; // skip closing brace
        Some(TexElement::Command {
            name: "underline".to_string(),
            args: vec![text],
        })
    }

    /// Parse `\footnote{text}`.
    pub(super) fn parse_footnote(&mut self) -> Option<TexElement> {
        self.position += "\\footnote{".len();
        let text = self.read_until('}');
        self.position += 1; // skip closing brace
        Some(TexElement::Footnote { text })
    }

    /// Parse `\caption{text}`.
    pub(super) fn parse_caption(&mut self) -> Option<TexElement> {
        self.position += "\\caption{".len();
        let text = self.read_until('}');
        self.position += 1; // skip closing brace
        Some(TexElement::Caption { text })
    }

    /// Parse `\url{link}`.
    pub(super) fn parse_url(&mut self) -> Option<TexElement> {
        self.position += "\\url{".len();
        let text = self.read_until('}');
        self.position += 1; // skip closing brace
        Some(TexElement::Command {
            name: "url".to_string(),
            args: vec![text],
        })
    }

    /// Parse `\verb<delim>text<delim>` or `\lstinline<delim>text<delim>`.
    /// The delimiter is the character immediately after the command name
    /// (any non-letter, non-whitespace character, commonly `|`, `!`, `+`, etc.).
    pub(super) fn parse_verb(&mut self) -> Option<TexElement> {
        let remaining = &self.content[self.position..];
        let cmd_len = if remaining.starts_with("\\lstinline") {
            "\\lstinline".len()
        } else {
            "\\verb".len()
        };

        self.position += cmd_len;

        // \verb* uses a star variant (visible spaces) — consume the *
        if self.position < self.content.len() && self.content[self.position..].starts_with('*') {
            self.position += 1;
        }

        if self.position >= self.content.len() {
            return None;
        }

        // Read the delimiter character (first char after \verb or \verb*)
        let delim = self.content[self.position..].chars().next()?;
        self.position += delim.len_utf8();

        // Read until the delimiter appears again
        let text = self.read_until(delim);
        self.position += delim.len_utf8(); // skip closing delimiter

        Some(TexElement::CodeBlock(text))
    }

    /// Parse `\href{url}{text}` (hyperref).
    pub(super) fn parse_href(&mut self) -> Option<TexElement> {
        self.position += "\\href{".len();
        let url = self.read_until('}');
        self.position += 1; // skip closing brace
        self.skip_whitespace_and_comments();
        let text = if self.content[self.position..].starts_with('{') {
            self.position += 1;
            let t = self.read_until('}');
            self.position += 1;
            t
        } else {
            String::new()
        };
        Some(TexElement::Command {
            name: "href".to_string(),
            args: vec![url, text],
        })
    }

    /// Parse `\raisebox{distance}{text}`.
    pub(super) fn parse_raisebox(&mut self) -> Option<TexElement> {
        self.position += "\\raisebox{".len();
        let distance = self.read_until('}');
        self.position += 1; // skip closing brace
        self.skip_whitespace_and_comments();
        let text = if self.content[self.position..].starts_with('{') {
            self.position += 1;
            let t = self.read_until('}');
            self.position += 1;
            t
        } else {
            String::new()
        };
        Some(TexElement::Command {
            name: "raisebox".to_string(),
            args: vec![distance, text],
        })
    }

    /// Parse `\rotatebox{angle}{text}`.
    pub(super) fn parse_rotatebox(&mut self) -> Option<TexElement> {
        self.position += "\\rotatebox{".len();
        let angle = self.read_until('}');
        self.position += 1; // skip closing brace
        self.skip_whitespace_and_comments();
        let text = if self.content[self.position..].starts_with('{') {
            self.position += 1;
            let t = self.read_until('}');
            self.position += 1;
            t
        } else {
            String::new()
        };
        Some(TexElement::Command {
            name: "rotatebox".to_string(),
            args: vec![angle, text],
        })
    }

    /// Parse `\scalebox{factor}{text}`.
    pub(super) fn parse_scalebox(&mut self) -> Option<TexElement> {
        self.position += "\\scalebox{".len();
        let factor = self.read_until('}');
        self.position += 1; // skip closing brace
        self.skip_whitespace_and_comments();
        let text = if self.content[self.position..].starts_with('{') {
            self.position += 1;
            let t = self.read_until('}');
            self.position += 1;
            t
        } else {
            String::new()
        };
        Some(TexElement::Command {
            name: "scalebox".to_string(),
            args: vec![factor, text],
        })
    }

    /// Parse `\colorbox{color}{text}`.
    pub(super) fn parse_colorbox(&mut self) -> Option<TexElement> {
        self.position += "\\colorbox{".len();
        let color = self.read_until('}');
        self.position += 1; // skip closing brace
        self.skip_whitespace_and_comments();
        let text = if self.content[self.position..].starts_with('{') {
            self.position += 1;
            let t = self.read_until('}');
            self.position += 1;
            t
        } else {
            String::new()
        };
        Some(TexElement::Command {
            name: "colorbox".to_string(),
            args: vec![color, text],
        })
    }

    /// Parse `\fcolorbox{framecolor}{backcolor}{text}`.
    pub(super) fn parse_fcolorbox(&mut self) -> Option<TexElement> {
        self.position += "\\fcolorbox{".len();
        let frame = self.read_until('}');
        self.position += 1; // skip closing brace
        self.skip_whitespace_and_comments();
        let back = if self.content[self.position..].starts_with('{') {
            self.position += 1;
            let b = self.read_until('}');
            self.position += 1;
            b
        } else {
            String::new()
        };
        self.skip_whitespace_and_comments();
        let text = if self.content[self.position..].starts_with('{') {
            self.position += 1;
            let t = self.read_until('}');
            self.position += 1;
            t
        } else {
            String::new()
        };
        Some(TexElement::Command {
            name: "fcolorbox".to_string(),
            args: vec![frame, back, text],
        })
    }

    /// Parse any command of the form `\name{text}` into a [`TexElement::Command`].
    pub(super) fn parse_simple_braced_command(
        &mut self,
        name: &str,
        prefix_len: usize,
    ) -> Option<TexElement> {
        self.position += prefix_len;
        let text = self.read_until('}');
        self.position += 1; // skip closing brace
        Some(TexElement::Command {
            name: name.to_string(),
            args: vec![text],
        })
    }

    /// Parse `\resizebox{width}{height}{content}`.
    pub(super) fn parse_resizebox(&mut self) -> Option<TexElement> {
        self.position += "\\resizebox".len();
        self.skip_whitespace_and_comments();
        let width = self.parse_braced_content()?;
        self.skip_whitespace_and_comments();
        let height = self.parse_braced_content()?;
        self.skip_whitespace_and_comments();
        let content = self.parse_braced_content()?;
        Some(TexElement::Command {
            name: "resizebox".to_string(),
            args: vec![width, height, content],
        })
    }

    /// Parse `\rule{width}{height}` for horizontal rules or vertical struts.
    pub(super) fn parse_rule(&mut self) -> Option<TexElement> {
        self.position += "\\rule{".len();
        let width = self.read_until('}');
        self.position += 1; // skip closing brace
        self.skip_whitespace_and_comments();
        let height = if self.content[self.position..].starts_with('{') {
            self.position += 1;
            let h = self.read_until('}');
            self.position += 1;
            h
        } else {
            String::new()
        };
        Some(TexElement::Command {
            name: "rule".to_string(),
            args: vec![width, height],
        })
    }

    /// Skip past an unknown command so parsing can continue.
    pub(super) fn parse_unknown_command(&mut self) {
        if self.position >= self.content.len() {
            return;
        }

        self.position += 1;

        while self.position < self.content.len() {
            let remaining = &self.content[self.position..];
            let Some(ch) = remaining.chars().next() else {
                break;
            };

            if ch.is_alphabetic() || ch == '*' {
                self.position += ch.len_utf8();
            } else {
                break;
            }
        }

        self.skip_whitespace_and_comments();
    }

    /// Parse `\parbox[alignment]{width}{text}`.
    pub(super) fn parse_parbox(&mut self) -> Option<TexElement> {
        self.position += "\\parbox".len();
        self.skip_whitespace_and_comments();

        // Optional [alignment]
        if self.position < self.content.len() && self.content[self.position..].starts_with('[') {
            self.position += 1;
            let _ = self.read_until(']');
            self.position += 1;
            self.skip_whitespace_and_comments();
        }

        // {width}
        if self.position < self.content.len() && self.content[self.position..].starts_with('{') {
            let _ = self.parse_braced_content();
            self.skip_whitespace_and_comments();
        }

        // {text}
        let text = if self.position < self.content.len() && self.content[self.position..].starts_with('{') {
            self.parse_braced_content().unwrap_or_default()
        } else {
            String::new()
        };
        Some(TexElement::Command {
            name: "parbox".to_string(),
            args: vec![text],
        })
    }

    /// Parse `\makebox[width][position]{text}`.
    pub(super) fn parse_makebox(&mut self) -> Option<TexElement> {
        self.position += "\\makebox".len();
        self.skip_whitespace_and_comments();

        // Optional [width]
        if self.position < self.content.len() && self.content[self.position..].starts_with('[') {
            self.position += 1;
            let _ = self.read_until(']');
            self.position += 1;
            self.skip_whitespace_and_comments();
        }

        // Optional [position]
        if self.position < self.content.len() && self.content[self.position..].starts_with('[') {
            self.position += 1;
            let _ = self.read_until(']');
            self.position += 1;
            self.skip_whitespace_and_comments();
        }

        // {text}
        let text = if self.position < self.content.len() && self.content[self.position..].starts_with('{') {
            self.parse_braced_content().unwrap_or_default()
        } else {
            String::new()
        };
        Some(TexElement::Command {
            name: "makebox".to_string(),
            args: vec![text],
        })
    }

    /// Parse `\multicolumn{n}{align}{content}`.
    pub(super) fn parse_multicolumn(&mut self) -> Option<TexElement> {
        self.position += "\\multicolumn".len();
        self.skip_whitespace_and_comments();

        let n = self.parse_braced_content().unwrap_or_default();
        self.skip_whitespace_and_comments();
        let align = self.parse_braced_content().unwrap_or_default();
        self.skip_whitespace_and_comments();
        let content = self.parse_braced_content().unwrap_or_default();

        Some(TexElement::Command {
            name: "multicolumn".to_string(),
            args: vec![n, align, content],
        })
    }
}

/// Clean a section title: keep the TeX form of
/// `\texorpdfstring{tex}{pdf}` (hyperref), drop accents markers are
/// already composed by the parser; collapse leftover `~` to spaces.
pub(super) fn clean_title(title: &str) -> String {
    let mut out = String::with_capacity(title.len());
    let mut i = 0usize;
    while i < title.len() {
        match title[i..].find("\\texorpdfstring") {
            Some(rel) => {
                out.push_str(&title[i..i + rel]);
                let mut j = i + rel + "\\texorpdfstring".len();
                let mut kept = String::new();
                for _ in 0..2 {
                    let before_trim = &title[j..];
                    let trimmed = before_trim.trim_start();
                    j += before_trim.len() - trimmed.len();
                    if let Some(after) = trimmed.strip_prefix('{') {
                        if let Some(end) = after.find('}') {
                            if kept.is_empty() {
                                kept = after[..end].to_string();
                            }
                            j += 1 + end + 1;
                            continue;
                        }
                    }
                    break;
                }
                out.push_str(&kept);
                i = j;
            }
            None => {
                out.push_str(&title[i..]);
                break;
            }
        }
    }
    out.replace('~', " ")
}

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

    #[test]
    fn texorpdfstring_keeps_tex_form() {
        assert_eq!(clean_title(r"Intro\texorpdfstring{~x}{ y}"), "Intro x");
        assert_eq!(clean_title(r"\texorpdfstring{A}{B}"), "A");
        assert_eq!(clean_title("plain"), "plain");
        assert_eq!(clean_title(r"a~b"), "a b");
    }
}