Skip to main content

flm_core/stdlib/backends/latex_recomposed/
feature.rs

1//! The `latex-recomposed` feature ([`LatexRecomposed`]), which registers the
2//! `latex-recomposed` backend: its native element set, its render options, its
3//! two structural lowering rules, its stages and their tables, the
4//! `latex-recomposed` output and the `latex-recomposed` workflow.
5//!
6//! A feature ([`FlmFeature`]) is a Rust value that contributes a related
7//! bundle of things to a registry. This feature registers beside three others
8//! that it relies on: the `lowering` feature
9//! ([`LoweringFeature`](crate::stdlib::backends::lowering::LoweringFeature)),
10//! which registers the shared presentation elements; the `latex` feature
11//! ([`LatexFamily`](crate::stdlib::backends::latex::LatexFamily)), which
12//! registers the LaTeX construct elements that this backend writes natively
13//! and the service slots through which the regions stage
14//! ([`LatexRecomposedRegionsStage`]) resolves package requests and definition
15//! pieces; and the `check` feature
16//! ([`check_feature`](crate::stdlib::check_feature)), which declares the
17//! collection `flm.validated` that the `latex-recomposed` workflow demands
18//! (see *What the workflow demands* below). A host normally obtains this
19//! feature through [`feature()`].
20//!
21//! # The native element set
22//!
23//! The native set ([`native_elements`]) lists the elements that the backend's
24//! emitter ([`emit_tree`](super::emit_tree)) writes as they are, without a
25//! lowering rule. It is small: the backend
26//! recomposes, so nearly everything reaches the emitter as a LaTeX construct
27//! element that a feature's own lowering rule staged (built into the lowered
28//! tree), and the emitter writes those construct elements and little else.
29//!
30//! - The four construct elements of the LaTeX family ([`construct::ALL`]): a
31//!   macro call, an environment, raw LaTeX text, and a definition. Every
32//!   lowering rule for this backend stages these.
33//! - [`MATH_PASSTHROUGH`](crate::stdlib::backends::pres::MATH_PASSTHROUGH) and
34//!   [`VERBATIM`](crate::stdlib::backends::pres::VERBATIM): mathematics and
35//!   verbatim content are written to LaTeX byte for byte, so the shared
36//!   elements that carry them as source need no translation; the emitter
37//!   writes the delimiters and the source. Mathematics itself is written from
38//!   its nodes by the `math-passthrough` feature's rules on this backend, so
39//!   that a user definition used inside a formula is handled; a
40//!   `flm.pres.math-passthrough` node reaches the emitter only from that
41//!   feature's rule for an unknown command of math mode
42//!   ([`OPAQUE_RULE`](crate::math_passthrough::OPAQUE_RULE)), when such
43//!   a node is lowered on its own, outside a math group and outside a
44//!   display-math environment, for instance in a math-mode argument of a user
45//!   definition written as a call.
46//! - [`UNKNOWN`](crate::stdlib::backends::pres::UNKNOWN): a macro or
47//!   environment that no feature declares is content the author wrote in
48//!   LaTeX syntax already; the emitter writes it as written, and the error
49//!   reported for it is among the run's diagnostics.
50//! - [`UNSUPPORTED`](crate::stdlib::backends::pres::UNSUPPORTED): the node
51//!   that the lowering driver stages in place of an accepted unrenderable
52//!   element (an element that the plan request accepts as one the backend
53//!   need not render; see
54//!   [`PlanRequest::unsupported`](crate::core::plan::PlanRequest::unsupported)).
55//!   Every backend must write it natively; the emitter writes a comment line
56//!   that gives the element's name.
57//! - [`DROPPED`](crate::stdlib::backends::pres::DROPPED): the node that a
58//!   lowering rule stages where it left out something it could not place
59//!   (stray content of a table of cells, the later of two overlapping cells);
60//!   the emitter writes a comment line that says what was left out.
61//! - [`SUBTREE`](crate::stdlib::backends::pres::SUBTREE): the place of
62//!   another tree of the document, such as the tree of a file included with a
63//!   heading of its own; the recomposed LaTeX of that tree is written at that
64//!   place.
65//! - Five structural elements
66//!   ([`StructuralElements`](crate::lang::structural::StructuralElements))
67//!   whose meaning LaTeX needs no translation for ([`FLOW_THROUGH`]):
68//!   `flm.text` (document text, which the emitter escapes; it must be native
69//!   rather than lowered because escaping happens where the bytes are
70//!   written), `flm.group` (a brace group), `flm.opaque-wrapper` (its
71//!   children, since it has no delimiters), `flm.comment` and
72//!   `flm.container`.
73//!
74//! The rest of the shared presentation elements (`par`, `span`,
75//! `block-heading`, `runin-heading`, `link`, `list`, `lines`, `image`, the
76//! decorations and their marks) are not in the set, because no rule of this
77//! backend produces them (the features' recomposition rules stage construct
78//! elements instead), and an element in the native set is an element the
79//! emitter promises to write. `flm.parbreak` and `flm.paragraph` are not in
80//! the set either: the two structural rules of [`mod@super::rules`] lower
81//! them, and the paragraph-break rule is where the backend states that it
82//! needs the raw tree. The set holds no element that a content feature owns.
83//! Each content feature registers its own recomposition rule for this backend
84//! ([`mod@super::rules`] explains how); this feature registers no lowering rule
85//! but its own two.
86//!
87//! # What the workflow demands
88//!
89//! The `latex-recomposed` [workflow](crate::core::registry::WorkflowDef)
90//! lists the `latex-recomposed` output and also *demands* one capability,
91//! that is, asks the plan for the stages that provide it
92//! ([`PlanRequest::demand`](crate::core::plan::PlanRequest::demand)). That
93//! capability is [`flm.validated`](crate::stdlib::VALIDATED), a collection
94//! ([`CollectionDef`](crate::core::registry::CollectionDef)): a name for a
95//! set of capabilities that any feature may add to. Each check in the
96//! registry adds its capability to it, and demanding the collection demands
97//! all of them. A recomposition therefore runs the same
98//! checks as every other workflow: a refused label type, a duplicate label or
99//! an error in mathematics content is reported here exactly as by the
100//! [`check` workflow](crate::stdlib::CHECK_WORKFLOW). The checks read the
101//! document tree, in which a use site of a user definition that this backend
102//! keeps is still a call of the definition; what the definition contains is
103//! checked by LaTeX. The collection is declared by the `check` feature
104//! ([`check_feature`](crate::stdlib::check_feature)), so a registry that
105//! offers this backend must also hold that feature; a registry without it
106//! fails to build, with an error that identifies this workflow's demands and
107//! the missing name.
108//!
109//! Everything else that a run needs follows from the requirements of the
110//! selected stages and lowering rules: the paragraph-break rule requires
111//! `flm.blocks.raw`, and the reference rules read the table of safe labels,
112//! so the stage that writes that table joins the plan.
113
114use std::collections::{BTreeMap, BTreeSet};
115use std::sync::Arc;
116
117use crate::core::region::RegionsOutput;
118use crate::core::settings::SettingsDecl;
119use crate::stdlib::backends::lowering::REGIONS_SLOT;
120use crate::core::registry::{
121    BackendDef, BuildError, FeatureBuilder, FeatureInfo, FlmFeature, OutputDef, WorkflowDef,
122};
123use crate::lang::structural;
124use crate::model::names::ElementName;
125use crate::model::options::Bind;
126use crate::stdlib::VALIDATED;
127use crate::stdlib::backends::latex::construct;
128use crate::stdlib::backends::latex::{ExtraPreamble, LatexPackageDef, UnicodeMode};
129use crate::stdlib::backends::lowering::{LoweredTrees, lowered_table_name};
130use crate::stdlib::backends::pieces::{LoweredPieces, PiecesStage, lowered_pieces_table_name};
131use crate::stdlib::backends::pres;
132
133use super::rules::rules;
134use super::stages::{
135    ARTIFACTS, DOCUMENT, EXTENSION, LatexRecomposedRegionsStage, MEDIA_TYPE, OUTPUT_TABLE, STYLE_FILE,
136    PACKAGES_TABLE, PREAMBLE_TABLE, REGIONS, WORKFLOW, stages,
137};
138
139/// The registered name of the [`LatexRecomposed`] feature, `latex-recomposed`.
140/// It is also the middle part of the identifiers of the conditions this
141/// backend reports, `flm.latex-recomposed.*`.
142pub const FEATURE_NAME: &str = "latex-recomposed";
143
144/// The declaration of the feature's settings: one option type,
145/// [`LatexRecomposedRenderOptions`], bound to the render request, whose fields
146/// are the settings keys. See [`crate::core::settings`].
147fn settings() -> SettingsDecl {
148    SettingsDecl::new(FEATURE_NAME)
149        .options::<LatexRecomposedRenderOptions>(
150            Bind::Render,
151            "how a non-ASCII character of the text is written (`declare`, the default, writes \
152            the character and declares it in the style file; `replace` writes its LaTeX \
153            spelling), and the spellings that replace the library's own for given characters; \
154            whether the document's source comments are left out; the LaTeX packages this \
155            library never requests, and the packages the style file always requests, with \
156            their options, merged with the requests that the document's content causes into \
157            one `\\RequirePackage` line per package; three parts of LaTeX text written byte for \
158            byte into the style file, before the packages, after them and at its end; the \
159            user-definition names written as the document spells them rather than under a \
160            prefix, and those written as robust commands rather than expandable macros; the \
161            stem of the style file's name (default `flmrecomposed`), to which the program's \
162            naming of files may add a prefix; when the style file is \
163            written (`when-needed`, the default, writes it only where the document needs \
164            something in it, `always` writes it for every document, and either way it is \
165            written where packages to request always or LaTeX text to write into it are given); \
166            whether headings are written through the LaTeX hook `\\flmHeading`, and labels \
167            and references through the LaTeX hooks `\\flmLabels`, \
168            `\\flmLabelsWithDisplayText` and `\\flmRef` (both on by default); whether the \
169            labels of an equation line are left out of the recomposed LaTeX in a registry \
170            without the references feature (off by default; no effect where that feature is \
171            registered); and whether a proof's back-reference is written as the author wrote \
172            it, for the `phfthm` package (the default), or resolved into the LaTeX hook \
173            `\\flmProofTitle`, for `amsthm` alone. Set per render request.",
174        )
175}
176
177/// The backend's registered name, `latex-recomposed`. A lowering rule marked
178/// as the default on this backend refers to it
179/// ([`DefaultMark::OnBackends`](crate::core::lowering::DefaultMark::OnBackends)),
180/// and the names of the backend's lowering stage and lowered-trees table
181/// (`flm.lowered.latex-recomposed`) are derived from it.
182pub const BACKEND: &str = "latex-recomposed";
183
184/// The default stem of the style file's name, `flmrecomposed`; see
185/// [`LatexRecomposedRenderOptions::style_stem`].
186pub const DEFAULT_STYLE_STEM: &str = "flmrecomposed";
187
188/// The structural elements that this backend's emitter writes natively,
189/// without a lowering rule: `flm.text`, `flm.group`, `flm.opaque-wrapper`,
190/// `flm.comment` and `flm.container` (see the module documentation and
191/// [structural elements](crate::guide::concepts_overview#structural-elements)).
192pub const FLOW_THROUGH: [&str; 5] = [
193    structural::TEXT,
194    structural::GROUP,
195    structural::OPAQUE_WRAPPER,
196    structural::COMMENT,
197    structural::CONTAINER,
198];
199
200/// The shared presentation elements ([`pres`]) that this backend's emitter
201/// writes natively: `flm.pres.math-passthrough`, `flm.pres.verbatim`,
202/// `flm.pres.unknown`, `flm.pres.unsupported`, `flm.pres.dropped`,
203/// `flm.pres.subtree` and `flm.pres.span` (see the module documentation). The
204/// span is here for the structural rule of `flm.math`
205/// ([`MATH_RULE`](crate::stdlib::backends::lowering::rules::MATH_RULE)),
206/// which every backend must be able to write; its content is written, its
207/// role and kinds are not.
208pub const SHARED_NATIVE: [&str; 7] = [
209    pres::MATH_PASSTHROUGH,
210    pres::VERBATIM,
211    pres::UNKNOWN,
212    pres::UNSUPPORTED,
213    pres::DROPPED,
214    pres::SUBTREE,
215    pres::SPAN,
216];
217
218/// The backend's native element set, the elements its emitter writes without
219/// a lowering rule: the four LaTeX construct elements ([`construct::ALL`]),
220/// then [`SHARED_NATIVE`], then [`FLOW_THROUGH`], and nothing else. The
221/// [`LatexRecomposed`] feature passes it to the backend's declaration
222/// ([`BackendDef`]); see the module documentation for why each element is in
223/// it.
224///
225/// # Examples
226///
227/// ```
228/// use flm_core::stdlib::backends::latex_recomposed::native_elements;
229///
230/// let native = native_elements();
231/// assert_eq!(native.len(), 16);
232/// assert!(native.iter().any(|element| element.as_str() == "flm.pres.latex.macro"));
233/// assert!(native.iter().all(|element| element.as_str() != "flm.pres.par"));
234/// ```
235pub fn native_elements() -> Vec<ElementName> {
236    construct::ALL
237        .iter()
238        .chain(SHARED_NATIVE.iter())
239        .chain(FLOW_THROUGH.iter())
240        .map(|name| ElementName::from(*name))
241        .collect()
242}
243/// The render options of the `latex-recomposed` backend: how text is
244/// escaped, which LaTeX packages and definitions the style file holds, how
245/// user definitions, headings, labels, references and proofs are written, and
246/// when the style file is written.
247///
248/// The option type is declared with [`Bind::Render`]: its value is set on the
249/// render request
250/// ([`PlanRequest::render_options`](crate::core::plan::PlanRequest::render_options())),
251/// never on the document, so two runs that ask for different values use two
252/// plans. The same fields are the keys of the feature's settings (see
253/// [`crate::core::settings`]). Every field has a default, listed in its
254/// documentation.
255///
256/// Several options are marked **You own this**: when you set them, the library
257/// no longer guarantees that the recomposed LaTeX compiles or means what the
258/// document says, and the documentation of the option states what you must
259/// then provide yourself.
260///
261/// # Examples
262///
263/// ```
264/// use flm_core::stdlib::backends::latex::UnicodeMode;
265/// use flm_core::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions;
266///
267/// let options = LatexRecomposedRenderOptions::default();
268/// assert_eq!(options.unicode, UnicodeMode::Declare);
269/// assert!(!options.drop_comments);
270/// assert_eq!(options.style_stem, "flmrecomposed");
271/// assert!(!options.drop_math_labels_without_refs);
272/// assert!(!options.resolved_proof_refs);
273/// ```
274#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Deserialize)]
275#[derive(schemars::JsonSchema)]
276#[serde(default, deny_unknown_fields)]
277pub struct LatexRecomposedRenderOptions {
278    /// What is written for a non-ASCII character of document text:
279    /// [`Declare`](UnicodeMode::Declare), the default, writes the character
280    /// itself as UTF-8 and declares it once in the style file;
281    /// [`Replace`](UnicodeMode::Replace) writes its LaTeX spelling in place
282    /// (see [`escape`](crate::stdlib::backends::latex::escape)). Mathematics
283    /// and verbatim content are written byte for byte in either mode.
284    pub unicode: UnicodeMode,
285    /// Per-character spellings that replace the spellings of the
286    /// Unicode-to-LaTeX table of [`untechxt`] (the table that
287    /// gives each character a LaTeX spelling and states what that spelling
288    /// needs), in either Unicode mode: for each character, the
289    /// LaTeX to write in its place, or to declare it with. Empty by default.
290    ///
291    /// **You own this when it is set.** Your spelling is written exactly as
292    /// you gave it, and **nothing it needs is added to the style file**: the
293    /// style file requests only what the Unicode-to-LaTeX table says its own
294    /// spellings need. You must provide a spelling that is valid wherever the
295    /// character occurs, in text and in mathematics alike, and load everything
296    /// that spelling needs in your document's preamble (or through
297    /// [`extra_packages`](Self::extra_packages) or
298    /// [`extra_preamble`](Self::extra_preamble)). Neither is checked.
299    pub unicode_overrides: BTreeMap<char, String>,
300    /// Whether the document's source comments are left out of the recomposed
301    /// LaTeX. Off by default: a comment is written with its comment prefix,
302    /// its text and the whitespace that followed it.
303    pub drop_comments: bool,
304    /// LaTeX packages that this library never requests, each given by the
305    /// name `\usepackage` takes (`amsmath`), for a user whose document class
306    /// loads them already. Empty by default.
307    ///
308    /// An entry stops every request that this library makes for the package:
309    /// the LaTeX family's own requests and the ones the document's content
310    /// caused. The one exception is the style file's request for `iftex`, which
311    /// the file makes wherever its package block tests which engine compiles
312    /// the document, since the test needs that package. An entry matches the
313    /// package, not the options it is loaded with: `fontenc` stops every
314    /// request for it, the `T1` one and the `T2A` one alike, and one of them
315    /// cannot be stopped without the other. Skipping `fontenc` also stops the
316    /// command that sets the default font encoding
317    /// ([`default_encoding_command`](crate::stdlib::backends::latex::style::default_encoding_command)),
318    /// under every engine, except where one of your own
319    /// [`extra_packages`](Self::extra_packages) requests loads `fontenc`
320    /// with an engine's own encoding (`T1` for pdfLaTeX, `TU` for LuaLaTeX and
321    /// XeLaTeX): the file writes that command, for that engine, for any
322    /// `fontenc` line its package block holds.
323    ///
324    /// **An explicit request of yours takes precedence.** A package you list
325    /// here *and* request through [`extra_packages`](Self::extra_packages) is
326    /// still requested, on a line of its own, with your options and no
327    /// others. Listing a package here and then requesting it is how you load a
328    /// package with an option list that this library's own requests cannot
329    /// add to. Your own requests for that package are still merged with **each
330    /// other**, by the rule that applies to every other package
331    /// ([`merge_requests`](crate::stdlib::backends::latex::packages::merge_requests)),
332    /// so the style file holds one line for the package; two of them that
333    /// give one option key two different values are reported as the same
334    /// Error ([`ConflictingPackageOptions`](super::ConflictingPackageOptions)),
335    /// and the package is then not requested.
336    ///
337    /// **You own this when it is set.** The recomposed LaTeX still uses what
338    /// the skipped packages provide, so your preamble or your document class
339    /// must load every package you list here; without them the document does
340    /// not compile. Where you skip `fontenc`, you must also set the document's
341    /// default font encoding.
342    pub skip_packages: BTreeSet<String>,
343    /// LaTeX packages that the style file always requests, each a package name
344    /// with the options it is loaded with, as a [`LatexPackageDef`]. Empty by
345    /// default.
346    ///
347    /// They join the requests that the document's content caused (the
348    /// packages that this library's lowering rules, definition pieces and
349    /// character spellings need), after them and in the order given. Every
350    /// request for one package is then merged into the single `\RequirePackage`
351    /// line that the style file writes for that package
352    /// ([`merge_requests`](crate::stdlib::backends::latex::packages::merge_requests)).
353    /// Requesting a package that this library requests itself therefore adds
354    /// your options to its line, and requesting the same package twice adds
355    /// your options once. A request of yours applies to every engine: the style
356    /// file writes it the same way under pdfLaTeX, LuaLaTeX and XeLaTeX, and
357    /// where this library's own request for that package differs by engine
358    /// (`fontenc` does), your options join each engine's line. Two requests
359    /// that give one option key two different values cannot be merged
360    /// (`papersize=a4` against `papersize=letter`, or the flag `draft` against
361    /// `draft=false`): that is the Error
362    /// [`ConflictingPackageOptions`](super::ConflictingPackageOptions), and the
363    /// style file then does not request that package at all.
364    ///
365    /// This option is where an author states what the parts of the document
366    /// that this library writes through unchanged need in order to compile.
367    /// Mathematics is written byte for byte, so a formula that uses
368    /// `\boldsymbol` needs `amsmath`, and the author requests it here, once,
369    /// rather than per definition or per use site.
370    ///
371    /// **You own this when it is set.** Nothing checks that the package
372    /// exists, that the options are its own, or that loading it is compatible
373    /// with what the document or your own preamble loads. A package that you
374    /// also list in [`skip_packages`](Self::skip_packages) is still requested,
375    /// on a line of its own, merged with your other requests for that package
376    /// and with none of this library's; that is how you state an option list
377    /// of your own.
378    ///
379    /// When this option holds a request, the style file is written regardless
380    /// of [`style_file`](Self::style_file), since the file is where the
381    /// requests are written.
382    pub extra_packages: Vec<LatexPackageDef>,
383    /// LaTeX text written into the style file exactly as given, in three
384    /// parts ([`ExtraPreamble`]), all empty by default.
385    ///
386    /// The three parts differ only in where the style file places them, and
387    /// each serves a different need:
388    ///
389    /// - [`before_packages`](ExtraPreamble::before_packages) is placed between
390    ///   the file's header and the package block. `\PassOptionsToPackage` must
391    ///   be written there to reach a package that the block requests, and a
392    ///   package that must be loaded before the others is loaded there.
393    /// - [`after_packages`](ExtraPreamble::after_packages) is placed directly
394    ///   after the package block and the command that sets the default font
395    ///   encoding, before everything this library defines. A definition made
396    ///   there takes precedence over the LaTeX family's own: every definition
397    ///   piece is guarded (`\ProvideDocumentCommand` and the related commands),
398    ///   so a LaTeX hook defined there is the one the document uses, with
399    ///   nothing patched.
400    /// - [`at_end`](ExtraPreamble::at_end) is placed at the bottom, after the
401    ///   character declarations, the definition pieces and the recomposed user
402    ///   definitions, and before the `\endinput` that ends the file, so it can
403    ///   use any of them: redefine a LaTeX hook, patch a definition piece, or
404    ///   define a command that the document's own mathematics uses.
405    ///
406    /// Each part is written under a comment line of its own, and an empty part
407    /// writes nothing at all. Where a part does not end in a line break, one is
408    /// added so that the next line begins on a line of its own; the part's own
409    /// bytes are written unchanged.
410    ///
411    /// **You own this when it is set.** Every part is written **byte for
412    /// byte**: nothing in it is escaped, quoted, parsed or checked. A stray
413    /// `\` or an unclosed group is yours to find, and so is a definition of a
414    /// name that this library's own output relies on. It is the same text you
415    /// would put in your document's preamble, placed where every recomposed
416    /// output of this document includes it.
417    ///
418    /// When any part is not empty, the style file is written regardless of
419    /// [`style_file`](Self::style_file), since the file is where the text is
420    /// written.
421    pub extra_preamble: ExtraPreamble,
422    /// The user-definition names (macro and environment names) that the
423    /// recomposed LaTeX writes exactly as the document spelled them, instead of
424    /// under the prefix that every recomposed user definition otherwise takes.
425    /// Empty by default; a name is given without a backslash, and one entry
426    /// applies to a macro and an environment of that name alike.
427    ///
428    /// By default a kept user definition
429    /// ([`kept`](crate::stdlib::features::userdefs::kept)) never keeps its
430    /// own name: the macro
431    /// `\emph` is recomposed as `\flmUDemph` and the environment `note` as
432    /// `flmUEnote`
433    /// ([`recomposed_name`](crate::stdlib::backends::latex::names::recomposed_name)),
434    /// so that the definition cannot disturb LaTeX, a package, or the style
435    /// file itself. Listing a name here asks for the opposite: the definition
436    /// is written under that name and replaces LaTeX's own command of that
437    /// name for the whole document.
438    ///
439    /// **You own this when it is set.** The document's definition becomes the
440    /// definition of that command everywhere the style file is loaded: in your
441    /// own text, in what a package writes, and in what the document class
442    /// writes, and nothing warns you where that changes a result. You must
443    /// provide a definition that can replace the command it overrides.
444    ///
445    /// Three kinds of entry are refused, each reported with the Error
446    /// `flm.latex-recomposed.definition-name-refused`
447    /// ([`DefinitionNameRefused`](super::DefinitionNameRefused)), which gives
448    /// the reason ([`DefinitionNameRefusal`](super::DefinitionNameRefusal)).
449    /// A name that begins with `flm` is refused, because that prefix is
450    /// reserved for the LaTeX names that this library writes itself; the
451    /// definition is then recomposed under its prefix as usual. An entry under
452    /// which two of the document's own definitions would become one LaTeX
453    /// command is refused too, because `\DeclareDocumentEnvironment{<name>}`
454    /// defines the commands `\<name>` and `\end<name>` itself: a name declared
455    /// as both a macro and an environment, or a macro named `end<name>` beside
456    /// an environment named `<name>` when both are listed. Those definitions
457    /// are still written as the option asked, and the author removes the
458    /// entry or renames one of the two definitions. Last, a name that the
459    /// document declares twice, once for text mode and once for mathematics
460    /// mode, is refused, because the two per-mode definitions are written
461    /// under two names of their own and cannot share one; both keep their
462    /// prefixed names.
463    pub bare_names: BTreeSet<String>,
464    /// The user-definition names written as **robust** LaTeX commands rather
465    /// than as the plain expandable macros that every recomposed definition
466    /// otherwise becomes. Empty by default; a name is given without a
467    /// backslash, and one entry applies to every definition of that name: a
468    /// macro, an environment, and both per-mode definitions of a name declared
469    /// once for text mode and once for mathematics mode.
470    ///
471    /// A *robust* command is one that LaTeX carries into a file of its own
472    /// (the table of contents, the list of figures, the auxiliary file) as the
473    /// call itself rather than as what the call stands for, and runs when that
474    /// file is read back. The opposite is an *expandable* macro, which is
475    /// replaced by what it stands for wherever text is expanded rather than
476    /// typeset.
477    ///
478    /// By default a recomposed macro is expandable
479    /// (`\providecommand\<name>[<n>]{<body>}`). A call of it therefore reaches
480    /// a PDF bookmark as the definition's own words, and `\MakeUppercase`
481    /// changes the case of those words. Listing a name here asks for the other
482    /// behavior: the macro is written with LaTeX's document command interface,
483    /// `\ProvideDocumentCommand\<name>{+m …}` with one `+m` per argument that
484    /// a call writes, which makes it protected from expansion. The call then
485    /// goes into a table of contents or an auxiliary file as itself;
486    /// `hyperref` cannot expand it into a PDF bookmark and leaves it out of
487    /// the bookmark with the log message "Token not allowed in a PDF string";
488    /// and a case change around the call leaves the definition's own words
489    /// exactly as the definition wrote them.
490    ///
491    /// **You own this when it is set.** Use it where a definition's body holds
492    /// something that must not be expanded early, and where you prefer that
493    /// the definition's own words survive a case change rather than appear in
494    /// a PDF bookmark. Nothing checks which of the two a document needs, and
495    /// the missing bookmark text is not reported.
496    ///
497    /// **No definition is refused for its form.** Every recomposed form can be
498    /// written either way: a call writes one brace group per argument
499    /// regardless of how the definition was written, the arguments of a
500    /// definition with more than
501    /// [`PLAIN_ARGUMENT_LIMIT`](crate::stdlib::backends::latex::construct::PLAIN_ARGUMENT_LIMIT)
502    /// arguments are passed in one group, and a verbatim argument's value is a
503    /// brace group like any other.
504    ///
505    /// **An entry that has nothing to act on is accepted and does nothing**,
506    /// so listing every name a document defines is safe. There are three such
507    /// entries. An **environment** listed here does not change, because an
508    /// environment is robust already: it is written with
509    /// `\ProvideDocumentEnvironment` and cannot be written otherwise, since
510    /// `\begin` opens a group, runs the begin code, sets the body and runs the
511    /// end code, and expansion alone could produce none of that. A name that
512    /// **no definition of the document** has does not change anything: an
513    /// entry states a wish about a name, not a claim that the document
514    /// declares it. A definition that **cannot be written as a LaTeX
515    /// definition at all**, so that every use site of it is written expanded
516    /// ([`NotRecomposable`](crate::lang::rewrites::userdefs::NotRecomposable)),
517    /// does not change either, since there is no definition to make robust.
518    ///
519    /// One kind of entry is refused, with the same Error
520    /// `flm.latex-recomposed.definition-name-refused` that
521    /// [`bare_names`](Self::bare_names) uses
522    /// ([`DefinitionNameRefusal::FamilyPrefix`](super::DefinitionNameRefusal::FamilyPrefix)):
523    /// a name that begins with `flm`, the prefix reserved for the LaTeX names
524    /// that this library writes itself. The entry is ignored and the
525    /// definition is written as an expandable macro, as usual.
526    pub robust_names: BTreeSet<String>,
527    /// The stem of the style file's name: the style file's own name is
528    /// `<stem>.<hash>`, where the hash is computed from the file's content
529    /// ([`content_hash`](crate::stdlib::backends::latex::style::content_hash)).
530    /// Without a naming of files by the program, the file is
531    /// `<stem>.<hash>.sty`; the program's naming of files may add to that
532    /// name, for instance a prefix from the name of the document's file
533    /// (`paper-flmrecomposed.1a2b3c4d.sty`).
534    /// The default is [`DEFAULT_STYLE_STEM`], `flmrecomposed`.
535    pub style_stem: String,
536    /// When the style file is written: [`WhenNeeded`](StyleFile::WhenNeeded),
537    /// the default, only where the document needs something in it, or
538    /// [`Always`](StyleFile::Always). In both cases the file is written when
539    /// [`extra_packages`](Self::extra_packages) holds a request or any of the
540    /// three parts of [`extra_preamble`](Self::extra_preamble) is not empty,
541    /// because the author asked for something to be in it.
542    pub style_file: StyleFile,
543    /// Whether a heading is written through the LaTeX hook `\flmHeading` (a
544    /// macro that the style file defines with a default and that a user may
545    /// redefine; see [`preamble`](crate::stdlib::backends::latex::preamble)).
546    /// On by default.
547    ///
548    /// When on, a heading is written as `\flmHeading[toc=true]`, a newline,
549    /// and `\section*{Title}{\flmLabels{\label{ref1}}}`; the hook is on a line of
550    /// its own so that the sectioning command is easy to read in the
551    /// recomposed LaTeX, and LaTeX reads the same tokens either way. The hook
552    /// runs the sectioning command as written and then makes the heading's
553    /// labels refer to it: by its number when the document class numbered it,
554    /// and by its **title** when it did not, so that a reference to a starred
555    /// heading, or to a level below the class's numbering depth, reads
556    /// "Introduction" instead of the number of the item LaTeX numbered last
557    /// ([`heading_piece`](crate::stdlib::backends::latex::preamble::heading_piece)).
558    /// The hook also takes a key-value argument of its own, with two keys:
559    /// `toc`, written on every heading (whether the heading is listed in the
560    /// table of contents), and `alt`, written where the heading was given an
561    /// alternative title (the heading key `alt=`), which LaTeX puts in the
562    /// table of contents, the running head and the PDF bookmark (on a starred
563    /// heading, only its line in the table of contents; see `heading_piece`).
564    /// When this option is off neither key is written.
565    ///
566    /// When off, the sectioning command is written on its own,
567    /// `\section*{Title}`, with the heading's labels after it: still inside
568    /// `\flmLabels` while [`label_hooks`](Self::label_hooks) is on, and as
569    /// bare `\label` commands otherwise. Nothing then replaces the hook's
570    /// test, and a reference to an unnumbered heading prints the last value
571    /// LaTeX recorded, with no warning.
572    ///
573    /// **You own this when it is off.** The library no longer guarantees that
574    /// a reference shows the right target. You must provide either a document
575    /// in which no unnumbered heading is the target of a reference, or a
576    /// mechanism of your own that gives such headings a display text.
577    pub heading_hook: bool,
578    /// Whether labels and references are written through the LaTeX hooks
579    /// `\flmLabels`, `\flmLabelsWithDisplayText` and `\flmRef` (macros that
580    /// the style file defines with a default and that a user may redefine;
581    /// see [`preamble`](crate::stdlib::backends::latex::preamble)). On by
582    /// default.
583    ///
584    /// When on, a group of labels is written `\flmLabels{\label{ref1}\label{ref2}}`
585    /// and a reference `\flmRef[<options>]{ref1}`, where `ref1` and `ref2`
586    /// are safe labels
587    /// ([`SafeLabels`](crate::stdlib::features::refs::SafeLabels)), the keys
588    /// the recomposed LaTeX writes for the document's labels. `\flmLabels`
589    /// makes every label after the first on a line of a display-math
590    /// environment refer to that line's number, which `amsmath` alone does
591    /// not do
592    /// ([`labels_piece`](crate::stdlib::backends::latex::preamble::labels_piece)),
593    /// and `\flmRef` is the macro that a user redefines to use a different
594    /// reference command
595    /// ([`refs_piece`](crate::stdlib::backends::latex::preamble::refs_piece)).
596    ///
597    /// When off, the recomposed LaTeX writes bare `\label{ref1}` commands and
598    /// `\zcref[<options>]{ref1}`, and requests the `zref-clever` package.
599    /// Several labels on one line of a display-math environment are then left
600    /// to LaTeX: `amsmath` keeps the last label of a line, loses the ones
601    /// before it, and warns `Multiple \label's`. A reference's options are
602    /// then FLM's own option names passed unchanged to `\zcref`, since the
603    /// hook's default is what translates them
604    /// ([`refs_piece`](crate::stdlib::backends::latex::preamble::refs_piece)).
605    ///
606    /// **You own this when it is off.** A reference to a lost label prints
607    /// `??`. You must provide either one label per line of a display-math
608    /// environment or an aliasing mechanism of your own, and reference options
609    /// that `zref-clever` accepts: `\ref[noprefix]{…}` stops the compilation,
610    /// where the hook would have translated it to `noname`.
611    pub label_hooks: bool,
612    /// Whether the labels written on the lines of a display-math environment
613    /// are left out of the recomposed LaTeX **in a registry that does not hold
614    /// the references feature**. Off by default.
615    ///
616    /// The references feature ([`refs`](crate::stdlib::features::refs)) assigns
617    /// the safe label of every label and resolves every `\ref`. A registry may
618    /// be built without it (for example by a host that needs mathematics and
619    /// little else), and an equation line may still carry a `\label` there.
620    /// Such a label is written as the document wrote it, inside the
621    /// `\flmLabels` group like every other label. This option says that it is
622    /// not written at all, neither the `\label` command nor the group, for a
623    /// host that keeps its mathematics free of anything but mathematics.
624    ///
625    /// **With the references feature registered, the option does nothing**,
626    /// and nothing is reported: a label is then a reference point with a safe
627    /// label, and a `\ref` in the document is written against that safe label,
628    /// so removing the `\label` would leave the reference pointing at nothing.
629    /// In such a registry the recomposed LaTeX is the same, byte for byte,
630    /// whether this option is set or not.
631    ///
632    /// **Only mathematics is affected.** A heading's labels are written as
633    /// they are, with or without the references feature, and so is a label
634    /// written anywhere else. No option of this kind exists for headings.
635    ///
636    /// **You own this when it is on.** A label that the document wrote is then
637    /// in no output: nothing in the recomposed LaTeX marks the equation line,
638    /// so anything of yours that refers to it (LaTeX you write around the
639    /// recomposed document, or a tool that reads the file) finds nothing.
640    /// Nothing else about the line changes: a `\tag` and a `\nonumber` are not
641    /// labels and are written as always.
642    pub drop_math_labels_without_refs: bool,
643    /// Whether a proof's **back-reference** is resolved into LaTeX hooks (on)
644    /// or written as the author wrote it over the `phfthm` package (off, the
645    /// default); the choice also decides which LaTeX package declares the
646    /// theorem-like environments. The back-reference is the title
647    /// `[*thm:x]`, which shows the statement that a proof proves, or
648    /// `[**thm:x]`, which records the relation without showing it. Off by
649    /// default.
650    ///
651    /// When off, the **authored form** is used: the back-reference is written
652    /// as the author wrote it, `\begin{proof}[*ref1]` or `[**ref1]` around the
653    /// statement's safe label, and the style file requests the `phfthm`
654    /// package, which reads exactly this syntax on top of `amsthm`. With it,
655    /// `[*ref1]` sets the heading "Proof of Theorem 1" where the document
656    /// loads `hyperref` (the package refers to the statement through
657    /// `hyperref`'s `\autoref`) and "Proof of 1" where it does not (through
658    /// `\ref`), and `[**ref1]` sets "Proof"; the package also declares the
659    /// theorem kinds through its own commands. The recomposed LaTeX does not
660    /// request `hyperref` for this: whether a document loads it is its
661    /// author's decision. The `phfthm` package is not part of every TeX
662    /// installation: a document compiled where it is absent lists it in
663    /// [`skip_packages`](Self::skip_packages) and defines the environments
664    /// itself.
665    ///
666    /// When on, the **resolved form** is used, and the recomposed LaTeX needs
667    /// `amsthm` alone. A back-reference that the proof shows is written inside
668    /// the proof title hook `\flmProofTitle` around the reference hook
669    /// `\flmRef` (LaTeX hooks, see
670    /// [`preamble`](crate::stdlib::backends::latex::preamble)),
671    /// `\begin{proof}[{\flmProofTitle{\flmRef{ref1}}}]`, which sets "Proof
672    /// (theorem 1)" by default; `[**ref1]` writes no optional argument,
673    /// `\begin{proof}`, and LaTeX sets its own "Proof".
674    ///
675    /// In both forms, a title that the author wrote on a proof is written
676    /// inside the proof title hook, `[{\flmProofTitle{Sketch}}]`, and
677    /// `\noproofref` is written as the author wrote it
678    /// ([`theorems::latex`](crate::stdlib::features::theorems::latex)).
679    pub resolved_proof_refs: bool,
680}
681
682/// When the style file is written: the value of the render option
683/// [`style_file`](LatexRecomposedRenderOptions::style_file).
684///
685/// The style file ([`style`](crate::stdlib::backends::latex::style)) is the
686/// `.sty` file written beside the recomposed LaTeX document, holding exactly
687/// the package requests, character declarations and definitions that the
688/// document needs to compile. A document that needs none of them (plain text
689/// with no heading, label, reference, verbatim content or declared character)
690/// needs no style file, unless its author asked for one through
691/// [`extra_packages`](LatexRecomposedRenderOptions::extra_packages) or
692/// [`extra_preamble`](LatexRecomposedRenderOptions::extra_preamble), whose
693/// content is written only into the style file.
694///
695/// The regions stage ([`LatexRecomposedRegionsStage`]) reads this value.
696#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Deserialize)]
697#[derive(schemars::JsonSchema)]
698#[serde(rename_all = "kebab-case")]
699pub enum StyleFile {
700    /// The style file is written only where it would hold something. A
701    /// document with no package request, no declared character, no definition
702    /// piece and no user definition, whose author set neither
703    /// [`extra_packages`](LatexRecomposedRenderOptions::extra_packages) nor
704    /// [`extra_preamble`](LatexRecomposedRenderOptions::extra_preamble), gets
705    /// no style artifact, and its recomposed LaTeX begins without the comment
706    /// line that gives the style file's name. The default.
707    #[default]
708    WhenNeeded,
709    /// The style file is always written, even where it holds nothing, for a
710    /// host that expects a style file beside every recomposed output.
711    Always,
712}
713
714impl StyleFile {
715    /// The value's stable name, as the settings write it: `when-needed` or
716    /// `always`.
717    pub fn as_str(self) -> &'static str {
718        match self {
719            StyleFile::WhenNeeded => "when-needed",
720            StyleFile::Always => "always",
721        }
722    }
723
724    /// The value whose stable name is `name` ([`as_str`](Self::as_str)), or
725    /// `None` when `name` is neither `when-needed` nor `always`.
726    pub fn parse(name: &str) -> Option<StyleFile> {
727        match name {
728            "when-needed" => Some(StyleFile::WhenNeeded),
729            "always" => Some(StyleFile::Always),
730            _ => None,
731        }
732    }
733}
734
735impl Default for LatexRecomposedRenderOptions {
736    fn default() -> LatexRecomposedRenderOptions {
737        LatexRecomposedRenderOptions {
738            unicode: UnicodeMode::Declare,
739            unicode_overrides: BTreeMap::new(),
740            drop_comments: false,
741            skip_packages: BTreeSet::new(),
742            extra_packages: Vec::new(),
743            extra_preamble: ExtraPreamble::default(),
744            bare_names: BTreeSet::new(),
745            robust_names: BTreeSet::new(),
746            style_stem: String::from(DEFAULT_STYLE_STEM),
747            style_file: StyleFile::WhenNeeded,
748            heading_hook: true,
749            label_hooks: true,
750            drop_math_labels_without_refs: false,
751            resolved_proof_refs: false,
752        }
753    }
754}
755
756
757/// The feature that registers the `latex-recomposed` backend (see the module
758/// documentation).
759///
760/// Use [`feature()`] to obtain it as a value that a package entry can list.
761/// When registered, it declares:
762///
763/// - the tables: the lowered trees that its lowering stage writes
764///   (`flm.lowered.latex-recomposed`), the three tables that its emit stage
765///   writes, the lowered pieces (document-level values such as the title,
766///   placed beside the content; [`Piece`](crate::core::piece::Piece)), the
767///   output regions, the style-file table,
768///   the artifact table and the artifact set (see [`mod@super::stages`]);
769/// - the settings, with the render options
770///   ([`LatexRecomposedRenderOptions`]);
771/// - the pieces stage ([`PiecesStage`]), which lowers only the pieces that
772///   the render request asks to place, and the regions stage
773///   ([`LatexRecomposedRegionsStage`]);
774/// - its regions output ([`RegionsOutput`]), contributed to the service slot
775///   `flm.output.regions` so that a host can assemble the output's regions
776///   through a template of its own;
777/// - the two structural lowering rules ([`super::rules()`]);
778/// - the backend ([`BackendDef`]), with its native element set and its
779///   lowering, emit and final stages ([`super::stages()`]);
780/// - the `latex-recomposed` output ([`OutputDef`]) and the
781///   `latex-recomposed` workflow ([`WorkflowDef`]).
782#[derive(Debug, Default, Clone, Copy)]
783pub struct LatexRecomposed;
784
785impl FlmFeature for LatexRecomposed {
786    fn info(&self) -> FeatureInfo {
787        FeatureInfo::new(FEATURE_NAME, "LaTeX (recomposed) backend").docs(
788            "the document recomposed into LaTeX from the raw tree: the `latex-recomposed` \
789             output and workflow, a body and a style file",
790        )
791    }
792
793    fn settings(&self) -> Option<SettingsDecl> {
794        Some(settings())
795    }
796
797    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
798        b.table_named::<LoweredTrees>(
799            lowered_table_name(&BACKEND.into()),
800            "the recomposed backend's lowered trees, one per document tree",
801        )?;
802        b.table(
803            OUTPUT_TABLE,
804            "per tree: the recomposed LaTeX, the characters it declares, the requirement \
805             identifiers it needs",
806        )?;
807        b.table(PACKAGES_TABLE, "the package identifiers the recomposed trees require")?;
808        b.table(
809            PREAMBLE_TABLE,
810            "the definition pieces the recomposed trees require and the user definitions \
811             they recomposed",
812        )?;
813        b.table(DOCUMENT, "the recomposed LaTeX and its style file as an artifact set")?;
814        b.table_named::<LoweredPieces>(
815            lowered_pieces_table_name(&BACKEND.into()),
816            "the pieces that the render request places, lowered for the recomposed backend",
817        )?;
818        // A LaTeX document places its pieces where LaTeX wants them (the
819        // title in `\title`), which a template knows and the fixed skeleton
820        // does not: the backend places none unless a render names them.
821        b.stage(Arc::new(PiecesStage::new(BACKEND).placing_only_named()))?;
822        b.table(REGIONS, "the body, the pieces and the style file's package name")?;
823        b.table(STYLE_FILE, "the style file beside the recomposed LaTeX, where it has one")?;
824        b.table(
825            ARTIFACTS,
826            "files a stage produces beside the recomposed LaTeX for it to refer to (copies of images), \
827             added to the document's set after the style file",
828        )?;
829        b.stage(Arc::new(LatexRecomposedRegionsStage))?;
830        b.contribute_to::<RegionsOutput>(
831            REGIONS_SLOT,
832            Arc::new(RegionsOutput {
833                output: BACKEND.into(),
834                backend: BACKEND.into(),
835                document: DOCUMENT.name().into(),
836                capability: DOCUMENT.name().into(),
837                regions: REGIONS.handle(),
838                artifacts: vec![STYLE_FILE.handle(), ARTIFACTS.handle()],
839            }),
840        )?;
841        for rule in rules() {
842            b.lowering_rule(rule)?;
843        }
844        let (lowering, emit, final_stage) = stages();
845        b.backend(
846            BackendDef::new(BACKEND, native_elements(), lowering, emit, final_stage)
847                .docs("LaTeX recomposed from the raw tree, with a style file"),
848        )?;
849        b.output(
850            OutputDef::new(BACKEND, DOCUMENT.name(), DOCUMENT.name(), MEDIA_TYPE, EXTENSION)
851                .docs("the document recomposed into LaTeX, with its style file"),
852        )?;
853        b.workflow(
854            WorkflowDef::new(WORKFLOW)
855                .output(BACKEND)
856                .demand(VALIDATED)
857                .docs(
858                    "recompose the document into LaTeX, running every check and leaving \
859                     every resolution to LaTeX",
860                ),
861        )?;
862        Ok(())
863    }
864}
865
866/// Returns the [`LatexRecomposed`] feature as a shared value, ready to be
867/// listed in a package entry.
868///
869/// A package that lists it must also list three other features, or the
870/// registry build fails with an error that identifies the missing name:
871///
872/// - the `lowering` feature
873///   ([`lowering::feature`](crate::stdlib::backends::lowering::feature())),
874///   which registers the shared presentation elements;
875/// - the `latex` feature
876///   ([`latex::feature`](crate::stdlib::backends::latex::feature())), which
877///   registers the LaTeX construct elements that this backend writes natively
878///   and the service slots that its regions stage reads;
879/// - the `check` feature ([`check_feature`](crate::stdlib::check_feature)),
880///   which declares the [`flm.validated`](crate::stdlib::VALIDATED)
881///   collection that this backend's workflow demands beside its output.
882///
883/// It depends on no content feature: each standard feature registers its own
884/// recomposition rule for this backend, and an absent feature contributes
885/// none. When the registry holds an element that a document may contain and
886/// that no selected rule leads to the native set, building a plan for this
887/// backend fails ([`PlanError::Incomplete`](crate::core::plan::PlanError::Incomplete)),
888/// unless the plan request accepts that element as unrenderable
889/// ([`PlanRequest::unsupported`](crate::core::plan::PlanRequest::unsupported)).
890///
891/// # Examples
892///
893/// ```
894/// use flm_core::stdlib::backends::latex_recomposed;
895///
896/// assert_eq!(latex_recomposed::feature().info().name.as_str(), latex_recomposed::FEATURE_NAME);
897/// ```
898pub fn feature() -> Arc<dyn FlmFeature> {
899    Arc::new(LatexRecomposed)
900}
901
902#[cfg(test)]
903mod tests {
904    use super::*;
905
906    #[test]
907    fn the_native_set_is_exactly_the_sixteen_elements_of_the_design() {
908        let native = native_elements();
909        let names: Vec<&str> = native.iter().map(|element| element.as_str()).collect();
910        assert_eq!(
911            names,
912            [
913                "flm.pres.latex.macro",
914                "flm.pres.latex.environment",
915                "flm.pres.latex.raw",
916                "flm.pres.latex.definition",
917                "flm.pres.math-passthrough",
918                "flm.pres.verbatim",
919                "flm.pres.unknown",
920                "flm.pres.unsupported",
921                "flm.pres.dropped",
922                "flm.pres.subtree",
923                "flm.pres.span",
924                "flm.text",
925                "flm.group",
926                "flm.opaque-wrapper",
927                "flm.comment",
928                "flm.container",
929            ]
930        );
931    }
932
933    #[test]
934    fn the_options_default_as_the_design_says() {
935        let options = LatexRecomposedRenderOptions::default();
936        assert_eq!(options.unicode, UnicodeMode::Declare);
937        assert!(options.unicode_overrides.is_empty());
938        assert!(!options.drop_comments);
939        assert!(options.skip_packages.is_empty());
940        assert!(options.extra_packages.is_empty());
941        assert!(options.extra_preamble.is_empty());
942        assert!(options.bare_names.is_empty());
943        assert!(options.robust_names.is_empty());
944        assert_eq!(options.style_stem, DEFAULT_STYLE_STEM);
945        assert_eq!(options.style_file, StyleFile::WhenNeeded);
946        assert!(options.heading_hook);
947        assert!(options.label_hooks);
948        assert!(!options.drop_math_labels_without_refs);
949        assert!(!options.resolved_proof_refs);
950    }
951
952    #[test]
953    fn the_style_file_setting_round_trips_through_its_name() {
954        for value in [StyleFile::WhenNeeded, StyleFile::Always] {
955            assert_eq!(StyleFile::parse(value.as_str()), Some(value));
956        }
957        assert_eq!(StyleFile::parse("sometimes"), None);
958    }
959}