flm_core/stdlib/backends/latex/style.rs
1//! The style file: a `.sty` file assembled for one document from the
2//! requirements of its lowered trees, holding exactly the definitions that the
3//! document's recomposed LaTeX needs to compile.
4//!
5//! A **style file** is the `.sty` file written beside the recomposed LaTeX
6//! document. Instead of a preamble pasted into the document, every definition
7//! the recomposed LaTeX relies on goes into one package file that the document
8//! loads with `\usepackage`: the package requests ([`super::packages`]), the
9//! declarations of the characters written as UTF-8 ([`super::escape`]), the
10//! definition pieces the lowering rules required ([`super::preamble`]), the
11//! definitions a feature writes from its configuration, and the user
12//! definitions the recomposed LaTeX calls ([`super::names`]).
13//!
14//! A user customizes what the file defines without editing it. Every
15//! definition piece and every definition a feature writes is guarded
16//! ([`super::preamble`]), so a definition the user made before
17//! loading the style file wins, and a `\renewcommand` or
18//! `\RenewDocumentCommand` after loading replaces one. A user definition
19//! written under its own prefix is guarded too; one written under the name the
20//! document spells (the render option `bare_names`) is made unconditionally.
21//! The comment line above each user definition gives the command that changes
22//! it after the file is loaded.
23//!
24//! # The order of the file
25//!
26//! [`style_body`] writes the file's body from what the caller resolved, in
27//! this order:
28//!
29//! 1. the LaTeX the document's author gives for the place before the packages
30//! ([`ExtraPreamble::before_packages`]);
31//! 2. the package requests, one per package: the caller has merged every
32//! request for one package into one line per engine
33//! ([`merge_requests`](super::packages::merge_requests)), and a line is
34//! written once where it is the same under every engine and inside a test
35//! of the engine where it differs, with the package [`IFTEX`] requested
36//! first where such a test is written;
37//! 3. the command that makes each engine's own font encoding the default,
38//! where the package block loads [`FONTENC`] with that encoding, inside a
39//! test of the engine of the same form as the block's;
40//! 4. the author's LaTeX for the place after the packages
41//! ([`ExtraPreamble::after_packages`]);
42//! 5. the declarations of the characters written as UTF-8, from the
43//! [`Declared`] record of the escaping;
44//! 6. the definition pieces, in the order given;
45//! 7. the definitions a feature writes from its configuration;
46//! 8. the recomposed user definitions;
47//! 9. the author's LaTeX for the end of the file
48//! ([`ExtraPreamble::at_end`]), followed by `\endinput`.
49//!
50//! The output is deterministic: the same inputs give the same bytes. Each
51//! block begins with a comment line that gives its title, and each package request
52//! and each definition piece follows a comment line that gives the
53//! identifiers it was resolved under, so that a reader of the file can find
54//! what asked for a line. A package request the document's author made
55//! through the render options is written in the same form and carries an
56//! identifier in the same way, but no requirement of the document is behind
57//! it: the author asked for it directly.
58//!
59//! # The name of the file
60//!
61//! The file is named after its content: [`content_hash`] gives eight
62//! hexadecimal digits of a digest of the body (everything after the
63//! `\ProvidesPackage` line), so that the style files of two documents do not
64//! clash in one directory and identical documents share one. The
65//! `latex-recomposed` backend builds the body first ([`style_body`]), then
66//! asks the host's naming service for the file's path, gives the package the
67//! name of that path without `.sty`, and adds the header for that name
68//! ([`with_header`]). The host's naming service prefixes the name with the
69//! name of the document's file (`paper-flmrecomposed.1a2b3c4d.sty`); without
70//! a naming service the package is `<stem>.<hash>`, after the render option
71//! `style_stem` and the hash. The hash is computed before the name is known,
72//! so it does not depend on the name. The backend's
73//! [`stages`](mod@crate::stdlib::backends::latex_recomposed::stages) module
74//! describes the rule in full, under "The style file's path".
75//! [`assemble_style`] does both steps for a name the caller chose.
76
77use std::collections::BTreeSet;
78
79use untechxt::preamble::{Engine, EngineSet};
80
81use crate::model::digest::Fnv1a64;
82
83use super::escape::Declared;
84use super::names::{LatexDefinitionMode, mode_of_twin_name};
85use super::packages::{ENGINES, PackageRequest};
86use super::preamble::LatexPreambleDef;
87
88/// The package whose option list decides which font encoding a document's
89/// text is set in, `fontenc`.
90///
91/// It is the only package this family requests whose option *order* has a
92/// meaning: `fontenc` makes the last encoding of its option list the
93/// document's default. A merged request has no meaningful last option, so
94/// [`style_body`] writes the command that makes each engine's own encoding
95/// the default ([`default_encoding_command`]) after the package block, per
96/// engine, instead of relying on the position of an encoding in the option
97/// list.
98pub const FONTENC: &str = "fontenc";
99
100/// The package whose tests of the engine the package block writes its
101/// requests inside where they differ by engine, `iftex`. The block requests
102/// it itself, first, where it writes such a test ([`style_body`]).
103pub const IFTEX: &str = "iftex";
104
105/// The font encoding the Unicode-to-LaTeX table's Latin spellings are written
106/// for under pdfLaTeX, `T1`, and the one the style file makes the default
107/// there.
108pub const DEFAULT_ENCODING_8BIT: &str = "T1";
109
110/// The font encoding of the Unicode fonts LuaLaTeX and XeLaTeX set text in,
111/// `TU`, and the one the style file makes the default there: a document in
112/// `T1` under those engines loses the characters typed into it directly.
113pub const DEFAULT_ENCODING_UNICODE: &str = "TU";
114
115/// The font encoding the style file makes the default under `engine`:
116/// [`DEFAULT_ENCODING_UNICODE`] under the engines that use Unicode fonts
117/// ([`EngineSet::UNICODE`]) and [`DEFAULT_ENCODING_8BIT`] under every other.
118pub fn default_encoding(engine: Engine) -> &'static str {
119 if EngineSet::UNICODE.contains(engine) {
120 DEFAULT_ENCODING_UNICODE
121 } else {
122 DEFAULT_ENCODING_8BIT
123 }
124}
125
126/// What the style file writes to make `encoding` the default font encoding,
127/// regardless of the order in which the encodings were loaded:
128/// `\renewcommand{\encodingdefault}{<encoding>}`.
129///
130/// `\encodingdefault` is the kernel's name for the encoding a font is
131/// selected in when nothing asks for another, and `fontenc` sets it to the
132/// last encoding of its own option list. Setting it decides the document's
133/// text encoding: selecting a font in the preamble
134/// (`\fontencoding{T1}\selectfont`) would not, because the default font is
135/// selected again from `\encodingdefault` when the document begins.
136///
137/// # Examples
138///
139/// ```
140/// use flm_core::stdlib::backends::latex::style::default_encoding_command;
141///
142/// assert_eq!(default_encoding_command("TU"), "\\renewcommand{\\encodingdefault}{TU}");
143/// ```
144pub fn default_encoding_command(encoding: &str) -> String {
145 format!("\\renewcommand{{\\encodingdefault}}{{{encoding}}}")
146}
147
148/// One user definition on its way into a style file: the name it is defined
149/// under, the name the document declared, and the LaTeX text.
150///
151/// A kept user definition is recomposed under a name of its own
152/// ([`recomposed_name`](super::names::recomposed_name)), so the two names
153/// usually differ; the style file's comment line above the definition gives
154/// both, so that an author reading the file recognizes their own definition.
155/// Where the document declared one name twice, once for text mode and once for
156/// mathematics mode (per-mode definitions), the file holds two definitions
157/// whose [`source_name`](Self::source_name) is the same authored name; the
158/// comment line then also gives the parsing mode the definition is for, read
159/// back from [`name`](Self::name) ([`mode_of_twin_name`]), so that the two
160/// lines differ.
161#[derive(Debug, Clone, PartialEq, Eq, Default)]
162pub struct RecomposedDefinition {
163 /// The name defined, as a user writes it: `\flmUDhello` for a macro,
164 /// `flmUEnote` for an environment. The style file holds one definition
165 /// per name.
166 pub name: String,
167 /// The name the document declared, written the same way: `\hello`,
168 /// `note`. Equal to [`name`](Self::name) for a definition written bare.
169 pub source_name: String,
170 /// The definition's LaTeX, as the emitter recomposed it.
171 pub text: String,
172 /// Whether the definition is a **robust** macro — one written through the
173 /// document command interface, which the render option `robust_names` asks
174 /// for — rather than the plain expandable macro a recomposed definition
175 /// otherwise is. It decides one thing here: which command the comment line
176 /// gives as the one that changes the definition after this file is loaded,
177 /// `\RenewDocumentCommand` for a robust macro and `\renewcommand` for an
178 /// expandable one. An environment is neither: it is always changed with
179 /// `\RenewDocumentEnvironment`.
180 pub robust: bool,
181 /// The feature that wrote the definition from its own configuration, where
182 /// the document declared none (`defterm` for the environment of a defined
183 /// term): such a definition is guarded, and the style file writes it
184 /// before the document's own definitions, its comment line giving the
185 /// feature's name. `None` for a user definition.
186 pub feature: Option<String>,
187 /// Whether the definition is a feature's **declaration** — LaTeX that
188 /// makes something other than a command definition, such as
189 /// `\newtheorem`, written as `\ifcsname <name>\endcsname\else …\fi`
190 /// ([`LatexDefinitionKind::Declaration`](super::LatexDefinitionKind::Declaration)).
191 /// [`name`](Self::name) is then the control sequence the test checks, and
192 /// the comment line above it says what the test does rather than which
193 /// command changes the definition.
194 pub declaration: bool,
195}
196
197impl RecomposedDefinition {
198 /// A definition of `name`, declared in the document under `source_name`,
199 /// whose LaTeX is `text`.
200 pub fn new(
201 name: impl Into<String>,
202 source_name: impl Into<String>,
203 text: impl Into<String>,
204 ) -> RecomposedDefinition {
205 RecomposedDefinition {
206 name: name.into(),
207 source_name: source_name.into(),
208 text: text.into(),
209 robust: false,
210 feature: None,
211 declaration: false,
212 }
213 }
214
215 /// The same definition written by the feature `feature` from its own
216 /// configuration ([`feature`](field@Self::feature)).
217 pub fn of_feature(mut self, feature: impl Into<String>) -> RecomposedDefinition {
218 self.feature = Some(feature.into());
219 self
220 }
221
222 /// The same definition marked as a robust macro
223 /// ([`robust`](field@Self::robust)).
224 pub fn robust(mut self) -> RecomposedDefinition {
225 self.robust = true;
226 self
227 }
228
229 /// The same definition marked as a feature's declaration
230 /// ([`declaration`](field@Self::declaration)).
231 pub fn declaration(mut self) -> RecomposedDefinition {
232 self.declaration = true;
233 self
234 }
235}
236
237/// `text` with every line break written as a space, so that it cannot end a
238/// comment line it is written into.
239fn one_line(text: &str) -> String {
240 text.chars().map(|ch| if ch == '\n' || ch == '\r' { ' ' } else { ch }).collect()
241}
242
243/// The LaTeX a document's author gives to be written into the style file
244/// exactly as given, in the three places it can go: the render option
245/// [`extra_preamble`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::extra_preamble)
246/// of the `latex-recomposed` backend.
247///
248/// Each of the three texts is written **byte for byte**: nothing in it is
249/// escaped, quoted, parsed or checked, and the only thing added is the line
250/// break the next line needs where the text does not end in one. Each is
251/// written under a comment line of its own, so that a reader of the file sees
252/// where the library's own output stops. A text left empty writes nothing at
253/// all — no comment line either.
254///
255/// The three differ only in where they are placed, and each place serves a
256/// different need:
257///
258/// - [`before_packages`](Self::before_packages) is placed between the file's
259/// header and the package block, which is where `\PassOptionsToPackage`
260/// must be to reach a package the block requests, and where a package that
261/// must be loaded before the others is loaded.
262/// - [`after_packages`](Self::after_packages) is placed directly after the
263/// package block and the default-encoding command, before everything the
264/// library defines. A definition made there wins over the LaTeX family's
265/// own, because every definition piece the family writes is guarded
266/// (`\ProvideDocumentCommand` and the related commands); this is how a
267/// LaTeX hook is replaced rather than patched.
268/// - [`at_end`](Self::at_end) is placed at the bottom, after everything the
269/// file holds and before `\endinput`, so it can use any of it: patch a
270/// definition piece, redefine a LaTeX hook, define a command the
271/// document's own mathematics uses.
272#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, serde::Deserialize)]
273#[derive(schemars::JsonSchema)]
274#[serde(default, deny_unknown_fields)]
275pub struct ExtraPreamble {
276 /// Written after the file's header and before the package block. Empty by
277 /// default.
278 pub before_packages: String,
279 /// Written after the package block and the default-encoding command, and
280 /// before the character declarations, the definition pieces and the user
281 /// definitions. Empty by default.
282 pub after_packages: String,
283 /// Written at the bottom of the file, after everything else and before
284 /// `\endinput`. Empty by default.
285 pub at_end: String,
286}
287
288impl ExtraPreamble {
289 /// Whether all three texts are empty, so that nothing of the author's own
290 /// is written into the style file.
291 ///
292 /// # Examples
293 ///
294 /// ```
295 /// use flm_core::stdlib::backends::latex::style::ExtraPreamble;
296 ///
297 /// assert!(ExtraPreamble::default().is_empty());
298 /// let mine = ExtraPreamble { at_end: String::from("\\relax"), ..Default::default() };
299 /// assert!(!mine.is_empty());
300 /// ```
301 pub fn is_empty(&self) -> bool {
302 self.before_packages.is_empty()
303 && self.after_packages.is_empty()
304 && self.at_end.is_empty()
305 }
306}
307
308/// Writes one of the author's three texts under `heading`, unchanged,
309/// with the one line break the next line needs where it does not end in one.
310/// An empty text writes nothing.
311fn write_author_piece(out: &mut String, heading: &str, text: &str) {
312 if text.is_empty() {
313 return;
314 }
315 out.push_str(heading);
316 out.push_str(text);
317 if !text.ends_with('\n') {
318 out.push('\n');
319 }
320}
321
322/// What one entry of the package block writes under each engine of
323/// [`ENGINES`], in that order: its text, ending in a newline, or nothing.
324type ByEngine = [Option<String>; 3];
325
326/// The position of pdfLaTeX in a [`ByEngine`].
327const PDFLATEX: usize = 0;
328/// The position of LuaLaTeX in a [`ByEngine`].
329const LUALATEX: usize = 1;
330/// The position of XeLaTeX in a [`ByEngine`].
331const XELATEX: usize = 2;
332
333/// How the known engines divide over what one entry writes under each of
334/// them, which decides the test of the engine the entry is written inside.
335#[derive(Clone, Copy, PartialEq, Eq)]
336enum Split {
337 /// The entry writes the same under every engine, and needs no test.
338 Same,
339 /// One test of the package `iftex` is enough: the engines for which the
340 /// test is true share what the entry writes under the engine at the given
341 /// position of a [`ByEngine`], and every other engine shares what it
342 /// writes under pdfLaTeX.
343 Test(&'static str, usize),
344 /// The entry writes something different under each engine.
345 Each,
346}
347
348impl Split {
349 /// The split of one entry.
350 fn of(entry: &ByEngine) -> Split {
351 let [pdflatex, lualatex, xelatex] = entry;
352 match (pdflatex == lualatex, lualatex == xelatex, pdflatex == xelatex) {
353 (true, true, _) => Split::Same,
354 (false, true, _) => Split::Test("\\iftutex", LUALATEX),
355 (true, false, _) => Split::Test("\\ifxetex", XELATEX),
356 (false, false, true) => Split::Test("\\ifluatex", LUALATEX),
357 (false, false, false) => Split::Each,
358 }
359 }
360}
361
362/// Writes `entries` in order, each run of neighbors that split the engines
363/// the same way ([`Split`]) inside one test of the engine, or with none where
364/// they write the same under every engine.
365fn write_by_engine(out: &mut String, entries: &[ByEngine]) {
366 for run in entries.chunk_by(|a, b| Split::of(a) == Split::of(b)) {
367 match Split::of(&run[0]) {
368 Split::Same => write_branch(out, run, PDFLATEX),
369 Split::Test(test, at) => write_conditional(out, run, &[(test, at)]),
370 Split::Each => write_conditional(
371 out,
372 run,
373 &[("\\ifluatex", LUALATEX), ("\\ifxetex", XELATEX)],
374 ),
375 }
376 }
377}
378
379/// Writes the entries of `run` inside the tests of `tests`, each a test of
380/// the package `iftex` and the position in a [`ByEngine`] of what to write
381/// where the test is true. What the entries write under pdfLaTeX is written
382/// where every test is false — where some entry writes anything under
383/// pdfLaTeX — so that an engine other than the three the family
384/// distinguishes ([`ENGINES`]) reads what pdfLaTeX reads.
385fn write_conditional(out: &mut String, run: &[ByEngine], tests: &[(&str, usize)]) {
386 for (number, (test, at)) in tests.iter().enumerate() {
387 if number > 0 {
388 out.push_str("\\else");
389 }
390 out.push_str(test);
391 out.push('\n');
392 write_branch(out, run, *at);
393 }
394 if run.iter().any(|entry| entry[PDFLATEX].is_some()) {
395 out.push_str("\\else\n");
396 write_branch(out, run, PDFLATEX);
397 }
398 for _ in tests {
399 out.push_str("\\fi");
400 }
401 out.push('\n');
402}
403
404/// Writes what each entry of `run` writes under the engine at the position
405/// `at` of a [`ByEngine`].
406fn write_branch(out: &mut String, run: &[ByEngine], at: usize) {
407 for text in run.iter().filter_map(|entry| entry[at].as_deref()) {
408 out.push_str(text);
409 }
410}
411
412/// The body of a style file: every block after the header, in the order the
413/// [module documentation](self#the-order-of-the-file) lists, followed by
414/// `\endinput`. The arguments are:
415///
416/// - `packages` are one entry per package, each holding the package's line
417/// under each engine the family knows ([`PackageRequest::by_engine`]), in
418/// the order given. The caller has resolved the requirement identifiers,
419/// added the packages the pieces and the declared characters need
420/// ([`LatexPreambleDef::requires`], [`Declared::packages`]), added the
421/// packages the author asked for, and **merged every request for one
422/// package into one line per engine**
423/// ([`merge_requests`](super::packages::merge_requests)), since LaTeX loads
424/// a package once and a second request with other options is a package
425/// option clash. A package whose line is the same under every engine is
426/// written once, as a `\RequirePackage` line
427/// ([`PackageRequest::requirepackage_line`]) under a comment line that
428/// lists every identifier behind it, separated by `, `. Where the lines
429/// differ, they are written inside `\iftutex … \else … \fi` — or
430/// `\ifluatex … \else\ifxetex … \else … \fi\fi` where all three differ —
431/// each under the comment line that lists every identifier behind that
432/// branch's line, and the package [`IFTEX`], which defines the tests, is
433/// requested first. The last branch is pdfLaTeX's, and an engine other than
434/// the three the family distinguishes ([`ENGINES`]) reads it too.
435///
436/// Where an engine's [`FONTENC`] line holds that engine's own encoding
437/// ([`default_encoding`]), the command that makes it the default
438/// ([`default_encoding_command`]) follows the block under a comment line of
439/// its own, in a separate test of the engine of the same form: `fontenc`
440/// makes the *last* encoding of its option list the document's default, and
441/// a merged option list has no meaningful last element, so the file states
442/// the default rather than arranging for it. Nothing is written for an
443/// engine under which the block loads no `fontenc`, or loads one without
444/// that engine's encoding: the style file states a default only for a
445/// package it requests itself, and where it requests none the document's
446/// default is the author's own to set.
447/// - `declared` gives the characters to declare, each as
448/// `\newunicodechar{<char>}{<spelling>}`, in character order.
449/// - `pieces` are written in the order given, each one's text as it is, a
450/// piece given twice written once.
451/// - `definitions` are [`RecomposedDefinition`] values in the order given.
452/// The comment line above each gives the definition's
453/// [`name`](RecomposedDefinition::name), as a user writes it
454/// (`\flmUDhello` for a macro, `flmUEnote` for an environment); where the
455/// document declared it under another name
456/// ([`source_name`](RecomposedDefinition::source_name)), that name too,
457/// with any line break in it written as a space so that it stays one
458/// comment line; and, where the definition is one of the two per-mode
459/// definitions of a name the document declared once per mode, the parsing
460/// mode it is for, so that the two lines differ. The comment line then
461/// says how the definition is made (guarded, so that a definition of the
462/// name made before this file is loaded wins, or unconditionally where the
463/// definition is written under the name the document spells) and gives the
464/// command that changes it after loading: `\renewcommand` for a macro,
465/// `\RenewDocumentCommand` for a robust one
466/// ([`robust`](field@RecomposedDefinition::robust)), and
467/// `\RenewDocumentEnvironment` for an environment, which is a name written
468/// without a backslash. A definition a feature wrote from its own
469/// configuration ([`feature`](field@RecomposedDefinition::feature)) is
470/// written first, in a block of its own, its comment line giving the
471/// feature's name; it is always guarded. A feature's declaration
472/// ([`declaration`](field@RecomposedDefinition::declaration)) is guarded by
473/// the test `\ifcsname` it is written inside, and its comment line gives
474/// the control sequence that the test checks.
475///
476/// - `extra_preamble` is the LaTeX the document's author gave to be written
477/// as given ([`ExtraPreamble`]), in its three places: before the
478/// package block, after the package block and the default-encoding command,
479/// and at the bottom before `\endinput`. Each text is written **byte for
480/// byte** under a comment line of its own — nothing in it is escaped,
481/// quoted or checked — with the one line break the next line needs where
482/// the text does not end in one. An empty text writes nothing at all.
483///
484/// A block with nothing in it is omitted entirely.
485pub fn style_body(
486 packages: &[PackageRequest],
487 declared: &Declared,
488 pieces: &[&LatexPreambleDef],
489 definitions: &[RecomposedDefinition],
490 extra_preamble: &ExtraPreamble,
491) -> String {
492 let mut out = String::new();
493
494 // The author's first piece: everything the library writes is below it, so
495 // this is where `\PassOptionsToPackage` reaches the requests below and
496 // where a package that must load before the others is loaded.
497 write_author_piece(
498 &mut out,
499 "% --- the author's own preamble: before the packages ---\n",
500 &extra_preamble.before_packages,
501 );
502
503 // What each package writes under each engine: the comment line naming
504 // the identifiers behind that engine's line, then the line itself;
505 // nothing under an engine the package has no line under. Two lines that
506 // differ only in their identifiers are two texts, and are written in two
507 // branches: the comment line is part of what a branch says.
508 let items: Vec<ByEngine> = packages
509 .iter()
510 .map(|request| {
511 ENGINES.map(|engine| {
512 let line = request.for_engine(engine)?;
513 // An identifier a feature contributed is a dotted name and
514 // holds no line break; one that came with an author's own
515 // request is minted from the package name the author wrote,
516 // so it can hold anything. A line break in it would end this
517 // comment line and leave the rest as LaTeX, so line breaks
518 // become spaces here, as they do in the comment line above a
519 // user definition. The request line below carries the package
520 // name as it was given — that part is the author's own LaTeX
521 // and no byte of it is altered — and the options the merge
522 // read out of the requests.
523 let named: Vec<String> = line.ids.iter().map(|id| one_line(id.as_str())).collect();
524 let requirepackage = request.requirepackage_line(engine)?;
525 Some(format!("% {}\n{requirepackage}\n", named.join(", ")))
526 })
527 })
528 .collect();
529 // The one thing the block cannot say by its order: under each engine, the
530 // command naming that engine's own encoding the default, where that
531 // engine's `fontenc` line loads it. See the rustdoc of
532 // `default_encoding_command` for why this command and not another.
533 let commands: ByEngine = ENGINES.map(|engine| {
534 let encoding = default_encoding(engine);
535 packages
536 .iter()
537 .any(|request| {
538 request.package == FONTENC
539 && request
540 .for_engine(engine)
541 .is_some_and(|line| line.options.iter().any(|option| option == encoding))
542 })
543 .then(|| format!("{}\n", default_encoding_command(encoding)))
544 });
545 if !items.is_empty() {
546 out.push_str("% --- packages ---\n");
547 if items.iter().chain([&commands]).any(|item| Split::of(item) != Split::Same) {
548 out.push_str(
549 "% Some lines below differ by TeX engine. They are written inside tests of the\n\
550 % engine, which the package iftex defines: \\iftutex is true under LuaLaTeX and\n\
551 % XeLaTeX, \\ifluatex under LuaLaTeX, and \\ifxetex under XeLaTeX. The last\n\
552 % branch of a test is for pdfLaTeX and any other engine.\n",
553 );
554 out.push_str(&format!("\\RequirePackage{{{IFTEX}}}\n"));
555 }
556 write_by_engine(&mut out, &items);
557 if commands.iter().any(Option::is_some) {
558 out.push_str("% --- the default font encoding ---\n");
559 out.push_str(
560 "% fontenc makes the last encoding of its option list the default, but the\n\
561 % options above may be merged from several requests, so their order carries\n\
562 % no meaning. The line below therefore sets the default for each engine whose\n\
563 % own encoding the request loads: T1 under pdfLaTeX, TU under LuaLaTeX and\n\
564 % XeLaTeX. A letter of another encoding switches to that encoding by itself.\n",
565 );
566 write_by_engine(&mut out, std::slice::from_ref(&commands));
567 }
568 }
569
570 // The author's second piece: below the requests, above everything the
571 // library defines. A definition made here wins over the family's own,
572 // every piece below being guarded.
573 write_author_piece(
574 &mut out,
575 "% --- the author's own preamble: after the packages ---\n",
576 &extra_preamble.after_packages,
577 );
578
579 if !declared.chars().is_empty() {
580 out.push_str("% --- unicode characters written as UTF-8 ---\n");
581 for (ch, spelling) in declared.chars() {
582 out.push_str("\\newunicodechar{");
583 out.push(*ch);
584 out.push_str("}{");
585 out.push_str(spelling);
586 out.push_str("}\n");
587 }
588 }
589
590 let mut seen = BTreeSet::new();
591 let pieces: Vec<&LatexPreambleDef> =
592 pieces.iter().copied().filter(|def| seen.insert(def.id.clone())).collect();
593 if !pieces.is_empty() {
594 out.push_str("% --- commands and environments the library defines for the document ---\n");
595 for def in pieces {
596 out.push_str("% ");
597 out.push_str(def.id.as_str());
598 out.push('\n');
599 out.push_str(&def.content);
600 if !def.content.ends_with('\n') {
601 out.push('\n');
602 }
603 }
604 }
605
606 // A feature's definitions, written from its configuration, stand apart
607 // from the document's own and before them, guarded like a piece.
608 let (by_features, by_document): (Vec<&RecomposedDefinition>, Vec<&RecomposedDefinition>) =
609 definitions.iter().partition(|definition| definition.feature.is_some());
610 if !by_features.is_empty() {
611 out.push_str("% --- definitions written from the configuration of FLM features ---\n");
612 for definition in by_features {
613 let RecomposedDefinition { name, text, robust, feature, declaration, .. } =
614 definition;
615 let renew = match (name.starts_with('\\'), robust) {
616 (true, false) => "\\renewcommand",
617 (true, true) => "\\RenewDocumentCommand",
618 (false, _) => "\\RenewDocumentEnvironment",
619 };
620 out.push_str("% ");
621 out.push_str(name);
622 out.push_str(" (the ");
623 out.push_str(feature.as_deref().unwrap_or_default());
624 if *declaration {
625 // A declaration defines no command a user redefines as a
626 // whole; the comment says what its test does.
627 out.push_str(" feature's, written from its configuration): declared unless \\");
628 out.push_str(name);
629 out.push_str(" is already defined, so a definition made earlier under that name is kept\n");
630 } else {
631 out.push_str(
632 " feature's, written from its configuration): defined unless the name is \
633 already taken, so a definition of it made before this file is loaded wins; ",
634 );
635 out.push_str(renew);
636 out.push_str(" after loading this file changes it\n");
637 }
638 out.push_str(text);
639 if !text.ends_with('\n') {
640 out.push('\n');
641 }
642 }
643 }
644
645 if !by_document.is_empty() {
646 out.push_str("% --- user definitions ---\n");
647 for definition in by_document {
648 let RecomposedDefinition { name, source_name, text, robust, .. } = definition;
649 let is_macro = name.starts_with('\\');
650 // What changes the definition after this file is loaded: an
651 // environment is a document environment, a robust macro is a
652 // document command, and an expandable macro is a plain macro.
653 let renew = match (is_macro, robust) {
654 (true, false) => "\\renewcommand",
655 (true, true) => "\\RenewDocumentCommand",
656 (false, _) => "\\RenewDocumentEnvironment",
657 };
658 // A definition written under a prefix of its own is guarded, so a
659 // definition of that name the user made before this file is loaded
660 // wins; one written under the name the document spelled is the
661 // render option `bare_names` at work, and is made unconditionally,
662 // since that name was listed exactly so that it replaces whatever
663 // else is defined under it. The two are told apart by the names:
664 // they are equal for a definition written bare and differ
665 // otherwise.
666 let bare = source_name == name;
667 out.push_str("% ");
668 out.push_str(name);
669 if !bare {
670 out.push_str(" (the document's ");
671 // The one place the *document's own* text reaches the file
672 // outside a definition body: a line break in it would end the
673 // comment and leave the rest as LaTeX, so line breaks become
674 // spaces. Every other character is harmless in a comment.
675 // The package block above normalizes its comment line for the
676 // same reason.
677 out.push_str(&one_line(source_name));
678 // A name the document declared once per parsing mode is two
679 // definitions here, both carrying that one authored name, so
680 // the authored name alone would give the two the same comment
681 // line. The mode the twin is for is read back out of the name
682 // the file defines, which is where the naming rule records it.
683 match mode_of_twin_name(name.strip_prefix('\\').unwrap_or(name)) {
684 Some(LatexDefinitionMode::Text) => out.push_str(", in text"),
685 Some(LatexDefinitionMode::Mathematics) => out.push_str(", in mathematics"),
686 // `Single` is not a twin and `mode_of_twin_name` never
687 // answers it; the arm is here because the type allows it.
688 Some(LatexDefinitionMode::Single) | None => {}
689 }
690 out.push(')');
691 }
692 if bare {
693 out.push_str(
694 ": defined unconditionally, under the name the document spells, as the \
695 render option bare_names asked; ",
696 );
697 } else {
698 out.push_str(
699 ": defined unless the name is already taken, so a definition of it made \
700 before this file is loaded wins; ",
701 );
702 }
703 out.push_str(renew);
704 out.push_str(" after loading this file changes it\n");
705 out.push_str(text);
706 if !text.ends_with('\n') {
707 out.push('\n');
708 }
709 }
710 }
711
712 // The author's last piece, after everything above and exactly as it was
713 // given: it may use anything above it, and nothing about it is this
714 // library's to second-guess.
715 write_author_piece(
716 &mut out,
717 "% --- the author's own preamble: at the end ---\n",
718 &extra_preamble.at_end,
719 );
720
721 out.push_str("\\endinput\n");
722 out
723}
724
725/// The eight hexadecimal digits in the name of a style file, derived from its
726/// content: the first eight digits of the FNV-1a digest ([`Fnv1a64`]) of
727/// `body`, which is the file's content without its header (what
728/// [`style_body`] returns).
729///
730/// # Examples
731///
732/// ```
733/// use flm_core::stdlib::backends::latex::style::content_hash;
734///
735/// let hash = content_hash("\\endinput\n");
736/// assert_eq!(hash.len(), 8);
737/// assert!(hash.chars().all(|c| c.is_ascii_hexdigit()));
738/// assert_eq!(hash, content_hash("\\endinput\n"));
739/// ```
740pub fn content_hash(body: &str) -> String {
741 let mut hasher = Fnv1a64::new();
742 hasher.write_bytes(body.as_bytes());
743 format!("{:016x}", hasher.value())[..8].to_string()
744}
745
746/// The header of the style file named `name`, followed by `body`:
747/// `\NeedsTeXFormat{LaTeX2e}` and `\ProvidesPackage{<name>}` on their own
748/// lines, then the body. `name` is the package name without `.sty`, the
749/// name a document loads with `\usepackage{<name>}`.
750pub fn with_header(name: &str, body: &str) -> String {
751 format!("\\NeedsTeXFormat{{LaTeX2e}}\n\\ProvidesPackage{{{name}}}\n{body}")
752}
753
754/// The whole style file named `name`: [`with_header`] over [`style_body`].
755/// See [the module documentation](self) for what the parts are and how a
756/// backend derives the file's name from its content.
757pub fn assemble_style(
758 name: &str,
759 packages: &[PackageRequest],
760 declared: &Declared,
761 pieces: &[&LatexPreambleDef],
762 definitions: &[RecomposedDefinition],
763 extra_preamble: &ExtraPreamble,
764) -> String {
765 with_header(name, &style_body(packages, declared, pieces, definitions, extra_preamble))
766}
767
768#[cfg(test)]
769mod tests {
770 use super::*;
771 use crate::model::names::Name;
772 use crate::stdlib::backends::latex::escape::{EscapeConfig, UnicodeMode, escape_into};
773 use crate::stdlib::backends::latex::packages::{
774 self, LatexPackageDef, merge_requests, standard_packages,
775 };
776 use crate::stdlib::backends::latex::preamble::{self, standard_pieces};
777
778 /// The requests of `defs` merged as the caller merges them, for the
779 /// tests below.
780 fn merged(defs: &[&LatexPackageDef]) -> Vec<PackageRequest> {
781 let (requests, conflicts) = merge_requests(defs.iter().copied());
782 assert!(conflicts.is_empty(), "{conflicts:?}");
783 requests
784 }
785
786 #[test]
787 fn an_empty_requirement_set_gives_a_header_and_endinput() {
788 let style = assemble_style("flmrecomposed.00000000", &[], &Declared::new(), &[], &[], &ExtraPreamble::default());
789 assert_eq!(
790 style,
791 "\\NeedsTeXFormat{LaTeX2e}\n\\ProvidesPackage{flmrecomposed.00000000}\n\\endinput\n"
792 );
793 }
794
795 #[test]
796 fn the_blocks_come_in_order_and_a_duplicate_is_written_once() {
797 let roster = standard_packages();
798 let amsmath = roster.iter().find(|d| d.id.as_str() == packages::AMSMATH).unwrap();
799 let pieces = standard_pieces();
800 let math = pieces.iter().find(|p| p.id.as_str() == preamble::MATH_ENVIRONMENT).unwrap();
801 let mut declared = Declared::new();
802 escape_into(&mut String::new(), "é", &EscapeConfig::new(UnicodeMode::Declare), &mut declared);
803 let body = style_body(
804 &merged(&[amsmath, amsmath]),
805 &declared,
806 &[math, math],
807 &[
808 RecomposedDefinition::new(
809 "\\flmUDhello",
810 "\\hello",
811 "\\providecommand\\flmUDhello{hi}",
812 ),
813 RecomposedDefinition::new("\\bare", "\\bare", "\\long\\def\\bare{hi}"),
814 RecomposedDefinition::new(
815 "\\flmUDfirm",
816 "\\firm",
817 "\\ProvideDocumentCommand\\flmUDfirm{+m}{hi#1}",
818 )
819 .robust(),
820 ],
821 &ExtraPreamble::default(),
822 );
823 let package_at = body.find("% --- packages ---").unwrap();
824 let chars_at = body.find("% --- unicode characters").unwrap();
825 let pieces_at = body
826 .find("% --- commands and environments the library defines for the document ---")
827 .unwrap();
828 let defs_at = body.find("% --- user definitions ---").unwrap();
829 assert!(package_at < chars_at && chars_at < pieces_at && pieces_at < defs_at);
830 assert_eq!(body.matches("\\RequirePackage{amsmath}").count(), 1);
831 assert_eq!(body.matches("\\ProvideDocumentCommand\\flmMathEnvironment").count(), 1);
832 assert!(body.contains("\\newunicodechar{é}{\\'e}\n"));
833 // A definition written under its prefix is guarded and says so; one
834 // written under the document's own name is made unconditionally and
835 // its comment line names it once.
836 assert!(body.contains(
837 "% \\flmUDhello (the document's \\hello): defined unless the name is already \
838 taken, so a definition of it made before this file is loaded wins; \
839 \\renewcommand after loading this file changes \
840 it\n\\providecommand\\flmUDhello{hi}\n"
841 ));
842 assert!(body.contains(
843 "% \\bare: defined unconditionally, under the name the document spells, as the \
844 render option bare_names asked; \\renewcommand after loading this file \
845 changes it\n\\long\\def\\bare{hi}\n"
846 ));
847 // A robust macro is guarded in the same way and is changed after
848 // loading with the document command interface it was made with.
849 assert!(body.contains(
850 "% \\flmUDfirm (the document's \\firm): defined unless the name is already \
851 taken, so a definition of it made before this file is loaded wins; \
852 \\RenewDocumentCommand after loading this file changes \
853 it\n\\ProvideDocumentCommand\\flmUDfirm{+m}{hi#1}\n"
854 ));
855 assert!(body.ends_with("\\endinput\n"));
856 }
857
858 /// Every request for one package is one line, whatever identifiers and
859 /// whatever options the requests carried, and the comment line above it
860 /// names every identifier behind it.
861 #[test]
862 fn one_package_is_one_line_naming_every_identifier_behind_it() {
863 let plain = LatexPackageDef::new("amsmath", "the author's");
864 let under_another_id = LatexPackageDef::new("amsmath", "a feature's").id("flm.x.amsmath");
865 let with_options = LatexPackageDef::new("amsmath", "the author's")
866 .id("flm.y.amsmath")
867 .options(["fleqn"]);
868 let body = style_body(
869 &merged(&[&plain, &under_another_id, &with_options]),
870 &Declared::new(),
871 &[],
872 &[],
873 &ExtraPreamble::default(),
874 );
875 assert_eq!(
876 body,
877 "% --- packages ---\n\
878 % flm.latex.pkg.amsmath, flm.x.amsmath, flm.y.amsmath\n\
879 \\RequirePackage[fleqn]{amsmath}\n\
880 \\endinput\n"
881 );
882 }
883
884 /// The comment lines the package block writes above a test of the engine
885 /// and above the default-encoding command, for the tests below.
886 const IFTEX_REQUEST: &str = "% Some lines below differ by TeX engine. They are written inside tests of the\n\
887 % engine, which the package iftex defines: \\iftutex is true under LuaLaTeX and\n\
888 % XeLaTeX, \\ifluatex under LuaLaTeX, and \\ifxetex under XeLaTeX. The last\n\
889 % branch of a test is for pdfLaTeX and any other engine.\n\
890 \\RequirePackage{iftex}\n";
891 const ENCODING_HEADING: &str = "% --- the default font encoding ---\n\
892 % fontenc makes the last encoding of its option list the default, but the\n\
893 % options above may be merged from several requests, so their order carries\n\
894 % no meaning. The line below therefore sets the default for each engine whose\n\
895 % own encoding the request loads: T1 under pdfLaTeX, TU under LuaLaTeX and\n\
896 % XeLaTeX. A letter of another encoding switches to that encoding by itself.\n";
897
898 /// The roster's `fontenc` definitions are one line per engine, written
899 /// inside a test of the engine, and the command naming each engine's own
900 /// encoding the default follows the block, in a separate test of the
901 /// engine of the same form — so that which encoding ends a merged list
902 /// decides nothing. A block with no `fontenc` in it gets no such command,
903 /// and one whose `fontenc` line lacks an engine's encoding gets none for
904 /// that engine.
905 #[test]
906 fn the_default_encoding_command_follows_each_engine_s_own_fontenc_line() {
907 let roster = standard_packages();
908 let fontenc: Vec<&LatexPackageDef> = roster
909 .iter()
910 .filter(|def| def.package == FONTENC)
911 .collect();
912 assert_eq!(fontenc.len(), 13);
913 let body = style_body(&merged(&fontenc), &Declared::new(), &[], &[], &ExtraPreamble::default());
914 assert!(body.starts_with(&format!("% --- packages ---\n{IFTEX_REQUEST}")), "{body}");
915 assert_eq!(body.matches("{fontenc}\n").count(), 2, "{body}");
916 assert!(body.contains("\\RequirePackage[T2A,TU,X2,T2B,T2C,OT2,T2D]{fontenc}\n"), "{body}");
917 assert!(body.contains("\\RequirePackage[T2A,T1,X2,T2B,T2C,OT2,T2D]{fontenc}\n"), "{body}");
918 let commands = format!(
919 "{ENCODING_HEADING}\\iftutex\n\\renewcommand{{\\encodingdefault}}{{TU}}\n\\else\n\
920 \\renewcommand{{\\encodingdefault}}{{T1}}\n\\fi\n"
921 );
922 assert!(body.ends_with(&format!("{commands}\\endinput\n")), "{body}");
923 // No fontenc: no test, no command.
924 let amsmath = roster.iter().find(|d| d.id.as_str() == packages::AMSMATH).unwrap();
925 let body = style_body(&merged(&[amsmath]), &Declared::new(), &[], &[], &ExtraPreamble::default());
926 assert!(!body.contains("iftex"), "{body}");
927 assert!(!body.contains("\\if"), "{body}");
928 assert!(!body.contains("\\encodingdefault"), "{body}");
929 // A `fontenc` request with neither engine's own encoding names an
930 // encoding the file never loaded, so no command is written.
931 let other = LatexPackageDef::new(FONTENC, "the author's own").options(["T2A"]);
932 let body = style_body(&merged(&[&other]), &Declared::new(), &[], &[], &ExtraPreamble::default());
933 assert!(!body.contains("\\encodingdefault"), "{body}");
934 // An author's `T1` for every engine: one line for every engine, and
935 // the command for pdfLaTeX alone, inside a test whose first branch is
936 // empty.
937 let t1 = LatexPackageDef::new(FONTENC, "the author's own").options(["T1"]);
938 let body = style_body(&merged(&[&t1]), &Declared::new(), &[], &[], &ExtraPreamble::default());
939 assert_eq!(
940 body,
941 format!(
942 "% --- packages ---\n{IFTEX_REQUEST}% flm.latex.pkg.fontenc\n\
943 \\RequirePackage[T1]{{fontenc}}\n{ENCODING_HEADING}\\iftutex\n\\else\n\
944 \\renewcommand{{\\encodingdefault}}{{T1}}\n\\fi\n\\endinput\n"
945 )
946 );
947 // An author's `T1,TU` for every engine: the command for each.
948 let both = LatexPackageDef::new(FONTENC, "the author's own").options(["T1,TU"]);
949 let body = style_body(&merged(&[&both]), &Declared::new(), &[], &[], &ExtraPreamble::default());
950 assert!(body.ends_with(&format!("{commands}\\endinput\n")), "{body}");
951 }
952
953 /// A package whose line differs by engine is written inside `\iftutex`,
954 /// the Unicode engines' line first and pdfLaTeX's after `\else`, each
955 /// under the identifiers behind it; `iftex` is requested first, and the
956 /// default-encoding command follows in the same shape.
957 #[test]
958 fn a_request_that_differs_by_engine_is_written_inside_an_iftex_test() {
959 let roster = standard_packages();
960 let by_id = |id: &Name| -> Vec<&LatexPackageDef> {
961 roster.iter().filter(|def| def.id == *id).collect()
962 };
963 let mut defs = by_id(&Name::from(packages::NEWUNICODECHAR));
964 defs.extend(by_id(&packages::chunk_package_id("fontenc-t1")));
965 defs.extend(by_id(&packages::chunk_package_id("fontenc-t2a")));
966 assert_eq!(defs.len(), 4);
967 let body = style_body(&merged(&defs), &Declared::new(), &[], &[], &ExtraPreamble::default());
968 assert_eq!(
969 body,
970 format!(
971 "% --- packages ---\n{IFTEX_REQUEST}\
972 % flm.latex.pkg.newunicodechar\n\
973 \\RequirePackage{{newunicodechar}}\n\
974 \\iftutex\n\
975 % flm.latex.pkg.untechxt.fontenc-t2a\n\
976 \\RequirePackage[T2A,TU]{{fontenc}}\n\
977 \\else\n\
978 % flm.latex.pkg.untechxt.fontenc-t1, flm.latex.pkg.untechxt.fontenc-t2a\n\
979 \\RequirePackage[T1,T2A]{{fontenc}}\n\
980 \\fi\n\
981 {ENCODING_HEADING}\
982 \\iftutex\n\
983 \\renewcommand{{\\encodingdefault}}{{TU}}\n\
984 \\else\n\
985 \\renewcommand{{\\encodingdefault}}{{T1}}\n\
986 \\fi\n\
987 \\endinput\n"
988 )
989 );
990 }
991
992 /// Where the line is different under each of the three engines, the
993 /// tests nest: `\ifluatex`, then `\ifxetex` after its `\else`, then
994 /// pdfLaTeX's line. Where a package has no line under pdfLaTeX, the test
995 /// has no `\else` branch.
996 #[test]
997 fn the_three_way_case_nests_ifluatex_and_ifxetex() {
998 let x = |options: &'static str, engines: EngineSet| {
999 LatexPackageDef::new("x", "a test's").options([options]).engines(engines)
1000 };
1001 let (a, b, c) = (
1002 x("a", EngineSet::PDFLATEX),
1003 x("b", EngineSet::LUALATEX),
1004 x("c", EngineSet::XELATEX),
1005 );
1006 let body = style_body(&merged(&[&a, &b, &c]), &Declared::new(), &[], &[], &ExtraPreamble::default());
1007 assert_eq!(
1008 body,
1009 format!(
1010 "% --- packages ---\n{IFTEX_REQUEST}\
1011 \\ifluatex\n% flm.latex.pkg.x\n\\RequirePackage[b]{{x}}\n\
1012 \\else\\ifxetex\n% flm.latex.pkg.x\n\\RequirePackage[c]{{x}}\n\
1013 \\else\n% flm.latex.pkg.x\n\\RequirePackage[a]{{x}}\n\
1014 \\fi\\fi\n\\endinput\n"
1015 )
1016 );
1017 let unicode = x("b", EngineSet::UNICODE);
1018 let body = style_body(&merged(&[&unicode]), &Declared::new(), &[], &[], &ExtraPreamble::default());
1019 assert_eq!(
1020 body,
1021 format!(
1022 "% --- packages ---\n{IFTEX_REQUEST}\
1023 \\iftutex\n% flm.latex.pkg.x\n\\RequirePackage[b]{{x}}\n\\fi\n\\endinput\n"
1024 )
1025 );
1026 }
1027
1028 /// Neighbors that differ by engine the same way share one test; a
1029 /// package the same under every engine between them ends the run.
1030 #[test]
1031 fn neighbors_that_differ_alike_share_one_test() {
1032 let split = |package: &'static str| {
1033 [
1034 LatexPackageDef::new(package, "the Unicode engines'")
1035 .options(["u"])
1036 .engines(EngineSet::UNICODE),
1037 LatexPackageDef::new(package, "pdfLaTeX's")
1038 .options(["p"])
1039 .engines(!EngineSet::UNICODE),
1040 ]
1041 };
1042 let [a_u, a_p] = split("a");
1043 let [b_u, b_p] = split("b");
1044 let same = LatexPackageDef::new("same", "every engine's");
1045 let body = style_body(
1046 &merged(&[&a_u, &a_p, &b_u, &b_p, &same]),
1047 &Declared::new(),
1048 &[],
1049 &[],
1050 &ExtraPreamble::default(),
1051 );
1052 assert_eq!(
1053 body,
1054 format!(
1055 "% --- packages ---\n{IFTEX_REQUEST}\
1056 \\iftutex\n\
1057 % flm.latex.pkg.a\n\\RequirePackage[u]{{a}}\n\
1058 % flm.latex.pkg.b\n\\RequirePackage[u]{{b}}\n\
1059 \\else\n\
1060 % flm.latex.pkg.a\n\\RequirePackage[p]{{a}}\n\
1061 % flm.latex.pkg.b\n\\RequirePackage[p]{{b}}\n\
1062 \\fi\n\
1063 % flm.latex.pkg.same\n\\RequirePackage{{same}}\n\
1064 \\endinput\n"
1065 )
1066 );
1067 // The same requests with the shared package between the two: two runs,
1068 // two tests.
1069 let body = style_body(
1070 &merged(&[&a_u, &a_p, &same, &b_u, &b_p]),
1071 &Declared::new(),
1072 &[],
1073 &[],
1074 &ExtraPreamble::default(),
1075 );
1076 assert_eq!(body.matches("\\iftutex\n").count(), 2, "{body}");
1077 }
1078
1079 /// The private positions of the writer name the engines of
1080 /// [`ENGINES`] they index.
1081 #[test]
1082 fn the_engine_positions_index_the_family_s_engines() {
1083 assert_eq!(ENGINES[PDFLATEX], Engine::PdfLatex);
1084 assert_eq!(ENGINES[LUALATEX], Engine::LuaLatex);
1085 assert_eq!(ENGINES[XELATEX], Engine::XeLatex);
1086 assert_eq!(default_encoding(Engine::PdfLatex), "T1");
1087 assert_eq!(default_encoding(Engine::LuaLatex), "TU");
1088 assert_eq!(default_encoding(Engine::XeLatex), "TU");
1089 }
1090
1091 /// A feature's declaration stands in the block of feature definitions,
1092 /// before the document's own, as written; its comment line names the
1093 /// control sequence its test names and says that what is defined under
1094 /// that name first stands.
1095 #[test]
1096 fn a_feature_declaration_is_written_in_the_feature_block_under_its_test() {
1097 let body = style_body(
1098 &[],
1099 &Declared::new(),
1100 &[],
1101 &[
1102 RecomposedDefinition::new("\\flmUDa", "\\a", "\\providecommand\\flmUDa{hi}"),
1103 RecomposedDefinition::new(
1104 "lemma",
1105 "lemma",
1106 "\\ifcsname lemma\\endcsname\\else\\newtheorem{lemma}[theorem]{Lemma}\\fi",
1107 )
1108 .of_feature("theorems")
1109 .declaration(),
1110 ],
1111 &ExtraPreamble::default(),
1112 );
1113 let expected = "% --- definitions written from the configuration of FLM features ---\n\
1114 % lemma (the theorems feature's, written from its configuration): declared unless \
1115 \\lemma is already defined, so a definition made earlier under that name is kept\n\
1116 \\ifcsname lemma\\endcsname\\else\\newtheorem{lemma}[theorem]{Lemma}\\fi\n\
1117 % --- user definitions ---\n";
1118 assert!(body.contains(expected), "{body}");
1119 }
1120
1121 /// The comment line above a package request cannot be ended by the text
1122 /// it names: an author's request carries an identifier minted from the
1123 /// package name the author wrote, so a line break in it becomes a space,
1124 /// as it does above a user definition. The package name itself is written
1125 /// as it was given.
1126 #[test]
1127 fn a_line_break_in_an_identifier_cannot_end_the_comment_line() {
1128 let def = LatexPackageDef::new("two\nlines", "the author's");
1129 let body = style_body(&merged(&[&def]), &Declared::new(), &[], &[], &ExtraPreamble::default());
1130 assert!(body.contains("% flm.latex.pkg.two lines\n"), "{body}");
1131 assert!(body.contains("\\RequirePackage{two\nlines}\n"), "{body}");
1132 }
1133
1134 /// The author's three pieces stand where the design puts them — before the
1135 /// packages, after them, at the end — each under a comment line of its
1136 /// own and written as it stands, with a line break added only where the
1137 /// next line would otherwise share theirs.
1138 #[test]
1139 fn the_three_preamble_pieces_stand_in_their_places_byte_for_byte() {
1140 let roster = standard_packages();
1141 let amsmath = roster.iter().find(|d| d.id.as_str() == packages::AMSMATH).unwrap();
1142 let block = "\\newcommand\\mine{% not a comment line of ours\n \\textbf{x}}";
1143 let author = ExtraPreamble {
1144 before_packages: String::from("\\PassOptionsToPackage{fleqn}{amsmath}"),
1145 after_packages: String::from("\\ProvideDocumentCommand\\flmRef{O{} m}{#2}"),
1146 at_end: String::from(block),
1147 };
1148 let body = style_body(
1149 &merged(&[amsmath]),
1150 &Declared::new(),
1151 &[],
1152 &[RecomposedDefinition::new("\\flmUDa", "\\a", "\\providecommand\\flmUDa{hi}")],
1153 &author,
1154 );
1155 let before_at = body.find("% --- the author's own preamble: before the packages ---\n\\PassOptionsToPackage{fleqn}{amsmath}\n").unwrap();
1156 let packages_at = body.find("% --- packages ---").unwrap();
1157 let after_at = body.find("% --- the author's own preamble: after the packages ---\n\\ProvideDocumentCommand\\flmRef{O{} m}{#2}\n").unwrap();
1158 let definitions_at = body.find("% --- user definitions ---").unwrap();
1159 let end_at = body.find("% --- the author's own preamble: at the end ---").unwrap();
1160 assert!(before_at < packages_at, "{body}");
1161 assert!(packages_at < after_at && after_at < definitions_at, "{body}");
1162 assert!(definitions_at < end_at, "{body}");
1163 assert!(body.ends_with(&format!("{block}\n\\endinput\n")), "{body}");
1164 // The first piece stands even where the package block is empty.
1165 let only_before = ExtraPreamble {
1166 before_packages: String::from("\\relax\n"),
1167 ..ExtraPreamble::default()
1168 };
1169 assert_eq!(
1170 style_body(&[], &Declared::new(), &[], &[], &only_before),
1171 "% --- the author's own preamble: before the packages ---\n\\relax\n\\endinput\n"
1172 );
1173 // A piece that ends in a line break gets no second one.
1174 let ends_in_break =
1175 ExtraPreamble { at_end: String::from("\\relax\n"), ..ExtraPreamble::default() };
1176 let body = style_body(&[], &Declared::new(), &[], &[], &ends_in_break);
1177 assert!(body.ends_with("\\relax\n\\endinput\n"), "{body}");
1178 // Empty pieces write no comment line and nothing at all.
1179 let body = style_body(&[], &Declared::new(), &[], &[], &ExtraPreamble::default());
1180 assert_eq!(body, "\\endinput\n");
1181 }
1182
1183 #[test]
1184 fn the_content_hash_names_the_body_and_ignores_the_header() {
1185 let body = style_body(&[], &Declared::new(), &[], &[], &ExtraPreamble::default());
1186 let hash = content_hash(&body);
1187 let style = with_header(&format!("stem.{hash}"), &body);
1188 assert!(style.starts_with("\\NeedsTeXFormat{LaTeX2e}\n\\ProvidesPackage{stem."));
1189 assert_eq!(content_hash(&style[style.find("\\endinput").unwrap()..]), hash);
1190 assert_ne!(content_hash("other"), hash);
1191 }
1192}