Skip to main content

flm_core/stdlib/features/numbering/
options.rs

1//! The numbering options of a document ([`NumberingOptions`]): per counter,
2//! the counter within which it is numbered, and the value it has before it is
3//! first advanced.
4//!
5//! The options are an option type of the numbering feature, bound on the
6//! document; a render request may set them again
7//! ([`Bind::Either`](crate::model::options::Bind::Either)). The numbering
8//! stage applies them at the start of every run, before it reads any
9//! reference point.
10
11use std::collections::BTreeMap;
12
13use crate::model::names::Name;
14
15use super::decl::Within;
16
17/// The place in the hierarchy of counters that a document's numbering options
18/// give a counter, replacing the place the declaring feature gave it.
19///
20/// The place decides two things: what restarts the counter, and what is
21/// written before its number.
22#[derive(Clone, PartialEq, Eq, Hash, Debug, serde::Deserialize)]
23#[derive(schemars::JsonSchema)]
24#[serde(rename_all = "kebab-case")]
25pub enum WithinOption {
26    /// Numbered within nothing: nothing restarts the counter, and no other
27    /// counter's number is written before its number.
28    ///
29    /// A document uses it to take a counter out of a hierarchy it does not
30    /// want. For example, a document whose subsections come before any
31    /// section, or whose sections are never advanced, numbers its subsections
32    /// within nothing, or gives the sections an
33    /// [`initial`](CounterOptions::initial) value.
34    Nothing,
35    /// Numbered within the counters this [`Within`] gives, with the numbers
36    /// written by its within-joiner.
37    Counter(Within),
38}
39
40/// What a document's numbering options say about one counter: the counter
41/// within which it is numbered, and the value it has before it is first
42/// advanced. A field left `None` keeps what the counter was declared with.
43#[derive(Clone, PartialEq, Eq, Hash, Debug, Default, serde::Deserialize)]
44#[derive(schemars::JsonSchema)]
45#[serde(default, deny_unknown_fields)]
46pub struct CounterOptions {
47    /// The counter's place in the hierarchy of counters. `None` keeps the
48    /// place its declaration gives.
49    pub within: Option<WithinOption>,
50    /// The value the counter has before it is first advanced, or `None` for a
51    /// counter that has no value until then.
52    ///
53    /// A counter with no value cannot be written, so a reference point
54    /// numbered within it takes no number and is reported as the Error
55    /// `flm.numbering.parent-uninitialized`. `Some(0)` gives the counter the
56    /// value `0`, so that a subsection written before any section is numbered
57    /// `0.1`. The counter is then advanced from that value: `Some(3)` makes
58    /// the first section `4`. The value applies under every combination of
59    /// the values of the counter's ancestors: an initial `0` for
60    /// `flm.headings.subsection` makes a subsubsection written in a section
61    /// that has no subsection yet read as though the subsection had the value
62    /// 0, `1.0.1`. When the parent that applies is chosen among several, the
63    /// counters with initial values count as advanced before the document
64    /// begins, the outermost counter first.
65    pub initial: Option<u32>,
66}
67
68impl CounterOptions {
69    /// Returns options that change nothing.
70    pub fn new() -> CounterOptions {
71        CounterOptions::default()
72    }
73
74    /// Builder: numbers the counter within the counters `within` gives, in
75    /// place of what it was declared with.
76    ///
77    /// The counters that `within` gives must be declared by some feature; a
78    /// counter in `within` that no feature declares is reported as a Warning
79    /// and the option changes nothing. The reports and their effects are
80    /// listed under [`NumberingOptions`].
81    pub fn within(mut self, within: Within) -> CounterOptions {
82        self.within = Some(WithinOption::Counter(within));
83        self
84    }
85
86    /// Builder: numbers the counter within nothing, so that it is never
87    /// restarted and no other counter's number is written before its own.
88    pub fn within_nothing(mut self) -> CounterOptions {
89        self.within = Some(WithinOption::Nothing);
90        self
91    }
92
93    /// Builder: gives the counter the value `value` before it is first
94    /// advanced (see [`initial`](CounterOptions::initial)).
95    pub fn initial(mut self, value: u32) -> CounterOptions {
96        self.initial = Some(value);
97        self
98    }
99}
100
101/// The numbering options of a document: per counter, the counter within which
102/// it is numbered, and the value it has before it is first advanced.
103///
104/// These are the per-document option values of the numbering feature: an
105/// option type bound on the document, which a render request may set again,
106/// its value then replacing the document's for that render
107/// ([`Bind::Either`](crate::model::options::Bind::Either)). In data, they are
108/// the settings key `counters` of the numbering feature, a map from a
109/// counter's name to its [`CounterOptions`].
110///
111/// Whether a reference point is numbered at all is not an option of this
112/// feature: a point whose number source gives a counter is numbered, and the
113/// feature that owns the point decides whether it gives one (for example the
114/// numbering depth of the headings feature, fixed when the registry is built).
115///
116/// A counter that the options do not mention keeps what its declaring feature
117/// said. The numbering stage reports, once per run, every entry it cannot
118/// apply, and applies the others:
119///
120/// - an entry for a counter no feature declares is a Warning
121///   (`flm.numbering.unknown-counter`) and changes nothing; an entry that
122///   numbers a counter within a counter no feature declares is the same
123///   Warning, and its `within` changes nothing (its `initial` still applies);
124/// - an entry that numbers a counter within a parent set no feature registers
125///   (`flm.numbering.unknown-parent-set`), within no counter at all (an empty
126///   list of parents, or a parent set that holds no counter;
127///   `flm.numbering.bad-within-joiner`), or through a within-joiner that does
128///   not compile (`flm.numbering.bad-within-joiner`) or that no feature
129///   registers (`flm.numbering.unknown-within-joiner`), is an Error, and its
130///   `within` changes nothing (its `initial` still applies);
131/// - an entry whose within-joiner writes a counter that, under the options,
132///   is not always one of the counters the counter is numbered within is an
133///   Error (`flm.numbering.not-an-ancestor`), and the counter keeps the place
134///   it was declared with;
135/// - an entry that moves a counter's ancestors so that the declared
136///   within-joiner or nesting joiner of a counter writes a counter it is no
137///   longer always numbered within is an Error
138///   (`flm.numbering.not-an-ancestor`), and no point counting in that counter
139///   is numbered in that run;
140/// - entries that make counters numbered within each other are an Error
141///   (`flm.numbering.hierarchy-cycle`), and no point counting in those
142///   counters is numbered in that run.
143///
144/// # Examples
145///
146/// ```
147/// use flm_core::stdlib::features::numbering::{NumberingOptions, Within};
148///
149/// let options = NumberingOptions::new()
150///     .initial("flm.headings.section", 0)
151///     .within("flm.math.equation", Within::parent("flm.headings.section"));
152/// assert_eq!(options.of("flm.headings.section").and_then(|entry| entry.initial), Some(0));
153/// assert!(options.of("example.figure").is_none());
154/// ```
155#[derive(Clone, PartialEq, Eq, Hash, Debug, Default, serde::Deserialize)]
156#[derive(schemars::JsonSchema)]
157#[serde(default, deny_unknown_fields)]
158pub struct NumberingOptions {
159    /// What the document says about each counter it mentions, in name order.
160    pub counters: BTreeMap<Name, CounterOptions>,
161}
162
163impl NumberingOptions {
164    /// Returns options that say nothing about any counter.
165    pub fn new() -> NumberingOptions {
166        NumberingOptions::default()
167    }
168
169    /// Returns what these options say about `counter`, or `None` when they say
170    /// nothing about it.
171    pub fn of(&self, counter: &str) -> Option<&CounterOptions> {
172        self.counters.get(&Name::new(counter))
173    }
174
175    /// Builder: replaces what the options say about `counter` by `entry`.
176    pub fn counter(mut self, counter: impl Into<Name>, entry: CounterOptions) -> NumberingOptions {
177        self.counters.insert(counter.into(), entry);
178        self
179    }
180
181    /// Builder: numbers `counter` within the counters `within` gives, keeping
182    /// the rest of what the options say about `counter`.
183    ///
184    /// The counters that `within` gives must be declared by some feature; a
185    /// counter in `within` that no feature declares is reported as a Warning
186    /// and the option changes nothing. The reports and their effects are
187    /// listed under [`NumberingOptions`].
188    pub fn within(mut self, counter: impl Into<Name>, within: Within) -> NumberingOptions {
189        self.counters.entry(counter.into()).or_default().within =
190            Some(WithinOption::Counter(within));
191        self
192    }
193
194    /// Builder: numbers `counter` within nothing, keeping the rest of what the
195    /// options say about `counter`.
196    pub fn within_nothing(mut self, counter: impl Into<Name>) -> NumberingOptions {
197        self.counters.entry(counter.into()).or_default().within = Some(WithinOption::Nothing);
198        self
199    }
200
201    /// Builder: gives `counter` the value `value` before it is first advanced,
202    /// keeping the rest of what the options say about `counter` (see
203    /// [`CounterOptions::initial`]).
204    pub fn initial(mut self, counter: impl Into<Name>, value: u32) -> NumberingOptions {
205        self.counters.entry(counter.into()).or_default().initial = Some(value);
206        self
207    }
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213
214    #[test]
215    fn the_builders_write_into_one_entry_per_counter() {
216        let options = NumberingOptions::new()
217            .initial("section", 0)
218            .within("section", Within::parent("chapter"));
219        assert_eq!(options.counters.len(), 1);
220        let entry = options.of("section").expect("set");
221        assert_eq!(entry.initial, Some(0));
222        assert!(matches!(entry.within, Some(WithinOption::Counter(_))));
223    }
224
225    #[test]
226    fn a_counter_the_document_says_nothing_about_has_no_entry() {
227        assert!(NumberingOptions::new().of("equation").is_none());
228    }
229}