flm_core/stdlib/features/defterm/mod.rs
1//! The `defterm` feature: defined terms. An author defines a term where it is
2//! explained, with the `defterm` environment, and links to that term
3//! definition from anywhere in the document with `\term`.
4//!
5//! # What an author writes
6//!
7//! ```text
8//! \begin{defterm}{Markov chain}\label{topic:markov}\aliasterm{Markov chains}
9//! A random process whose next state depends on its present state alone.
10//! \end{defterm}
11//!
12//! Every \term{Markov chain} forgets its past, as \term{Markov chains} do;
13//! \term[Markov chain]{such a process} does too. See \ref{topic:markov}.
14//! ```
15//!
16//! A **term definition** is the environment `defterm`. Its one argument is
17//! the **term** being defined, inline content (`\(\alpha\)-decay`,
18//! `\emph{Markov} chain`), and its body holds the explanation's paragraphs.
19//! After the term, the environment accepts two repeatable fields, in any
20//! order:
21//!
22//! - `\label{…}`, a label by which `\ref` and `\hyperref` refer to the term
23//! definition, of the label type `term` or `topic` ([`LABEL_TYPES`]); a
24//! reference to a term definition shows its term;
25//! - `\aliasterm{…}`, an **alias**: another way of writing the term (a
26//! plural, an inflected form), under which a term link finds the same term
27//! definition.
28//!
29//! A **term link** is `\term[ref]{shown}`: a link to the definition of the
30//! term `ref`, or of the term `shown` where the bracket is left out or blank,
31//! showing the text `shown`. Terms are matched by their **identity**: the source text
32//! they are written as, with whitespace collapsed
33//! ([`spelling_identity`](crate::stdlib::backends::pres::spelling_identity)).
34//! The match is exact, case and markup included, so `\term{Entropy}` finds no
35//! definition of `entropy`. A term's other forms are declared with
36//! `\aliasterm`; nothing else matches a term to a term definition. The
37//! language guide describes these commands for authors under [Defined
38//! terms](crate::guide::language_syntax#defined-terms).
39//!
40//! # A term link is a reference
41//!
42//! A term definition declares one [reference
43//! point](crate::model::aspects::RefPoint) and a term link declares one
44//! [reference site](crate::model::aspects::RefSite) ([`elements`] gives the
45//! labels; see [reference points, labels and
46//! anchors](crate::guide::concepts_overview#reference-points-labels-and-anchors)).
47//! The [references](crate::stdlib::features::refs) feature resolves the site
48//! against the point through its stages and tables, as it resolves `\ref`;
49//! no code of this feature looks a term definition up. A term definition's
50//! reference point carries a label computed from its term, one computed from
51//! each alias, then the labels the author wrote ([`elements`]). Therefore:
52//!
53//! - a term link that nothing resolves is reported by the references feature
54//! as `flm.refs.unresolved`, an Error by default;
55//! - two term definitions of one term carry the same computed label, which
56//! the references feature reports as `flm.refs.duplicate-label`, and every
57//! term link finds the first one;
58//! - a term definition's anchor is the one that feature computes from the
59//! point's first label: the label computed from the term, where the term is
60//! not empty.
61//!
62//! # How they are written
63//!
64//! A term definition is written as a block holding its body, whose first
65//! paragraph opens with the **lead-in**: the configured lead-in template
66//! ([`DeftermConfig`]), `#{term}: ` by default, so that the term definition
67//! reads `Markov chain: A random process …`. The lead-in is set as a run-in
68//! heading is, and shows the term where the term definition writes it, never
69//! a copy ([`lead_in`]). A term link is a link of the kind `term` around the
70//! text written for it, except inside the definition of its own term, where
71//! it is the term being defined: a span of role `flm.defterm.term`, linked to
72//! nothing ([`rules`]).
73//!
74//! On the text and `html` backends the lead-in is followed by the backend's
75//! run-in stop (the render option `run_in_stop`, a period by default) only
76//! where it ends without punctuation.
77//!
78//! - On the **text backend**, the lead-in is printed before the first
79//! paragraph's words, and a term link is its text.
80//! - On the **`html` backend**, a term definition is a block carrying its
81//! anchor and a term link is a link of kind `term`; the term being defined
82//! is a span that the feature's stylesheet sets in italics ([`html`]).
83//! - On the **`latex-recomposed` backend**, a term definition is written back
84//! as the environment `defterm`, its labels made to refer to it with the
85//! term as their display text, and the style file defines the environment
86//! from the configured lead-in. A term link is the LaTeX hook
87//! `\flmTerm{<label>}{<shown>}`, and, inside the definition of its own
88//! term, `\flmTermInDefterm{<shown>}`; an author redefines either
89//! ([`latex`]).
90//!
91//! The rendering guide describes the outputs under [Defined
92//! terms](crate::guide::rendering#defined-terms), [Defined terms in
93//! HTML](crate::guide::rendering#defined-terms-in-html) and [Defined terms in
94//! the recomposed LaTeX](crate::guide::rendering#defined-terms-in-the-recomposed-latex).
95//!
96//! # What the feature provides to the pipeline
97//!
98//! - **Elements.** [`DEFTERM`] (`flm.defterm`), the environment `defterm`,
99//! and [`TERM`] (`flm.term`), the command `\term`, both available in text
100//! mode; and the synthesized element [`TERM_POINTER`], which shows the term
101//! inside a lead-in ([`lead_in`]); no document can write it.
102//! - **Two argument roles**, each stating what an argument holds
103//! ([`ArgDef::role`](crate::lang::mint::ArgDef::role)).
104//! [`DEFINED_TERM_ARG_ROLE`] (`flm.defterm.defined-term`) is the role of
105//! the term a `defterm` environment defines and of its `\aliasterm`
106//! field's argument; [`TARGET_ARG_ROLE`] (`flm.defterm.target`) is the role
107//! of the term a `\term` points to.
108//! - **The general lowering rules**, [`DEFINITION_RULE`], [`TERM_RULE`] and
109//! [`POINTER_RULE`], each the default on every backend ([`rules`],
110//! [`lead_in`]).
111//! The term definition's general rule requires the feature's style
112//! identifier `flm.defterm.style` ([`html::STYLE`]) at every definition it
113//! stages, and the term link's where it writes the term inside its own
114//! definition.
115//! - **On the `html` backend**, the feature's stylesheet,
116//! `flm.defterm.style` ([`html`]).
117//! - **On the `latex-rendered` backend**, the definition piece
118//! `flm.latex.def.flmx.defterm` ([`latex_rendered`]), which the same
119//! requirement brings into the style file.
120//! - **On the `latex-recomposed` backend**, the rules of the three elements
121//! and the feature's definition piece `flm.latex.def.defterm` ([`latex`]).
122//! - **A configuration**, [`DeftermConfig`], whose one field, the lead-in
123//! template, is the feature's settings key. It is fixed when the registry is
124//! built (see [settings, options and
125//! configuration](crate::guide::concepts_overview#settings-options-and-configuration)),
126//! and a build hook ([`LateInit`](crate::core::registry::LateInit))
127//! compiles the template once the language is built.
128//!
129//! # Interactions with other features
130//!
131//! The feature reads the references feature's anchors and resolutions tables
132//! optionally, and declares them through peer declarations
133//! ([`PeerName`](crate::core::registry::PeerName)); it declares the same way
134//! the argument role that the references feature gives the argument of the
135//! `\label` field ([`DEFINED_LABEL_ARG_ROLE`](refs::DEFINED_LABEL_ARG_ROLE)).
136//! It therefore builds and renders in a registry without the references
137//! feature: a term definition declares its reference point, which nothing
138//! reads, and is written with no anchor, and a term link is its text. The rules of the `latex-recomposed`
139//! backend are registered under peer declarations of their backend and of
140//! the LaTeX family's elements; in a registry without them, those rules are
141//! set aside (excluded from rule selection; see
142//! [`PeerName`](crate::core::registry::PeerName)).
143//!
144//! # Map of the items
145//!
146//! - The feature: [`Defterm`], [`feature`], [`FEATURE`].
147//! - The configuration: [`DeftermConfig`], [`DEFAULT_LEAD_IN`].
148//! - The elements, their arguments and the identity of a term: [`elements`]
149//! ([`DEFTERM`], [`TERM`], [`term_target`], [`in_own_definition`]).
150//! - The lead-in and the term pointer: [`lead_in`].
151//! - The general rules: [`rules`].
152//! - The conditions: [`EmptyTerm`], [`PointerRefused`].
153//! - The stylesheet: [`html`]. The `latex-recomposed` backend's own rules:
154//! [`latex`].
155
156// A term link is resolved by the references feature, with no lookup of this
157// feature's own: that feature already resolves every reference site under one
158// set of conditions and one severity rule, which a second lookup would repeat
159// and could contradict.
160
161mod config;
162mod diagnostics;
163pub mod elements;
164pub mod html;
165pub mod latex;
166pub mod latex_rendered;
167pub mod lead_in;
168pub mod rules;
169
170use std::sync::Arc;
171
172use crate::core::settings::SettingsDecl;
173use crate::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature};
174use crate::lang::mint::{BodyDef, ElementDef, SyntaxDef};
175use crate::stdlib::features::refs;
176
177pub use config::{DEFAULT_LEAD_IN, DeftermConfig};
178pub use diagnostics::{EmptyTerm, PointerRefused};
179pub use elements::{
180 ALIAS_ARG, ALIAS_FIELD, DEFINED_TERM_ARG_ROLE, DEFINITION_KIND, DEFTERM, DeftermElement,
181 LABEL_TYPES, REF_ARG, SHOWN_ARG, TARGET_ARG_ROLE, TERM, TERM_ARG, TermElement, defterm_args, defterm_element, in_own_definition,
182 term_args, term_element, term_target,
183};
184pub use lead_in::{LEAD_IN_ROLE, POINTER_RULE, PointerRule, TERM_PLACEHOLDER, TERM_POINTER};
185pub use rules::{
186 DEFINITION_RULE, DefinitionRule, TERM_LINK_KIND, TERM_ROLE, TERM_RULE, TermRule,
187};
188
189/// The feature's registered name, `defterm`.
190pub const FEATURE: &str = "defterm";
191
192/// The declaration of the feature's settings: the fields of [`DeftermConfig`] are its keys, and
193/// the lead-in template is FLM markup. See [`crate::core::settings`].
194fn settings() -> SettingsDecl {
195 SettingsDecl::new(FEATURE)
196 .config::<DeftermConfig>(
197 "The lead-in of a term definition (the `defterm` environment): a template in which \
198 `#{term}` is the term being defined, or none for no lead-in. Fixed when the \
199 registry is built: it cannot vary per document or per render.",
200 )
201 .markup("lead_in")
202}
203
204/// The `defterm` feature ([`FlmFeature`]): under a [`DeftermConfig`], it
205/// registers the environment `defterm` and the command `\term`, the term
206/// pointer, their lowering rules on every backend, and the build hook that
207/// compiles the lead-in template. See the [module documentation](self).
208///
209/// Construct it with [`Defterm::new`], or use [`feature`] for the default
210/// configuration. The registry build fails when the lead-in template does
211/// not compile.
212#[derive(Debug, Default, Clone)]
213pub struct Defterm {
214 config: DeftermConfig,
215}
216
217impl Defterm {
218 /// Creates the feature with the configuration `config`, which is fixed for
219 /// the life of the registry the feature is registered into.
220 pub fn new(config: DeftermConfig) -> Defterm {
221 Defterm { config }
222 }
223
224 /// The configuration this feature was constructed with.
225 pub fn config(&self) -> &DeftermConfig {
226 &self.config
227 }
228}
229
230impl FlmFeature for Defterm {
231 fn info(&self) -> FeatureInfo {
232 FeatureInfo::new(FEATURE, "Defined terms").docs(
233 "Defined terms: the `defterm` environment, which defines a term and carries one \
234 reference point, and `\\term`, a link to a term's definition, which the references \
235 feature resolves.",
236 )
237 }
238
239 fn settings(&self) -> Option<SettingsDecl> {
240 Some(settings())
241 }
242
243 fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
244 let owner = b.feature().clone();
245 b.argument_role(
246 DEFINED_TERM_ARG_ROLE,
247 "A term that a definition defines, by which term links point to the definition.",
248 )?;
249 b.argument_role(TARGET_ARG_ROLE, "The term that a term link points to.")?;
250 // The `\label` field of the environment is the references feature's,
251 // with that feature's role on its argument; declared as a peer, so
252 // that a registry without that feature still builds.
253 b.peer_argument_role(refs::DEFINED_LABEL_ARG_ROLE)?;
254 b.element(
255 ElementDef::new(
256 owner.clone(),
257 ["defterm"],
258 SyntaxDef::Environment { args: defterm_args(), body: BodyDef::new().blocks() },
259 defterm_element(),
260 )
261 .docs(
262 "Defines a term: its body is the definition, which term links point to. Labels \
263 and aliases of the term may be written after it.",
264 ),
265 )?;
266 b.element(
267 ElementDef::new(owner.clone(), ["term"], SyntaxDef::Macro { args: term_args() }, term_element())
268 .docs(
269 "Shows a text linked to the definition of a term: the term in brackets, or \
270 the text itself where the brackets are left out or blank.",
271 ),
272 )?;
273 // The term pointer a lead-in holds: synthesized, so no document can
274 // write it.
275 let pointer = lead_in::pointer_element();
276 b.element(
277 ElementDef::new(
278 owner.clone(),
279 Vec::<&str>::new(),
280 SyntaxDef::Synthesized,
281 Arc::clone(&pointer),
282 )
283 .docs(
284 "The term of a term definition, shown where the lead-in template places \
285 `#{term}`. It is never written in a document: the term definition's rule puts it \
286 there.",
287 ),
288 )?;
289 b.element_type_text(
290 elements::DEFTERM,
291 "The definition of a term: a body of blocks that defines the term, which term links \
292 point to.",
293 )?;
294 b.element_type_text(
295 elements::TERM,
296 "A link to the definition of a term, shown as the text written for it.",
297 )?;
298 b.element_type_text(
299 lead_in::TERM_POINTER,
300 "The term of a term definition, shown in the definition's lead-in.",
301 )?;
302 // The two tables belong to the references feature, which may be
303 // absent: the rules read them optionally, and write a definition with
304 // no anchor and a term link as its text.
305 b.peer_table::<refs::Anchors>(
306 refs::ANCHORS.name(),
307 "the references feature's anchors table, which the term definition's rule reads for \
308 the anchor of the term definition's reference point",
309 )?;
310 b.peer_table::<refs::RefResolutions>(
311 refs::REF_RESOLUTIONS.name(),
312 "the references feature's resolutions table, which the term link's rule reads for \
313 the term definition a term link resolved to",
314 )?;
315 let lead_in = Arc::new(lead_in::LeadIn::new(self.config.lead_in.clone(), pointer));
316 b.late_init(Arc::new(lead_in::CompileLeadIn { lead_in: Arc::clone(&lead_in) }))?;
317 b.lowering_rule(rules::definition_rule(Arc::clone(&lead_in)))?;
318 b.lowering_rule(rules::term_rule())?;
319 b.lowering_rule(lead_in::pointer_rule())?;
320 b.digest_input(&self.config.digest_bytes())?;
321 html::register(b)?;
322 latex_rendered::register(b)?;
323 latex::register(b, lead_in)?;
324 Ok(())
325 }
326}
327
328/// The [`Defterm`] feature under the default configuration (the lead-in
329/// [`DEFAULT_LEAD_IN`]), ready to be listed in a package entry
330/// ([`PackageEntry`](crate::core::registry::PackageEntry)).
331///
332/// Use `Arc::new(Defterm::new(config))` to list the feature under a
333/// [`DeftermConfig`] of your own.
334pub fn feature() -> Arc<dyn FlmFeature> {
335 Arc::new(Defterm::default())
336}
337
338#[cfg(test)]
339mod tests {
340 use super::*;
341
342 #[test]
343 fn the_feature_names_itself() {
344 assert_eq!(Defterm::default().info().name, FEATURE);
345 }
346}