flm_core/stdlib/features/refs/mod.rs
1//! The `refs` feature: labels and references. An author attaches a label to a
2//! construct with `\label{sec:intro}` and refers to it with `\ref{sec:intro}`,
3//! and the feature turns each reference into a link to the labeled place,
4//! showing that place's number or title.
5//!
6//! The terms are those of the concepts overview, [Reference points, labels and
7//! anchors](crate::guide::concepts_overview#reference-points-labels-and-anchors):
8//! a *reference point* ([`RefPoint`](crate::model::aspects::RefPoint)) is one
9//! place in a document that can be referred to, numbered, or given an anchor
10//! (a heading, an equation line, a theorem, a footnote); a *label* is the text
11//! an author attaches to it with `\label{type:label}`; an *anchor* is the
12//! identifier a link points at, computed once for every point ([`ANCHORS`]);
13//! and a *reference site* ([`RefSite`](crate::model::aspects::RefSite)) is one
14//! place that points at a reference point, such as a `\ref`.
15//!
16//! # What an author writes
17//!
18//! - **`\label{type:label}`**, written right after a construct that accepts
19//! labels (`\section{Introduction}\label{sec:intro}`). The *label type* is
20//! the part before the colon and says what sort of place the label marks;
21//! each construct accepts a fixed set of types (a heading accepts `sec` and
22//! `topic`). A label may be written only once in a document. A `\label` is a
23//! [field](crate::guide::concepts_overview#fields-data-a-construct-reads), a
24//! macro that the construct before it reads as data, so it is available only
25//! after a construct that declares it.
26//! - **`\ref[options]{type:label}`**, a reference that shows what its target
27//! has to show: its number, else its content (a heading's title, for
28//! instance), else the label as written. Several targets may be written in
29//! one `\ref`, separated by commas (`\ref{eq:a,eq:b}`), and are shown as one
30//! list. The options choose the wording of the word before a number:
31//! `noprefix` leaves that word out, `S` asks for the capitalized wording
32//! where the [counter
33//! style](crate::stdlib::features::numbering::CounterStyleDecl) (how the
34//! numbering feature shows a counter's value; see [counters and counter
35//! styles](crate::guide::concepts_overview#counters-and-counter-styles))
36//! declares one, and any other key asks for the
37//! wording variant of that name (`abbreviated`, `lowercase`, `capital`).
38//! - **`\hyperref[type:label]{text}`**, a reference that shows the author's
39//! own text instead of what the target has to show.
40//!
41//! The syntax guide shows these commands from an author's side, under
42//! [Labels and references](crate::guide::language_syntax#labels-and-references).
43//!
44//! # What a reference displays
45//!
46//! A reference point states the two things a reference to it may show: a
47//! number source ([`NumberSource`](crate::model::aspects::NumberSource)), the
48//! counter and the counter style it is numbered by, where it can be numbered
49//! at all; and content of the document, where it has any. For each target, a
50//! `\ref` shows the first of these that exists:
51//!
52//! 1. the number this document gave the point;
53//! 2. else the point's content;
54//! 3. else the label the reference was written with, as written.
55//!
56//! A point that states a number source may still receive no number in a run:
57//! no numbering feature is registered, nobody declares its counter, or a
58//! counter it is numbered within has no value yet. A point that ends up with
59//! neither a number nor content has nothing to show (an unnumbered float with
60//! no caption, an equation in a registry without the numbering feature), and a
61//! reference to it is the Error [`NothingToShow`] (`flm.refs.nothing-to-show`).
62//!
63//! The number is read from the counter table of the
64//! [`numbering`](crate::stdlib::features::numbering) feature, which the
65//! `\ref` lowering rule reads optionally, through a peer declaration
66//! ([`PeerName`](crate::core::registry::PeerName)): in a registry without that
67//! feature, a reference shows the point's content or its label. The counter
68//! style of the point decides what a number looks like
69//! (the word before it, the delimiters around it, how several numbers are
70//! joined), and the options written on a `\ref` choose among the wording
71//! variants that the style declares. The key `S` asks for the variant
72//! [`CAPITAL_VARIANT`] where the style declares it and for the usual wording
73//! otherwise. Any other key asks for the variant of its own name, and where
74//! the counter style of a numbered target does not declare that variant, the
75//! reference is the Error [`UndeclaredVariant`].
76//!
77//! **A `\ref` with several targets** is written as one list. Its first items
78//! are the numbers, one item per counter style, each written by that style
79//! with consecutive numbers collapsed into a range; then come the other
80//! targets, one item each, in the order the reference wrote them. The items
81//! are joined by the texts of the feature's configuration, [`RefsConfig`]:
82//! `Eq. (1) and Thm. 1.1`, `Eq. (1), Thm. 1.1, and A note`. Another feature
83//! that shows a reference from a command of its own calls
84//! [`lower_reference`], which writes the items.
85//!
86//! A point's content (a heading's title, for instance) is copied out of the
87//! frozen tree into a [synthesized
88//! value](crate::guide::concepts_overview#synthesized-values), a small tree
89//! held in a table, when the anchors stage writes the point's target. Content
90//! that the point's element built itself because no node of the tree holds it
91//! (the bullet beside a list's item,
92//! [`ContentRef::Synthesized`](crate::model::aspects::ContentRef::Synthesized))
93//! is already such a tree and is shared rather than copied. The `\ref` rule
94//! splices the synthesized value into the nodes it stages (builds into the
95//! lowered tree; see [`Lowerer`](crate::core::lowering::Lowerer)): the value is first
96//! brought up to date by [value
97//! catch-up](crate::guide::concepts_overview#value-catch-up), which runs the
98//! plan's rewrites and the per-tree stages the lowering depends on over the
99//! value alone, and is then lowered through the rules. A `\ref` written inside
100//! a heading's title therefore resolves exactly like one written in the body.
101//!
102//! # What the feature registers
103//!
104//! The `refs` feature ([`Refs`], a [`FlmFeature`])
105//! registers:
106//!
107//! - **Two elements.** [`REF`] (`flm.ref`), the `\ref` element, and
108//! [`HYPERREF`] (`flm.hyperref`), the `\hyperref` element. A node of either
109//! declares its reference sites through the
110//! [`Referencing`](crate::model::aspects::Referencing) aspect, one per
111//! target, and goes through the same stages; the two differ in what they
112//! display. The feature registers no element for the `\label` written after
113//! a construct: like every tack-on field,
114//! its node carries the language's field element
115//! ([`FIELD`](crate::lang::structural::FIELD)).
116//! - **A scoped package.** A scoped package
117//! ([`ScopedPackageDef`](crate::lang::mint::ScopedPackageDef)) is a set of
118//! element declarations that can be written only inside the environment
119//! bodies and arguments whose declarations refer to it by name
120//! ([scoped packages](crate::guide::concepts_overview#scoped-packages)).
121//! [`LABEL_PACKAGE`] (`flm.refs.label`, built by [`label_package`]) holds
122//! `\label` as a command, for the arguments that refer to it, such as the
123//! optional argument of `\footnote`.
124//! - **Two argument roles.** An argument role states what an argument holds
125//! ([`ArgDef::role`](crate::lang::mint::ArgDef::role)). [`TARGET_ARG_ROLE`]
126//! (`flm.refs.target`) is the role of the target argument of `\ref` and
127//! `\hyperref`, the label or labels a reference points to.
128//! [`DEFINED_LABEL_ARG_ROLE`] (`flm.refs.defined-label`) is the role of the
129//! argument of `\label`, the label it attaches to a construct, in the
130//! `\label` field and in the scoped package's `\label` command.
131//! - **Four tables.** [`LABELS`] (`flm.labels`): the first point that wrote
132//! each label, the labels written more than once, and the labels refused for
133//! their type.
134//! [`ANCHORS`] (`flm.anchors`): each point's anchor, or none.
135//! [`REF_TARGETS`] (`flm.refs.targets`): for each label, the point, its link
136//! target and what a reference to it shows. [`REF_RESOLUTIONS`]
137//! (`flm.refs.resolutions`): how each reference site resolved.
138//! - **An external table.** [`EXTERNAL_INDEX`] (`flm.refs.external-index`):
139//! labels of other documents, with their link targets and the content a
140//! reference to them shows. An external table is a table that no stage of
141//! the run writes: the caller installs its value when the run is
142//! constructed ([`Externals`](crate::core::run::Externals)). The resolve
143//! stage reads it when the caller has installed it.
144//! - **Four stages.** [`SCAN`] records the first point that wrote each label;
145//! [`ANCHORS_STAGE`] gives every point its anchor and writes the targets;
146//! [`RESOLVE`] resolves every reference site; [`CHECK_LABELS`] reports the
147//! duplicate labels and the labels of a type their point does not accept.
148//! The check provides the capability of its own name, a member of the
149//! [`flm.validated`](crate::stdlib::VALIDATED) collection of capabilities,
150//! which every standard workflow demands (asks the plan to
151//! provide; see [`PlanRequest`](crate::core::plan::PlanRequest)). The documentation of each
152//! constant says what its stage reads and writes.
153//! - **Render options.** [`RefsRenderOptions`], set per render request:
154//! whether an unresolved reference is an Error or a Warning.
155//! - **A configuration.** [`RefsConfig`], the texts that join the items of a
156//! reference to several targets. A feature's configuration is the plain
157//! Rust value the feature is constructed from; it is fixed when the registry
158//! is built ([settings, options and
159//! configuration](crate::guide::concepts_overview#settings-options-and-configuration)).
160//! - **Lowering rules, per backend.** On every backend, [`REF_RULE`] lowers a
161//! `\ref` to a [`flm.pres.link`](crate::stdlib::backends::pres::LINK) to
162//! each target, around the number, the content or the label it shows, and
163//! [`HYPERREF_RULE`] lowers a `\hyperref` to a link around the author's
164//! text; a target that nothing resolves becomes a
165//! [`flm.pres.span`](crate::stdlib::backends::pres::SPAN) styled as an
166//! unresolved reference instead of a link. The HTML backend writes the link
167//! as an `<a>` element ([References in
168//! HTML](crate::guide::rendering#references-in-html)). On the
169//! `latex-recomposed` backend, the rules of the submodule [`latex`] are the
170//! default instead: they leave the resolution to LaTeX and write `\label`,
171//! `\flmRef` and `\flmHyperref` around safe labels (see *Recomposing to
172//! LaTeX* below).
173//! - **The stages and tables of the recomposed LaTeX**, in the submodule
174//! [`safe_labels`]: the safe labels the recomposed LaTeX writes in place of
175//! the document's labels.
176//!
177//! # Anchors
178//!
179//! An anchor is the identifier a link points at for a reference point. The
180//! element of the point chooses how it is formed
181//! ([`AnchorPolicy`](crate::model::aspects::AnchorPolicy)), and the anchors
182//! stage computes it once:
183//!
184//! - `<type>-<label>` from the first label the point keeps: `sec-intro`
185//! ([`label_anchor`]);
186//! - `<prefix>--<title>` for an unlabeled heading: `sec--Introduction`
187//! ([`title_anchor`]);
188//! - `<prefix>--<position><four letters>` for an unlabeled point whose element
189//! asks for its position (an equation line, a list item, an xnote):
190//! `eq--8otbc` for the eighth equation line ([`auto_anchor`]);
191//! - `<prefix>-<numbers>` from the number the document gave the point, for an
192//! element that asks for it (a theorem, a float): `theorem-2-3`
193//! ([`value_anchor`]); a point the document did not number takes its first
194//! label instead;
195//! - an identifier the element gives itself, used as given.
196//!
197//! The element states the prefix, so that the anchor of a point begins the
198//! same way whether it was labeled or not. The prefix, the parts of a label,
199//! a title and a number text go through one encoder, [`encode_anchor`]: a text
200//! made only of ASCII letters, digits, `.`,
201//! `-` and single spaces is reproduced exactly, each space written `_`; any
202//! other text is stripped of accents, every run of other characters is
203//! replaced by `_` or `-`, and `~` and six hexadecimal digits of a hash of the
204//! text as written are appended. No counter
205//! takes part in a label's anchor, so one label always yields one anchor,
206//! regardless of what else the document contains.
207//!
208//! An anchor made from a title is never refused: where another point already
209//! holds the anchor it would take (another heading with the same title, or a
210//! point whose anchor encodes alike), it takes the next free number
211//! (`sec--Introduction-2`), and nothing is reported. Any other anchor that
212//! another point already holds is a collision: the Error [`AnchorCollision`]
213//! is reported, the first point keeps the anchor, and the second gets none.
214//!
215//! # Label types
216//!
217//! A reference point declares which label types may be written for it
218//! ([`RefPoint::accepts`](crate::model::aspects::RefPoint::accepts)): a heading
219//! accepts `sec` and `topic`, so `\section{X}\label{eq:x}` defines no label. A
220//! point that declares
221//! [`AcceptedRefTypes::Any`](crate::model::aspects::AcceptedRefTypes) accepts
222//! every type; a feature declares it for a construct that fixes no set. A
223//! label of a type the point does not accept defines nothing: no reference
224//! resolves through it, and a point whose every label was refused gets no
225//! anchor from a label. [`CHECK_LABELS`] reports it as
226//! [`LabelTypeNotAccepted`] (`flm.refs.label-type-not-accepted`).
227//!
228//! A text that is not spelled `type:label` at all is no label: the construct
229//! keeps it among the point's
230//! [malformed](crate::model::aspects::RefPoint::malformed) texts, and the
231//! label scan reports it at the field where it was written, as [`BadLabel`]
232//! (`flm.refs.bad-label`). The scan reports a `\ref` or `\hyperref` target
233//! that is not spelled `type:label` the same way.
234//!
235//! # Duplicate labels and unresolved references
236//!
237//! A label written for two points is the Error [`DuplicateLabelCondition`]
238//! (`flm.refs.duplicate-label`), reported by [`CHECK_LABELS`]: the first point
239//! in document order keeps the label. This depends on the document alone.
240//!
241//! A reference that nothing resolves is reported as [`Unresolved`]
242//! (`flm.refs.unresolved`): an Error by default, a Warning under
243//! [`RefsRenderOptions`] with `unresolved: allow`. Either way, the reference
244//! shows its own text marked as unresolved: the label text for a `\ref`, the
245//! author's text for a `\hyperref`. In a plan that renders nothing, such as
246//! one of the [`check` workflow](crate::stdlib::CHECK_WORKFLOW), it is always
247//! a Warning, because whether a label resolves is decided per render, and a
248//! render may install an index of labels defined in other documents.
249//!
250//! # Declaring a labeled construct in another feature
251//!
252//! A feature gives one of its constructs labels in three steps:
253//!
254//! 1. The element's last argument is [`label_fields_arg`], the trailing
255//! tack-on argument (the trailing argument that absorbs field macros;
256//! [`ArgStdKind::TackOn`](crate::lang::mint::ArgStdKind::TackOn)) that holds
257//! the `\label` fields, so that `\thing{…}\label{x:y}` parses. The
258//! argument of the `\label` field has the argument role
259//! [`DEFINED_LABEL_ARG_ROLE`], which this feature declares; the other
260//! feature declares that role as a peer
261//! ([`FeatureBuilder::peer_argument_role`](crate::core::registry::FeatureBuilder::peer_argument_role)),
262//! so that a registry without the references feature still builds.
263//! 2. The element carries the
264//! [`Referenceable`](crate::model::aspects::Referenceable) aspect, whose
265//! implementation reads those fields with [`label_uses`], splits them with
266//! [`point_labels`], and returns the point (or points) the node declares.
267//! 3. Each point states the label types it accepts in its
268//! [`accepts`](crate::model::aspects::RefPoint::accepts) field: a list of
269//! types, or
270//! [`AcceptedRefTypes::Any`](crate::model::aspects::AcceptedRefTypes) for a
271//! construct that fixes none.
272//!
273//! A construct with a recomposition rule of its own writes its labels there
274//! with [`stage_label`] and [`stage_label_group`] (submodule [`latex`]). No
275//! other rule writes a label, because a field node that reaches a backend is
276//! an error.
277//!
278//! Two kinds of `\label` are not tack-on fields. Inside a display-math
279//! environment's body, the `math` feature declares `\label` as a command of
280//! its own ([`math::lines`](crate::stdlib::features::math::lines)); inside an
281//! argument that refers to the scoped package [`LABEL_PACKAGE`] (a construct
282//! whose labels are written in an argument of their own, as in
283//! `\footnote[\label{fn:x}]{…}`), this feature's package declares it. Both
284//! are field nodes of the same field name: [`label_use`] reads
285//! one such node, and [`label_uses_in`] reads every one of a run of nodes.
286//!
287//! # Recomposing to LaTeX
288//!
289//! The `latex-recomposed` backend writes the document back as LaTeX and
290//! leaves the resolution of references to LaTeX. LaTeX label keys must avoid
291//! certain characters, so the recomposed LaTeX writes a *safe label*
292//! ([`SafeLabels`]) in place of each FLM label: `ref1`, `ref2`, … in the order
293//! the document first mentions the labels. The submodule [`safe_labels`] holds
294//! the document-scope stage [`SAFE_LABELS_STAGE`], which writes the table
295//! [`SAFE_LABELS`] (`flm.labels.safe`), and the per-tree stage
296//! [`VALUE_SAFE_LABELS_STAGE`], which writes the table [`VALUE_SAFE_LABELS`]
297//! (`flm.labels.safe.value`) for the references of a synthesized value. The
298//! submodule [`latex`] holds the recomposition rules [`REF_LATEX_RULE`] and
299//! [`HYPERREF_LATEX_RULE`], the helpers [`stage_label`] and
300//! [`stage_label_group`] that a labeled construct's own rule writes its labels
301//! with, and the render options [`RefsRecomposeOptions`]. This feature
302//! registers those rules too; it declares the backend and the two LaTeX
303//! constructs they stage as peer declarations
304//! ([`PeerName`](crate::core::registry::PeerName)), so that a registry without
305//! the LaTeX features still builds, with those rules set aside (excluded from
306//! rule selection). The
307//! rendering guide describes the result under [References and safe
308//! labels](crate::guide::rendering#references-and-safe-labels).
309//!
310//! # Items for other features
311//!
312//! - Declaring and reading labels: [`label_fields_arg`], [`label_field`],
313//! [`label_uses`], [`label_uses_in`], [`label_use`], [`point_labels`],
314//! [`field_text`], [`label_package`].
315//! - Reading references: [`ref_targets`], [`hyperref_target`],
316//! [`reference_targets`], [`split_targets`], [`ref_display_options`],
317//! [`ref_args`], [`hyperref_args`].
318//! - Showing a reference from another command: [`lower_reference`]; what a
319//! reference to a label shows, for a host: [`designation`], [`Designation`].
320//! - Anchors: [`encode_anchor`], [`label_anchor`], [`title_anchor`],
321//! [`auto_anchor`], [`value_anchor`]; copying content into a synthesized
322//! value: [`content_value`], [`value_of`].
323//! - Writing labels and references in the recomposed LaTeX: [`stage_label`],
324//! [`stage_label_group`], [`stage_labels_with_display_text`],
325//! [`target_spelling`], [`label_spelling`], [`stage_spelling`],
326//! [`read_target_at_lowering`], [`reference_type_words`],
327//! [`stage_reference_type_setup`].
328
329// The label is a declared field that the labeled construct reads, not an element
330// of this feature: a construct declares its labels as it declares any other
331// argument, and a label is read by the construct that carries it and by nothing
332// else.
333// The element of a point chooses how its anchor is formed, because what a point
334// is reachable at depends on what kind of thing it is, which only the element
335// knows. An anchor from a label that another point already holds is reported,
336// never made unique by a suffix: a label is a name the author chose, and a
337// suffix would make its anchor depend on document order.
338// An unresolved reference is an Error by default because a dangling reference
339// in a finished document is worse than a failed render; a draft allows it
340// through the render options.
341
342mod content;
343mod elements;
344mod list;
345mod rules;
346mod stages;
347mod tables;
348pub mod latex;
349pub mod safe_labels;
350
351use std::sync::Arc;
352
353use crate::core::settings::SettingsDecl;
354use crate::model::options::Bind;
355use crate::core::registry::{BuildError, CapabilityDef, FeatureBuilder, FeatureInfo, FlmFeature};
356use crate::lang::mint::{ElementDef, SyntaxDef};
357use crate::stdlib::VALIDATED;
358use crate::stdlib::features::numbering::{COUNTERS, Counters};
359
360use list::{CompileList, ListTexts};
361
362pub use content::{
363 CopyError, auto_anchor, content_value, encode_anchor, label_anchor,
364 title_anchor, value_anchor, value_of,
365};
366pub use elements::{
367 ABBREVIATED_VARIANT, CAPITAL_KEY, CAPITAL_VARIANT, DEFINED_LABEL_ARG_ROLE, FIELDS_ARG, HYPERREF,
368 HyperrefElement, LABEL_FIELD, LABEL_PACKAGE, LOWERCASE_VARIANT, LabelUse, NO_PREFIX_KEY, OPTIONS_ARG, REF,
369 RefElement, RefTargetText, TARGET_ARG, TARGET_ARG_ROLE, TEXT_ARG, field_text, hyperref_args, hyperref_element, hyperref_target,
370 label_field, label_fields_arg, label_package, label_use, label_uses, label_uses_in, point_labels,
371 ref_args, ref_display_options, ref_element, ref_targets, reference_targets, split_targets,
372};
373pub use list::RefsConfig;
374pub use rules::{
375 Designation, HYPERREF_RULE, HyperrefRule, LINK_KIND, REF_RULE, RefRule, designation, lower_reference,
376};
377pub use stages::{
378 ANCHORS_STAGE, AnchorCollision, BadLabel, CHECK_LABELS, DisplayUnavailable,
379 DuplicateLabelCondition, LabelTypeNotAccepted, RESOLVE, RefsRenderOptions, SCAN, StageFailed,
380 NothingToShow, UndeclaredVariant, Unresolved, UnresolvedRefs,
381};
382pub use tables::{
383 ANCHORS, Anchors, DuplicateLabel, EXTERNAL_INDEX,
384 ExternalIndex, ExternalTarget, LABELS, Labels, PointDisplay, REF_RESOLUTIONS, REF_TARGETS,
385 RefResolutions, RefTarget, RefTargets, RefusedLabel, Resolution, SiteId,
386};
387pub use latex::{
388 HYPERREF_LATEX_RULE, HyperrefLatexRule, LABEL_COMMAND, LabelSpelling, REF_LATEX_RULE,
389 RefLatexRule, RefsRecomposeOptions, SafeLabelMode, ZCREF_COMMAND, label_spelling,
390 read_target_at_lowering, reference_type_words, stage_label, stage_label_group,
391 stage_labels_with_display_text, stage_ref_options, stage_reference_type_setup, stage_spelling,
392 target_spelling,
393};
394pub use safe_labels::{
395 REF_DOMAIN, SAFE_LABELS, STAGE as SAFE_LABELS_STAGE, SafeLabels, SafeLabelsStage,
396 VALUE_SAFE_LABELS, VALUE_STAGE as VALUE_SAFE_LABELS_STAGE, ValueSafeLabels,
397 ValueSafeLabelsStage, label_key, value_name,
398};
399
400/// The feature's registered name, `refs`.
401pub const FEATURE: &str = "refs";
402
403/// The declaration of the feature's settings: the fields of [`RefsConfig`],
404/// [`RefsRenderOptions`] and [`RefsRecomposeOptions`] are its settings keys.
405/// See [`crate::core::settings`].
406fn settings() -> SettingsDecl {
407 SettingsDecl::new(FEATURE)
408 .config::<RefsConfig>(
409 "The texts that join the items of a reference to several targets. Fixed when the \
410 registry is built: it cannot vary per document or per render.",
411 )
412 .options::<RefsRenderOptions>(
413 Bind::Render,
414 "Whether a reference that points at no label is reported as an Error (the \
415 default) or, under `unresolved: allow`, as a Warning. Set per render request.",
416 )
417 .options::<RefsRecomposeOptions>(
418 Bind::Render,
419 "How the recomposed LaTeX writes labels and references: the label types written \
420 as the document wrote them instead of as generated keys, and whether a \
421 reference is protected against a command that changes the case of its \
422 argument. Set per render request.",
423 )
424 .markup("join")
425}
426
427/// The `refs` feature ([`FlmFeature`]): it registers the `\ref` and
428/// `\hyperref` elements, the scoped package of `\label`, six stages (four that
429/// check and resolve labels and references, and two that serve the recomposed
430/// LaTeX), the tables they write, the
431/// render options and the lowering rules. See the module documentation.
432///
433/// Its configuration, [`RefsConfig`], holds the texts that join the items of
434/// a reference to several targets; `Refs::default()` uses the default texts.
435///
436/// The feature reads the tables of the
437/// [`refpoints`](crate::stdlib::features::refpoints) and
438/// [`index`](crate::stdlib::features::index) features as required reads, so
439/// a registry that holds this feature must hold those two. The
440/// [`numbering`](crate::stdlib::features::numbering) feature is optional: with
441/// it, a reference shows its target's number.
442#[derive(Debug, Default, Clone)]
443pub struct Refs {
444 config: RefsConfig,
445}
446
447impl Refs {
448 /// The feature with the configuration `config`.
449 pub fn new(config: RefsConfig) -> Refs {
450 Refs { config }
451 }
452}
453
454impl FlmFeature for Refs {
455 fn info(&self) -> FeatureInfo {
456 FeatureInfo::new(FEATURE, "References").docs(
457 "Labels and references: the `\\ref` and `\\hyperref` commands, the labels \
458 written after constructs, the link identifier of every reference point, the \
459 resolution of every reference, and the check of duplicate labels and label \
460 types.",
461 )
462 }
463
464 fn settings(&self) -> Option<SettingsDecl> {
465 Some(settings())
466 }
467
468 fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
469 let owner = b.feature().clone();
470 b.argument_role(
471 TARGET_ARG_ROLE,
472 "The label, or several labels separated by commas, that a reference points to, \
473 each written `type:label` (`sec:intro`).",
474 )?;
475 b.argument_role(
476 DEFINED_LABEL_ARG_ROLE,
477 "A label attached to a construct, written `type:label` (`sec:intro`), by which \
478 references point to the construct.",
479 )?;
480 b.element(
481 ElementDef::new(
482 owner.clone(),
483 ["ref"],
484 SyntaxDef::Macro { args: ref_args() },
485 ref_element(),
486 )
487 .docs(
488 "Refers to a labeled place, showing its number, else its content, else the \
489 label.",
490 ),
491 )?;
492 b.element(
493 ElementDef::new(
494 owner.clone(),
495 ["hyperref"],
496 SyntaxDef::Macro { args: hyperref_args() },
497 hyperref_element(),
498 )
499 .docs(
500 "Refers to a labeled place, showing the text written in the braces.",
501 ),
502 )?;
503 b.element_type_text(
504 REF,
505 "A reference to a labeled place, shown as the place's number, or, for a place \
506 with no number, its content or its label.",
507 )?;
508 b.element_type_text(
509 HYPERREF,
510 "A reference to a labeled place, shown as the text the author wrote for it.",
511 )?;
512 b.scoped_package(label_package(owner.clone()))?;
513 b.table(
514 LABELS,
515 "For every label, the reference point that keeps it; the labels written more \
516 than once; and the labels whose type their point does not accept.",
517 )?;
518 b.table(
519 ANCHORS,
520 "Every reference point's anchor (the identifier a link points at), formed from \
521 its first label, its title, its position or its number, or given by its \
522 element, or none when the point has nothing to form it from or an earlier point \
523 holds the same one.",
524 )?;
525 b.table(
526 REF_TARGETS,
527 "For every label whose point received an anchor: the reference point that keeps \
528 it, its link target (`#` and the anchor) and what a reference to it shows; read \
529 by the resolve stage.",
530 )?;
531 b.table(
532 REF_RESOLUTIONS,
533 "How every reference site resolved: to a reference point of this document, to \
534 a label of another document from the external index, or not at all.",
535 )?;
536 b.external_table(
537 EXTERNAL_INDEX,
538 "Labels of other documents, each with its link target and the content a \
539 reference to it shows; installed by the caller when the run is constructed, \
540 and read only when installed.",
541 )?;
542 b.capability(CapabilityDef::new(CHECK_LABELS).docs(
543 "The labels have been checked: every label written for two reference points and \
544 every label whose type its point does not accept has been reported as an \
545 Error, and every reference has been resolved, a reference that points at no \
546 label being reported.",
547 ))?;
548 b.collection_member(VALIDATED, CHECK_LABELS)?;
549 // The counter table belongs to the `numbering` feature, which a
550 // registry need not hold: the `\ref` rule reads it optionally, under
551 // this peer declaration, and shows a target's content or its label
552 // where nothing numbers.
553 b.peer_table::<Counters>(
554 COUNTERS.name(),
555 "The counter values, read to show the number that the target of a reference \
556 was given.",
557 )?;
558 b.stage(Arc::new(stages::Scan))?;
559 b.stage(Arc::new(stages::AnchorsStage))?;
560 b.stage(Arc::new(stages::Resolve))?;
561 b.stage(Arc::new(stages::CheckLabels))?;
562 // The joining texts are parsed once the language is built, and the
563 // `\ref` rule reads them from there.
564 let list = Arc::new(ListTexts::default());
565 for rule in rules::rules(&list) {
566 b.lowering_rule(rule)?;
567 }
568 b.digest_input(&self.config.digest_bytes())?;
569 b.late_init(Arc::new(CompileList { texts: list, decl: self.config.join.clone() }))?;
570 b.table(
571 SAFE_LABELS,
572 "For the recomposed LaTeX: the safe label (`ref1`, `ref2`, …) written in place of \
573 every label whose type is not written raw, numbered in the order the document \
574 first mentions the labels, and the reverse correspondence.",
575 )?;
576 b.stage(Arc::new(SafeLabelsStage))?;
577 b.table(
578 VALUE_SAFE_LABELS,
579 "For the recomposed LaTeX: for every reference node of a synthesized value, the \
580 name written for each target that has no safe label in the document \
581 (`ref-v1`, …); held in the value's catch-up store, and empty for a document \
582 tree.",
583 )?;
584 b.stage(Arc::new(ValueSafeLabelsStage))?;
585 latex::register(b)?;
586 Ok(())
587 }
588}
589
590/// The [`Refs`] feature with the default configuration, ready to be listed in
591/// a package entry ([`PackageEntry`](crate::core::registry::PackageEntry)).
592pub fn feature() -> Arc<dyn FlmFeature> {
593 Arc::new(Refs::default())
594}
595
596#[cfg(test)]
597mod tests {
598 use super::*;
599
600 #[test]
601 fn the_feature_names_itself() {
602 assert_eq!(Refs::default().info().name, FEATURE);
603 }
604
605 #[test]
606 fn the_two_referencing_elements_are_the_feature_s_source_elements() {
607 assert_eq!(ref_element().name, REF);
608 assert_eq!(hyperref_element().name, HYPERREF);
609 }
610}