flm_core/stdlib/features/headings/mod.rs
1//! This module defines the `headings` feature, which provides the commands that create
2//! the headings of a document, `\section` to `\subparagraph` by default. A program can
3//! declare its own heading kinds and heading commands in the configuration of the
4//! feature, [`HeadingsConfig`].
5//!
6//! # Writing a heading
7//!
8//! A heading consists of a heading command, an optional star, an optional key-value
9//! argument in square brackets, the title, and optional `\label` commands after the
10//! title:
11//!
12//! ```text
13//! \section{Introduction}\label{sec:intro}
14//! \subsection*{Notation}
15//! \section[toc=false]{Acknowledgments}
16//! ```
17//!
18//! The star and the key-value argument set the options of the heading (see [The options
19//! of a heading](#the-options-of-a-heading)). A label written after the title can be
20//! referred to with `\ref`. The language guide describes headings for authors
21//! ([headings](crate::guide::language_syntax#headings)).
22//!
23//! # Heading kinds and heading commands
24//!
25//! A *heading kind* is a type of heading, such as a section, a subsection or an
26//! appendix. A heading kind has a name and a *level*. Levels count from 0, and an outer
27//! heading has a smaller level than the headings inside it. A heading kind is declared
28//! with a [`HeadingDecl`]. This declaration also contains the settings for the numbering
29//! of the headings of the kind, for their listing in a table of contents, for run-in
30//! headings, and for the labels that the headings accept.
31//!
32//! A *heading command* is a macro, such as `\section`, that an author writes to create a
33//! heading of one heading kind. A heading command is declared with a [`HeadingCommand`],
34//! separately from the heading kind, because headings of the same kind can be written
35//! with several commands. For instance, the sections written with a second command for
36//! the kind `section` can be left out of the table of contents unless the author writes
37//! `toc=true`. A heading kind can also have no command at all. A program then creates
38//! the headings of this kind itself, for instance in a stage.
39//!
40//! The heading kinds and the heading commands are part of the configuration of the
41//! feature, [`HeadingsConfig`]. A program passes the configuration to [`Headings::new`]
42//! or to [`StdlibConfig::headings`](crate::stdlib::StdlibConfig::headings). The
43//! configuration is fixed when the registry is built (see [settings, options and
44//! configuration](crate::guide::concepts_overview#settings-options-and-configuration)).
45//! The default configuration ([`HeadingsConfig::new`]) contains the five heading kinds
46//! `section`, `subsection`, `subsubsection`, `paragraph` and `subparagraph` at the
47//! levels 1 to 5, as in LaTeX, with one heading command of the same name for each kind.
48//!
49//! The following example adds a heading kind `appendix` and a second heading command
50//! for sections:
51//!
52//! ```
53//! use flm_core::stdlib::features::headings::{HeadingCommand, HeadingDecl, HeadingsConfig};
54//! use flm_core::stdlib::features::numbering::NumberTemplate;
55//!
56//! // The five standard kinds, an `\appendix` numbered A, B, C, and a second
57//! // command for sections that are not listed in the table of contents.
58//! let mut kinds = HeadingsConfig::new().headings;
59//! kinds.push(HeadingDecl::new("appendix", 1).number_format(NumberTemplate::formats("#{Alph}")));
60//! let config = HeadingsConfig::new()
61//! .headings(kinds)
62//! .command(HeadingCommand::new("quietsection", "section").default_value("toc", "false"));
63//! assert_eq!(config.heading("appendix").map(|kind| kind.level), Some(1));
64//! assert_eq!(config.commands_of("section").count(), 2);
65//! ```
66//!
67//! In LaTeX, `\appendix` is a switch and not a sectioning command. A program that
68//! declares a heading kind `appendix` therefore maps it to a LaTeX sectioning command for
69//! the `latex-recomposed` backend, with the render option
70//! [`HeadingsLatexOptions`](latex::HeadingsLatexOptions). The extension guide gives a
71//! complete example ([heading kinds and commands of your
72//! own](crate::guide::extending#heading-kinds-and-commands-of-your-own)).
73//!
74//! # The options of a heading
75//!
76//! A heading has two options, which [`heading_options`] returns as a
77//! [`HeadingOccurrence`]:
78//!
79//! - `numbered`: whether the heading is numbered, provided that its heading kind is
80//! numbered. A star after the command, as in `\section*{…}`, is equivalent to
81//! `numbered=false`.
82//! - `toc`: whether the heading is listed in a table of contents. The star does not
83//! change this option: `\section*{…}` is listed, and `\section*[toc=false]{…}` is
84//! neither numbered nor listed. The headings of a heading kind declared with
85//! [`skip_toc`](HeadingDecl::skip_toc) are never listed, and the option `toc` has no
86//! effect on them.
87//!
88//! Both options are `true` by default. They are set, in this order, by the default
89//! options of the heading command ([`HeadingCommand::defaults`]), by the star, and by
90//! the key-value argument from left to right. A later setting replaces an earlier one.
91//! A key written without a value, as in `[numbered]`, is equivalent to the value `true`.
92//!
93//! With the key `alt` ([`ALT_KEY`]), an author gives the heading an *alternative
94//! title*, as in `\section[alt={Short title}]{A long title with \emph{markup}}`. The
95//! value is FLM content, which [`heading_alt`] returns. In a table of contents, the
96//! alternative title is displayed in place of the title ([`Sectioning::toc_title`]).
97//! The full title is displayed at the heading itself and in the references to the
98//! heading, and the anchor of a heading without a label is derived from the full title.
99//! The `latex-recomposed` backend passes the alternative title to LaTeX ([`latex`]).
100//!
101//! The key `pdfbookmark` (the title of a PDF bookmark) is reserved and not implemented
102//! ([`RESERVED_KEYS`]).
103//!
104//! The lowering rule of a heading reports the following problems in the key-value
105//! argument:
106//!
107//! - a reserved key: the warning `flm.heading.key-not-implemented`
108//! ([`KeyNotImplemented`]);
109//! - the key `alt` without a value: the error `flm.heading.missing-value`
110//! ([`MissingValue`]);
111//! - a key other than `numbered`, `toc`, `alt` and the reserved keys: the error
112//! `flm.heading.unknown-key` ([`UnknownKey`]);
113//! - a value of `numbered` or `toc` other than `true` and `false`: the error
114//! `flm.heading.bad-value` ([`BadValue`]);
115//! - a key that is not plain text: the error `flm.heading.unreadable-options`
116//! ([`UnreadableOptions`]).
117//!
118//! In each case, the heading is still written. The key in question is ignored; for the
119//! last error, the whole key-value argument is ignored. Each problem is reported once
120//! per render, by the lowering rule. [`heading_options`] and the aspects of the heading
121//! element report nothing.
122//!
123//! # Numbering
124//!
125//! The headings of each standard heading kind are counted in a *counter* of their own (a
126//! dotted name under which things are counted in document order; see [counters and
127//! counter styles](crate::guide::concepts_overview#counters-and-counter-styles)). The
128//! name of the counter is the name of the heading kind after the prefix
129//! [`COUNTER_PREFIX`], as in `flm.headings.section`. The counter of a heading kind is
130//! numbered within the counter of the kind above it, so the second subsection of the
131//! first section is numbered `1.2`. The submodule [`numbers`] declares the counters and
132//! their *counter styles*, with which the numbers are formatted, and describes the
133//! numbering of the standard heading kinds in detail.
134//!
135//! The heading kinds that are numbered are selected with the setting
136//! [`HeadingsConfig::numbering`] of the configuration, a [`HeadingNumbering`]:
137//!
138//! - [`NothingNumbered`](HeadingNumbering::NothingNumbered), the default: no heading is
139//! numbered;
140//! - [`AllNumbered`](HeadingNumbering::AllNumbered): every heading kind that has a
141//! counter is numbered;
142//! - [`UpToDepth(n)`](HeadingNumbering::UpToDepth): every heading kind that has a
143//! counter and a level of at most `n` is numbered.
144//!
145//! Like the rest of the configuration, this setting is fixed when the registry is
146//! built:
147//!
148//! ```
149//! use flm_core::stdlib::features::headings::{HeadingNumbering, HeadingsConfig};
150//!
151//! // Number the sections and the subsections, and leave the three deeper
152//! // levels unnumbered.
153//! let config = HeadingsConfig::new().numbering(HeadingNumbering::UpToDepth(2));
154//! assert!(config.numbers(config.heading("subsection").expect("shipped")));
155//! assert!(!config.numbers(config.heading("subsubsection").expect("shipped")));
156//! ```
157//!
158//! A heading that is not numbered does not advance its counter. This applies to the
159//! headings of a heading kind that is not numbered, and to a heading written with a star
160//! or with `numbered=false`. The headings after such a heading continue the numbering
161//! from the last number given, as in LaTeX. A heading kind declared with
162//! [`HeadingDecl::no_counter`] has no counter and is never numbered.
163//!
164//! The counter and the counter style of a heading kind that is not numbered are
165//! declared all the same. Therefore, another counter can be numbered within this
166//! counter with the numbering options of a document.
167//!
168//! The *parent set* [`LEVELS_PARENT_SET`] (`flm.headings.levels`) is also declared in
169//! the `headings` feature. It contains the counters of all heading kinds. A counter
170//! numbered within this parent set ([`Within::parent_set`]) is numbered within the most
171//! recent heading, whatever its level.
172//!
173//! # Run-in headings
174//!
175//! A *run-in heading* is a heading set at the start of the paragraph that it introduces,
176//! on the first line of the paragraph. For instance, if `paragraph` is a run-in heading
177//! kind, the plain-text output of `\paragraph{Note} Some content.` is
178//! `Note. Some content.`. Other headings are set as blocks, on lines of their own.
179//!
180//! The headings of a kind are run-in headings if the field [`HeadingDecl::run_in`] of
181//! the kind is `true`. This field is `false` for every standard heading kind.
182//! [`HeadingsConfig::run_in_levels`] sets it by level.
183//!
184//! A run-in heading differs from a block heading in two respects:
185//!
186//! - Its block role ([`BlockRoleAspect`]) is [`BlockRole::BlockDecorator`] at
187//! [`Placement::Leads`], and not [`BlockRole::Block`]. The block-structure pass
188//! ([`crate::lang::rewrites::blocks`]) therefore starts a paragraph at the heading, and
189//! the content after the heading becomes part of this paragraph. A run-in heading that
190//! is followed by no content, for instance by a blank line, is placed in a paragraph
191//! of its own.
192//! - The lowering rule [`RULE`] produces a
193//! [`flm.pres.deco.runin`](crate::stdlib::backends::pres::DECO_RUNIN) decoration that
194//! contains a [`flm.pres.runin-heading`](crate::stdlib::backends::pres::RUNIN_HEADING)
195//! node, and not a
196//! [`flm.pres.block-heading`](crate::stdlib::backends::pres::BLOCK_HEADING) node. A
197//! *decoration* is a node that the lowering driver moves from the content of the
198//! enclosing presentation node into an attached slot of that node
199//! ([`Decoration`](crate::stdlib::backends::pres::Decoration); see [decorations,
200//! roles and kinds](crate::guide::concepts_overview#decorations-roles-and-kinds)). The
201//! backend therefore writes the heading at the start of the paragraph.
202//!
203//! In all other respects, a run-in heading is the same as a block heading. It has a
204//! level, it is listed in a table of contents unless `toc=false` is given, and it has a
205//! reference point.
206//!
207//! # The reference point
208//!
209//! Every heading has one *reference point*: a place in the document that can be referred
210//! to, numbered, or given an anchor ([`RefPoint`]; see [reference points, labels and
211//! anchors](crate::guide::concepts_overview#reference-points-labels-and-anchors)). The
212//! reference point of a heading has the following properties:
213//!
214//! - Its reference kind ([`RefKind`]) is the [`ref_kind`](HeadingDecl::ref_kind) of the
215//! heading kind, [`KIND`] (`section`) by default.
216//! - Its labels are the `\label` commands written after the title. They are read with
217//! [`label_uses`](refs::label_uses) from a trailing argument of the heading that
218//! contains them (see
219//! [fields](crate::guide::concepts_overview#fields-data-a-construct-reads)). A label
220//! must have the form `type:label`, as in `\label{sec:intro}`. The label check of the
221//! `refs` feature reports a label that does not have this form.
222//! - Its accepted label types are the [`label_types`](HeadingDecl::label_types) of the
223//! heading kind, [`LABEL_TYPES`] (`sec` and `topic`) by default.
224//! - A reference to the heading (`\ref`) expands to the number of the heading, or to its
225//! title if the heading has no number.
226//! - Its anchor (the identifier that a link points to) is derived from the first label of
227//! the heading, as in `sec-intro`. The anchor of a heading without a label is derived
228//! from its title, after the [`anchor_prefix`](HeadingDecl::anchor_prefix) of the
229//! heading kind ([`ANCHOR_PREFIX`] by default), as in `sec--Introduction`. If two
230//! headings without a label have the same title, the anchors stage of the `refs`
231//! feature appends a number to the anchor of the second one
232//! (`sec--Introduction-2`).
233//!
234//! # The element
235//!
236//! Every heading is a node of the element type [`HEADING`] (`flm.heading`). Each heading
237//! kind is a separate element value of this type, which contains a [`HeadingElement`]:
238//! the declaration of the heading kind and its heading commands. The names of the heading
239//! commands are the names of the element value. The element value of a heading kind
240//! without a command has no name and is synthesized ([`SyntaxDef::Synthesized`]), so no
241//! document can write it.
242//!
243//! Every heading command takes the arguments returned by [`heading_args`]: the star, the
244//! optional key-value argument, the title, and the trailing argument that contains the
245//! `\label` commands.
246//!
247//! The element value has three aspects:
248//!
249//! - its block role: a block, or for a run-in heading kind a decorator that leads a
250//! paragraph;
251//! - [`Sectioning`], which returns the level of the heading and whether the heading is
252//! listed in a table of contents;
253//! - [`Referenceable`], which returns the reference point of the heading.
254//!
255//! A second element, [`title::NUMBER_ELEMENT`] (`flm.heading.number`), is declared in
256//! the `headings` feature. It contains the number of a numbered heading in the text
257//! written before its title. No document can write it; see [`title`].
258//!
259//! # The output on each backend
260//!
261//! - On the `text` backend, a heading at the root heading level
262//! ([`TextRenderOptions::root_heading_level`](crate::stdlib::backends::text::TextRenderOptions::root_heading_level),
263//! 1 by default) or one level deeper is written as its title, underlined. A deeper
264//! heading is written as its title after `#` characters. A run-in heading is written
265//! as its title followed by a period
266//! ([`TextRenderOptions::run_in_stop`](crate::stdlib::backends::text::TextRenderOptions::run_in_stop)),
267//! at the start of its paragraph.
268//! - On the `html` backend, a heading is an element `<h1>` to `<h6>` that corresponds to
269//! its level relative to the root heading level. Another element can be set for a
270//! heading kind with the render option
271//! [`heading_tags`](crate::stdlib::backends::html::HtmlRenderOptions::heading_tags).
272//! The element has the anchor as its `id`, and the
273//! attributes `data-flm-heading`, `data-flm-level` and `data-flm-toc`. A run-in heading
274//! is a `<span>` with the same attributes at the start of its paragraph ([headings in
275//! HTML](crate::guide::rendering#headings-in-html)).
276//! - On the `latex-recomposed` backend, a heading is the LaTeX sectioning command of its
277//! heading kind, inside the LaTeX hook `\flmHeading` (see [`latex`] and
278//! [hooks](crate::stdlib::backends::latex::preamble)).
279//!
280//! On the `text` and `html` backends, the number of a numbered heading is written before
281//! its title, as in `1.2. Notation`. On the `latex-recomposed` backend, the numbering
282//! setting of the configuration has no effect. A heading written with a star or with
283//! `numbered=false` is written with a starred sectioning command, every other heading
284//! with an unstarred one, and LaTeX numbers the headings according to the document
285//! class.
286//!
287//! # The lowering rules
288//!
289//! [`RULE`] (`flm.heading.lower.default`), implemented by [`HeadingRule`], is the
290//! lowering rule of headings on every backend except `latex-recomposed`. It produces a
291//! [`flm.pres.block-heading`](crate::stdlib::backends::pres::BLOCK_HEADING) node, or
292//! for a run-in heading the decoration described in [Run-in
293//! headings](#run-in-headings). The payload of the node ([`HeadingPayload`]) contains the
294//! name and the level of the heading kind, whether the heading is listed in a table of
295//! contents, and the anchor.
296//!
297//! The content of the node is the title, preceded by the number if the heading is
298//! numbered. The number is written with the *heading title template* of the heading kind
299//! ([`title_number_format`](HeadingDecl::title_number_format), `#{number}. ` by
300//! default). In the output of the template, the number is a
301//! [`flm.pres.span`](crate::stdlib::backends::pres::SPAN) node with the role
302//! [`NUMBER_ROLE`](numbers::NUMBER_ROLE). Since the number is part of the content, a
303//! backend that measures the heading includes the number: on the `text` backend, the
304//! line under a numbered heading is as wide as `1. Introduction`, and not only as wide
305//! as `Introduction`.
306//!
307//! The rule reads the anchors table [`ANCHORS`] of the `refs` feature and the counter
308//! table [`COUNTERS`] of the `numbering` feature. Both tables are declared as peer
309//! declarations ([`PeerName`](crate::core::registry::PeerName)) and read optionally, so
310//! a registry without one of these features still builds. Without the `numbering`
311//! feature, headings have no numbers, and without the `refs` feature, headings have no
312//! anchors. In both cases, the registry build reports one note about the missing table,
313//! and nothing is reported at the headings.
314//!
315//! A heading can lack an anchor even if the anchors table is present:
316//!
317//! - The anchors stage of the `refs` feature gave the heading no anchor, for instance
318//! because every label of the heading is also defined at an earlier place. A stage of
319//! the `refs` feature reports the cause. The heading is written without an anchor, so
320//! no link can point to it. This cannot happen to a heading without a label, since its
321//! anchor is derived from its title.
322//! - The anchors table has no entry for the heading. This means that the rule lowers
323//! content on which the stages did not run (see [value
324//! catch-up](crate::guide::concepts_overview#value-catch-up)). The rule reports
325//! `flm.run.missing-entry` ([`MissingEntry`]) and fails.
326//!
327//! [`latex::LATEX_RULE`] (`flm.heading.lower.latex-recomposed`) is the lowering rule of
328//! headings on the `latex-recomposed` backend. It writes each heading as the LaTeX
329//! sectioning command of its heading kind
330//! ([`HeadingsLatexOptions`](latex::HeadingsLatexOptions)). The rule is registered with
331//! peer declarations of the backend and of the LaTeX elements that it produces. A
332//! registry without the LaTeX features therefore still builds, and the rule is then not
333//! used. See [`latex`].
334//!
335//! # Settings
336//!
337//! The settings of the feature (its configuration and options in data form; see
338//! [`crate::core::settings`]) consist of two parts:
339//!
340//! - the configuration [`HeadingsConfig`], with the keys `headings`, `commands` and
341//! `numbering`, which is fixed when the registry is built;
342//! - the render option [`HeadingsLatexOptions`](latex::HeadingsLatexOptions), with the
343//! key `latex_commands`, which is set for each render.
344//!
345//! In settings data, the values of `headings` and `commands` are maps from the names of
346//! the heading kinds and heading commands to their declarations.
347//!
348//! # Related features
349//!
350//! - `refs` ([`refs`]): The labels of a heading are read with functions of the `refs`
351//! feature, and its anchor is read from the anchors table. On the `latex-recomposed`
352//! backend, each label is written as its safe label, the form of the label used in the
353//! LaTeX output ([`SafeLabels`](crate::stdlib::features::refs::SafeLabels)).
354//! - `numbering` ([`numbering`](crate::stdlib::features::numbering)): The counters, the
355//! counter styles and the parent set of the heading kinds are declared in the
356//! `headings` feature as peer contributions to the service slots of the `numbering`
357//! feature (see [services and service
358//! slots](crate::guide::concepts_overview#services-and-service-slots) and
359//! [`numbers`]). The lowering rules read the number of each heading from the counter
360//! table.
361//! - `blocks` ([`blocks`](crate::stdlib::features::blocks)): The block-structure pass
362//! places a heading according to its block role.
363//! - `userdefs` ([`userdefs`](crate::stdlib::features::userdefs)): If the value of
364//! `numbered` or `toc` is given by a placeholder of a user definition, the value
365//! cannot be read until the definition is expanded. The lowering rules then return
366//! [`LowerError::PlaceholderCharacters`], so that the use sites of the definition are
367//! expanded first.
368//! - The backends: [`RULE`] requires the style identifier [`STYLE`] for every heading.
369//! On the `html` backend, [`STYLE`] refers to an empty style definition
370//! ([`stylesheet`]). On the `latex-rendered` backend, [`STYLE`] is defined in the
371//! definition piece [`latex_rendered::piece`]. [`latex::LATEX_RULE`] requires the
372//! definition piece of the LaTeX hook `\flmHeading`
373//! ([`heading_piece`](crate::stdlib::backends::latex::preamble::heading_piece)).
374
375pub mod latex;
376pub mod latex_rendered;
377pub mod numbers;
378pub mod title;
379
380use std::collections::BTreeSet;
381use std::hash::{Hash, Hasher};
382use std::sync::Arc;
383
384use techy::core::node::{BuildId, NodeRef};
385use techy::error::{Diagnostic, DiagnosticInfo};
386use techy::extract::parse_keyval_drop_annotations;
387
388use crate::core::settings::{SettingsDecl, named};
389use crate::model::aspects::{
390 AcceptedRefTypes, AnchorPolicy, BlockRole, BlockRoleAspect, ContentRef, FixedBlockRole,
391 NumberSource, Placement, PointId, RefPoint, Referenceable, Sectioning,
392};
393use crate::model::element::{ElementSpec, element_value};
394use crate::core::lowering::{
395 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
396 chars_at_lowering,
397};
398use crate::model::names::{CapName, ElementName, Name, RefKind};
399use crate::model::options::Bind;
400use crate::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature, StyleDef};
401use crate::core::run::MissingEntry;
402use crate::lang::Flm;
403use crate::lang::copy::{
404 ValueContent, ValuePiece, WrittenPiece, copy_pieces_into_value, key_value_pieces,
405};
406use crate::lang::guard::{GuardPolicy, on_worker_thread};
407use crate::lang::mint::{ArgDef, ArgStdKind, ElementDef, SyntaxDef};
408use crate::lang::text::is_space;
409use crate::stdlib::backends::lowering::{lower_arg_named_or_nothing, lower_written_pieces};
410use crate::stdlib::backends::pres::{self, DecorationPayload, HeadingPayload};
411use crate::stdlib::features::numbering::{
412 COUNTERS, Counters, FormatOptions, NumberTemplate, Within,
413};
414use crate::stdlib::features::refs::{self, ANCHORS};
415
416use title::{CompileTitles, NumberRule, Titles, DEFAULT_TITLE_NUMBER_FORMAT};
417
418/// The feature's registered name, `headings`.
419pub const FEATURE: &str = "headings";
420
421/// Returns the declaration of the settings of the `headings` feature. The
422/// settings consist of the configuration [`HeadingsConfig`] and the render
423/// option [`HeadingsLatexOptions`](latex::HeadingsLatexOptions); the fields of
424/// these two types are the keys of the settings. See [`crate::core::settings`].
425fn settings() -> SettingsDecl {
426 SettingsDecl::new(FEATURE)
427 .config::<HeadingsConfig>(
428 "The heading kinds, the heading commands, and the heading kinds that are numbered. \
429 For each heading kind, the configuration contains its level, its counter and \
430 counter style, the counter it is numbered within, its number format, the text \
431 written before the title of a numbered heading, whether its headings are listed in \
432 a table of contents or set as run-in headings, and the labels and anchors of its \
433 headings. For each heading command, it contains the heading kind of the headings \
434 written with the command and the default values of the options `numbered` and \
435 `toc`. Fixed when the registry is built; it cannot vary per document or per render.",
436 )
437 .options::<latex::HeadingsLatexOptions>(
438 Bind::Render,
439 "The LaTeX sectioning command of each heading kind in the recomposed LaTeX, given \
440 by the name of the heading kind. A heading kind that is not listed is written as the \
441 command of the same name, such as `\\section` for the kind `section`. Set per render \
442 request.",
443 )
444 .merge_entries("headings", || named::to_data(&HeadingsConfig::default().headings, "name"))
445 .remove_false("headings")
446 .merge_entries("commands", || named::to_data(&HeadingsConfig::default().commands, "name"))
447 .remove_false("commands")
448 .markup("headings.*.within.joiner.joined")
449 .markup("headings.*.within.joiner.template")
450 .markup("headings.*.number_format")
451 .markup("headings.*.title_number_format")
452}
453
454/// The name of the element type of all headings, `flm.heading`. Each heading
455/// kind is a separate element value of this type, which contains a
456/// [`HeadingElement`].
457pub const HEADING: &str = "flm.heading";
458
459/// The name of the default lowering rule of headings,
460/// `flm.heading.lower.default`, implemented by [`HeadingRule`]. This rule lowers
461/// the headings on every backend except `latex-recomposed`, which uses
462/// [`latex::LATEX_RULE`].
463pub const RULE: &str = "flm.heading.lower.default";
464
465/// The style identifier of the `headings` feature, `flm.headings.style`.
466///
467/// The lowering rule [`RULE`] requires this identifier for every heading. On
468/// the `html` backend, the identifier refers to an empty style definition
469/// ([`stylesheet`]). On the `latex-rendered` backend, the identifier is defined
470/// in the definition piece [`latex_rendered::piece`]. The names of the counter styles of
471/// the heading kinds ([`STYLE_PREFIX`]) begin with the same text, but they are
472/// counter styles and not style definitions.
473pub const STYLE: &str = "flm.headings.style";
474
475/// Returns the style definition of [`STYLE`] for the `html` backend.
476///
477/// The definition contains no style rules, since headings need no stylesheet of
478/// their own. It exists so that the identifier that [`RULE`] requires is
479/// defined on the `html` backend.
480pub fn stylesheet() -> StyleDef {
481 StyleDef {
482 id: Name::from(STYLE),
483 content: Vec::new(),
484 docs: String::from("headings, which need no style rules"),
485 }
486}
487
488/// The default reference kind of the reference point of a heading, `section`.
489/// A reference kind is the category of a reference point ([`RefPoint`]), such
490/// as a section. Another reference kind can be declared for a heading kind with
491/// [`HeadingDecl::ref_kind`].
492pub const KIND: &str = "section";
493
494/// The label types that a heading accepts by default, `sec` and `topic`. Other
495/// label types can be declared for a heading kind with
496/// [`HeadingDecl::label_types`].
497///
498/// The type of a label is the part before the colon. A heading therefore
499/// accepts labels such as `\label{sec:intro}` and `\label{topic:intro}`. A
500/// label of another type defines no label, and the label check of the `refs`
501/// feature ([`CHECK_LABELS`](crate::stdlib::features::refs::CHECK_LABELS))
502/// reports it as `flm.refs.label-type-not-accepted`. The type `topic` is
503/// accepted so that the heading that introduces a subject can be labeled for
504/// references from other documents.
505pub const LABEL_TYPES: [&str; 2] = ["sec", "topic"];
506
507/// The default text at the start of the anchor of a heading without a label,
508/// `sec`. Another prefix can be declared for a heading kind with
509/// [`HeadingDecl::anchor_prefix`].
510///
511/// The anchor of a heading without a label is derived from its title: the
512/// heading `\section{Examples}` has the anchor `sec--Examples`. The prefix is
513/// the first of the [`LABEL_TYPES`], so that the anchors of labeled headings
514/// begin in the same way: `\section{Examples}\label{sec:examples}` has the
515/// anchor `sec-examples`.
516pub const ANCHOR_PREFIX: &str = LABEL_TYPES[0];
517
518/// The text at the start of the name of the counter style of a heading kind,
519/// `flm.headings.style.`. Another counter style can be declared for a heading
520/// kind with [`HeadingDecl::style`]. By default, the numbers of the heading
521/// kind `section` are formatted with the counter style
522/// `flm.headings.style.section`.
523pub const STYLE_PREFIX: &str = "flm.headings.style.";
524
525/// The text at the start of the name of the counter of a heading kind,
526/// `flm.headings.`. Another counter can be declared for a heading kind with
527/// [`HeadingDecl::counter`]. By default, the headings of the kind `section` are
528/// counted in the counter `flm.headings.section`.
529///
530/// The name of the counter is distinct from the name of the heading kind. A
531/// counter is always given by its full name: in a [`Within`], in a document's
532/// [numbering options](crate::stdlib::features::numbering::NumberingOptions),
533/// and in a placeholder such as `#{flm.headings.section}` of a within template.
534pub const COUNTER_PREFIX: &str = "flm.headings.";
535
536/// The name of the star argument of every heading command, `star`.
537pub const STAR_ARG: &str = "star";
538
539/// The name of the optional key-value argument of every heading command,
540/// `options`. In `\section[toc=false]{…}`, this argument is `[toc=false]`.
541pub const OPTIONS_ARG: &str = "options";
542
543/// The name of the title argument of every heading command, `title`.
544pub const TITLE_ARG: &str = "title";
545
546/// The option key with which an author selects whether a heading is numbered,
547/// `numbered`. Its value is `true` or `false`. A star after the heading command
548/// is equivalent to `numbered=false`.
549pub const NUMBERED_KEY: &str = "numbered";
550
551/// The option key with which an author selects whether a heading is listed in a
552/// table of contents, `toc`. Its value is `true` or `false`.
553pub const TOC_KEY: &str = "toc";
554
555/// The option key with which an author gives a heading an alternative title,
556/// `alt`, as in `\section[alt={Short \emph{title}}]{…}`.
557///
558/// The value is FLM content, which [`heading_alt`] returns. In a table of
559/// contents, the alternative title is displayed in place of the title
560/// ([`Sectioning::toc_title`]). The key written without a value is reported as
561/// [`MissingValue`].
562pub const ALT_KEY: &str = "alt";
563
564/// The option keys that are reserved for headings but not implemented:
565/// `pdfbookmark`, the title of a PDF bookmark. A reserved key is ignored and
566/// reported as the warning [`KeyNotImplemented`].
567pub const RESERVED_KEYS: [&str; 1] = ["pdfbookmark"];
568
569/// The name of the parent set declared in the `headings` feature,
570/// `flm.headings.levels`.
571///
572/// A *parent set* is a named list of counters
573/// ([`ParentSetDecl`](crate::stdlib::features::numbering::ParentSetDecl)). A
574/// counter numbered within a parent set ([`Within::parent_set`]) is numbered
575/// within the counter of the set that advanced most recently. This parent set
576/// contains the counters of the heading kinds that have one, ordered by level
577/// from the outermost level, and in the order of declaration within one level.
578///
579/// A counter numbered within this parent set is therefore numbered within the
580/// most recent heading. For instance, if a program declares a heading kind
581/// `chapter` above the sections, an equation after the heading of chapter 4 and
582/// before any section is numbered `(4.1)`, and an equation after subsection
583/// 4.1.2 is numbered `(4.1.2.1)`. The counter of a heading kind that is not
584/// numbered never advances, so its headings are never the parent of such a
585/// counter.
586pub const LEVELS_PARENT_SET: &str = "flm.headings.levels";
587
588/// A `HeadingNumbering` is the setting with which a program selects the heading
589/// kinds that are numbered ([`HeadingsConfig::numbering`]).
590///
591/// A heading kind is numbered if it has a counter ([`HeadingDecl::counter`])
592/// and its level is among the levels selected with this setting. A single
593/// heading of a numbered kind is not numbered if it is written with a star or
594/// with `numbered=false`.
595#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Deserialize, serde::Serialize)]
596#[derive(schemars::JsonSchema)]
597#[serde(rename_all = "kebab-case")]
598pub enum HeadingNumbering {
599 /// No heading kind is numbered. This is the default.
600 #[default]
601 NothingNumbered,
602 /// Every heading kind that has a counter is numbered.
603 AllNumbered,
604 /// Every heading kind that has a counter and a level of at most the given
605 /// number is numbered. For instance, with `UpToDepth(2)`, the sections and
606 /// the subsections of the standard configuration are numbered.
607 UpToDepth(u8),
608}
609
610impl HeadingNumbering {
611 /// Returns whether a kind at `level` is numbered under this depth, provided
612 /// the kind has a counter.
613 pub fn admits(self, level: u8) -> bool {
614 match self {
615 HeadingNumbering::NothingNumbered => false,
616 HeadingNumbering::AllNumbered => true,
617 HeadingNumbering::UpToDepth(depth) => level <= depth,
618 }
619 }
620}
621
622// --- the declarations -----------------------------------------------------------------------
623
624/// The declaration of a heading kind.
625///
626/// A *heading kind* is a type of heading, such as a section, a subsection or an
627/// appendix. A heading kind has a name and a level. Its declaration also
628/// contains the settings for the numbering of its headings, for their listing in
629/// a table of contents, for run-in headings, and for the labels that its
630/// headings accept. The heading kinds of a registry are listed in
631/// [`HeadingsConfig::headings`].
632///
633/// [`HeadingDecl::new`] creates a heading kind from a name and a level, with
634/// default values for all other fields. Each of these fields has a builder
635/// method of the same name that changes it.
636///
637/// The declaration of a heading kind does not list the commands with which its
638/// headings are written. These commands are declared separately, as
639/// [`HeadingCommand`] values in [`HeadingsConfig::commands`], because headings of
640/// the same kind can be written with several commands.
641///
642/// # Examples
643///
644/// ```
645/// use flm_core::stdlib::features::headings::HeadingDecl;
646/// use flm_core::stdlib::features::numbering::{NumberTemplate, Within};
647///
648/// // An appendix at the level of the sections, numbered A, B, C.
649/// let appendix =
650/// HeadingDecl::new("appendix", 1).number_format(NumberTemplate::formats("#{Alph}"));
651/// assert_eq!(
652/// appendix.counter.as_ref().map(|name| name.as_str()),
653/// Some("flm.headings.appendix")
654/// );
655/// assert_eq!(
656/// appendix.style.as_ref().map(|name| name.as_str()),
657/// Some("flm.headings.style.appendix")
658/// );
659///
660/// // A heading kind that is never numbered and never listed in a table of
661/// // contents.
662/// let aside = HeadingDecl::new("aside", 3).no_counter().skip_toc(true);
663/// assert!(aside.counter.is_none());
664///
665/// // A heading kind numbered within the sections, as in `2.1`. The `Within`
666/// // value refers to the counter of the sections by its full name.
667/// let sub = HeadingDecl::new("subsection", 2).within(Within::parent("flm.headings.section"));
668/// # let _ = sub;
669/// ```
670#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
671#[derive(schemars::JsonSchema)]
672#[serde(deny_unknown_fields)]
673#[schemars(transform = heading_decl_schema)]
674pub struct HeadingDecl {
675 /// The name of the heading kind, such as `section`. The name identifies the
676 /// heading kind in the attribute `data-flm-heading` of the HTML output and
677 /// in the render option [`HeadingsLatexOptions`](latex::HeadingsLatexOptions).
678 /// In settings data, the name is the key of the entry and not a field.
679 #[schemars(skip)]
680 pub name: Name,
681 /// The level of the heading kind. Levels count from 0, and an outer heading
682 /// has a smaller level than the headings inside it. The standard heading
683 /// kinds have the levels 1 to 5, so a heading kind above the sections, such
684 /// as a chapter, can have the level 0.
685 ///
686 /// The [`Sectioning`] aspect returns the level. The HTML element of a
687 /// heading corresponds to its level, unless another element is set with a
688 /// render option. The format of a heading in plain text also depends on its
689 /// level. Whether the heading kind is numbered depends on its level and on
690 /// the setting [`HeadingNumbering`].
691 pub level: u8,
692 /// The counter in which the headings of this kind are counted, given by its
693 /// full name. The default is `flm.headings.<name>` ([`COUNTER_PREFIX`]).
694 /// `None` means that the heading kind is never numbered; no counter is then
695 /// declared for it in the `numbering` feature.
696 pub counter: Option<Name>,
697 /// The counter style with which the numbers of this heading kind are
698 /// formatted. The default is `flm.headings.style.<name>` ([`STYLE_PREFIX`]).
699 /// A heading kind with a counter must have a counter style.
700 /// [`HeadingDecl::no_counter`] removes both the counter and the counter
701 /// style.
702 pub style: Option<Name>,
703 /// The counter within which the counter of this heading kind is numbered,
704 /// and how the number of that counter is written before the number of this
705 /// heading kind. The default, `None`, means that the counter is not
706 /// numbered within another counter. Counters are given by their full names,
707 /// as in `Within::parent("flm.headings.section")`.
708 pub within: Option<Within>,
709 /// The format of the number of this heading kind, without the numbers of
710 /// its parent counters, in the number-template language of
711 /// [`NumberTemplate`]. The default is `#{arabic}`.
712 pub number_format: NumberTemplate,
713 /// The *heading title template* of this heading kind: the text written
714 /// before the title of a numbered heading. The text is written in the
715 /// template language (see [the template language shared by
716 /// features](crate::guide::concepts_overview#the-template-language-shared-by-features)),
717 /// and the placeholder `#{number}` stands for the number of the heading. The
718 /// default is [`DEFAULT_TITLE_NUMBER_FORMAT`] (`#{number}. `), so a numbered
719 /// section reads `1. Introduction`.
720 ///
721 /// The template can contain words and markup around the number, as in
722 /// `Chapter~#{number}: `. With `#[bare]{number}`, the number is written
723 /// without the numbers of the parent counters. With `#[Roman]{number}`, the
724 /// number of this heading kind is written in Roman numerals. The number
725 /// itself has the role [`NUMBER_ROLE`](numbers::NUMBER_ROLE), with which it
726 /// can be formatted in a stylesheet or a lowering rule. A template without a
727 /// placeholder is allowed: the headings are then counted, but their numbers
728 /// are not written. The template is not used for a heading that is not
729 /// numbered.
730 ///
731 /// The registry build fails if the template cannot be parsed, if it contains
732 /// a placeholder other than `number`, or if `number` is written with a key
733 /// that it does not accept. [`title`] describes the template in full.
734 pub title_number_format: String,
735 /// Whether the headings of this kind are never listed in a table of
736 /// contents. If `true`, the option `toc` of these headings has no effect.
737 /// The default is `false`.
738 pub skip_toc: bool,
739 /// Whether the headings of this kind are run-in headings, set at the start
740 /// of the paragraph that they introduce (see [run-in
741 /// headings](self#run-in-headings)). The default is `false`.
742 pub run_in: bool,
743 /// The reference kind of the reference point of a heading of this kind. The
744 /// default is [`KIND`] (`section`).
745 pub ref_kind: RefKind,
746 /// The label types that a heading of this kind accepts. The default is
747 /// [`LABEL_TYPES`] (`sec` and `topic`).
748 pub label_types: Vec<String>,
749 /// The text at the start of the anchor of a heading of this kind that has
750 /// no label. The default is [`ANCHOR_PREFIX`] (`sec`).
751 pub anchor_prefix: String,
752 /// A description of the heading kind in one sentence, used in the
753 /// description of its element value in the registry. The default is empty,
754 /// and an empty description is replaced with `A heading of level <level>.`.
755 pub docs: String,
756}
757
758
759/// Changes the JSON schema of a heading kind in settings data so that only
760/// `level` is required. The other fields are optional, because the entry is
761/// read on top of the declaration that [`HeadingDecl::new`] creates from the
762/// name and the level.
763fn heading_decl_schema(schema: &mut schemars::Schema) {
764 crate::core::settings::named::require_only(schema, &["level"]);
765}
766impl HeadingDecl {
767 /// Returns the heading kind `name` at the level `level`, with the following
768 /// default values of the other fields:
769 ///
770 /// - the counter `flm.headings.<name>` ([`COUNTER_PREFIX`]) and the counter
771 /// style `flm.headings.style.<name>` ([`STYLE_PREFIX`]);
772 /// - no counter within which the counter is numbered;
773 /// - the number format `#{arabic}` and the heading title template
774 /// [`DEFAULT_TITLE_NUMBER_FORMAT`];
775 /// - headings listed in a table of contents and set as blocks;
776 /// - the reference kind [`KIND`], the label types [`LABEL_TYPES`] and the
777 /// anchor prefix [`ANCHOR_PREFIX`];
778 /// - an empty description.
779 pub fn new(name: impl Into<Name>, level: u8) -> HeadingDecl {
780 let name = name.into();
781 HeadingDecl {
782 counter: Some(Name::new(format!("{COUNTER_PREFIX}{}", name.as_str()))),
783 style: Some(Name::new(format!("{STYLE_PREFIX}{}", name.as_str()))),
784 name,
785 level,
786 within: None,
787 number_format: NumberTemplate::formats("#{arabic}"),
788 title_number_format: String::from(DEFAULT_TITLE_NUMBER_FORMAT),
789 skip_toc: false,
790 run_in: false,
791 ref_kind: RefKind::from(KIND),
792 label_types: LABEL_TYPES.iter().map(|label| String::from(*label)).collect(),
793 anchor_prefix: String::from(ANCHOR_PREFIX),
794 docs: String::new(),
795 }
796 }
797
798 /// Sets the counter of this heading kind to `counter`, given by its full
799 /// name.
800 pub fn counter(mut self, counter: impl Into<Name>) -> HeadingDecl {
801 self.counter = Some(counter.into());
802 self
803 }
804
805 /// Removes the counter and the counter style of this heading kind. A heading
806 /// kind without a counter is never numbered, and no counter is declared for
807 /// it in the `numbering` feature.
808 pub fn no_counter(mut self) -> HeadingDecl {
809 self.counter = None;
810 self.style = None;
811 self
812 }
813
814 /// Sets the counter style of this heading kind to `style`.
815 pub fn style(mut self, style: impl Into<Name>) -> HeadingDecl {
816 self.style = Some(style.into());
817 self
818 }
819
820 /// Sets the counter within which the counter of this heading kind is
821 /// numbered (see the field [`within`](HeadingDecl::within)).
822 pub fn within(mut self, within: Within) -> HeadingDecl {
823 self.within = Some(within);
824 self
825 }
826
827 /// Sets the format of the number of this heading kind.
828 pub fn number_format(mut self, number_format: NumberTemplate) -> HeadingDecl {
829 self.number_format = number_format;
830 self
831 }
832
833 /// Sets the heading title template of this heading kind: the text written
834 /// before the title of a numbered heading, in which `#{number}` stands for
835 /// the number (see the field
836 /// [`title_number_format`](HeadingDecl::title_number_format)).
837 pub fn title_number_format(mut self, text: impl Into<String>) -> HeadingDecl {
838 self.title_number_format = text.into();
839 self
840 }
841
842 /// Sets whether the headings of this kind are never listed in a table of
843 /// contents.
844 pub fn skip_toc(mut self, skip_toc: bool) -> HeadingDecl {
845 self.skip_toc = skip_toc;
846 self
847 }
848
849 /// Sets whether the headings of this kind are run-in headings.
850 pub fn run_in(mut self, run_in: bool) -> HeadingDecl {
851 self.run_in = run_in;
852 self
853 }
854
855 /// Sets the reference kind of the reference point of a heading of this
856 /// kind.
857 pub fn ref_kind(mut self, ref_kind: impl Into<RefKind>) -> HeadingDecl {
858 self.ref_kind = ref_kind.into();
859 self
860 }
861
862 /// Sets the label types that a heading of this kind accepts.
863 pub fn label_types(mut self, types: impl IntoIterator<Item = impl Into<String>>) -> HeadingDecl {
864 self.label_types = types.into_iter().map(Into::into).collect();
865 self
866 }
867
868 /// Sets the text at the start of the anchor of a heading of this kind that
869 /// has no label.
870 pub fn anchor_prefix(mut self, prefix: impl Into<String>) -> HeadingDecl {
871 self.anchor_prefix = prefix.into();
872 self
873 }
874
875 /// Sets the description of this heading kind (see the field
876 /// [`docs`](HeadingDecl::docs)). If the crate is built without its cargo
877 /// feature `docs`, the text is discarded and the field stays empty.
878 pub fn docs(mut self, docs: impl Into<String>) -> HeadingDecl {
879 self.docs = crate::kept_docs(docs);
880 self
881 }
882
883 /// Returns the number source of a numbered heading of this kind: the
884 /// counter and the counter style of the kind. The counter advances by one
885 /// at each such heading. Returns `None` for a heading kind without a
886 /// counter or without a counter style.
887 fn number_source(&self) -> Option<NumberSource> {
888 Some(NumberSource {
889 counter: self.counter.clone()?,
890 instances: Vec::new(),
891 style: self.style.clone()?,
892 advance: vec![0],
893 number_format: None,
894 })
895 }
896}
897
898/// The declaration of a heading command.
899///
900/// A *heading command* is a macro, such as `\section`, that an author writes to
901/// create a heading. The headings written with a heading command are of one
902/// heading kind ([`HeadingDecl`]). A heading command can be declared with
903/// default values for the options `numbered` and `toc` of these headings.
904///
905/// Headings of the same kind can be written with several heading commands. All
906/// heading commands take the same arguments ([`heading_args`]), so two commands
907/// of one kind differ only in their default options. The default options are
908/// applied before the star and the key-value argument of the heading. An author
909/// can therefore change them with the star and the key-value argument (see [the
910/// options of a heading](self#the-options-of-a-heading)).
911///
912/// The key of each default option must be [`NUMBERED_KEY`] or [`TOC_KEY`], and
913/// its value must be `true` or `false`. Otherwise, the registry build fails
914/// ([`HeadingsConfig::validate`]).
915///
916/// # Examples
917///
918/// ```
919/// use flm_core::stdlib::features::headings::HeadingCommand;
920///
921/// // A heading written with `\quietsection{…}` is a section that is not listed
922/// // in the table of contents, unless the heading is written with `toc=true`.
923/// let quiet = HeadingCommand::new("quietsection", "section").default_value("toc", "false");
924/// assert_eq!(quiet.defaults, [(String::from("toc"), String::from("false"))]);
925/// ```
926#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
927#[derive(schemars::JsonSchema)]
928#[serde(deny_unknown_fields)]
929pub struct HeadingCommand {
930 /// The name of the command without the backslash, such as `section`. In
931 /// settings data, the name is the key of the entry and not a field.
932 #[schemars(skip)]
933 pub name: String,
934 /// The name of the heading kind of the headings written with the command.
935 pub heading: Name,
936 /// The default options of the headings written with this command, as
937 /// key-value pairs. They are applied in order, before the star and the
938 /// key-value argument of the heading.
939 #[serde(default)]
940 pub defaults: Vec<(String, String)>,
941}
942
943impl HeadingCommand {
944 /// Returns the heading command `name`, with which headings of the kind
945 /// `heading` are written, without default options.
946 pub fn new(name: impl Into<String>, heading: impl Into<Name>) -> HeadingCommand {
947 HeadingCommand { name: name.into(), heading: heading.into(), defaults: Vec::new() }
948 }
949
950 /// Adds the default option `key=value`. It is applied after the default
951 /// options added before it.
952 pub fn default_value(
953 mut self,
954 key: impl Into<String>,
955 value: impl Into<String>,
956 ) -> HeadingCommand {
957 self.defaults.push((key.into(), value.into()));
958 self
959 }
960}
961
962/// The configuration of the [`headings`](self) feature. It contains the heading
963/// kinds ([`HeadingDecl`]), the heading commands ([`HeadingCommand`]), and the
964/// setting [`numbering`](HeadingsConfig::numbering), with which the heading kinds
965/// that are numbered are selected.
966///
967/// A program passes the configuration to [`Headings::new`], or to
968/// [`StdlibConfig::headings`](crate::stdlib::StdlibConfig::headings). The
969/// configuration is fixed when the registry is built (see [settings, options and
970/// configuration](crate::guide::concepts_overview#settings-options-and-configuration)).
971///
972/// The default configuration, [`HeadingsConfig::new`], contains the five heading
973/// kinds `section`, `subsection`, `subsubsection`, `paragraph` and `subparagraph`
974/// at the levels 1 to 5, and one heading command with the same name for each
975/// heading kind. No heading kind is numbered by default. The submodule
976/// [`numbers`] describes the counters and the number formats of these heading
977/// kinds.
978///
979/// When the registry is built, the `headings` feature checks the configuration
980/// with [`HeadingsConfig::validate`], and the registry build fails if the check
981/// fails. A heading kind without a heading command is accepted. No document can
982/// write a heading of such a kind, but a program can create one, for instance in
983/// a stage.
984///
985/// # Examples
986///
987/// ```
988/// use flm_core::stdlib::features::headings::{HeadingNumbering, HeadingsConfig};
989///
990/// let config = HeadingsConfig::new()
991/// .run_in_levels([4, 5])
992/// .numbering(HeadingNumbering::UpToDepth(2));
993/// assert!(config.heading("paragraph").is_some_and(|kind| kind.run_in));
994/// assert!(!config.heading("subsubsection").is_some_and(|kind| kind.run_in));
995/// assert_eq!(config.commands.len(), 5);
996/// ```
997#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
998#[derive(schemars::JsonSchema)]
999#[serde(default, deny_unknown_fields)]
1000pub struct HeadingsConfig {
1001 /// The heading kinds. The default is the five heading kinds `section`,
1002 /// `subsection`, `subsubsection`, `paragraph` and `subparagraph`.
1003 #[serde(deserialize_with = "crate::core::settings::named::deserialize")]
1004 #[schemars(
1005 transform = crate::core::settings::named::map_schema,
1006 with = "std::collections::BTreeMap<String, HeadingDecl>"
1007 )]
1008 pub headings: Vec<HeadingDecl>,
1009 /// The heading commands. The default is one heading command for each of the
1010 /// five default heading kinds, with the name of the heading kind.
1011 #[serde(deserialize_with = "crate::core::settings::named::deserialize")]
1012 #[schemars(
1013 transform = crate::core::settings::named::map_schema,
1014 with = "std::collections::BTreeMap<String, HeadingCommand>"
1015 )]
1016 pub commands: Vec<HeadingCommand>,
1017 /// The heading kinds that are numbered. The default is
1018 /// [`HeadingNumbering::NothingNumbered`]: no heading is numbered.
1019 pub numbering: HeadingNumbering,
1020}
1021
1022impl Default for HeadingsConfig {
1023 fn default() -> HeadingsConfig {
1024 HeadingsConfig::new()
1025 }
1026}
1027
1028impl HeadingsConfig {
1029 /// Returns the default configuration: the five heading kinds `section` to
1030 /// `subparagraph`, one heading command with the same name for each heading
1031 /// kind, and no numbered heading kind (see [`HeadingsConfig`]).
1032 // The formats, the hierarchy, the fourth level showing nothing of its
1033 // parents, and the texts of `numbers` are the Python product's shipped
1034 // defaults, read from its headings feature, except that `paragraph` is
1035 // numbered within whichever of the three kinds above it came last rather
1036 // than within `subsubsection` alone, so that a `\paragraph` directly under a
1037 // `\subsection` is numbered too, and restarts there as it does in LaTeX.
1038 pub fn new() -> HeadingsConfig {
1039 let letters = || NumberTemplate::formats("#{alph}");
1040 let counter = |kind: &str| format!("{COUNTER_PREFIX}{kind}");
1041 HeadingsConfig::default_commands_for(vec![
1042 HeadingDecl::new("section", 1),
1043 HeadingDecl::new("subsection", 2).within(Within::parent(counter("section"))),
1044 HeadingDecl::new("subsubsection", 3).within(Within::parent(counter("subsection"))),
1045 HeadingDecl::new("paragraph", 4)
1046 .number_format(letters())
1047 .within(
1048 Within::parents(["section", "subsection", "subsubsection"].map(counter))
1049 .displayed_bare(),
1050 ),
1051 HeadingDecl::new("subparagraph", 5)
1052 .number_format(letters())
1053 .within(Within::parent(counter("paragraph"))),
1054 ])
1055 }
1056
1057 /// Returns the configuration with the heading kinds `headings`, one heading
1058 /// command with the same name and without default options for each heading
1059 /// kind, and no numbered heading kind.
1060 fn default_commands_for(headings: Vec<HeadingDecl>) -> HeadingsConfig {
1061 let commands = headings
1062 .iter()
1063 .map(|kind| HeadingCommand::new(kind.name.as_str(), kind.name.clone()))
1064 .collect();
1065 HeadingsConfig { headings, commands, numbering: HeadingNumbering::default() }
1066 }
1067
1068 /// Replaces the heading kinds with `headings`, and replaces the heading
1069 /// commands with one heading command for each heading kind. Each of these
1070 /// commands has the name of its heading kind and no default options. The
1071 /// setting [`numbering`](HeadingsConfig::numbering) is kept.
1072 ///
1073 /// Call this method before [`command`](HeadingsConfig::command), since it
1074 /// discards the heading commands added before it.
1075 pub fn headings(self, headings: impl IntoIterator<Item = HeadingDecl>) -> HeadingsConfig {
1076 HeadingsConfig {
1077 numbering: self.numbering,
1078 ..HeadingsConfig::default_commands_for(headings.into_iter().collect())
1079 }
1080 }
1081
1082 /// Sets the heading kinds that are numbered (see [`HeadingNumbering`]).
1083 pub fn numbering(mut self, numbering: HeadingNumbering) -> HeadingsConfig {
1084 self.numbering = numbering;
1085 self
1086 }
1087
1088 /// Returns whether the heading kind `kind` is numbered under this
1089 /// configuration. This is the case if `kind` has a counter and the setting
1090 /// [`numbering`](HeadingsConfig::numbering) includes the level of `kind`.
1091 pub fn numbers(&self, kind: &HeadingDecl) -> bool {
1092 kind.counter.is_some() && self.numbering.admits(kind.level)
1093 }
1094
1095 /// Replaces the heading commands with `commands`.
1096 pub fn commands(mut self, commands: impl IntoIterator<Item = HeadingCommand>) -> HeadingsConfig {
1097 self.commands = commands.into_iter().collect();
1098 self
1099 }
1100
1101 /// Adds the heading command `command` after the heading commands that the
1102 /// configuration already contains.
1103 pub fn command(mut self, command: HeadingCommand) -> HeadingsConfig {
1104 self.commands.push(command);
1105 self
1106 }
1107
1108 /// Makes the heading kinds at the levels `levels` run-in heading kinds, and
1109 /// all other heading kinds block heading kinds (see
1110 /// [`HeadingDecl::run_in`]).
1111 ///
1112 /// This method changes the heading kinds that the configuration contains
1113 /// when the method is called. Therefore, call it after
1114 /// [`headings`](HeadingsConfig::headings).
1115 pub fn run_in_levels(mut self, levels: impl IntoIterator<Item = u8>) -> HeadingsConfig {
1116 let levels: BTreeSet<u8> = levels.into_iter().collect();
1117 for kind in &mut self.headings {
1118 kind.run_in = levels.contains(&kind.level);
1119 }
1120 self
1121 }
1122
1123 /// Returns the heading kind with the name `name`, or `None` if the
1124 /// configuration contains no such heading kind.
1125 pub fn heading(&self, name: &str) -> Option<&HeadingDecl> {
1126 self.headings.iter().find(|kind| kind.name.as_str() == name)
1127 }
1128
1129 /// Returns the heading commands of the heading kind with the name `name`, in
1130 /// the order of [`commands`](HeadingsConfig::commands).
1131 pub fn commands_of<'c>(&'c self, name: &'c str) -> impl Iterator<Item = &'c HeadingCommand> {
1132 self.commands.iter().filter(move |command| command.heading.as_str() == name)
1133 }
1134
1135 /// Checks that the configuration is consistent. The `headings` feature calls
1136 /// this method when the registry is built, and the registry build fails if
1137 /// the method returns an error.
1138 ///
1139 /// # Errors
1140 ///
1141 /// Returns an error message for the first of the following problems that is
1142 /// found:
1143 ///
1144 /// - two heading kinds with the same name;
1145 /// - two heading kinds with the same counter, or with the same counter style;
1146 /// - a heading kind with a counter and without a counter style;
1147 /// - two heading commands with the same name;
1148 /// - a heading command whose heading kind is not in the configuration;
1149 /// - a default option of a heading command whose key is not
1150 /// [`NUMBERED_KEY`] or [`TOC_KEY`], or whose value is not `true` or
1151 /// `false`.
1152 pub fn validate(&self) -> Result<(), String> {
1153 let mut names = BTreeSet::new();
1154 let mut counters = BTreeSet::new();
1155 let mut styles = BTreeSet::new();
1156 for kind in &self.headings {
1157 if !names.insert(kind.name.as_str()) {
1158 return Err(format!("Duplicate heading kind ‘{}’", kind.name));
1159 }
1160 if let Some(counter) = &kind.counter {
1161 if !counters.insert(counter.as_str()) {
1162 return Err(format!(
1163 "Duplicate counter ‘{counter}’ for heading kind ‘{}’: each heading kind \
1164 must have a counter of its own",
1165 kind.name
1166 ));
1167 }
1168 if kind.style.is_none() {
1169 return Err(format!(
1170 "Missing counter style for heading kind ‘{}’ with counter ‘{counter}’",
1171 kind.name
1172 ));
1173 }
1174 }
1175 if let Some(style) = &kind.style {
1176 if !styles.insert(style.as_str()) {
1177 return Err(format!(
1178 "Duplicate counter style ‘{style}’ for heading kind ‘{}’: each heading \
1179 kind must have a counter style of its own",
1180 kind.name
1181 ));
1182 }
1183 }
1184 }
1185 let mut commands = BTreeSet::new();
1186 for command in &self.commands {
1187 if !commands.insert(command.name.as_str()) {
1188 return Err(format!("Duplicate heading command ‘\\{}’", command.name));
1189 }
1190 if !names.contains(command.heading.as_str()) {
1191 return Err(format!(
1192 "Unknown heading kind ‘{}’ of heading command ‘\\{}’",
1193 command.heading, command.name
1194 ));
1195 }
1196 for (key, value) in &command.defaults {
1197 if key != NUMBERED_KEY && key != TOC_KEY {
1198 return Err(format!(
1199 "Invalid default option ‘{key}’ of heading command ‘\\{}’: default \
1200 options must be ‘{NUMBERED_KEY}’ or ‘{TOC_KEY}’",
1201 command.name
1202 ));
1203 }
1204 if boolean(value).is_none() {
1205 return Err(format!(
1206 "Invalid default option ‘{key}={value}’ of heading command ‘\\{}’: the \
1207 value must be ‘true’ or ‘false’",
1208 command.name
1209 ));
1210 }
1211 }
1212 }
1213 Ok(())
1214 }
1215
1216 /// Returns the configuration encoded as bytes. The `headings` feature adds
1217 /// these bytes to the registry digest ([`crate::model::digest`]), a number
1218 /// with which a program can tell whether two registries produce the same
1219 /// output. The [`Hash`] implementation of `HeadingsConfig` also hashes these
1220 /// bytes.
1221 ///
1222 /// The bytes encode every field of every heading kind and of every heading
1223 /// command, in the order of the lists, except the descriptions of the
1224 /// heading kinds ([`HeadingDecl::docs`]). A description has no effect on a
1225 /// parse or a render, so a change of a description does not change the
1226 /// registry digest.
1227 ///
1228 /// Two configurations give the same bytes if and only if they are equal
1229 /// apart from the descriptions. For instance, two configurations that list
1230 /// the same heading kinds in different orders give different bytes.
1231 pub fn digest_bytes(&self) -> Vec<u8> {
1232 let mut out = Vec::new();
1233 push_len(&mut out, self.headings.len());
1234 for kind in &self.headings {
1235 push_text(&mut out, kind.name.as_str());
1236 out.push(kind.level);
1237 push_opt_text(&mut out, kind.counter.as_ref().map(|name| name.as_str()));
1238 push_opt_text(&mut out, kind.style.as_ref().map(|name| name.as_str()));
1239 match &kind.within {
1240 None => out.push(0),
1241 Some(within) => {
1242 out.push(1);
1243 within.digest_into(&mut out);
1244 }
1245 }
1246 match &kind.number_format {
1247 NumberTemplate::Formats(text) => {
1248 out.push(0);
1249 push_text(&mut out, text);
1250 }
1251 NumberTemplate::Initial(text) => {
1252 out.push(1);
1253 push_text(&mut out, text);
1254 }
1255 }
1256 push_text(&mut out, &kind.title_number_format);
1257 out.push(u8::from(kind.skip_toc));
1258 out.push(u8::from(kind.run_in));
1259 push_text(&mut out, kind.ref_kind.as_str());
1260 push_len(&mut out, kind.label_types.len());
1261 for label in &kind.label_types {
1262 push_text(&mut out, label);
1263 }
1264 push_text(&mut out, &kind.anchor_prefix);
1265 }
1266 push_len(&mut out, self.commands.len());
1267 for command in &self.commands {
1268 push_text(&mut out, &command.name);
1269 push_text(&mut out, command.heading.as_str());
1270 push_len(&mut out, command.defaults.len());
1271 for (key, value) in &command.defaults {
1272 push_text(&mut out, key);
1273 push_text(&mut out, value);
1274 }
1275 }
1276 match self.numbering {
1277 HeadingNumbering::NothingNumbered => out.push(0),
1278 HeadingNumbering::AllNumbered => out.push(1),
1279 HeadingNumbering::UpToDepth(depth) => {
1280 out.push(2);
1281 out.push(depth);
1282 }
1283 }
1284 out
1285 }
1286}
1287
1288/// Appends `len` to `out` as eight little-endian bytes.
1289fn push_len(out: &mut Vec<u8>, len: usize) {
1290 out.extend_from_slice(&(len as u64).to_le_bytes());
1291}
1292
1293/// Appends `text` to `out`: first its length in bytes ([`push_len`]), then its
1294/// bytes.
1295fn push_text(out: &mut Vec<u8>, text: &str) {
1296 push_len(out, text.len());
1297 out.extend_from_slice(text.as_bytes());
1298}
1299
1300/// Appends `text` to `out`: the byte 0 if `text` is `None`, and otherwise the
1301/// byte 1 followed by the text ([`push_text`]).
1302fn push_opt_text(out: &mut Vec<u8>, text: Option<&str>) {
1303 match text {
1304 None => out.push(0),
1305 Some(text) => {
1306 out.push(1);
1307 push_text(out, text);
1308 }
1309 }
1310}
1311
1312impl Hash for HeadingsConfig {
1313 fn hash<H: Hasher>(&self, state: &mut H) {
1314 state.write(&self.digest_bytes());
1315 }
1316}
1317
1318// --- the element ----------------------------------------------------------------------------
1319
1320/// The data of the element value of one heading kind (see [the
1321/// element](self#the-element)). It contains the declaration of the heading kind,
1322/// its heading commands, and whether the heading kind is numbered.
1323///
1324/// All heading commands of a heading kind share one element value. A lowering
1325/// rule obtains the `HeadingElement` of a heading with [`element_value`].
1326/// `HeadingElement` also implements the [`Sectioning`] and [`Referenceable`]
1327/// aspects of the element value.
1328#[derive(Debug, Clone, PartialEq, Eq)]
1329pub struct HeadingElement {
1330 /// The declaration of the heading kind.
1331 pub decl: HeadingDecl,
1332 /// The heading commands of the heading kind, in the order of
1333 /// [`HeadingsConfig::commands`].
1334 pub commands: Vec<HeadingCommand>,
1335 /// Whether the heading kind is numbered under the configuration of the
1336 /// `headings` feature ([`HeadingsConfig::numbers`]).
1337 pub numbered: bool,
1338}
1339
1340impl HeadingElement {
1341 /// Returns the heading command with which the heading `node` is written.
1342 ///
1343 /// Returns `None` if the node has no name, for instance a heading that a
1344 /// program created, or if no heading command of this heading kind has the
1345 /// name of the node.
1346 pub fn command_of(&self, node: &NodeRef<'_, Flm>) -> Option<&HeadingCommand> {
1347 let name = node.name()?;
1348 self.commands.iter().find(|command| command.name == name)
1349 }
1350
1351 /// Returns the options of the heading `node`. This method calls
1352 /// [`heading_options`] with the heading command of the node
1353 /// ([`command_of`](HeadingElement::command_of)).
1354 pub fn occurrence(&self, node: &NodeRef<'_, Flm>) -> HeadingOccurrence {
1355 heading_options(node, self.command_of(node))
1356 }
1357}
1358
1359/// The options of one heading: whether the heading is numbered, and whether it
1360/// is listed in a table of contents. [`heading_options`] returns these options
1361/// (see [the options of a heading](self#the-options-of-a-heading)).
1362#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1363pub struct HeadingOccurrence {
1364 /// The option `numbered`. The heading is numbered only if this option is
1365 /// `true` and its heading kind is numbered.
1366 pub numbered: bool,
1367 /// The option `toc`. The heading is listed in a table of contents only if
1368 /// this option is `true` and its heading kind is not declared with
1369 /// [`skip_toc`](HeadingDecl::skip_toc).
1370 pub toc: bool,
1371}
1372
1373/// Returns whether the heading `node` is written with a star, as in
1374/// `\section*{…}`. Returns `false` for a node without a star argument.
1375///
1376/// Writing a star is equivalent to writing `numbered=false`.
1377/// [`heading_options`] takes the star into account.
1378pub fn starred(node: &NodeRef<'_, Flm>) -> bool {
1379 node.arguments()
1380 .and_then(|args| args.get_named(STAR_ARG))
1381 .is_some_and(|arg| arg.is_provided())
1382}
1383
1384/// Returns the options of the heading `node`, which is written with the heading
1385/// command `command`.
1386///
1387/// The options are read, in this order, from the default options of `command`,
1388/// from the star, and from the key-value argument of the heading. A later value
1389/// replaces an earlier one (see [the options of a
1390/// heading](self#the-options-of-a-heading)). Pass `None` as `command` for a
1391/// heading without a heading command, for instance a heading that a program
1392/// created; no default options are then applied. [`HeadingElement::occurrence`]
1393/// finds the heading command of a node and calls this function.
1394///
1395/// This function reports no diagnostic. It ignores every key other than
1396/// `numbered` and `toc`, and every value that it cannot read. The lowering rules
1397/// of headings report these problems.
1398pub fn heading_options(
1399 node: &NodeRef<'_, Flm>,
1400 command: Option<&HeadingCommand>,
1401) -> HeadingOccurrence {
1402 read_options(node, command).0
1403}
1404
1405/// Returns the alternative title of the heading `node`, which is the value of
1406/// the key `alt` ([`ALT_KEY`]) in the key-value argument of the heading.
1407///
1408/// The alternative title is returned as a list of [`WrittenPiece`]s, which
1409/// refer to the nodes and to the characters of the document
1410/// ([`key_value_pieces`]). Whitespace at the start and at the end of the value
1411/// is left out. If the value is a single group, the content of the group is
1412/// returned, as in LaTeX's key-value lists. For instance, for
1413/// `alt={Short \emph{title}}` the function returns the text `Short ` and the
1414/// `\emph` node, and for `alt={}` it returns an empty list. If the key `alt` is
1415/// given several times, the last `alt` with a value is used.
1416///
1417/// Returns `None` if the heading has no key `alt` with a value, or if the
1418/// key-value argument cannot be read. This function reports no diagnostic; the
1419/// lowering rules of headings report the problems in the key-value argument.
1420/// The aspect method [`Sectioning::toc_title`] of a heading returns a copy of
1421/// the alternative title.
1422pub fn heading_alt<'t>(node: &NodeRef<'t, Flm>) -> Option<Vec<WrittenPiece<'t>>> {
1423 let content = node.argument_content_nodes_named(OPTIONS_ARG).ok().flatten()?;
1424 let keyvals = parse_keyval_drop_annotations(content).ok()?;
1425 let entry = keyvals.iter().filter(|entry| entry.key() == ALT_KEY && entry.value().is_some()).last()?;
1426 let pieces = key_value_pieces(&content, entry.value()?);
1427 // A value written as one group, whitespace around it dropped, is the
1428 // group's content: the group's children, trimmed the same way.
1429 match pieces.as_slice() {
1430 [WrittenPiece::Node(group)] if group.is_group() => {
1431 Some(key_value_pieces(&group.children(), group.children()))
1432 }
1433 _ => Some(pieces),
1434 }
1435}
1436
1437/// A problem in the key-value argument of a heading, found by
1438/// [`read_options`]. Each variant except `Placeholder` corresponds to a
1439/// diagnostic condition.
1440#[derive(Debug, Clone, PartialEq, Eq)]
1441enum OptionProblem {
1442 /// A reserved key, with the key ([`KeyNotImplemented`]).
1443 NotImplemented(String),
1444 /// The key [`ALT_KEY`] without a value, with the key ([`MissingValue`]).
1445 MissingValue(String),
1446 /// An unknown key, with the key ([`UnknownKey`]).
1447 Unknown(String),
1448 /// A value of `numbered` or `toc` other than `true` and `false`, with the
1449 /// key and the value ([`BadValue`]).
1450 BadValue(String, String),
1451 /// A key that is not plain text ([`UnreadableOptions`]).
1452 Unreadable,
1453 /// A value of `numbered` or `toc` that contains a placeholder of a user
1454 /// definition, lowered without expansion. The characters of the value are
1455 /// known only at a use site of the definition
1456 /// ([`LowerError::PlaceholderCharacters`]).
1457 Placeholder,
1458}
1459
1460/// Returns `Some(true)` for the text `true`, `Some(false)` for the text
1461/// `false`, and `None` for any other text.
1462fn boolean(value: &str) -> Option<bool> {
1463 match value {
1464 "true" => Some(true),
1465 "false" => Some(false),
1466 _ => None,
1467 }
1468}
1469
1470/// Sets the option `key` of `occurrence` to `value`, if `key` is
1471/// [`NUMBERED_KEY`] or [`TOC_KEY`]. Any other key leaves `occurrence`
1472/// unchanged.
1473fn apply(occurrence: &mut HeadingOccurrence, key: &str, value: bool) {
1474 if key == NUMBERED_KEY {
1475 occurrence.numbered = value;
1476 } else if key == TOC_KEY {
1477 occurrence.toc = value;
1478 }
1479}
1480
1481/// Reads the options of the heading `node` as [`heading_options`] does, and
1482/// also returns the problems found in the key-value argument of the heading,
1483/// in the order in which they are written.
1484fn read_options(
1485 node: &NodeRef<'_, Flm>,
1486 command: Option<&HeadingCommand>,
1487) -> (HeadingOccurrence, Vec<OptionProblem>) {
1488 let mut occurrence = HeadingOccurrence { numbered: true, toc: true };
1489 let mut problems = Vec::new();
1490 // The command's defaults were checked when the registry was built.
1491 for (key, value) in command.map(|command| command.defaults.as_slice()).unwrap_or_default() {
1492 if let Some(value) = boolean(value) {
1493 apply(&mut occurrence, key, value);
1494 }
1495 }
1496 if starred(node) {
1497 apply(&mut occurrence, NUMBERED_KEY, false);
1498 }
1499 let Ok(Some(content)) = node.argument_content_nodes_named(OPTIONS_ARG) else {
1500 return (occurrence, problems);
1501 };
1502 let Ok(keyvals) = parse_keyval_drop_annotations(content) else {
1503 problems.push(OptionProblem::Unreadable);
1504 return (occurrence, problems);
1505 };
1506 for entry in keyvals.iter() {
1507 let key = entry.key();
1508 if key.is_empty() {
1509 continue;
1510 }
1511 if RESERVED_KEYS.contains(&key) {
1512 problems.push(OptionProblem::NotImplemented(key.to_string()));
1513 continue;
1514 }
1515 // The alternative title is content, read by `heading_alt`; only its
1516 // absence is a problem here.
1517 if key == ALT_KEY {
1518 if entry.value().is_none() {
1519 problems.push(OptionProblem::MissingValue(key.to_string()));
1520 }
1521 continue;
1522 }
1523 if key != NUMBERED_KEY && key != TOC_KEY {
1524 problems.push(OptionProblem::Unknown(key.to_string()));
1525 continue;
1526 }
1527 // A key written without a value means `true`.
1528 let text = match entry.value_content() {
1529 None => Some(String::from("true")),
1530 Some(value) => match chars_at_lowering(value.iter()) {
1531 Ok(read) => read.ok().map(|text| text.trim_matches(is_space).to_string()),
1532 Err(_) => {
1533 problems.push(OptionProblem::Placeholder);
1534 continue;
1535 }
1536 },
1537 };
1538 match text.as_deref().and_then(boolean) {
1539 Some(value) => apply(&mut occurrence, key, value),
1540 None => problems.push(OptionProblem::BadValue(
1541 key.to_string(),
1542 text.unwrap_or_else(|| String::from("(not plain text)")),
1543 )),
1544 }
1545 }
1546 (occurrence, problems)
1547}
1548
1549/// The warning that is reported when the key-value argument of a heading
1550/// contains a reserved key (`flm.heading.key-not-implemented`).
1551///
1552/// A reserved key is set aside for an option of headings that is not
1553/// implemented. The reserved keys are listed in [`RESERVED_KEYS`]: the only
1554/// reserved key is `pdfbookmark`. Reported by the lowering rule of the heading
1555/// when it is invoked. The key is ignored, and the heading is otherwise written
1556/// as usual.
1557#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
1558#[diagnostic(
1559 id = "flm.heading.key-not-implemented",
1560 message = "Unsupported heading option ‘{key}’"
1561)]
1562pub struct KeyNotImplemented {
1563 /// The key as written.
1564 pub key: String,
1565}
1566
1567/// The error that is reported when the key-value argument of a heading
1568/// contains an unknown key (`flm.heading.unknown-key`).
1569///
1570/// The keys of a heading are `numbered`, `toc` and `alt`, as in
1571/// `\section[toc=false]{Acknowledgments}`, and the reserved keys of
1572/// [`RESERVED_KEYS`]. Reported by the lowering rule of the heading when it is
1573/// invoked. The key is ignored, and the heading is otherwise written as usual.
1574#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
1575#[diagnostic(
1576 id = "flm.heading.unknown-key",
1577 message = "Unknown heading option ‘{key}’: the heading options are ‘numbered’, ‘toc’ \
1578 and ‘alt’"
1579)]
1580pub struct UnknownKey {
1581 /// The key as written.
1582 pub key: String,
1583}
1584
1585/// The error that is reported when the option `numbered` or `toc` of a
1586/// heading has a value other than `true` and `false` (`flm.heading.bad-value`).
1587///
1588/// The value of these options must be `true` or `false`, as in
1589/// `\section[numbered=false]{Notation}`. A key without a value, as in
1590/// `\section[numbered]{Notation}`, has the value `true`. Reported by the
1591/// lowering rule of the heading when it is invoked. The key is ignored: the
1592/// option has the value that was read before the key, from the default options
1593/// of the heading command, from the star, or from an earlier key.
1594#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
1595#[diagnostic(
1596 id = "flm.heading.bad-value",
1597 message = "Invalid value ‘{value}’ of heading option ‘{key}’: the value must be ‘true’ \
1598 or ‘false’"
1599)]
1600pub struct BadValue {
1601 /// The key as written.
1602 pub key: String,
1603 /// The value as written, without whitespace at the start and at the end.
1604 /// If the value is not plain text, this field contains the text
1605 /// `(not plain text)`.
1606 pub value: String,
1607}
1608
1609/// The error that is reported when the key `alt` of a heading has no value
1610/// (`flm.heading.missing-value`).
1611///
1612/// With the key `alt`, an author gives the heading an alternative title. The
1613/// key must be given a value, as in `\section[alt={Short title}]{A long title}`.
1614/// Reported by the lowering rule of the heading when it is invoked. The key is
1615/// ignored, and the heading is otherwise written as usual.
1616#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
1617#[diagnostic(
1618 id = "flm.heading.missing-value",
1619 message = "Missing value for heading option ‘{key}’"
1620)]
1621pub struct MissingValue {
1622 /// The key as written.
1623 pub key: String,
1624}
1625
1626/// The error that is reported when a key in the key-value argument of a
1627/// heading is not plain text (`flm.heading.unreadable-options`).
1628///
1629/// Each key must be plain text, as `toc` in `\section[toc=false]{Notation}`.
1630/// Reported by the lowering rule of the heading when it is invoked. The whole
1631/// key-value argument is ignored: the options of the heading are read only from
1632/// the default options of the heading command and from the star.
1633#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
1634#[diagnostic(
1635 id = "flm.heading.unreadable-options",
1636 message = "Invalid heading options: each key must be plain text"
1637)]
1638pub struct UnreadableOptions;
1639
1640/// Reports one diagnostic for each problem in the key-value argument of the
1641/// heading `node`, in the order in which the problems are written. `value` is
1642/// the element value of the heading.
1643///
1644/// Both lowering rules of headings, [`RULE`] and [`latex::LATEX_RULE`], call
1645/// this function. During a render, one of these rules is applied to each
1646/// heading, so each problem is reported once per render.
1647///
1648/// # Errors
1649///
1650/// Returns [`LowerError::PlaceholderCharacters`], and reports no diagnostic, if
1651/// the value of `numbered` or `toc` contains a placeholder of a user definition
1652/// that is lowered without expansion. The value is known only at the use sites
1653/// of the definition. This error causes the use sites of the definition to be
1654/// expanded, and the heading is then lowered at each use site.
1655fn report_option_problems(
1656 node: &NodeRef<'_, Flm>,
1657 value: &HeadingElement,
1658 lw: &mut dyn Lowerer,
1659) -> Result<(), LowerError> {
1660 let (_, problems) = read_options(node, value.command_of(node));
1661 if problems.contains(&OptionProblem::Placeholder) {
1662 return Err(LowerError::PlaceholderCharacters);
1663 }
1664 for problem in problems {
1665 let span = node.span().clone();
1666 lw.diagnose(match problem {
1667 OptionProblem::NotImplemented(key) => {
1668 Diagnostic::warning(KeyNotImplemented { key }, span)
1669 }
1670 OptionProblem::MissingValue(key) => Diagnostic::error(MissingValue { key }, span),
1671 OptionProblem::Unknown(key) => Diagnostic::error(UnknownKey { key }, span),
1672 OptionProblem::BadValue(key, value) => {
1673 Diagnostic::error(BadValue { key, value }, span)
1674 }
1675 OptionProblem::Unreadable => Diagnostic::error(UnreadableOptions, span),
1676 OptionProblem::Placeholder => continue,
1677 });
1678 }
1679 Ok(())
1680}
1681
1682impl Sectioning for HeadingElement {
1683 fn level(&self, _node: &NodeRef<'_, Flm>) -> u32 {
1684 u32::from(self.decl.level)
1685 }
1686
1687 fn in_toc(&self, node: &NodeRef<'_, Flm>) -> bool {
1688 !self.decl.skip_toc && self.occurrence(node).toc
1689 }
1690
1691 /// Returns the alternative title of the heading ([`heading_alt`]) if the
1692 /// heading has one, and the title argument otherwise.
1693 ///
1694 /// The alternative title is copied into a synthesized value, as content
1695 /// that is displayed a second time ([`ValueContent::Shown`]). For instance,
1696 /// a footnote in the alternative title is copied as its mark only. Returns
1697 /// `None` if the copy fails, which happens only for content nested deeper
1698 /// than the [recursion guard](crate::lang::guard) allows. No diagnostic is
1699 /// reported in this case.
1700 fn toc_title(&self, node: &NodeRef<'_, Flm>) -> Option<ContentRef> {
1701 let Some(alt) = heading_alt(node) else {
1702 return Some(ContentRef::ArgumentNamed(TITLE_ARG.to_string()));
1703 };
1704 let pieces: Vec<ValuePiece<'_, '_>> = alt.iter().map(WrittenPiece::as_value_piece).collect();
1705 on_worker_thread(|| {
1706 copy_pieces_into_value(&pieces, node, ValueContent::Shown, GuardPolicy::StackBudget)
1707 })
1708 .ok()?
1709 .ok()
1710 .map(ContentRef::Synthesized)
1711 }
1712}
1713
1714impl Referenceable for HeadingElement {
1715 fn points(&self, node: &NodeRef<'_, Flm>) -> Vec<RefPoint> {
1716 let (labels, malformed) = refs::point_labels(refs::label_uses(node).iter());
1717 let anchor = if labels.is_empty() {
1718 AnchorPolicy::Slug {
1719 prefix: self.decl.anchor_prefix.clone(),
1720 content: ContentRef::ArgumentNamed(TITLE_ARG.to_string()),
1721 }
1722 } else {
1723 AnchorPolicy::FromFirstLabel
1724 };
1725 // A heading of a kind the depth leaves unnumbered, or one that opts
1726 // out — a star, or `numbered=false` — states no number source, so it
1727 // advances nothing and the headings after it go on under the last
1728 // number given. A numbered one counts in its kind's counter, is shown
1729 // in its kind's style, and advances the number itself — level 0 — by
1730 // one.
1731 let numbered = self.numbered && self.occurrence(node).numbered;
1732 let number = if numbered { self.decl.number_source() } else { None };
1733 vec![RefPoint {
1734 kind: self.decl.ref_kind.clone(),
1735 labels,
1736 malformed,
1737 computed: 0,
1738 anchor,
1739 number,
1740 content: Some(ContentRef::ArgumentNamed(TITLE_ARG.to_string())),
1741 accepts: AcceptedRefTypes::these(self.decl.label_types.iter().map(String::as_str)),
1742 }]
1743 }
1744}
1745
1746/// Returns the block role of the headings of `kind`: [`BlockRole::Block`], or
1747/// for a run-in heading kind [`BlockRole::BlockDecorator`] at
1748/// [`Placement::Leads`], a decorator at the start of the paragraph that the
1749/// heading introduces.
1750fn block_role(kind: &HeadingDecl) -> BlockRole {
1751 if kind.run_in { BlockRole::BlockDecorator(Placement::Leads) } else { BlockRole::Block }
1752}
1753
1754/// Returns the description of the heading kind `kind`, for the description of
1755/// its element value: the field [`docs`](HeadingDecl::docs) of `kind`, or
1756/// `A heading of level <level>.` if this field is empty.
1757fn kind_docs(kind: &HeadingDecl) -> String {
1758 if kind.docs.is_empty() { format!("A heading of level {}.", kind.level) } else { kind.docs.clone() }
1759}
1760
1761/// Returns the description of the heading commands of the heading kind
1762/// `kind`: `Starts a heading of level <level>.` The field
1763/// [`docs`](HeadingDecl::docs) of `kind` is used only in the description of
1764/// the element value ([`kind_docs`]).
1765fn command_docs(kind: &HeadingDecl) -> String {
1766 format!("Starts a heading of level {}.", kind.level)
1767}
1768
1769/// Returns the element value of the heading kind `kind`, an element of type
1770/// [`HEADING`]. Its value is a [`HeadingElement`] that contains `kind`,
1771/// `commands` and `numbered`. The element value has the block role of the
1772/// heading kind ([`block_role`]) and the [`Sectioning`] and [`Referenceable`]
1773/// aspects.
1774fn element(kind: &HeadingDecl, commands: Vec<HeadingCommand>, numbered: bool) -> Arc<ElementSpec> {
1775 let value = Arc::new(HeadingElement { decl: kind.clone(), commands, numbered });
1776 Arc::new(
1777 ElementSpec::new(HEADING)
1778 .docs(format!("`{}`: {}", kind.name, kind_docs(kind)))
1779 .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(block_role(kind))))
1780 .with::<dyn Sectioning>(Arc::clone(&value) as Arc<dyn Sectioning>)
1781 .with::<dyn Referenceable>(Arc::clone(&value) as Arc<dyn Referenceable>)
1782 .with_value(value),
1783 )
1784}
1785
1786/// Returns the arguments of a heading command, in this order: the star, the
1787/// optional key-value argument, the title, and a trailing argument that
1788/// contains the `\label` commands written after the title (see
1789/// [fields](crate::guide::concepts_overview#fields-data-a-construct-reads)).
1790///
1791/// Use this list for a command of your own feature that is written like a
1792/// heading command. For a command with other arguments that also accepts
1793/// `\label` commands after it, declare the trailing argument with
1794/// [`label_fields_arg`](refs::label_fields_arg).
1795pub fn heading_args() -> Vec<ArgDef> {
1796 vec![
1797 ArgDef::named(STAR_ARG, ArgStdKind::Star)
1798 .docs("With a star, the heading is not numbered, as with `numbered=false`."),
1799 ArgDef::named(OPTIONS_ARG, ArgStdKind::KeyVals).docs(
1800 "The options of the heading, as key-value pairs: `numbered=true|false`, \
1801 `toc=true|false`, and `alt={…}` for the title in a table of contents.",
1802 ),
1803 ArgDef::mandatory(TITLE_ARG).docs("The heading's title."),
1804 refs::label_fields_arg(),
1805 ]
1806}
1807
1808/// The lowering rule [`RULE`] of headings, which is used on every backend except
1809/// `latex-recomposed` (see [the lowering rules](self#the-lowering-rules)).
1810///
1811/// The rule lowers a heading to a
1812/// [`flm.pres.block-heading`](crate::stdlib::backends::pres::BLOCK_HEADING)
1813/// node. The payload of this node ([`HeadingPayload`]) contains the name and the
1814/// level of the heading kind, whether the heading is listed in a table of
1815/// contents, the anchor of the heading, and the number of the heading as plain
1816/// text. The content of the node is the title of the heading, preceded by the
1817/// number if the heading is numbered.
1818///
1819/// If the heading has an alternative title (`alt=`, [`heading_alt`]), the rule
1820/// also lowers the alternative title, into the slot [`ALT_SLOT`](pres::ALT_SLOT)
1821/// of the node. The title is in the slot [`BODY_SLOT`](pres::BODY_SLOT). The
1822/// `latex-rendered` backend writes the alternative title as the key `alt` of the
1823/// heading. The `html` and `text` backends write only the title.
1824///
1825/// The rule lowers a run-in heading to a
1826/// [`flm.pres.deco.runin`](crate::stdlib::backends::pres::DECO_RUNIN)
1827/// decoration. The payload of a decoration is empty. Therefore, the decoration
1828/// contains a
1829/// [`flm.pres.runin-heading`](crate::stdlib::backends::pres::RUNIN_HEADING)
1830/// node, with the same payload and the same content as a block heading.
1831///
1832/// The rule also reports the problems in the key-value argument of the heading
1833/// (see [the options of a heading](self#the-options-of-a-heading)).
1834///
1835/// A `HeadingRule` can be constructed only in the `headings` feature, because
1836/// the rule contains the compiled heading title templates of the heading kinds
1837/// ([`HeadingDecl::title_number_format`]).
1838#[derive(Debug, Clone)]
1839pub struct HeadingRule {
1840 titles: Arc<Titles>,
1841}
1842
1843impl HeadingRule {
1844 /// Builds the nodes written before the title of a heading in the lowered
1845 /// tree (see [`Lowerer`]), and returns them. The heading has the heading
1846 /// kind `kind` and the reference point `point`.
1847 ///
1848 /// The nodes are the output of the [heading title
1849 /// template](HeadingDecl::title_number_format) of the heading kind, in which
1850 /// each `#{number}` is replaced with the number of the heading. The number is
1851 /// placed in a span with the role [`NUMBER_ROLE`](numbers::NUMBER_ROLE). The
1852 /// number is formatted without the word of its counter style (such as `§`),
1853 /// which belongs to a reference to the heading, and without delimiters.
1854 ///
1855 /// Returns an empty list if the heading has no number. This is the case for
1856 /// a heading that is not numbered, for every heading of a heading kind that
1857 /// is not numbered ([`HeadingsConfig::numbering`]), and for every heading in
1858 /// a registry without the `numbering` feature.
1859 ///
1860 /// # Errors
1861 ///
1862 /// Returns [`LowerError`] if the counter table cannot be read, if a node
1863 /// cannot be built, if the heading title template of the heading kind is not
1864 /// compiled, or if the number cannot be formatted from the counter record.
1865 /// The last case is a fault in the program: the numbering stage refuses a
1866 /// counter record that its counter style cannot format.
1867 fn number(
1868 &self,
1869 kind: &Name,
1870 point: PointId,
1871 cx: &mut LowerCx<'_>,
1872 lw: &mut dyn Lowerer,
1873 ) -> Result<Vec<BuildId>, LowerError> {
1874 // The table is absent in a registry holding no numbering feature, and
1875 // holds no record for a heading whose counter this document switched
1876 // off; both are a heading with no number. The number is staged inside
1877 // the heading's content rather than in its payload, so that a backend
1878 // measuring the heading measures it.
1879 let options = FormatOptions::new().without_word().without_delimiters();
1880 let written = {
1881 let Some(counters) = lw.get(COUNTERS)? else { return Ok(Vec::new()) };
1882 if counters.record(point).is_none() {
1883 return Ok(Vec::new());
1884 }
1885 title::title_number(&self.titles, kind, |keys| {
1886 counters
1887 .format_with_keys(point, keys, &options)
1888 .map(|result| result.map_err(|error| error.to_string()))
1889 })?
1890 };
1891 let Some(written) = written else { return Ok(Vec::new()) };
1892 lw.splice(cx, &written)
1893 }
1894}
1895
1896impl Lower for HeadingRule {
1897 fn lower(
1898 &self,
1899 node: NodeRef<'_, Flm>,
1900 cx: &mut LowerCx<'_>,
1901 lw: &mut dyn Lowerer,
1902 ) -> Result<Lowering, LowerError> {
1903 let value = element_value::<HeadingElement>(&node)
1904 .ok_or_else(|| LowerError::structure("a heading without its element's data"))?;
1905 report_option_problems(&node, value, lw)?;
1906 let point = PointId { addr: lw.addr(), index: 0 };
1907 // The table itself is absent in a registry that holds no feature
1908 // computing anchors: the heading is printed with no anchor, and the
1909 // registry build's Note about the unresolved declaration is the whole
1910 // report. With the table present, `Some(None)` is a heading the
1911 // anchors stage saw and gave no anchor, because another point had
1912 // claimed the same one: the heading is printed, unlinkable. `None` is
1913 // a heading the stage never saw, which is the access-site error.
1914 let anchor: Option<String> = match lw.get(ANCHORS)? {
1915 None => None,
1916 Some(anchors) => {
1917 let Some(entry) = anchors.lookup(point) else {
1918 let table = CapName::from(ANCHORS.name());
1919 let producer = lw
1920 .producer_of(&table)
1921 .map(|stage| stage.to_string())
1922 .unwrap_or_else(|| "nobody".to_string());
1923 lw.diagnose(Diagnostic::error(
1924 MissingEntry {
1925 table: table.to_string(),
1926 producer,
1927 element: HEADING.to_string(),
1928 },
1929 node.span().clone(),
1930 ));
1931 return Err(LowerError::structure("the heading has no anchor entry"));
1932 };
1933 entry.map(String::from)
1934 }
1935 };
1936 self.write(&node, value, point, anchor, cx, lw)
1937 }
1938}
1939
1940impl HeadingRule {
1941 /// Lowers the heading `node` as described in [`HeadingRule`]. `value` is the
1942 /// element value of the heading, `point` its reference point, and `anchor`
1943 /// its anchor.
1944 fn write(
1945 &self,
1946 node: &NodeRef<'_, Flm>,
1947 value: &HeadingElement,
1948 point: PointId,
1949 anchor: Option<String>,
1950 cx: &mut LowerCx<'_>,
1951 lw: &mut dyn Lowerer,
1952 ) -> Result<Lowering, LowerError> {
1953 let level = value.decl.level;
1954 // A title a parse recovery left absent lowers to nothing: an empty
1955 // heading, and no second report of what the parse already reported.
1956 // The number, where this document gave the heading one, stands before
1957 // the title inside the heading's own content.
1958 let mut body = self.number(&value.decl.name, point, cx, lw)?;
1959 body.extend(lower_arg_named_or_nothing(cx, lw, node, TITLE_ARG)?);
1960 let alt = match heading_alt(node) {
1961 Some(pieces) => Some(lower_written_pieces(cx, lw, &pieces)?),
1962 None => None,
1963 };
1964 let payload = HeadingPayload {
1965 name: value.decl.name.clone(),
1966 level,
1967 in_toc: value.in_toc(node),
1968 anchor,
1969 number: number_text(point, lw)?,
1970 };
1971 lw.require(&Name::from(STYLE));
1972 let element = ElementName::from(if value.decl.run_in {
1973 pres::RUNIN_HEADING
1974 } else {
1975 pres::BLOCK_HEADING
1976 });
1977 let heading = match alt {
1978 None => lw.pres_with(cx, &element, payload, body)?,
1979 Some(alt) => lw.pres_slots_with(
1980 cx,
1981 &element,
1982 payload,
1983 vec![(String::from(pres::BODY_SLOT), body), (String::from(pres::ALT_SLOT), alt)],
1984 )?,
1985 };
1986 if value.decl.run_in {
1987 let title = heading;
1988 let deco = lw.pres_with(
1989 cx,
1990 &ElementName::from(pres::DECO_RUNIN),
1991 DecorationPayload,
1992 vec![title],
1993 )?;
1994 return Ok(Lowering::Emit(vec![deco]));
1995 }
1996 Ok(Lowering::Emit(vec![heading]))
1997 }
1998}
1999
2000/// Returns the number of the heading with the reference point `point` as plain
2001/// text, for the payload of the heading.
2002///
2003/// The number is formatted without the word and the delimiters of its counter
2004/// style, and converted to plain text with [`plain_text`](pres::plain_text).
2005/// Returns `None` if the heading has no number, that is, if the registry has no
2006/// counter table, or if the counter table has no number for `point`.
2007///
2008/// # Errors
2009///
2010/// Returns [`LowerError`] if the counter table cannot be read, or if the number
2011/// cannot be formatted from the counter record. The second case is a fault in
2012/// the program, as for [`HeadingRule::number`].
2013fn number_text(point: PointId, lw: &mut dyn Lowerer) -> Result<Option<String>, LowerError> {
2014 let options = FormatOptions::new().without_word().without_delimiters();
2015 let Some(counters) = lw.get(COUNTERS)? else { return Ok(None) };
2016 let Some(segments) = counters.format(point, &options) else { return Ok(None) };
2017 let segments = segments.map_err(|error| LowerError::other(error.to_string()))?;
2018 let text = segments
2019 .iter()
2020 .map(|segment| pres::plain_text(segment.content().root().children().iter()))
2021 .collect::<String>();
2022 Ok(Some(text))
2023}
2024
2025// --- the feature ----------------------------------------------------------------------------
2026
2027/// The `headings` feature, which provides the headings of a document (see the
2028/// [module documentation](self)). The feature is constructed from a
2029/// [`HeadingsConfig`].
2030///
2031/// The feature contributes the following items to the registry:
2032///
2033/// - one element value of type [`HEADING`] for each heading kind of the
2034/// configuration, with the names of the heading commands of the kind;
2035/// - the lowering rules of headings, [`RULE`] and [`latex::LATEX_RULE`];
2036/// - the element [`title::NUMBER_ELEMENT`], which contains the number of a
2037/// heading in its title, with its lowering rules;
2038/// - the counters, the counter styles and the parent set of the heading kinds
2039/// ([`numbers`]);
2040/// - a late-initialization hook ([`LateInit`](crate::core::registry::LateInit))
2041/// that compiles the heading title templates of the heading kinds.
2042#[derive(Debug, Default, Clone)]
2043pub struct Headings {
2044 config: HeadingsConfig,
2045}
2046
2047impl Headings {
2048 /// Returns the `headings` feature with the configuration `config`.
2049 pub fn new(config: HeadingsConfig) -> Headings {
2050 Headings { config }
2051 }
2052
2053 /// Returns the configuration of this feature.
2054 pub fn config(&self) -> &HeadingsConfig {
2055 &self.config
2056 }
2057}
2058
2059impl FlmFeature for Headings {
2060 fn info(&self) -> FeatureInfo {
2061 FeatureInfo::new(FEATURE, "Headings").docs(
2062 "The headings of a document, such as sections and subsections, written with the \
2063 heading commands `\\section` to `\\subparagraph` by default. Each heading kind has \
2064 a level. A heading can be numbered, listed in a table of contents, and referred \
2065 to with a label.",
2066 )
2067 }
2068
2069 fn settings(&self) -> Option<SettingsDecl> {
2070 Some(settings())
2071 }
2072
2073 fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
2074 let owner = b.feature().clone();
2075 self.config
2076 .validate()
2077 .map_err(|detail| BuildError::Feature { feature: owner.clone(), detail })?;
2078 // The `\label` field of a heading command is the references
2079 // feature's, with that feature's role on its argument; declared as a
2080 // peer, so that a registry without that feature still builds.
2081 b.peer_argument_role(refs::DEFINED_LABEL_ARG_ROLE)?;
2082 // One value per kind, written under the names of every command of the
2083 // kind. A kind no command writes still has its value, synthesized (no
2084 // name, so no document can write it): a program may create its
2085 // headings itself, for instance in a stage.
2086 for kind in &self.config.headings {
2087 let commands: Vec<HeadingCommand> =
2088 self.config.commands_of(kind.name.as_str()).cloned().collect();
2089 let names: Vec<String> = commands.iter().map(|command| command.name.clone()).collect();
2090 let (syntax, docs) = if names.is_empty() {
2091 let docs = format!(
2092 "`{}`: {} This heading kind has no heading command; only a program can \
2093 create its headings.",
2094 kind.name,
2095 kind_docs(kind)
2096 );
2097 (SyntaxDef::Synthesized, docs)
2098 } else {
2099 (SyntaxDef::Macro { args: heading_args() }, command_docs(kind))
2100 };
2101 b.element(
2102 ElementDef::new(
2103 owner.clone(),
2104 names,
2105 syntax,
2106 element(kind, commands, self.config.numbers(kind)),
2107 )
2108 .docs(docs),
2109 )?;
2110 }
2111 // The anchors table belongs to the references feature, so the rule
2112 // declares it as a peer table and reads it optionally: without that
2113 // feature the rule still runs and the heading is printed with no
2114 // anchor.
2115 b.peer_table::<refs::Anchors>(
2116 ANCHORS.name(),
2117 "the anchors table of the `refs` feature, from which the lowering rule of \
2118 headings reads the anchor of each heading",
2119 )?;
2120 // The counter table belongs to the numbering feature, which may not be
2121 // there either; the rule then shows no number. The heading counters
2122 // and their styles are declared into that feature's slots the same
2123 // way, as peer contributions.
2124 b.peer_table::<Counters>(
2125 COUNTERS.name(),
2126 "the counter table of the `numbering` feature, from which the lowering rule of \
2127 headings reads the number of each heading",
2128 )?;
2129 numbers::declare(b, &self.config)?;
2130 // The number node a kind's title number format puts where it writes
2131 // `#{number}`: synthesized, so no document can write it, and lowered
2132 // by a rule of its own to the span of the number's role. The rule is
2133 // registered whatever the configuration says, so the span is produced
2134 // at any level.
2135 let number_element = title::number_element();
2136 b.element(
2137 ElementDef::new(
2138 owner.clone(),
2139 Vec::<&str>::new(),
2140 SyntaxDef::Synthesized,
2141 Arc::clone(&number_element),
2142 )
2143 .docs(
2144 "The number of a heading, placed in its title where the heading title template \
2145 of the heading kind contains `#{number}`. This element cannot be written in a \
2146 document; the lowering rule of the heading inserts it.",
2147 ),
2148 )?;
2149 b.element_type_text(
2150 HEADING,
2151 "A heading that starts a part of the document, such as a section or a subsection. \
2152 A heading has the level of its heading kind, and it can be numbered.",
2153 )?;
2154 b.element_type_text(
2155 title::NUMBER_ELEMENT,
2156 "The number of a heading, placed in its title where the heading title template of \
2157 the heading kind contains `#{number}`.",
2158 )?;
2159 b.lowering_rule(
2160 LoweringRule::new(
2161 title::NUMBER_RULE,
2162 title::NUMBER_ELEMENT,
2163 LoweringDecl::new().produces(pres::SPAN),
2164 Arc::new(NumberRule),
2165 DefaultMark::Everywhere,
2166 )
2167 .docs(
2168 "the number of a heading lowers to a `flm.pres.span` node with the role \
2169 `flm.heading.number` that contains the number",
2170 ),
2171 )?;
2172 // Every kind's title number format is compiled once the language is
2173 // built, and the heading rule reads the compiled templates.
2174 let titles = Arc::new(Titles::new(
2175 self.config
2176 .headings
2177 .iter()
2178 .map(|kind| (kind.name.clone(), kind.title_number_format.clone()))
2179 .collect(),
2180 number_element,
2181 ));
2182 b.late_init(Arc::new(CompileTitles { titles: Arc::clone(&titles) }))?;
2183 // The decoration and the run-in title inside it are produced only
2184 // where a kind is set run in, since a registry in which none can occur
2185 // must not demand that its backend render them.
2186 let mut decl = LoweringDecl::new()
2187 .reads_opt(ANCHORS)
2188 .reads_opt(COUNTERS)
2189 .produces(pres::BLOCK_HEADING);
2190 if self.config.headings.iter().any(|kind| kind.run_in) {
2191 decl = decl.produces(pres::DECO_RUNIN).produces(pres::RUNIN_HEADING);
2192 }
2193 b.lowering_rule(
2194 LoweringRule::new(
2195 RULE,
2196 HEADING,
2197 decl,
2198 Arc::new(HeadingRule { titles }),
2199 DefaultMark::Everywhere,
2200 )
2201 .docs(
2202 "a heading lowers to a `flm.pres.block-heading` node that contains the number of \
2203 the heading, if the heading is numbered, followed by the title; a run-in \
2204 heading lowers to a `flm.pres.deco.runin` decoration that contains a \
2205 `flm.pres.runin-heading` node with the same content",
2206 ),
2207 )?;
2208 b.style_def(stylesheet())?;
2209 b.digest_input(&self.config.digest_bytes())?;
2210 latex::register(b)?;
2211 latex_rendered::register(b)?;
2212 Ok(())
2213 }
2214}
2215
2216/// Returns the [`Headings`] feature with the default configuration
2217/// ([`HeadingsConfig::new`]), for the list of features of a package entry.
2218///
2219/// To use a [`HeadingsConfig`] of your own, list
2220/// `Arc::new(Headings::new(config))` in place of this feature.
2221pub fn feature() -> Arc<dyn FlmFeature> {
2222 Arc::new(Headings::default())
2223}
2224
2225/// In settings data, a heading kind is an entry of the map
2226/// [`HeadingsConfig::headings`], with the name of the heading kind as its key.
2227/// The entry must contain the field `level`. The other fields are optional; a
2228/// field that is left out has the value set by [`HeadingDecl::new`].
2229impl named::NamedEntry for HeadingDecl {
2230 fn read_entry(name: &str, data: serde_json::Value) -> Result<HeadingDecl, String> {
2231 let level = named::required(name, &data, "level")?;
2232 let mut kind: HeadingDecl = named::read_over(&HeadingDecl::new(name, level), "name", name, data)?;
2233 // The text read from data goes through the builder, as a text given in
2234 // Rust does, so that the cargo feature `docs` decides for both.
2235 let docs = std::mem::take(&mut kind.docs);
2236 Ok(kind.docs(docs))
2237 }
2238}
2239
2240/// In settings data, a heading command is an entry of the map
2241/// [`HeadingsConfig::commands`], with the name of the command as its key.
2242impl named::NamedEntry for HeadingCommand {
2243 fn read_entry(name: &str, data: serde_json::Value) -> Result<HeadingCommand, String> {
2244 named::read_with_name("name", name, data)
2245 }
2246}
2247
2248#[cfg(test)]
2249mod tests {
2250 use super::*;
2251
2252 #[test]
2253 fn a_heading_value_is_a_block_carrying_its_declaration_and_aspects() {
2254 let config = HeadingsConfig::new();
2255 let kind = config.heading("subsection").expect("declared");
2256 let element = element(kind, config.commands_of("subsection").cloned().collect(), true);
2257 assert_eq!(element.name, HEADING);
2258 let value = element.value_as::<HeadingElement>().expect("valued");
2259 assert_eq!(value.decl.level, 2);
2260 assert!(value.numbered);
2261 assert_eq!(value.commands.len(), 1);
2262 assert!(element.has_aspect::<dyn Sectioning>());
2263 assert!(element.has_aspect::<dyn Referenceable>());
2264 }
2265
2266 #[test]
2267 fn a_run_in_kind_is_a_leading_decorator_and_every_other_kind_a_block() {
2268 let config = HeadingsConfig::new().run_in_levels([4]);
2269 let role = |name: &str| block_role(config.heading(name).expect("declared"));
2270 assert_eq!(role("paragraph"), BlockRole::BlockDecorator(Placement::Leads));
2271 assert_eq!(role("subsubsection"), BlockRole::Block);
2272 let shipped = HeadingsConfig::new();
2273 assert_eq!(block_role(shipped.heading("paragraph").expect("declared")), BlockRole::Block);
2274 }
2275
2276 #[test]
2277 fn the_digest_bytes_change_with_every_field_but_the_documentation_texts() {
2278 let bytes = |config: &HeadingsConfig| config.digest_bytes();
2279 let shipped = bytes(&HeadingsConfig::new());
2280 assert_eq!(shipped, bytes(&HeadingsConfig::new()));
2281 assert_ne!(shipped, bytes(&HeadingsConfig::new().run_in_levels([4])));
2282 let edit = |f: fn(HeadingDecl) -> HeadingDecl| {
2283 let mut config = HeadingsConfig::new();
2284 config.headings[0] = f(config.headings[0].clone());
2285 bytes(&config)
2286 };
2287 for changed in [
2288 edit(|kind| HeadingDecl { level: 7, ..kind }),
2289 edit(|kind| kind.counter("other")),
2290 edit(|kind| kind.no_counter()),
2291 edit(|kind| kind.style("other.style")),
2292 edit(|kind| kind.within(Within::parent("part"))),
2293 edit(|kind| kind.within(Within::parents(["part"]))),
2294 edit(|kind| kind.within(Within::parent_set("part"))),
2295 edit(|kind| kind.within(Within::parent("part").no_restart())),
2296 edit(|kind| kind.number_format(NumberTemplate::initial("1"))),
2297 edit(|kind| kind.title_number_format("#{number} ")),
2298 edit(|kind| kind.skip_toc(true)),
2299 edit(|kind| kind.run_in(true)),
2300 edit(|kind| kind.ref_kind("chapter")),
2301 edit(|kind| kind.label_types(["sec"])),
2302 edit(|kind| kind.anchor_prefix("s")),
2303 ] {
2304 assert_ne!(shipped, changed);
2305 }
2306 // A kind's documentation text is left out.
2307 assert_eq!(shipped, edit(|kind| HeadingDecl { docs: String::from("Other."), ..kind }));
2308 let with_default =
2309 HeadingsConfig::new().command(HeadingCommand::new("q", "section").default_value("toc", "false"));
2310 let with_other_default =
2311 HeadingsConfig::new().command(HeadingCommand::new("q", "section").default_value("toc", "true"));
2312 assert_ne!(bytes(&with_default), bytes(&with_other_default));
2313 let depths = [
2314 HeadingNumbering::NothingNumbered,
2315 HeadingNumbering::AllNumbered,
2316 HeadingNumbering::UpToDepth(1),
2317 HeadingNumbering::UpToDepth(2),
2318 ];
2319 for (index, depth) in depths.iter().enumerate() {
2320 for other in &depths[index + 1..] {
2321 assert_ne!(
2322 bytes(&HeadingsConfig::new().numbering(*depth)),
2323 bytes(&HeadingsConfig::new().numbering(*other))
2324 );
2325 }
2326 }
2327 }
2328
2329 #[test]
2330 fn the_depth_numbers_the_kinds_with_a_counter_it_admits() {
2331 let config = HeadingsConfig::new();
2332 let numbered = |config: &HeadingsConfig| {
2333 config
2334 .headings
2335 .iter()
2336 .filter(|kind| config.numbers(kind))
2337 .map(|kind| kind.name.to_string())
2338 .collect::<Vec<_>>()
2339 };
2340 assert!(numbered(&config).is_empty());
2341 assert_eq!(numbered(&config.clone().numbering(HeadingNumbering::UpToDepth(2))), ["section", "subsection"]);
2342 assert_eq!(numbered(&config.clone().numbering(HeadingNumbering::AllNumbered)).len(), 5);
2343 // A kind with no counter is never numbered, whatever the depth.
2344 let mut kinds = config.headings.clone();
2345 kinds.push(HeadingDecl::new("aside", 1).no_counter());
2346 let with_aside = config.headings(kinds).numbering(HeadingNumbering::AllNumbered);
2347 assert!(!with_aside.numbers(with_aside.heading("aside").expect("declared")));
2348 // Replacing the kinds keeps the depth.
2349 assert_eq!(with_aside.numbering, HeadingNumbering::AllNumbered);
2350 }
2351
2352 #[test]
2353 fn the_shipped_kinds_run_from_section_to_subparagraph() {
2354 let config = HeadingsConfig::new();
2355 let kinds: Vec<(&str, u8)> =
2356 config.headings.iter().map(|kind| (kind.name.as_str(), kind.level)).collect();
2357 assert_eq!(
2358 kinds,
2359 [
2360 ("section", 1),
2361 ("subsection", 2),
2362 ("subsubsection", 3),
2363 ("paragraph", 4),
2364 ("subparagraph", 5)
2365 ]
2366 );
2367 let commands: Vec<&str> =
2368 config.commands.iter().map(|command| command.name.as_str()).collect();
2369 assert_eq!(commands, ["section", "subsection", "subsubsection", "paragraph", "subparagraph"]);
2370 assert!(config.commands.iter().all(|command| command.defaults.is_empty()));
2371 assert_eq!(config.validate(), Ok(()));
2372 }
2373
2374 #[test]
2375 fn a_configuration_that_clashes_is_refused() {
2376 let refused = |config: HeadingsConfig| config.validate().is_err();
2377 assert!(refused(HeadingsConfig::new().command(HeadingCommand::new("x", "nokind"))));
2378 let mut kinds = HeadingsConfig::new().headings;
2379 kinds.push(HeadingDecl::new("section", 1));
2380 assert!(refused(HeadingsConfig::new().headings(kinds)));
2381 let twice = HeadingsConfig::new().command(HeadingCommand::new("section", "section"));
2382 assert!(refused(twice));
2383 let mut kinds = HeadingsConfig::new().headings;
2384 kinds.push(HeadingDecl::new("appendix", 1).counter("flm.headings.section"));
2385 assert!(refused(HeadingsConfig::new().headings(kinds)));
2386 let mut kinds = HeadingsConfig::new().headings;
2387 kinds.push(HeadingDecl::new("appendix", 1).style("flm.headings.style.section"));
2388 assert!(refused(HeadingsConfig::new().headings(kinds)));
2389 let bad_default = HeadingsConfig::new()
2390 .command(HeadingCommand::new("q", "section").default_value("alt", "x"));
2391 assert!(refused(bad_default));
2392 let bad_value = HeadingsConfig::new()
2393 .command(HeadingCommand::new("q", "section").default_value("toc", "maybe"));
2394 assert!(refused(bad_value));
2395 let mut kinds = HeadingsConfig::new().headings;
2396 kinds.push(HeadingDecl::new("part", 0));
2397 let part = HeadingsConfig::new().headings(kinds);
2398 assert_eq!(part.validate(), Ok(()), "a kind of level 0 is accepted");
2399 let mut kinds = HeadingsConfig::new().headings;
2400 kinds.push(HeadingDecl::new("orphan", 2));
2401 let commands = HeadingsConfig::new().commands;
2402 let orphan = HeadingsConfig::new().headings(kinds).commands(commands);
2403 assert_eq!(orphan.validate(), Ok(()), "a kind no command writes is accepted");
2404 }
2405}