flm_core/stdlib/backends/latex/packages.rs
1//! Package requests: how a lowering rule asks for a LaTeX package, and how
2//! all the requests of a document become the `\RequirePackage` lines of its
3//! style file.
4//!
5//! A **package request** is a LaTeX package that a lowering rule or an
6//! emitter requires by identifier (`flm.latex.pkg.<name>`), resolved through
7//! the service slot `flm.latex.packages` to a package definition and merged
8//! with every other request for that package into one `\RequirePackage` line
9//! per package and engine. This module holds the package definition
10//! ([`LatexPackageDef`]), the slot ([`SLOT`]) and its readers
11//! ([`packages_named`], [`packages`]), the standard package definitions
12//! ([`standard_packages`]), the definitions derived from the Unicode-to-LaTeX
13//! table ([`chunk_packages`]), and the merge ([`merge_requests`]). The
14//! concepts overview places package requests among the other LaTeX
15//! requirements under [LaTeX package requests, definition pieces and
16//! hooks](crate::guide::concepts_overview#latex-package-requests-definition-pieces-and-hooks).
17//!
18//! # Identifiers
19//!
20//! A **package identifier** is the name a lowering rule or an emitter puts
21//! into a lowered tree's requirements to say "this document needs this LaTeX
22//! package": `flm.latex.pkg.<name>`, for instance [`AMSMATH`]
23//! (`flm.latex.pkg.amsmath`). The identifier resolves through the slot to a
24//! [`LatexPackageDef`], which says which package to load and with which
25//! options. Requirements carry identifiers rather than package names, so that
26//! the same package needed with options by one feature and without options by
27//! another is two separate declared entries; [`merge_requests`] then combines
28//! the two into the one line LaTeX reads.
29//!
30//! The slot accepts any number of contributions, kept in registration order.
31//! The `latex` feature contributes the standard package definitions
32//! ([`standard_packages`]); another feature contributes its own package
33//! definitions the same way and then requires them by identifier from its
34//! rules.
35//!
36//! # One line per package
37//!
38//! LaTeX loads a package once: a second `\RequirePackage` for a package
39//! already loaded with other options is a package option clash and stops the
40//! compilation. So every request for one package (the LaTeX family's own, the
41//! ones the document's content needs, and the ones the document's author added) is
42//! merged into a single [`PackageRequest`] whose options are the union of the
43//! requests' options, each option once, in the order it was first found. The
44//! rule is the same for every package: there is no merge policy per package.
45//! Two requests that give one option key *different* values cannot be merged;
46//! that is a [`PackageOptionConflict`], which the caller reports, and no line
47//! is written for that package under the engines where its requests conflict.
48//!
49//! # A request applies to a set of engines
50//!
51//! Every request an author or the family writes by hand applies to every
52//! LaTeX engine; a request derived from a chunk of the Unicode-to-LaTeX table
53//! applies to the engines of its case, so one identifier may resolve to one
54//! definition per set of engines ([`engines`](field@LatexPackageDef::engines),
55//! [`packages_named`]). The merge runs once per engine the family knows
56//! ([`ENGINES`]) and gives one line per engine ([`PackageRequest::by_engine`]).
57//! Where a package's line differs by engine, the style file writes the lines
58//! inside a test of the engine ([`style_body`](super::style::style_body)), so
59//! the style file is the same regardless of the engine that reads it.
60//!
61//! # Packages the author loads in their own preamble
62//!
63//! A package the document's author requests in their own preamble is not part
64//! of the merge, and LaTeX's own rule applies to it: for most packages, a
65//! request with an option the package's first request lacked is an option
66//! clash. An author who loads a package that the style file also loads
67//! therefore gives both requests the same options.
68//!
69//! # The packages of the Unicode-to-LaTeX table
70//!
71//! The packages the escaping needs ([`super::escape`]) are not chosen here:
72//! the Unicode-to-LaTeX table of [`untechxt`] states, entry by entry, what
73//! each spelling needs, as a set of *chunks* ([`Chunk`]). A **package chunk**
74//! loads a package under every engine, with options that can differ by engine
75//! ([`is_package_chunk`]); any other chunk is one block of declarations that
76//! no package makes ([`ChunkPreamble`]). A package chunk resolves to the
77//! package definitions derived from it ([`chunk_packages`]), under the
78//! identifier [`chunk_package_id`] gives; a declaration chunk resolves to a
79//! definition piece of [`super::preamble`], under the identifier
80//! [`chunk_piece_id`](super::preamble::chunk_piece_id) gives. [`table_chunks`]
81//! lists every chunk. None of this is kept in step with the table by hand: the
82//! data is untechxt's, read when the registry is built.
83
84use std::borrow::Cow;
85
86use untechxt::builtin::needs_profiles::PROFILES;
87use untechxt::preamble::{Chunk, ChunkPreamble, Engine, EngineSet, Profile};
88use crate::core::services::Services;
89use crate::model::names::Name;
90
91/// The name of the service slot of package definitions, `flm.latex.packages`:
92/// every contribution is a [`LatexPackageDef`], kept in registration order.
93/// The `latex` feature declares the slot ([`super::LatexFamily`]).
94pub const SLOT: &str = "flm.latex.packages";
95
96/// The prefix of every package identifier, `flm.latex.pkg.`.
97pub const ID_PREFIX: &str = "flm.latex.pkg.";
98
99/// `flm.latex.pkg.amsmath` — the `amsmath` package: the display-math
100/// environments other than `equation`, `\text` in mathematics and `\eqref`,
101/// which the rules of the `math` and `math-passthrough` features request where
102/// the document uses them. The
103/// Unicode-to-LaTeX table's `amsmath` chunk is a definition of its own,
104/// `flm.latex.pkg.untechxt.amsmath` ([`chunk_packages`]); where both are
105/// requested, the merge combines them into one line,
106/// `\RequirePackage{amsmath}`, under a comment line that gives both
107/// identifiers ([`merge_requests`]).
108pub const AMSMATH: &str = "flm.latex.pkg.amsmath";
109/// `flm.latex.pkg.zref-clever` — the `zref-clever` package: `\zcref`, the
110/// command that the default reference hook (`\flmRef`,
111/// [`refs_piece`](super::preamble::refs_piece)) sets a reference with.
112pub const ZREF_CLEVER: &str = "flm.latex.pkg.zref-clever";
113/// `flm.latex.pkg.textcase` — the `textcase` package: `\NoCaseChange`, the
114/// wrapper that keeps a reference out of a command that rewrites its
115/// argument (`\MakeUppercase`), written around a reference under the `refs`
116/// feature's `protect` option. The package supplies the command on every
117/// kernel; on a kernel of 2022 or later, where the kernel defines it itself,
118/// the package is a compatibility layer over the kernel's.
119pub const TEXTCASE: &str = "flm.latex.pkg.textcase";
120/// `flm.latex.pkg.hyperref` — the `hyperref` package: links in the PDF,
121/// among them `\hyperref`, the command that shows a text of the document's
122/// own as a link to a labeled place, and `\href`.
123///
124/// A reference that shows the author's own words requests the package only
125/// where the render option
126/// [`label_hooks`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::label_hooks)
127/// is off, since the recomposed LaTeX then writes `\hyperref` itself. With
128/// that option on (the default), the LaTeX hook `\flmHyperref` links through
129/// the package where the document loaded it and prints the text
130/// alone where it did not, so such a reference leaves the choice to the
131/// author ([`hyperref_piece`](super::preamble::hyperref_piece)). The definition
132/// pieces of the `href` feature (hyperlink hooks built on `\href`;
133/// [`href::latex`](crate::stdlib::features::href::latex)) and of the
134/// `defterm` feature (which writes `\phantomsection`;
135/// [`defterm::latex`](crate::stdlib::features::defterm::latex)) request it,
136/// and so does the `floats` feature's rule, for the `\phantomsection` it
137/// writes before the labels of an unnumbered float's caption
138/// ([`floats::latex`](crate::stdlib::features::floats::latex)).
139pub const HYPERREF: &str = "flm.latex.pkg.hyperref";
140/// `flm.latex.pkg.fvextra` — the `fvextra` package (which loads
141/// `fancyvrb`): `\EscVerb` and the `Verbatim` environment the verbatim
142/// definition piece builds on.
143pub const FVEXTRA: &str = "flm.latex.pkg.fvextra";
144/// `flm.latex.pkg.newunicodechar` — the `newunicodechar` package:
145/// `\newunicodechar`, with which the style file declares the characters
146/// written through as UTF-8 under the `Declare` Unicode mode.
147pub const NEWUNICODECHAR: &str = "flm.latex.pkg.newunicodechar";
148/// `flm.latex.pkg.enumitem` — the `enumitem` package: the `label=` key of a
149/// list environment's optional argument, which the recomposed LaTeX writes a
150/// list's own label template as, and the commands `\arabic*`, `\alph*`,
151/// `\Alph*`, `\roman*` and `\Roman*` that stand for the item's number in it.
152pub const ENUMITEM: &str = "flm.latex.pkg.enumitem";
153
154/// `flm.latex.pkg.amsthm` — the `amsthm` package: `\newtheorem`,
155/// `\theoremstyle` and the `proof` environment, over which the recomposed
156/// LaTeX declares the theorem-like environments where a proof's
157/// back-reference is written resolved.
158pub const AMSTHM: &str = "flm.latex.pkg.amsthm";
159
160/// `flm.latex.pkg.phfthm` — the `phfthm` package: theorem and proof
161/// environments over `amsthm` that read a proof's back-reference as it is
162/// written (`\begin{proof}[*thm:x]`), `\phfMakeTheorem`,
163/// `\phfMakeProofEnv` and `\noproofref`. Requested with the option
164/// `thmset=empty`, `\RequirePackage[thmset=empty]{phfthm}`, so that the
165/// package declares no theorem environment of its own: the style file
166/// declares every theorem kind the document uses, from the `theorems`
167/// feature's configuration, and an environment of that name the author
168/// defines before the style file is loaded is kept. An author
169/// who loads the package too gives it the same option (see the
170/// [module documentation](self#packages-the-author-loads-in-their-own-preamble)).
171/// It is not part of every TeX installation.
172pub const PHFTHM: &str = "flm.latex.pkg.phfthm";
173
174/// `flm.latex.pkg.phfcc` — the `phfcc` package: a reviewer's commenting
175/// commands, each made by `\phfMakeCommentingCommand[<keys>]{<name>}`,
176/// which defines `\<name>{…}` and `\<name> … \end<name>` (a highlighted
177/// passage) and `\<name>[…]` (a comment), each colored in the reviewer's
178/// color, the colors assigned in the order the commands are made. The
179/// recomposed LaTeX of the `annotations` feature is written over it,
180/// requested with no option. It is not part of every TeX installation.
181pub const PHFCC: &str = "flm.latex.pkg.phfcc";
182
183/// `flm.latex.pkg.graphicx` — the `graphicx` package: `\includegraphics`,
184/// with which the `graphics` feature's LaTeX hook `\flmIncludeGraphics`
185/// ([`preamble`](super::preamble#the-features-pieces)) shows a picture.
186pub const GRAPHICX: &str = "flm.latex.pkg.graphicx";
187
188/// `flm.latex.pkg.adjustbox` — the `adjustbox` package loaded with the option
189/// `export`, `\RequirePackage[export]{adjustbox}`: the option makes its keys
190/// available to `\includegraphics`, among them `max width`, with which the
191/// `graphics` feature's LaTeX hook `\flmIncludeGraphics` keeps a picture
192/// within the line's width.
193pub const ADJUSTBOX: &str = "flm.latex.pkg.adjustbox";
194
195/// `flm.latex.pkg.caption` — the `caption` package: `\caption*`, a caption
196/// set with no number, with which the `floats` feature's LaTeX hook, the
197/// environment `flmFloat`, sets the caption of a float that has one and no
198/// number.
199pub const CAPTION: &str = "flm.latex.pkg.caption";
200/// `flm.latex.pkg.tabularray` — the `tabularray` package: the `tblr`
201/// environment, in which the `cells` feature's LaTeX hook `\flmCellsTable`
202/// sets a table of cells, and `\NewTableCommand`, with which the `cells`
203/// feature's definition piece defines the table command a cell's custom style
204/// is written as.
205pub const TABULARRAY: &str = "flm.latex.pkg.tabularray";
206
207/// `flm.latex.pkg.xcolor` — the `xcolor` package: `\providecolor`, with
208/// which the `cells` feature's definition piece declares the background
209/// colors of the cell styles the `cells` feature declares by default.
210pub const XCOLOR: &str = "flm.latex.pkg.xcolor";
211
212/// The identifier of the package `name`: [`ID_PREFIX`] followed by the name.
213pub fn package_id(name: &str) -> Name {
214 Name::from(format!("{ID_PREFIX}{name}"))
215}
216
217/// The LaTeX engines the LaTeX family ([`super`]) writes for, in this order:
218/// pdfLaTeX, LuaLaTeX, XeLaTeX ([`Engine`]). A package request applies to a
219/// set of them ([`LatexPackageDef::engines`](field@LatexPackageDef::engines));
220/// the merge
221/// gives one line per engine ([`PackageRequest::by_engine`], in this order);
222/// and the style file writes the lines that differ inside a test of the
223/// engine ([`style_body`](super::style::style_body)), whose last branch is
224/// pdfLaTeX's and is also what an engine not in this list reads.
225pub const ENGINES: [Engine; 3] = [Engine::PdfLatex, Engine::LuaLatex, Engine::XeLatex];
226
227/// The prefix of the identifier of a package definition derived from a chunk
228/// of the Unicode-to-LaTeX table, `flm.latex.pkg.untechxt.`: it begins with
229/// [`ID_PREFIX`], so the identifier is read as a package identifier
230/// everywhere, and the part after [`ID_PREFIX`] says where the definition
231/// comes from.
232pub const CHUNK_ID_PREFIX: &str = "flm.latex.pkg.untechxt.";
233
234/// The identifier of the package definitions derived from the chunk whose
235/// identifier is `chunk_id`: [`CHUNK_ID_PREFIX`] followed by it
236/// (`flm.latex.pkg.untechxt.fontenc-t2a`).
237pub fn chunk_package_id(chunk_id: &str) -> Name {
238 Name::from(format!("{CHUNK_ID_PREFIX}{chunk_id}"))
239}
240
241/// Every chunk of the Unicode-to-LaTeX table: the chunks of [`untechxt`]'s
242/// builtin profiles ([`PROFILES`]), each once by identifier, in order of first
243/// appearance. It is everything a spelling of the table can need, and so what
244/// the definitions derived from the package chunks ([`chunk_packages`]) and
245/// the pieces of [`super::preamble`] cover between them.
246pub fn table_chunks() -> Vec<&'static Chunk> {
247 let mut chunks: Vec<&'static Chunk> = Vec::new();
248 for chunk in PROFILES.iter().flat_map(Profile::chunks) {
249 if !chunks.iter().any(|held| held.id() == chunk.id()) {
250 chunks.push(chunk);
251 }
252 }
253 chunks
254}
255
256/// Whether `chunk` is a package in this family: every case of it loads a
257/// package, with or without options. Every other chunk is one block of
258/// declarations no package makes, which the family writes as a definition
259/// piece ([`chunk_pieces`](super::preamble::chunk_pieces)).
260pub fn is_package_chunk(chunk: &Chunk) -> bool {
261 chunk.cases().iter().all(|case| case.preamble().is_package())
262}
263
264/// The package definitions of the Unicode-to-LaTeX table's package chunks
265/// ([`table_chunks`], [`is_package_chunk`]), in the chunks' order: for each
266/// chunk, one definition per case, under the identifier [`chunk_package_id`]
267/// gives the chunk's identifier, with the case's package name and option text
268/// borrowed from untechxt's static data, applying to the engines of the case
269/// that no earlier case of the chunk took — a chunk's first case that applies
270/// to an engine is what the chunk is under it, so the cases are read in order
271/// ([`Chunk::preamble_for`]). The [`docs`](LatexPackageDef::docs) text of
272/// each says that characters of the document need the package and gives the
273/// chunk's identifier.
274///
275/// The option text of a case is one string (`T2A,TU`), kept as one entry: the
276/// merge reads an entry as LaTeX reads an option list ([`option_list`]).
277pub fn chunk_packages() -> Vec<LatexPackageDef> {
278 let mut defs = Vec::new();
279 for chunk in table_chunks().into_iter().filter(|chunk| is_package_chunk(chunk)) {
280 // The engines an earlier case of this chunk applies to.
281 let mut taken = EngineSet::EMPTY;
282 for case in chunk.cases() {
283 // Cloning a borrowed `Cow` copies the pointer, not the text: the
284 // definition borrows untechxt's static data.
285 let (package, options) = match case.preamble() {
286 ChunkPreamble::Package(name) => (name.clone(), Vec::new()),
287 ChunkPreamble::PackageWithOptions(name, options) => {
288 (name.clone(), vec![options.clone()])
289 }
290 // Every case loads a package: `is_package_chunk` said so.
291 ChunkPreamble::Snippet(_) => {
292 unreachable!("a package chunk loads a package under every case")
293 }
294 };
295 defs.push(LatexPackageDef {
296 id: chunk_package_id(chunk.id()),
297 package,
298 options,
299 docs: crate::kept_docs(format!(
300 "needed by characters of the document whose LaTeX spelling uses this \
301 package (chunk `{}` of untechxt's Unicode-to-LaTeX table)",
302 chunk.id()
303 )),
304 // The case's engines without the earlier cases' ones;
305 // `EngineSet` has no difference operator, so it is spelled
306 // through the complement.
307 engines: !(!case.engines() | taken),
308 });
309 taken = taken | case.engines();
310 }
311 }
312 defs
313}
314
315/// The definition of one package request: the package to load and its
316/// options, under the identifier a package request resolves through.
317///
318/// A feature contributes a definition to the slot [`SLOT`], and a lowering
319/// rule requires it by its [`id`](Self::id). A definition is not by itself a
320/// line of the style file: every request for one package is merged into the
321/// single [`PackageRequest`] the file writes for that package
322/// ([`merge_requests`]), whose options are the union of theirs and whose
323/// comment line lists every identifier behind it. A request applies to the
324/// engines of [`engines`](field@Self::engines): a request written by hand to
325/// every engine, a request derived from a chunk of the Unicode-to-LaTeX table
326/// to the engines of its case. [`requirepackage_line`](Self::requirepackage_line)
327/// writes this one request on its own, for a caller that asks what a single
328/// request says rather than what the style file holds.
329///
330/// The same value is also how a document's author asks for a package of their
331/// own: the `latex-recomposed` render option
332/// [`extra_packages`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::extra_packages)
333/// is a list of these, which join the document's own requests, after them,
334/// before the merge. Such a request is built directly (in Rust with
335/// [`new`](Self::new); in settings as a map with the keys `id`, `package`,
336/// `options` and `docs`, all required) rather than contributed to the slot,
337/// since no rule requires it by identifier.
338#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Deserialize)]
339#[derive(schemars::JsonSchema)]
340#[serde(deny_unknown_fields)]
341pub struct LatexPackageDef {
342 /// The identifier, `flm.latex.pkg.<name>`.
343 pub id: Name,
344 /// The package's name as `\usepackage` takes it (`zref-clever`).
345 pub package: Cow<'static, str>,
346 /// The options, written comma-separated in brackets when not empty.
347 pub options: Vec<Cow<'static, str>>,
348 /// A short text, for a person reading the definition, saying what the
349 /// package provides and when a document needs it. It is not written into
350 /// the style file.
351 pub docs: String,
352 /// The engines the request applies to. A request an author writes, and
353 /// every request the family declares by hand, is one case for every
354 /// engine ([`EngineSet::ALL`]); a request derived from a chunk of the
355 /// Unicode-to-LaTeX table applies to the engines of its case
356 /// ([`chunk_packages`]), and one identifier then resolves to one
357 /// definition per set of engines ([`packages_named`]). It is not part of
358 /// the author-facing form of a request: the settings schema does not
359 /// show it, and settings that give it are refused.
360 #[serde(skip, default = "every_engine")]
361 pub engines: EngineSet,
362}
363
364/// Every engine: what a request applies to unless it says otherwise.
365fn every_engine() -> EngineSet {
366 EngineSet::ALL
367}
368
369impl LatexPackageDef {
370 /// The request of the package `package` under the identifier
371 /// [`package_id`]`(package)`, with no options, applying to every engine;
372 /// `docs` says what the package provides and when a document needs it
373 /// ([`docs`](field@Self::docs)).
374 pub fn new(
375 package: impl Into<Cow<'static, str>>,
376 docs: impl Into<String>,
377 ) -> LatexPackageDef {
378 let package = package.into();
379 LatexPackageDef {
380 id: package_id(&package),
381 package,
382 options: Vec::new(),
383 docs: crate::kept_docs(docs),
384 engines: EngineSet::ALL,
385 }
386 }
387
388 /// The same request under another identifier, for a package requested
389 /// twice with different options, each request under an identifier of its
390 /// own.
391 pub fn id(mut self, id: impl Into<Name>) -> LatexPackageDef {
392 self.id = id.into();
393 self
394 }
395
396 /// The same request with the given package options.
397 pub fn options(
398 mut self,
399 options: impl IntoIterator<Item = impl Into<Cow<'static, str>>>,
400 ) -> Self {
401 self.options = options.into_iter().map(Into::into).collect();
402 self
403 }
404
405 /// The same request applying to `engines` alone
406 /// ([`engines`](field@Self::engines)).
407 pub fn engines(mut self, engines: EngineSet) -> Self {
408 self.engines = engines;
409 self
410 }
411
412 /// The options in brackets, or nothing when there are none.
413 fn bracketed_options(&self) -> String {
414 if self.options.is_empty() {
415 String::new()
416 } else {
417 format!("[{}]", self.options.join(","))
418 }
419 }
420
421 /// The request as a document writes it: `\usepackage[opts]{package}`,
422 /// without a newline. The line says nothing of the engines the request
423 /// applies to ([`engines`](field@Self::engines)).
424 pub fn usepackage_line(&self) -> String {
425 format!("\\usepackage{}{{{}}}", self.bracketed_options(), self.package)
426 }
427
428 /// The request as a style file writes it: `\RequirePackage[opts]{package}`,
429 /// without a trailing newline. The line says nothing of the engines the
430 /// request applies to ([`engines`](field@Self::engines)): where a package's
431 /// requests differ by engine, the style file's block writes the lines
432 /// inside a test of the engine ([`style_body`](super::style::style_body)),
433 /// and the style file is the same regardless of the engine that reads it.
434 pub fn requirepackage_line(&self) -> String {
435 format!("\\RequirePackage{}{{{}}}", self.bracketed_options(), self.package)
436 }
437}
438
439/// One package of a style file's package block: under each engine the family
440/// knows, the `\RequirePackage` line the block writes for it (the merged
441/// options and the identifiers of the requests behind them), or nothing where
442/// no request asks for the package under that engine.
443///
444/// [`merge_requests`] makes one of these from every request for one package,
445/// and [`style_body`](super::style::style_body) writes it: each line under a
446/// comment line that lists its [`ids`](PackageLine::ids), so that a reader of
447/// the style file can find what asked for the line (every request, where
448/// several were merged into one), once where the line is the same under every
449/// engine and inside a test of the engine where it differs.
450///
451/// A caller may merge requests in **groups** and write the groups one after
452/// another, as the `latex-recomposed` backend does: the library's requests
453/// together with the author's requests
454/// ([`extra_packages`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::extra_packages))
455/// form one group, and the author's requests for a package listed in the
456/// render option
457/// [`skip_packages`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::skip_packages)
458/// form another. A package never appears in both groups, so the file still
459/// holds one line per package.
460#[derive(Debug, Clone, PartialEq, Eq)]
461pub struct PackageRequest {
462 /// The package's name as `\RequirePackage` takes it (`fontenc`).
463 pub package: String,
464 /// The line under each engine of [`ENGINES`], in that order.
465 pub by_engine: [Option<PackageLine>; 3],
466}
467
468/// The merged request for one package under one engine: the options and the
469/// identifiers of the requests behind them.
470#[derive(Debug, Clone, PartialEq, Eq)]
471pub struct PackageLine {
472 /// The options, each entry one option, in the order the merge first found
473 /// it.
474 pub options: Vec<String>,
475 /// The identifiers of the requests behind this line, in the order they
476 /// were first found, each once.
477 pub ids: Vec<Name>,
478}
479
480impl PackageRequest {
481 /// The line under `engine`, or `None` where nothing requests the package
482 /// under it.
483 pub fn for_engine(&self, engine: Engine) -> Option<&PackageLine> {
484 ENGINES
485 .iter()
486 .position(|known| *known == engine)
487 .and_then(|at| self.by_engine[at].as_ref())
488 }
489
490 /// The line as a style file writes it under `engine`,
491 /// `\RequirePackage[opts]{package}` without a trailing newline, or `None`
492 /// where nothing requests the package under it.
493 pub fn requirepackage_line(&self, engine: Engine) -> Option<String> {
494 let line = self.for_engine(engine)?;
495 let options = if line.options.is_empty() {
496 String::new()
497 } else {
498 format!("[{}]", line.options.join(","))
499 };
500 Some(format!("\\RequirePackage{}{{{}}}", options, self.package))
501 }
502}
503
504/// Two requests for one package that give one option key different values,
505/// which no merge can resolve: `papersize=a4` against `papersize=letter`, or a
506/// flag `draft` against `draft=false`.
507///
508/// [`merge_requests`] returns one of these per package and key and writes no
509/// line for that package under the engines where the requests conflict:
510/// either value would be wrong for one of the two requests. The
511/// `latex-recomposed` backend reports each conflict as the Error
512/// [`ConflictingPackageOptions`](crate::stdlib::backends::latex_recomposed::ConflictingPackageOptions).
513#[derive(Debug, Clone, PartialEq, Eq)]
514pub struct PackageOptionConflict {
515 /// The package's name (`geometry`).
516 pub package: String,
517 /// The option key the two requests disagree on (`papersize`).
518 pub key: String,
519 /// The option as the request that was found first wrote it
520 /// (`papersize=a4`).
521 pub first: String,
522 /// The option as the request that disagrees with it wrote it
523 /// (`papersize=letter`).
524 pub second: String,
525}
526
527/// Every entry of `options` split at its top-level commas (a comma inside
528/// braces belongs to the value it is part of and does not split), each part
529/// trimmed of the spaces around it, empty parts dropped.
530///
531/// This is how an option list is read wherever one is compared with another:
532/// an author may write a whole list as one string
533/// (`.options(["a4paper,margin=2cm"])`) or one string per option, and the two
534/// must mean the same thing.
535///
536/// # Examples
537///
538/// ```
539/// use flm_core::stdlib::backends::latex::packages::option_list;
540///
541/// assert_eq!(option_list(&[String::from("a4paper, margin=2cm")]), ["a4paper", "margin=2cm"]);
542/// assert_eq!(option_list(&[String::from("keys={a,b}")]), ["keys={a,b}"]);
543/// ```
544pub fn option_list<S: AsRef<str>>(options: &[S]) -> Vec<String> {
545 let mut out: Vec<String> = Vec::new();
546 for entry in options {
547 let entry = entry.as_ref();
548 let mut depth = 0usize;
549 let mut start = 0usize;
550 for (at, ch) in entry.char_indices() {
551 match ch {
552 '{' => depth += 1,
553 '}' => depth = depth.saturating_sub(1),
554 ',' if depth == 0 => {
555 let piece = entry[start..at].trim();
556 if !piece.is_empty() {
557 out.push(String::from(piece));
558 }
559 start = at + ch.len_utf8();
560 }
561 _ => {}
562 }
563 }
564 let piece = entry[start..].trim();
565 if !piece.is_empty() {
566 out.push(String::from(piece));
567 }
568 }
569 out
570}
571
572/// The key and the value of one option: everything before the first
573/// top-level `=` is the key, everything after it the value, both trimmed of
574/// the spaces around them; an option with no such `=` is a *flag*, whose key
575/// is the whole option and whose value is `None`.
576///
577/// A flag and a `key=value` option with the same key are two different values
578/// of that key: `draft` is not `draft=false` as far as this library can tell,
579/// so the two conflict rather than merge.
580///
581/// # Examples
582///
583/// ```
584/// use flm_core::stdlib::backends::latex::packages::option_key_value;
585///
586/// assert_eq!(option_key_value("papersize=a4"), ("papersize", Some("a4")));
587/// assert_eq!(option_key_value("fleqn"), ("fleqn", None));
588/// assert_eq!(option_key_value("keys={a=1,b=2}"), ("keys", Some("{a=1,b=2}")));
589/// ```
590pub fn option_key_value(option: &str) -> (&str, Option<&str>) {
591 let mut depth = 0usize;
592 for (at, ch) in option.char_indices() {
593 match ch {
594 '{' => depth += 1,
595 '}' => depth = depth.saturating_sub(1),
596 '=' if depth == 0 => {
597 return (option[..at].trim(), Some(option[at + 1..].trim()));
598 }
599 _ => {}
600 }
601 }
602 (option.trim(), None)
603}
604
605/// Merges `requests` into one [`PackageRequest`] per package, with one line
606/// per engine of [`ENGINES`]: under each engine, the union of the options of
607/// every request that applies to it ([`engines`](field@LatexPackageDef::engines)),
608/// each option once, in the order it was first found, and the identifiers of
609/// every request behind the line.
610///
611/// The packages come out in the order each was first requested, under any
612/// engine, so a package keeps the place its first request had. Options are
613/// read with [`option_list`] and compared by key with [`option_key_value`]:
614/// an option already in the union with the same value is dropped, and one
615/// with a *different* value is a [`PackageOptionConflict`], returned in the
616/// second element of the result, once regardless of how many engines it was
617/// found under. A package whose requests conflict under an engine gets **no** line
618/// under that engine — and none at all where they conflict under every
619/// engine, as two requests applying to every engine do — since either value
620/// would be wrong for one of the two requests that asked. A package left with
621/// no line under any engine is not in the result.
622///
623/// There is no merge policy per package or per engine: every standard package
624/// definition and every package an author adds is merged this way, under
625/// every engine. Where an ordering among the options would otherwise carry
626/// meaning — `fontenc`, whose last encoding would become the document's
627/// default — the style file states what it needs in a command of its own,
628/// per engine ([`style_body`](super::style::style_body)).
629///
630/// # Examples
631///
632/// ```
633/// use flm_core::stdlib::backends::latex::LatexPackageDef;
634/// use flm_core::stdlib::backends::latex::packages::merge_requests;
635/// use flm_core::untechxt::preamble::{Engine, EngineSet};
636///
637/// let t1 = LatexPackageDef::new("fontenc", "Latin letters")
638/// .id("a")
639/// .options(["T1"])
640/// .engines(!EngineSet::UNICODE);
641/// let t2a = LatexPackageDef::new("fontenc", "Cyrillic letters").id("b").options(["T2A", "T1"]);
642/// let (merged, conflicts) = merge_requests([&t1, &t2a]);
643/// assert!(conflicts.is_empty());
644/// assert_eq!(merged.len(), 1);
645/// assert_eq!(
646/// merged[0].requirepackage_line(Engine::PdfLatex).as_deref(),
647/// Some("\\RequirePackage[T1,T2A]{fontenc}")
648/// );
649/// assert_eq!(
650/// merged[0].requirepackage_line(Engine::LuaLatex).as_deref(),
651/// Some("\\RequirePackage[T2A,T1]{fontenc}")
652/// );
653/// ```
654pub fn merge_requests<'a>(
655 requests: impl IntoIterator<Item = &'a LatexPackageDef>,
656) -> (Vec<PackageRequest>, Vec<PackageOptionConflict>) {
657 let requests: Vec<&LatexPackageDef> = requests.into_iter().collect();
658 // One entry per package, in the order the packages were first met over
659 // every engine. A linear scan over a handful of packages is cheaper than a
660 // map, and it is what keeps the order the caller resolved the
661 // requirements in.
662 let mut merged: Vec<PackageRequest> = Vec::new();
663 for def in &requests {
664 if !merged.iter().any(|request| *request.package == *def.package) {
665 merged.push(PackageRequest {
666 package: def.package.to_string(),
667 by_engine: Default::default(),
668 });
669 }
670 }
671 let mut conflicts: Vec<PackageOptionConflict> = Vec::new();
672 for (at, engine) in ENGINES.into_iter().enumerate() {
673 let (lines, met) = merge_under(&requests, engine);
674 for (package, line) in lines {
675 if let Some(request) = merged.iter_mut().find(|request| request.package == package) {
676 request.by_engine[at] = Some(line);
677 }
678 }
679 for conflict in met {
680 if !conflicts.contains(&conflict) {
681 conflicts.push(conflict);
682 }
683 }
684 }
685 merged.retain(|request| request.by_engine.iter().any(Option::is_some));
686 (merged, conflicts)
687}
688
689/// The merge of [`merge_requests`] under the single engine `engine`, over the
690/// requests that apply to it: each package's line, in the order the packages
691/// were first found, and the conflicts found. A package with a conflict has
692/// no line.
693fn merge_under(
694 requests: &[&LatexPackageDef],
695 engine: Engine,
696) -> (Vec<(String, PackageLine)>, Vec<PackageOptionConflict>) {
697 let mut lines: Vec<(String, PackageLine)> = Vec::new();
698 // Which packages turned out unmergeable, so that no line is written for
699 // them however many further requests arrive.
700 let mut refused: Vec<String> = Vec::new();
701 let mut conflicts: Vec<PackageOptionConflict> = Vec::new();
702 for def in requests.iter().filter(|def| def.engines.contains(engine)) {
703 let at = match lines.iter().position(|(package, _)| **package == *def.package) {
704 Some(at) => at,
705 None => {
706 lines.push((
707 def.package.to_string(),
708 PackageLine { options: Vec::new(), ids: Vec::new() },
709 ));
710 lines.len() - 1
711 }
712 };
713 let line = &mut lines[at].1;
714 if !line.ids.contains(&def.id) {
715 line.ids.push(def.id.clone());
716 }
717 for option in option_list(&def.options) {
718 let (key, value) = option_key_value(&option);
719 let seen = line
720 .options
721 .iter()
722 .find(|written| option_key_value(written).0 == key)
723 .cloned();
724 match seen {
725 Some(written) if option_key_value(&written).1 == value => {}
726 Some(written) => {
727 let conflict = PackageOptionConflict {
728 package: def.package.to_string(),
729 key: String::from(key),
730 first: written,
731 second: option.clone(),
732 };
733 if !conflicts.contains(&conflict) {
734 conflicts.push(conflict);
735 }
736 if !refused.iter().any(|package| **package == *def.package) {
737 refused.push(def.package.to_string());
738 }
739 }
740 None => line.options.push(option),
741 }
742 }
743 }
744 lines.retain(|(package, _)| !refused.contains(package));
745 (lines, conflicts)
746}
747
748/// The standard package definitions the `latex` feature contributes: the
749/// packages that the standard features' rules and definition pieces may
750/// require —
751/// [`AMSMATH`], [`ZREF_CLEVER`], [`TEXTCASE`], [`HYPERREF`], [`FVEXTRA`],
752/// [`NEWUNICODECHAR`], [`ENUMITEM`], [`AMSTHM`], [`PHFTHM`], [`PHFCC`],
753/// [`GRAPHICX`], [`ADJUSTBOX`], [`CAPTION`], [`TABULARRAY`], [`XCOLOR`] — in
754/// that order, followed by the definitions derived from the Unicode-to-LaTeX
755/// table's package chunks ([`chunk_packages`]), which the escaping requires.
756pub fn standard_packages() -> Vec<LatexPackageDef> {
757 let mut packages = vec![
758 LatexPackageDef::new(
759 "amsmath",
760 "the display-math environments other than `equation`, `\\text` in mathematics and \
761 `\\eqref`; needed where the document uses them",
762 ),
763 LatexPackageDef::new(
764 "zref-clever",
765 "`\\zcref`, which prints a reference with the name of its target (\"Section 2\"); \
766 needed by every reference",
767 ),
768 LatexPackageDef::new(
769 "textcase",
770 "`\\NoCaseChange`, which keeps a reference unchanged inside a command that changes \
771 the case of its argument; needed where references are protected that way",
772 ),
773 LatexPackageDef::new(
774 "hyperref",
775 "`\\hyperref`, `\\href` and `\\phantomsection`: links in the PDF; needed by \
776 hyperlinks, defined terms, the labeled captions of unnumbered floats, and \
777 references to the author's own words when the render option `label_hooks` is off",
778 ),
779 LatexPackageDef::new(
780 "fvextra",
781 "`\\EscVerb` and the `Verbatim` environment (version 1.5 or later); needed by \
782 verbatim content",
783 ),
784 LatexPackageDef::new(
785 "newunicodechar",
786 "`\\newunicodechar`, with which the style file declares the non-ASCII characters \
787 that the document holds as UTF-8; needed where the document holds such characters",
788 ),
789 LatexPackageDef::new(
790 "enumitem",
791 "the `label=` key of a list environment; needed by a list with a label of its own",
792 ),
793 LatexPackageDef::new(
794 "amsthm",
795 "`\\newtheorem`, `\\theoremstyle` and `proof`; needed by theorems and proofs when \
796 a proof's back-reference is written resolved",
797 ),
798 LatexPackageDef::new(
799 "phfthm",
800 "`\\phfMakeTheorem` and `\\phfMakeProofEnv`; needed by theorems and proofs when a \
801 proof's back-reference is written as the author wrote it",
802 )
803 .options(["thmset=empty"]),
804 LatexPackageDef::new(
805 "phfcc",
806 "`\\phfMakeCommentingCommand`; needed by a reviewer's highlights and comments",
807 ),
808 LatexPackageDef::new("graphicx", "`\\includegraphics`; needed by pictures"),
809 LatexPackageDef::new(
810 "adjustbox",
811 "the `max width` key and the other keys of `adjustbox` on `\\includegraphics`; \
812 needed by pictures",
813 )
814 .options(["export"]),
815 LatexPackageDef::new(
816 "caption",
817 "`\\caption*`, a caption without a number; needed by floats",
818 ),
819 LatexPackageDef::new(
820 "tabularray",
821 "the `tblr` environment and `\\NewTableCommand`; needed by tables of cells",
822 ),
823 LatexPackageDef::new(
824 "xcolor",
825 "`\\providecolor`, for the background colors of cells; needed by tables of cells",
826 ),
827 ];
828 packages.extend(chunk_packages());
829 packages
830}
831
832/// Every package definition the registry holds, in contribution order.
833pub fn packages(services: &Services) -> impl Iterator<Item = &LatexPackageDef> + '_ {
834 services.services_named::<LatexPackageDef>(SLOT)
835}
836
837/// Every package definition with the identifier `id`, in contribution order:
838/// one for a request that is the same under every engine, and one per set of
839/// engines for a request that differs between engines
840/// ([`engines`](field@LatexPackageDef::engines)); none when no feature
841/// contributed one — which a caller reports as an unknown requirement rather
842/// than fails on.
843pub fn packages_named<'s>(
844 services: &'s Services,
845 id: &'s str,
846) -> impl Iterator<Item = &'s LatexPackageDef> + 's {
847 packages(services).filter(move |def| def.id.as_str() == id)
848}
849
850#[cfg(test)]
851mod tests {
852 use std::collections::BTreeSet;
853
854 use super::*;
855
856 /// The package chunks of the table are fifteen and the declaration chunks
857 /// five; the fifteen give twenty-one definitions, one per case, each
858 /// applying to the engines its case took from the earlier ones.
859 #[test]
860 fn the_chunk_definitions_are_the_table_s_package_chunks_with_their_engine_cases() {
861 let chunks = table_chunks();
862 assert_eq!(chunks.iter().filter(|chunk| is_package_chunk(chunk)).count(), 15);
863 assert_eq!(chunks.iter().filter(|chunk| !is_package_chunk(chunk)).count(), 5);
864 let defs = chunk_packages();
865 assert_eq!(defs.len(), 21);
866 for def in &defs {
867 let chunk_id = def.id.as_str().strip_prefix(CHUNK_ID_PREFIX).unwrap_or_else(|| {
868 panic!("{} does not begin with {CHUNK_ID_PREFIX}", def.id)
869 });
870 #[cfg(feature = "docs")]
871 assert_eq!(
872 def.docs,
873 format!(
874 "needed by characters of the document whose LaTeX spelling uses this \
875 package (chunk `{chunk_id}` of untechxt's Unicode-to-LaTeX table)"
876 )
877 );
878 #[cfg(not(feature = "docs"))]
879 assert_eq!(def.docs, "", "{chunk_id}");
880 }
881 let of = |chunk_id: &str| -> Vec<&LatexPackageDef> {
882 let id = chunk_package_id(chunk_id);
883 defs.iter().filter(|def| def.id == id).collect()
884 };
885 let t2a = of("fontenc-t2a");
886 assert_eq!(t2a.len(), 2);
887 assert_eq!(t2a[0].package, "fontenc");
888 assert_eq!(t2a[0].options, ["T2A,TU"]);
889 assert_eq!(t2a[0].engines, EngineSet::UNICODE);
890 assert_eq!(t2a[1].package, "fontenc");
891 assert_eq!(t2a[1].options, ["T2A,T1"]);
892 assert_eq!(t2a[1].engines, !EngineSet::UNICODE);
893 let t1 = of("fontenc-t1");
894 assert_eq!(t1.len(), 1);
895 assert_eq!(t1[0].options, ["T1"]);
896 assert_eq!(t1[0].engines, !EngineSet::UNICODE);
897 let dsfont = of("dsfont");
898 assert_eq!(dsfont.len(), 1);
899 assert!(dsfont[0].options.is_empty());
900 assert_eq!(dsfont[0].engines, EngineSet::ALL);
901 // The identifiers, each once in order of first appearance, are the
902 // package chunks' in the table's order.
903 let mut ids: Vec<Name> = Vec::new();
904 for def in &defs {
905 if !ids.contains(&def.id) {
906 ids.push(def.id.clone());
907 }
908 }
909 let expected: Vec<Name> = [
910 "dsfont",
911 "nicefrac",
912 "fontenc-t2a",
913 "fontenc-t1",
914 "tipa",
915 "amssymb",
916 "amsmath",
917 "mathrsfs",
918 "bbm",
919 "fontenc-x2",
920 "fontenc-t2b",
921 "fontenc-t2c",
922 "fontenc-ot2",
923 "fontenc-t2d",
924 "tipx",
925 ]
926 .into_iter()
927 .map(chunk_package_id)
928 .collect();
929 assert_eq!(ids, expected);
930 }
931
932 /// The declarations of the table's chunks define no command in the
933 /// family's own name space (`\flm…`,
934 /// [`FAMILY_PREFIX`](super::super::names::FAMILY_PREFIX)): the style file
935 /// writes them as untechxt ships them, under untechxt's prefix `\UnxT…`,
936 /// beside the family's own definitions.
937 #[test]
938 fn no_chunk_declaration_takes_a_family_name() {
939 use crate::stdlib::backends::latex::names::FAMILY_PREFIX;
940 // A negative assertion over the lines the scan recognizes would pass
941 // over a table whose declarations it recognizes none of; the count
942 // says the scan read something.
943 let mut checked = 0;
944 for chunk in table_chunks().into_iter().filter(|chunk| !is_package_chunk(chunk)) {
945 let ChunkPreamble::Snippet(latex) = chunk.cases()[0].preamble() else {
946 panic!("the declaration chunk {} does not hold declarations", chunk.id());
947 };
948 for line in latex.lines() {
949 let Some(rest) = line.strip_prefix("\\DeclareMathAlphabet{\\")
950 .or_else(|| line.strip_prefix("\\DeclareMathSymbol{\\"))
951 .or_else(|| line.strip_prefix("\\DeclareTextSymbol{\\"))
952 else {
953 continue;
954 };
955 let name = rest.split('}').next().unwrap_or_default();
956 assert!(
957 !name.starts_with(FAMILY_PREFIX),
958 "the chunk {} defines `\\{name}`, a name in the family's own \
959 `\\{FAMILY_PREFIX}…` space",
960 chunk.id()
961 );
962 checked += 1;
963 }
964 }
965 assert!(checked > 0, "no declaration of the table was recognized, so none was checked");
966 }
967
968 /// A request's line carries its options and nothing of the engines it
969 /// applies to: the two `fontenc-t2a` definitions write their own lines
970 /// whatever their engines.
971 #[test]
972 fn the_request_lines_carry_their_options_and_say_nothing_of_the_engine() {
973 let defs = chunk_packages();
974 let id = chunk_package_id("fontenc-t2a");
975 let t2a: Vec<&LatexPackageDef> = defs.iter().filter(|def| def.id == id).collect();
976 assert_eq!(t2a[0].usepackage_line(), r"\usepackage[T2A,TU]{fontenc}");
977 assert_eq!(t2a[0].requirepackage_line(), r"\RequirePackage[T2A,TU]{fontenc}");
978 assert_eq!(t2a[1].usepackage_line(), r"\usepackage[T2A,T1]{fontenc}");
979 assert_eq!(t2a[1].requirepackage_line(), r"\RequirePackage[T2A,T1]{fontenc}");
980 let roster = standard_packages();
981 let amsmath = roster.iter().find(|d| d.id.as_str() == AMSMATH).unwrap();
982 assert_eq!(amsmath.requirepackage_line(), r"\RequirePackage{amsmath}");
983 }
984
985 /// Every identifier of the roster is a package identifier, and under each
986 /// engine it resolves to at most one definition — the one that engine
987 /// reads.
988 #[test]
989 fn the_roster_identifiers_are_prefixed_and_resolve_to_one_definition_per_engine() {
990 let roster = standard_packages();
991 assert!(roster.iter().all(|def| def.id.as_str().starts_with(ID_PREFIX)));
992 let ids: BTreeSet<&Name> = roster.iter().map(|def| &def.id).collect();
993 for engine in ENGINES {
994 for id in &ids {
995 let under = roster
996 .iter()
997 .filter(|def| def.id == **id && def.engines.contains(engine))
998 .count();
999 assert!(under <= 1, "{id} under {engine:?}: {under} definitions");
1000 }
1001 }
1002 for id in [AMSMATH, ZREF_CLEVER, FVEXTRA, NEWUNICODECHAR, TEXTCASE] {
1003 assert!(ids.contains(&Name::from(id)), "{id}");
1004 }
1005 assert!(ids.contains(&chunk_package_id("dsfont")));
1006 // Two packages are requested under more than one identifier: `fontenc`,
1007 // once per encoding chunk, and `amsmath`, by the math features and by
1008 // the table.
1009 let shared: BTreeSet<&str> = roster
1010 .iter()
1011 .filter(|def| {
1012 roster.iter().any(|other| other.package == def.package && other.id != def.id)
1013 })
1014 .map(|def| &*def.package)
1015 .collect();
1016 assert_eq!(shared, BTreeSet::from(["amsmath", "fontenc"]));
1017 let amsmath: Vec<&str> = roster
1018 .iter()
1019 .filter(|def| def.package == "amsmath")
1020 .map(|def| def.id.as_str())
1021 .collect();
1022 assert_eq!(amsmath, [AMSMATH, chunk_package_id("amsmath").as_str()]);
1023 }
1024
1025 /// The whole roster merges into one entry per package: the `fontenc`
1026 /// definitions become one line per engine, whose options are the
1027 /// encodings that engine's definitions load, each once, in the order the
1028 /// definitions stand in, and each line carries the identifiers behind it.
1029 #[test]
1030 fn the_rosters_fontenc_definitions_merge_into_one_line_per_engine() {
1031 let roster = standard_packages();
1032 let (merged, conflicts) = merge_requests(roster.iter());
1033 assert!(conflicts.is_empty(), "{conflicts:?}");
1034 let names: BTreeSet<&str> = roster.iter().map(|def| &*def.package).collect();
1035 assert_eq!(merged.len(), names.len());
1036 let fontenc = merged.iter().find(|request| request.package == "fontenc").unwrap();
1037 assert_eq!(
1038 fontenc.requirepackage_line(Engine::PdfLatex).as_deref(),
1039 Some(r"\RequirePackage[T2A,T1,X2,T2B,T2C,OT2,T2D]{fontenc}")
1040 );
1041 for engine in [Engine::LuaLatex, Engine::XeLatex] {
1042 assert_eq!(
1043 fontenc.requirepackage_line(engine).as_deref(),
1044 Some(r"\RequirePackage[T2A,TU,X2,T2B,T2C,OT2,T2D]{fontenc}")
1045 );
1046 }
1047 let chunk_ids = |chunk_ids: &[&str]| -> Vec<Name> {
1048 chunk_ids.iter().map(|id| chunk_package_id(id)).collect()
1049 };
1050 assert_eq!(
1051 fontenc.for_engine(Engine::PdfLatex).unwrap().ids,
1052 chunk_ids(&[
1053 "fontenc-t2a",
1054 "fontenc-t1",
1055 "fontenc-x2",
1056 "fontenc-t2b",
1057 "fontenc-t2c",
1058 "fontenc-ot2",
1059 "fontenc-t2d"
1060 ])
1061 );
1062 assert_eq!(
1063 fontenc.for_engine(Engine::LuaLatex).unwrap().ids,
1064 chunk_ids(&[
1065 "fontenc-t2a",
1066 "fontenc-x2",
1067 "fontenc-t2b",
1068 "fontenc-t2c",
1069 "fontenc-ot2",
1070 "fontenc-t2d"
1071 ])
1072 );
1073 // A package requested the same way under every engine has the same
1074 // line under every engine, here named by the two identifiers that
1075 // request it.
1076 let amsmath = merged.iter().find(|request| request.package == "amsmath").unwrap();
1077 for engine in ENGINES {
1078 assert_eq!(
1079 amsmath.requirepackage_line(engine).as_deref(),
1080 Some(r"\RequirePackage{amsmath}")
1081 );
1082 assert_eq!(
1083 amsmath.for_engine(engine).unwrap().ids,
1084 [Name::from(AMSMATH), chunk_package_id("amsmath")]
1085 );
1086 }
1087 }
1088
1089 /// The union is in the order the options were first met, whatever order
1090 /// the requests arrive in, and a package keeps the place of its first
1091 /// request.
1092 #[test]
1093 fn the_merged_options_are_the_union_in_the_order_first_seen() {
1094 let first = LatexPackageDef::new("geometry", "the document's").options(["a4paper"]);
1095 let other = LatexPackageDef::new("xcolor", "the document's");
1096 let second = LatexPackageDef::new("geometry", "the author's")
1097 .id("flm.latex.pkg.geometry-2")
1098 .options(["margin=2cm", "a4paper"]);
1099 let (merged, conflicts) = merge_requests([&first, &other, &second]);
1100 assert!(conflicts.is_empty(), "{conflicts:?}");
1101 assert_eq!(merged.len(), 2);
1102 assert_eq!(
1103 merged[0].requirepackage_line(Engine::PdfLatex).as_deref(),
1104 Some(r"\RequirePackage[a4paper,margin=2cm]{geometry}")
1105 );
1106 assert_eq!(merged[1].package, "xcolor");
1107 let line = merged[0].for_engine(Engine::PdfLatex).unwrap();
1108 let ids: Vec<&str> = line.ids.iter().map(|id| id.as_str()).collect();
1109 assert_eq!(ids, ["flm.latex.pkg.geometry", "flm.latex.pkg.geometry-2"]);
1110 // Requests that apply to every engine give the same line under each.
1111 assert_eq!(merged[0].by_engine[0], merged[0].by_engine[1]);
1112 assert_eq!(merged[0].by_engine[1], merged[0].by_engine[2]);
1113 }
1114
1115 /// One option key with two values is a conflict, and the package is then
1116 /// written not at all. A flag and a `key=value` option with the same key
1117 /// count as two values.
1118 #[test]
1119 fn one_key_with_two_values_is_a_conflict_and_the_package_is_left_out() {
1120 let a4 = LatexPackageDef::new("geometry", "the document's").options(["papersize=a4"]);
1121 let letter = LatexPackageDef::new("geometry", "the author's")
1122 .id("flm.latex.pkg.geometry-2")
1123 .options(["papersize=letter"]);
1124 let kept = LatexPackageDef::new("amsmath", "the document's");
1125 let (merged, conflicts) = merge_requests([&a4, &letter, &kept]);
1126 assert_eq!(merged.len(), 1);
1127 assert_eq!(merged[0].package, "amsmath");
1128 assert_eq!(
1129 conflicts,
1130 [PackageOptionConflict {
1131 package: String::from("geometry"),
1132 key: String::from("papersize"),
1133 first: String::from("papersize=a4"),
1134 second: String::from("papersize=letter"),
1135 }]
1136 );
1137 // A flag against a value of the same key.
1138 let flag = LatexPackageDef::new("draftpkg", "one").options(["draft"]);
1139 let value =
1140 LatexPackageDef::new("draftpkg", "another").id("x").options(["draft=false"]);
1141 let (merged, conflicts) = merge_requests([&flag, &value]);
1142 assert!(merged.is_empty());
1143 assert_eq!(conflicts.len(), 1);
1144 assert_eq!(conflicts[0].key, "draft");
1145 }
1146
1147 /// Two requests that conflict under one engine alone leave the package
1148 /// without a line under that engine only; the conflict is reported once.
1149 #[test]
1150 fn a_conflict_under_one_engine_alone_leaves_the_package_out_there_only() {
1151 let a4 = LatexPackageDef::new("geometry", "every engine's").options(["papersize=a4"]);
1152 let letter = LatexPackageDef::new("geometry", "the Unicode engines'")
1153 .id("flm.latex.pkg.geometry-2")
1154 .options(["papersize=letter"])
1155 .engines(EngineSet::UNICODE);
1156 let (merged, conflicts) = merge_requests([&a4, &letter]);
1157 assert_eq!(
1158 conflicts,
1159 [PackageOptionConflict {
1160 package: String::from("geometry"),
1161 key: String::from("papersize"),
1162 first: String::from("papersize=a4"),
1163 second: String::from("papersize=letter"),
1164 }]
1165 );
1166 assert_eq!(merged.len(), 1);
1167 assert_eq!(
1168 merged[0].requirepackage_line(Engine::PdfLatex).as_deref(),
1169 Some(r"\RequirePackage[papersize=a4]{geometry}")
1170 );
1171 assert_eq!(merged[0].for_engine(Engine::LuaLatex), None);
1172 assert_eq!(merged[0].for_engine(Engine::XeLatex), None);
1173 }
1174
1175 /// A request that applies to some engines gives no line under the others,
1176 /// and a package keeps the place its first request had, whatever engines
1177 /// that request applies to.
1178 #[test]
1179 fn a_request_absent_under_an_engine_gives_no_line_under_it() {
1180 let t1 = LatexPackageDef::new("fontenc", "pdfLaTeX's")
1181 .options(["T1"])
1182 .engines(!EngineSet::UNICODE);
1183 let (merged, conflicts) = merge_requests([&t1]);
1184 assert!(conflicts.is_empty(), "{conflicts:?}");
1185 assert_eq!(
1186 merged[0].requirepackage_line(Engine::PdfLatex).as_deref(),
1187 Some(r"\RequirePackage[T1]{fontenc}")
1188 );
1189 assert_eq!(merged[0].for_engine(Engine::LuaLatex), None);
1190 assert_eq!(merged[0].for_engine(Engine::XeLatex), None);
1191 assert_eq!(merged[0].requirepackage_line(Engine::LuaLatex), None);
1192 // A request for the Unicode engines alone, met first, keeps the first
1193 // place for its package.
1194 let unicode = LatexPackageDef::new("fontspec", "the Unicode engines'")
1195 .engines(EngineSet::UNICODE);
1196 let every = LatexPackageDef::new("amsmath", "every engine's");
1197 let (merged, conflicts) = merge_requests([&unicode, &every, &t1]);
1198 assert!(conflicts.is_empty(), "{conflicts:?}");
1199 let order: Vec<&str> = merged.iter().map(|request| request.package.as_str()).collect();
1200 assert_eq!(order, ["fontspec", "amsmath", "fontenc"]);
1201 }
1202
1203 /// An option list written as one string is read as a list, and a comma
1204 /// inside braces belongs to the value it stands in.
1205 #[test]
1206 fn an_option_list_is_read_at_its_top_level_commas() {
1207 let one = LatexPackageDef::new("geometry", "one").options(["a4paper, margin=2cm"]);
1208 let two = LatexPackageDef::new("geometry", "two")
1209 .id("x")
1210 .options(["margin=2cm", "headings={a,b}"]);
1211 let (merged, conflicts) = merge_requests([&one, &two]);
1212 assert!(conflicts.is_empty(), "{conflicts:?}");
1213 assert_eq!(
1214 merged[0].requirepackage_line(Engine::PdfLatex).as_deref(),
1215 Some(r"\RequirePackage[a4paper,margin=2cm,headings={a,b}]{geometry}")
1216 );
1217 }
1218
1219 /// One request merged on its own — which is what a group of one is —
1220 /// gives the line the author asked for, its option list read as LaTeX
1221 /// reads one.
1222 #[test]
1223 fn a_group_of_one_request_gives_the_line_the_author_asked_for() {
1224 let def = LatexPackageDef::new("mypackage", "the author's")
1225 .options(["my,fixed,set,of,options"]);
1226 let (merged, conflicts) = merge_requests([&def]);
1227 assert!(conflicts.is_empty(), "{conflicts:?}");
1228 assert_eq!(
1229 merged[0].requirepackage_line(Engine::PdfLatex).as_deref(),
1230 Some(r"\RequirePackage[my,fixed,set,of,options]{mypackage}")
1231 );
1232 let line = merged[0].for_engine(Engine::PdfLatex).unwrap();
1233 assert_eq!(line.options, ["my", "fixed", "set", "of", "options"]);
1234 assert_eq!(line.ids.len(), 1);
1235 }
1236}