Skip to main content

flm_core/stdlib/backends/latex/
escape.rs

1//! The escaping of document text for LaTeX: ten special ASCII characters are
2//! written as commands, every non-ASCII character is written according to
3//! one of two **Unicode modes** through the Unicode-to-LaTeX table of
4//! [`untechxt`], with per-character overrides, and the [`Declared`] record
5//! collects what the style file must declare because of the escaped text.
6//!
7//! Escaping is the only transformation document text undergoes on its way
8//! into LaTeX output. It happens where the bytes are written (in the
9//! emitter, through the sink's `text` method,
10//! [`super::sink::LatexSink::text`]) and never earlier, so the lowered tree
11//! holds the characters the document denotes and a text node is escaped
12//! exactly once. [`escape_into`] does the escaping; it is public so that a
13//! test or a host can see exactly what the sink writes. The escaping is
14//! configured by an [`EscapeConfig`], which the `latex-recomposed` backend
15//! builds from its render options `unicode` and `unicode_overrides`
16//! ([`LatexRecomposedRenderOptions`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions)).
17//!
18//! # The special characters
19//!
20//! Ten ASCII characters mean something to LaTeX and are written as a
21//! command: `$ & # _ %` as `\$ \& \# \_ \%`, and `^ { } \ ~` as
22//! `\textasciicircum{}`, `\{`, `\}`, `\textbackslash{}`,
23//! `\textasciitilde{}` ([`escape_special`]). The caret is written as
24//! `\textasciicircum{}` and never as `\^`: `\^` is the circumflex accent
25//! command, which takes the character after it as its argument, so `2^10`
26//! written as `2\^10` would set an accent over the `1` instead of printing
27//! a caret. Any of the ten can reach a text node: a literal-character command
28//! such as `\{` or `\%` lowers to the character it represents, and a
29//! recovered parse or a user definition's template can put any of them into
30//! text. This escaping keeps the recomposed LaTeX compiling regardless of
31//! what reaches a text node. Where an author wrote a literal-character
32//! command, the recomposition rule of the `literals` feature writes the
33//! author's spelling instead, so the escaping applies only where no such rule
34//! did. Every other ASCII
35//! character, newlines and tabs included, is written as it is.
36//!
37//! # The Unicode modes
38//!
39//! Every non-ASCII character has a *spelling*: the LaTeX that prints it
40//! (`\'e` for `é`, `\ensuremath{\alpha}` for `α`), from the Unicode-to-LaTeX
41//! table of [`untechxt`] ([`spelling_for`]) unless an override replaces it.
42//! [`UnicodeMode`] says what is written for such a character:
43//!
44//! - [`Declare`](UnicodeMode::Declare), the default: the character itself,
45//!   as UTF-8, and the style file declares it once with
46//!   `\newunicodechar{<char>}{<spelling>}` so that the document compiles on
47//!   any engine. The recomposed LaTeX stays what the author typed. The characters
48//!   to declare, each with its spelling, are collected in [`Declared`].
49//! - [`Replace`](UnicodeMode::Replace): the spelling, in place, protected
50//!   exactly as untechxt's standard strategy for text output protects a value
51//!   ([`StandardProtection`]): braced when it ends with a command name, so that
52//!   it cannot merge with the letters after it.
53//!
54//! In both modes, what a spelling needs in the preamble is recorded in the
55//! [`Declared`] record, so that the style file holds it. The Unicode-to-LaTeX
56//! table gives, for each entry, what it needs as a set of *chunks of the
57//! table* ([`PreambleNeeds`], made of [`Chunk`](untechxt::preamble::Chunk)
58//! values; see [the packages of the Unicode-to-LaTeX
59//! table](super::packages#the-packages-of-the-unicode-to-latex-table)). A
60//! chunk of the table is either a package with the options it is loaded with
61//! (`\ensuremath{\mathbb{C}}` needs `amssymb`, `\ensuremath{\mathds{1}}` needs
62//! `dsfont`, a Cyrillic letter needs `fontenc` with the encoding that declares
63//! its command) or a block of declarations no package makes
64//! (`\ensuremath{\UnxTBbold{0}}` needs the `bbold` family declared as a math
65//! alphabet). [`Declared::packages`] returns the first kind as package
66//! identifiers and [`Declared::pieces`] the second as identifiers of
67//! definition pieces ([`LatexPreambleDef`](super::LatexPreambleDef)).
68//! [`packages::is_package_chunk`] says which of the two a chunk is: a package
69//! under every engine, or one block of declarations. A
70//! package chunk's request can differ by engine — `fontenc` loads `T2A`
71//! beside `T1` under pdfLaTeX and beside `TU` under LuaLaTeX and XeLaTeX — and
72//! the style file's package block writes such lines inside a test of the
73//! engine ([`style_body`](super::style::style_body)); the escaped text itself
74//! is the same under every engine.
75//!
76//! A character no spelling is known for is *unknown*: under `Declare` it is
77//! written through as it is, under `Replace` it is replaced by a spelling
78//! that shows its code point
79//! (`\ensuremath{\langle}\texttt{U+0E18}\ensuremath{\rangle}`,
80//! [`unknown_unihex`]). In both modes [`escape_into`] returns it, and the
81//! `latex-recomposed` emitter reports each unknown character once per
82//! lowered tree as a Warning
83//! ([`UnknownCharacter`](crate::stdlib::backends::latex_recomposed::UnknownCharacter)).
84//!
85//! # Overrides
86//!
87//! An override replaces the table's spelling for one character, in either
88//! mode: the **user's overrides** in [`EscapeConfig::overrides`], a map from a
89//! character to the spelling to write for it. Such a spelling is written as
90//! the user gave it and nothing is recorded for it here: the user provides
91//! what it needs in the preamble (for example through the render option
92//! `extra_packages`), not the style file. This library corrects no spelling
93//! on its own: a spelling the Unicode-to-LaTeX table gets wrong is corrected in
94//! that table.
95//!
96//! Text is composed to Unicode's canonical composed form ([`nfc`]) before any
97//! of this, so that a letter followed by a combining accent is the accented
98//! letter the table knows and the declared character is the composed one.
99//!
100//! Mathematics and verbatim content never pass through here: they are
101//! written byte for byte in every mode.
102//!
103//! # Addresses
104//!
105//! An address — the target of a link to somewhere outside the document — is
106//! not document text, and is written through an escaping of its own,
107//! [`escape_url`]: it is handed to `hyperref`'s `\href` inside an ordinary
108//! argument of one of the `href` feature's LaTeX hooks (`\flmHref`,
109//! `\flmUrl`, `\flmEmail`), so the three characters LaTeX would otherwise read as
110//! syntax there are each preceded by a backslash, and every other character,
111//! non-ASCII ones included, is written as it is.
112
113use std::collections::{BTreeMap, BTreeSet};
114
115use untechxt::builtin::DEFAULT_TABLE;
116use untechxt::lookuptable::LookupTable;
117use untechxt::normalizer::nfc;
118use untechxt::preamble::{PreambleNeeds, Profile};
119use untechxt::protection::{
120    MacroNameProtection, ProtectInput, ReplacementProtection, ReplacementProtectionHint,
121    StandardProtection,
122};
123use untechxt::report::NoReport;
124use untechxt::unknown_unihex;
125use crate::model::names::Name;
126
127use super::{packages, preamble};
128
129/// What is written for a non-ASCII character that has a spelling (the LaTeX
130/// that prints it, [`spelling_for`]).
131///
132/// See [the module documentation](self) for the two modes; the default is
133/// `Declare`. The `latex-recomposed` backend takes the mode from its render
134/// option `unicode`, written `declare` or `replace` in settings.
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Deserialize)]
136#[derive(schemars::JsonSchema)]
137#[serde(rename_all = "kebab-case")]
138pub enum UnicodeMode {
139    /// The character itself, as UTF-8, declared once in the style file.
140    #[default]
141    Declare,
142    /// The spelling, in place.
143    Replace,
144}
145
146impl UnicodeMode {
147    /// The mode's stable name: `declare` or `replace`.
148    pub fn as_str(self) -> &'static str {
149        match self {
150            UnicodeMode::Declare => "declare",
151            UnicodeMode::Replace => "replace",
152        }
153    }
154
155    /// The mode of a stable name, if any.
156    pub fn parse(name: &str) -> Option<UnicodeMode> {
157        match name {
158            "declare" => Some(UnicodeMode::Declare),
159            "replace" => Some(UnicodeMode::Replace),
160            _ => None,
161        }
162    }
163}
164
165/// How document text is escaped: the Unicode mode and the user's overrides.
166/// A [`LatexSink`](super::LatexSink) escapes all the text it writes under one
167/// configuration.
168#[derive(Debug, Clone, PartialEq, Eq, Default)]
169pub struct EscapeConfig {
170    /// What is written for a non-ASCII character.
171    pub mode: UnicodeMode,
172    /// The user's spelling for a character, replacing the Unicode-to-LaTeX
173    /// table's, in either mode. Only a non-ASCII character
174    /// is looked up; an entry for an ASCII character is ignored, since the
175    /// ten special characters are escaped and the rest of ASCII is written
176    /// directly.
177    pub overrides: BTreeMap<char, String>,
178}
179
180impl EscapeConfig {
181    /// The configuration under `mode` with no overrides.
182    pub fn new(mode: UnicodeMode) -> EscapeConfig {
183        EscapeConfig { mode, overrides: BTreeMap::new() }
184    }
185
186    /// The same configuration with one more override: `ch` is spelled
187    /// `spelling`.
188    pub fn with_override(mut self, ch: char, spelling: impl Into<String>) -> EscapeConfig {
189        self.overrides.insert(ch, spelling.into());
190        self
191    }
192
193    /// The same configuration with the given overrides added.
194    pub fn with_overrides(mut self, overrides: BTreeMap<char, String>) -> EscapeConfig {
195        self.overrides.extend(overrides);
196        self
197    }
198}
199
200/// The ten special characters and their escaped spellings, in the order
201/// `$ & # ^ _ % { } \ ~`.
202pub const SPECIALS: [(char, &str); 10] = [
203    ('$', "\\$"),
204    ('&', "\\&"),
205    ('#', "\\#"),
206    ('^', "\\textasciicircum{}"),
207    ('_', "\\_"),
208    ('%', "\\%"),
209    ('{', "\\{"),
210    ('}', "\\}"),
211    ('\\', "\\textbackslash{}"),
212    ('~', "\\textasciitilde{}"),
213];
214
215/// The escaped spelling of a special character, or `None` for any other
216/// character.
217///
218/// # Examples
219///
220/// ```
221/// use flm_core::stdlib::backends::latex::escape::escape_special;
222///
223/// assert_eq!(escape_special('%'), Some("\\%"));
224/// assert_eq!(escape_special('^'), Some("\\textasciicircum{}"));
225/// assert_eq!(escape_special('\\'), Some("\\textbackslash{}"));
226/// assert_eq!(escape_special('a'), None);
227/// ```
228pub fn escape_special(ch: char) -> Option<&'static str> {
229    SPECIALS.iter().find(|(special, _)| *special == ch).map(|(_, spelling)| *spelling)
230}
231
232/// The characters [`escape_url`] precedes with a backslash: `#`, `%` and
233/// `\`.
234///
235/// These are the characters a LaTeX argument cannot hold as themselves — a
236/// parameter marker, a comment and an escape — and which `hyperref`'s `\href`
237/// reads back as the character they stand for, in its address and in the
238/// argument of `\nolinkurl`, when they are written `\#`, `\%` and `\\`. Braces
239/// need no escaping: an address the parser read without an error holds its
240/// braces balanced, and `\href` keeps a balanced pair as it is, where `\{`
241/// would reach the address as a backslash and a brace. (After a missing
242/// closing brace, which the parser reports, the address it recovers may hold
243/// an unbalanced one, and the LaTeX written from it does not compile.) The other special characters
244/// of document text (`$ & ^ _ ~`) are written as they are: `\href` takes them
245/// as the characters they are.
246pub const URL_SPECIALS: [char; 3] = ['#', '%', '\\'];
247
248/// An address written as the argument of one of the LaTeX family's hyperlink
249/// hooks, `\flmHref`, `\flmUrl` and `\flmEmail`: every character of
250/// [`URL_SPECIALS`] preceded by a backslash, every other character as it is.
251///
252/// It is the only escaping of an address in this family. `\href` reads the
253/// three escaped characters back as themselves, and so do `\flmUrl` and
254/// `\flmEmail` when they derive the displayed text from the address: they drop
255/// the escaping backslashes before they remove a leading `http://`,
256/// `https://` or `mailto:` and the trailing run of the characters `/`, `#`
257/// and `?`. The three hooks
258/// are defined by the `href` feature's definition piece
259/// ([`href::latex`](crate::stdlib::features::href::latex)).
260///
261/// # Examples
262///
263/// ```
264/// use flm_core::stdlib::backends::latex::escape::escape_url;
265///
266/// assert_eq!(escape_url("https://x.org/a%20b#c"), "https://x.org/a\\%20b\\#c");
267/// assert_eq!(escape_url("x.org/{a}_b~c\\d"), "x.org/{a}_b~c\\\\d");
268/// ```
269pub fn escape_url(address: &str) -> String {
270    let mut out = String::with_capacity(address.len());
271    for ch in address.chars() {
272        if URL_SPECIALS.contains(&ch) {
273            out.push('\\');
274        }
275        out.push(ch);
276    }
277    out
278}
279
280/// How a spelling the style file declares is written: with nothing around it
281/// (`\textemdash`); the argument of `\newunicodechar` is a group of its own.
282const DECLARE_NAMES: MacroNameProtection = MacroNameProtection::NoProtection;
283
284/// How a spelling written in place under `Replace` mode is kept from merging
285/// with the letters after it: braced when it ends with a command name
286/// (`{\textemdash}`), which is untechxt's standard protection for text.
287const REPLACE_NAMES: MacroNameProtection = MacroNameProtection::BracesAround;
288
289/// Appends `encoded` to `out` as untechxt's standard strategy for text output
290/// ([`StandardProtection::text_mode`]) writes a value under the macro-name
291/// protection `names`: wrapped in `\ensuremath{…}` when `hint` says the value
292/// is valid in math mode alone, and otherwise as it is, with `names` applied
293/// when it ends with a command name.
294fn write_spelling(
295    out: &mut String,
296    encoded: &str,
297    hint: ReplacementProtectionHint,
298    names: MacroNameProtection,
299) {
300    let strategy = StandardProtection { protect_names: names, ..StandardProtection::text_mode() };
301    // A `String` takes every write, so the strategy cannot fail into one.
302    let _ = strategy.write_protected(out, &mut NoReport, ProtectInput::new(encoded, hint));
303}
304
305/// The spelling of a non-ASCII character under `config`, with what it needs in
306/// the preamble: the user's override, else the Unicode-to-LaTeX table's
307/// spelling; `None` when neither knows the character (an *unknown* character).
308///
309/// The spelling is what the style file declares, and what `Replace` mode
310/// protects before writing: the table's LaTeX wrapped for text where it is
311/// valid in math mode alone (`\ensuremath{\alpha}`) and as it is otherwise
312/// (`\'e`, `\textemdash`), with nothing around it; an override exactly as the
313/// user gave it. What it needs is the table entry's [`Profile`] (what a
314/// document must have in its preamble to print it), or `None` for a spelling
315/// the LaTeX kernel prints by itself and for a user's override, whose needs
316/// the user provides. The character is looked up as given; [`escape_into`]
317/// composes its text first.
318///
319/// # Examples
320///
321/// ```
322/// use flm_core::stdlib::backends::latex::escape::{EscapeConfig, UnicodeMode, spelling_for};
323///
324/// let config = EscapeConfig::new(UnicodeMode::Replace).with_override('α', "\\alpha");
325/// assert_eq!(spelling_for('é', &config).unwrap().0, "\\'e");
326/// assert_eq!(spelling_for('α', &config).unwrap(), (String::from("\\alpha"), None));
327/// assert_eq!(spelling_for('𝟙', &config).unwrap().0, "\\ensuremath{\\mathds{1}}");
328/// assert_eq!(spelling_for('ธ', &config), None);
329/// ```
330pub fn spelling_for(ch: char, config: &EscapeConfig) -> Option<(String, Option<&'static Profile>)> {
331    if let Some(spelling) = config.overrides.get(&ch) {
332        return Some((spelling.clone(), None));
333    }
334    DEFAULT_TABLE.lookup(ch).map(|entry| {
335        let mut spelling = String::new();
336        write_spelling(&mut spelling, entry.encoded, entry.hint, DECLARE_NAMES);
337        (spelling, entry.needs)
338    })
339}
340
341/// What the style file must declare because of the text escaped so far: the
342/// characters written through under `Declare` mode, each with the spelling
343/// to declare it with, and what the spellings written in either mode need in
344/// the preamble.
345///
346/// One record accumulates across every text the emitter writes for one tree;
347/// records of several trees are joined with [`merge`](Self::merge). The
348/// characters are in character order and the chunks in the order first
349/// needed, and what the style file reads of the record
350/// ([`packages`](Self::packages), [`pieces`](Self::pieces)) is sorted, so the
351/// style file built from it is the same regardless of the order in which the
352/// texts were escaped.
353#[derive(Debug, Clone, PartialEq, Eq, Default)]
354pub struct Declared {
355    chars: BTreeMap<char, String>,
356    needs: PreambleNeeds,
357}
358
359impl Declared {
360    /// An empty record.
361    pub fn new() -> Declared {
362        Declared::default()
363    }
364
365    /// The characters to declare, each with its spelling, in character
366    /// order. Empty unless `Declare` mode wrote a non-ASCII character that
367    /// has a spelling.
368    pub fn chars(&self) -> &BTreeMap<char, String> {
369        &self.chars
370    }
371
372    /// What the spellings written or declared need in the preamble, as the
373    /// Unicode-to-LaTeX table states it ([`PreambleNeeds`]). A user's override
374    /// contributes nothing here: the user requests what it needs separately.
375    pub fn needs(&self) -> &PreambleNeeds {
376        &self.needs
377    }
378
379    /// The package identifiers the escaped text needs, in identifier order:
380    /// one per chunk of [`needs`](Self::needs) that is a **package**
381    /// ([`packages::is_package_chunk`]), under the identifier
382    /// [`packages::chunk_package_id`] gives the chunk's identifier, plus
383    /// [`packages::NEWUNICODECHAR`] whenever a character is declared, since
384    /// declaring one is what `\newunicodechar` is for.
385    ///
386    /// Every identifier here resolves to the package definitions derived from
387    /// the chunk ([`packages::chunk_packages`]), one per set of engines the
388    /// chunk differs between, and the style file writes its `\RequirePackage`
389    /// lines from those definitions. A chunk that is declarations rather than
390    /// a package is a definition piece instead: see [`pieces`](Self::pieces).
391    pub fn packages(&self) -> BTreeSet<Name> {
392        let mut ids: BTreeSet<Name> = self
393            .needs
394            .chunks()
395            .filter(|chunk| packages::is_package_chunk(chunk))
396            .map(|chunk| packages::chunk_package_id(chunk.id()))
397            .collect();
398        if !self.chars.is_empty() {
399            ids.insert(Name::from(packages::NEWUNICODECHAR));
400        }
401        ids
402    }
403
404    /// The definition-piece identifiers the escaped text needs, in identifier
405    /// order: one per chunk of [`needs`](Self::needs) that is
406    /// **declarations** no package makes ([`packages::is_package_chunk`]),
407    /// under the identifier [`preamble::chunk_piece_id`] gives the chunk's
408    /// identifier.
409    ///
410    /// Every identifier here resolves to one of the family's standard
411    /// definition pieces ([`preamble::chunk_pieces`]), which the style file
412    /// writes after its package requests, so that the packages the
413    /// declarations call into are already loaded.
414    pub fn pieces(&self) -> BTreeSet<Name> {
415        self.needs
416            .chunks()
417            .filter(|chunk| !packages::is_package_chunk(chunk))
418            .map(|chunk| preamble::chunk_piece_id(chunk.id()))
419            .collect()
420    }
421
422    /// Whether nothing was recorded.
423    pub fn is_empty(&self) -> bool {
424        self.chars.is_empty() && self.needs.is_empty()
425    }
426
427    /// Adds everything `other` recorded. A character both records declare
428    /// keeps this record's spelling; since every record of one render
429    /// escapes under one configuration, the two spellings are the same.
430    pub fn merge(&mut self, other: &Declared) {
431        for (ch, spelling) in &other.chars {
432            self.chars.entry(*ch).or_insert_with(|| spelling.clone());
433        }
434        self.needs.merge(&other.needs);
435    }
436
437    /// Records `needs`, when the spelling needed anything.
438    fn include(&mut self, needs: Option<&Profile>) {
439        if let Some(needs) = needs {
440            self.needs.include(needs);
441        }
442    }
443
444    fn declare(&mut self, ch: char, spelling: &str, needs: Option<&Profile>) {
445        self.include(needs);
446        self.chars.entry(ch).or_insert_with(|| String::from(spelling));
447    }
448}
449
450/// Appends `text` to `out`, escaped for LaTeX under `config`, recording in
451/// `declared` what the style file must declare, and returns the unknown
452/// characters found (each once, in order of first occurrence) for the caller
453/// to report. See [the module documentation](self) for the rules.
454///
455/// # Examples
456///
457/// ```
458/// use flm_core::stdlib::backends::latex::escape::{
459///     Declared, EscapeConfig, UnicodeMode, escape_into,
460/// };
461///
462/// let mut out = String::new();
463/// let mut declared = Declared::new();
464/// let unknown = escape_into(
465///     &mut out,
466///     "50% of café",
467///     &EscapeConfig::new(UnicodeMode::Replace),
468///     &mut declared,
469/// );
470/// assert_eq!(out, "50\\% of caf\\'e");
471/// assert!(unknown.is_empty());
472/// assert!(declared.chars().is_empty());
473///
474/// let mut out = String::new();
475/// escape_into(&mut out, "café", &EscapeConfig::new(UnicodeMode::Declare), &mut declared);
476/// assert_eq!(out, "café");
477/// assert_eq!(declared.chars().get(&'é').map(String::as_str), Some("\\'e"));
478/// ```
479pub fn escape_into(
480    out: &mut String,
481    text: &str,
482    config: &EscapeConfig,
483    declared: &mut Declared,
484) -> Vec<char> {
485    let composed = nfc(text);
486    let mut unknown: Vec<char> = Vec::new();
487    for ch in composed.chars() {
488        if let Some(spelling) = escape_special(ch) {
489            out.push_str(spelling);
490        } else if ch.is_ascii() {
491            out.push(ch);
492        } else if let Some((spelling, needs)) = spelling_for(ch, config) {
493            match config.mode {
494                UnicodeMode::Declare => {
495                    out.push(ch);
496                    declared.declare(ch, &spelling, needs);
497                }
498                UnicodeMode::Replace => {
499                    let hint = ReplacementProtectionHint::any_mode(&spelling);
500                    write_spelling(out, &spelling, hint, REPLACE_NAMES);
501                    declared.include(needs);
502                }
503            }
504        } else {
505            if !unknown.contains(&ch) {
506                unknown.push(ch);
507            }
508            match config.mode {
509                UnicodeMode::Declare => out.push(ch),
510                UnicodeMode::Replace => out.push_str(&unknown_unihex(ch)),
511            }
512        }
513    }
514    unknown
515}
516
517/// [`escape_into`] into a fresh string, for the callers that want the
518/// escaped text alone; the unknown characters are dropped, so use
519/// [`escape_into`] where they must be reported.
520pub fn escape(text: &str, config: &EscapeConfig, declared: &mut Declared) -> String {
521    let mut out = String::new();
522    escape_into(&mut out, text, config, declared);
523    out
524}
525
526#[cfg(test)]
527mod tests {
528    use super::*;
529
530    /// The study's probe string: an accented letter, a dash, curly quotes,
531    /// a vulgar fraction, a relation, a Greek letter.
532    const PROBE: &str = "Café — naïve “quotes” ½ ≤ α";
533
534    fn run(text: &str, config: &EscapeConfig) -> (String, Declared, Vec<char>) {
535        let mut out = String::new();
536        let mut declared = Declared::new();
537        let unknown = escape_into(&mut out, text, config, &mut declared);
538        (out, declared, unknown)
539    }
540
541    #[test]
542    fn the_ten_specials_are_escaped_and_other_ascii_passes_through() {
543        let (out, declared, unknown) =
544            run("$&#^_%{}\\~ a-z 0-9 \"'<>|\n\t", &EscapeConfig::new(UnicodeMode::Replace));
545        assert_eq!(
546            out,
547            "\\$\\&\\#\\textasciicircum{}\\_\\%\\{\\}\\textbackslash{}\\textasciitilde{} \
548             a-z 0-9 \"'<>|\n\t"
549        );
550        assert!(declared.is_empty());
551        assert!(unknown.is_empty());
552    }
553
554    #[test]
555    fn replace_mode_writes_protected_spellings_in_place() {
556        let (out, declared, unknown) = run(PROBE, &EscapeConfig::new(UnicodeMode::Replace));
557        assert_eq!(
558            out,
559            "Caf\\'e {\\textemdash} na\\\"ive {\\textquotedblleft}quotes{\\textquotedblright} \
560             {\\textonehalf} \\ensuremath{\\leq} \\ensuremath{\\alpha}"
561        );
562        assert!(unknown.is_empty());
563        assert!(declared.chars().is_empty());
564        // Every spelling here is one the LaTeX kernel prints by itself.
565        assert!(declared.needs().is_empty());
566        assert!(declared.packages().is_empty());
567    }
568
569    #[test]
570    fn declare_mode_writes_the_characters_and_records_their_spellings() {
571        let (out, declared, unknown) = run(PROBE, &EscapeConfig::new(UnicodeMode::Declare));
572        assert_eq!(out, PROBE);
573        assert!(unknown.is_empty());
574        let chars: Vec<(char, &str)> =
575            declared.chars().iter().map(|(c, s)| (*c, s.as_str())).collect();
576        // In character order, which is the record's order.
577        assert_eq!(chars, [
578            ('½', "\\textonehalf"),
579            ('é', "\\'e"),
580            ('ï', "\\\"i"),
581            ('α', "\\ensuremath{\\alpha}"),
582            ('—', "\\textemdash"),
583            ('“', "\\textquotedblleft"),
584            ('”', "\\textquotedblright"),
585            ('≤', "\\ensuremath{\\leq}"),
586        ]);
587        let ids = declared.packages();
588        let packages: Vec<&str> = ids.iter().map(Name::as_str).collect();
589        assert_eq!(packages, [packages::NEWUNICODECHAR]);
590    }
591
592    #[test]
593    fn the_table_s_needs_are_recorded_in_both_modes() {
594        let (out, declared, _) = run("𝟙", &EscapeConfig::new(UnicodeMode::Replace));
595        assert_eq!(out, "\\ensuremath{\\mathds{1}}");
596        assert_eq!(declared.needs().chunks().map(|c| c.id()).collect::<Vec<_>>(), ["dsfont"]);
597        assert!(declared.packages().contains(&packages::chunk_package_id("dsfont")));
598        let (out, declared, _) = run("𝟙", &EscapeConfig::new(UnicodeMode::Declare));
599        assert_eq!(out, "𝟙");
600        assert_eq!(declared.chars()[&'𝟙'], "\\ensuremath{\\mathds{1}}");
601        assert!(declared.packages().contains(&packages::chunk_package_id("dsfont")));
602        // The style file also needs the package the declaration is made with.
603        assert!(declared.packages().contains(packages::NEWUNICODECHAR));
604    }
605
606    #[test]
607    fn a_user_override_wins_over_the_table_and_needs_nothing_of_its_own() {
608        let config = EscapeConfig::new(UnicodeMode::Replace)
609            .with_override('𝟙', "\\mathbb{1}")
610            .with_override('é', "\\'{e}");
611        let (out, declared, _) = run("𝟙é", &config);
612        assert_eq!(out, "\\mathbb{1}\\'{e}");
613        // What an override's spelling needs is the user's own template's to
614        // provide: nothing is recorded, and nothing is guessed from its
615        // commands.
616        assert!(declared.needs().is_empty());
617        assert!(declared.packages().is_empty());
618    }
619
620    #[test]
621    fn an_unknown_character_is_returned_once_and_written_by_mode() {
622        let (out, _, unknown) = run("ธ x ธ", &EscapeConfig::new(UnicodeMode::Declare));
623        assert_eq!(out, "ธ x ธ");
624        assert_eq!(unknown, ['ธ']);
625        let (out, declared, unknown) = run("ธ", &EscapeConfig::new(UnicodeMode::Replace));
626        assert_eq!(out, "\\ensuremath{\\langle}\\texttt{U+0E18}\\ensuremath{\\rangle}");
627        assert_eq!(unknown, ['ธ']);
628        assert!(declared.is_empty());
629    }
630
631    #[test]
632    fn a_cyrillic_spelling_carries_its_font_encoding_and_needs_it() {
633        let (out, declared, _) = run("я", &EscapeConfig::new(UnicodeMode::Replace));
634        assert_eq!(out, "{\\fontencoding{T2A}\\selectfont\\cyrya}");
635        assert_eq!(declared.needs().chunks().map(|c| c.id()).collect::<Vec<_>>(), ["fontenc-t2a"]);
636        assert!(declared.packages().contains(&packages::chunk_package_id("fontenc-t2a")));
637    }
638
639    #[test]
640    fn a_combining_mark_is_composed_when_it_can_be_and_unknown_otherwise() {
641        // `e` + combining acute composes to `é`.
642        let (out, _, unknown) = run("e\u{0301}", &EscapeConfig::new(UnicodeMode::Replace));
643        assert_eq!(out, "\\'e");
644        assert!(unknown.is_empty());
645        // `q` + combining dot above has no composed form; the table's
646        // free-standing accent is not used.
647        let (out, _, unknown) = run("q\u{0307}", &EscapeConfig::new(UnicodeMode::Declare));
648        assert_eq!(out, "q\u{0307}");
649        assert_eq!(unknown, ['\u{0307}']);
650    }
651
652    #[test]
653    fn merging_two_records_keeps_every_character_and_package() {
654        let (_, mut first, _) = run("é", &EscapeConfig::new(UnicodeMode::Declare));
655        let (_, second, _) = run("α 𝟙", &EscapeConfig::new(UnicodeMode::Declare));
656        first.merge(&second);
657        assert_eq!(first.chars().len(), 3);
658        assert!(first.packages().contains(&packages::chunk_package_id("dsfont")));
659        assert!(first.packages().contains(packages::NEWUNICODECHAR));
660    }
661
662    #[test]
663    fn the_mode_names_round_trip() {
664        for mode in [UnicodeMode::Declare, UnicodeMode::Replace] {
665            assert_eq!(UnicodeMode::parse(mode.as_str()), Some(mode));
666        }
667        assert_eq!(UnicodeMode::default(), UnicodeMode::Declare);
668    }
669}