Skip to main content

flm_core/stdlib/features/citations/
config.rs

1//! The configuration of the `citations` feature ([`CitationsConfig`]): where
2//! the citation entries are shown, the form of a citation mark, the citation
3//! counter style, the heading of the list of cited works, and the text written
4//! before a note.
5//!
6//! The doc comments of the configuration's types and fields are also the
7//! descriptions of the feature's settings in the settings schema.
8
9use std::hash::{Hash, Hasher};
10
11use serde::Deserialize;
12
13use crate::core::settings::named;
14
15use crate::stdlib::features::numbering::{
16    digest_style, CounterStyleDecl, Delimiters, JoinDecl, PluralWords, PrefixWords,
17};
18
19/// The name of the citation counter style, `flm.citations.style.citation`
20/// ([`default_style`]). The citation counter style is the feature's own counter
21/// style; a configuration read from settings data keeps this name.
22pub const STYLE_NAME: &str = "flm.citations.style.citation";
23
24/// The name of the citation counter style's variant of words that the flag `S` of
25/// `\R` selects, `capital`: `Ref.~` and `Refs.~` rather than `ref.~` and
26/// `refs.~`.
27///
28/// The `refs` feature gives the same name to its capitalized variant
29/// ([`refs::CAPITAL_VARIANT`](crate::stdlib::features::refs::CAPITAL_VARIANT)),
30/// so one counter style can serve both features.
31pub const CAPITAL_VARIANT: &str = "capital";
32
33/// Where the citation entries of the cited works are shown. In settings data,
34/// `listed` or `in-place`.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Deserialize)]
36#[derive(schemars::JsonSchema)]
37#[serde(rename_all = "kebab-case")]
38pub enum CitationPlacement {
39    /// Listed after the content, under a heading, one citation entry per cited
40    /// work in the order of the numbers; a citation mark shows the numbers of
41    /// its works, as its form ([`MarkForm`]) says. The default.
42    #[default]
43    Listed,
44    /// In place: a citation mark shows the citation entries themselves, one
45    /// group per item between the citation counter style's delimiters (`[Knuth,
46    /// 1984][Lamport, 1994; Thm 4]`), and no list is placed. The form of a
47    /// citation mark has no effect.
48    InPlace,
49}
50
51impl CitationPlacement {
52    /// Returns the byte the placement writes into the registry digest.
53    fn digest_byte(self) -> u8 {
54        match self {
55            CitationPlacement::Listed => 0,
56            CitationPlacement::InPlace => 1,
57        }
58    }
59}
60
61/// How a citation mark shows the numbers of the works its citation chunk
62/// cites, where the citation entries are listed after the content
63/// ([`CitationPlacement::Listed`]); it has no effect under the in-place
64/// placement. In settings data, `bracketed` or `superscript`.
65///
66/// The form decides the delimiters wherever numbers are shown. Under the
67/// bracketed form, a citation mark and an entry's label in the list of cited
68/// works carry the citation counter style's delimiters; under the superscript
69/// form they carry none.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Deserialize, serde::Serialize)]
71#[derive(schemars::JsonSchema)]
72#[serde(rename_all = "kebab-case")]
73pub enum MarkForm {
74    /// The numbers inline, between the citation counter style's delimiters:
75    /// `text [1,3–5]`, with a no-break space written before the citation mark
76    /// of a `\cite`. The default.
77    #[default]
78    Bracketed,
79    /// The numbers raised, with no delimiters: `text¹˒³⁻⁵`, with nothing
80    /// written before the citation mark of a `\cite`. A citation written with
81    /// `\R` is never raised: its numbers are shown inline, with no delimiters
82    /// (`refs.~1,2`).
83    Superscript,
84}
85
86impl MarkForm {
87    /// Returns the byte the form writes into the registry digest.
88    fn digest_byte(self) -> u8 {
89        match self {
90            MarkForm::Bracketed => 0,
91            MarkForm::Superscript => 1,
92        }
93    }
94}
95
96/// The configuration of the `citations` feature: where the citation entries are
97/// shown, the form of a citation mark, the citation counter style, the heading
98/// of the list of cited works, and the text between the numbers and a note.
99///
100/// It is the plain Rust value the feature is constructed from
101/// ([`Citations::new`](super::Citations::new)), fixed when the registry is
102/// built ([configuration](crate::guide::concepts_overview#settings-options-and-configuration)).
103/// It enters the [registry digest](crate::model::digest)
104/// ([`digest_bytes`](CitationsConfig::digest_bytes)), and its texts are
105/// compiled when the registry is built: a text that is not valid FLM fails
106/// the build with a message that identifies the text. The standard features
107/// take it as
108/// [`StdlibConfig::citations`](crate::stdlib::StdlibConfig::citations).
109///
110/// The citation counter style is the feature's own: the counter styles a host
111/// sets in the numbering feature's configuration
112/// ([`NumberingConfig::styles`](crate::stdlib::features::numbering::NumberingConfig::styles))
113/// do not replace it, and a host changes it here.
114///
115/// # Examples
116///
117/// ```
118/// use flm_core::stdlib::features::citations::{CitationsConfig, MarkForm};
119/// use flm_core::stdlib::features::numbering::Delimiters;
120///
121/// let mut config = CitationsConfig::new().mark(MarkForm::Superscript);
122/// config.style.delimiters = Delimiters::new("(", ")");
123/// assert_eq!(config.note_separator, "; ");
124/// assert!(config.style.ranges);
125/// assert_eq!(config.heading_title.as_deref(), Some("References"));
126///
127/// // The list with no heading above it.
128/// assert_eq!(CitationsConfig::new().without_heading().heading_title, None);
129/// ```
130#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
131#[derive(schemars::JsonSchema)]
132#[serde(default, deny_unknown_fields)]
133pub struct CitationsConfig {
134    /// Where the citation entries are shown: listed after the content, the
135    /// default, or in the citation marks in place of the numbers
136    /// ([`CitationPlacement`]).
137    pub placement: CitationPlacement,
138    /// How a citation mark shows its numbers under the listed placement, and
139    /// how the list of cited works labels its entries: [`MarkForm::Bracketed`]
140    /// by default. It has no effect under [`CitationPlacement::InPlace`].
141    pub mark: MarkForm,
142    /// The citation counter style, a counter style
143    /// ([`CounterStyleDecl`]): how a number is written, the delimiters, the
144    /// texts joining several numbers, whether consecutive numbers make a
145    /// range, and the words `\R` writes before a citation mark. By default
146    /// ([`default_style`]): arabic numbers, `[` and `]`, the compact join,
147    /// ranges on, the words `ref.~` and `refs.~`, and the variant `capital`
148    /// with the words `Ref.~` and `Refs.~`.
149    ///
150    /// In settings data, the fields written replace those of the default
151    /// citation counter style, and the name is not written: it is always
152    /// [`STYLE_NAME`].
153    #[serde(deserialize_with = "read_style")]
154    pub style: CounterStyleDecl,
155    /// The title of the heading above the list of cited works, as FLM text:
156    /// `References` by default; `None` for a list with no heading above it
157    /// ([`without_heading`](CitationsConfig::without_heading)).
158    pub heading_title: Option<String>,
159    /// The level of the heading above the list of cited works, counted from
160    /// zero like every heading level; 2 by default, the level of the heading
161    /// above a list of footnotes. The feature passes it to the heading
162    /// unchanged, and accepts every value. It has no effect on a list with no
163    /// heading.
164    pub heading_level: u8,
165    /// The text written between a group's numbers and its note, as FLM text:
166    /// `; ` by default, as in `[1; Thm 4]`.
167    pub note_separator: String,
168}
169
170/// Returns the default citation counter style, named [`STYLE_NAME`]: arabic
171/// numbers, the delimiters `[` and `]`, the compact join (`1,2` and `1–3,5`),
172/// ranges on, and the words `ref.~` and `refs.~`, with the variant
173/// [`CAPITAL_VARIANT`] holding `Ref.~` and `Refs.~`.
174pub fn default_style() -> CounterStyleDecl {
175    let mut style = CounterStyleDecl::new(STYLE_NAME);
176    style.delimiters = Delimiters::new("[", "]");
177    style.join = JoinDecl::compact();
178    style.prefix_words = PrefixWords::new("ref.~", "refs.~")
179        .with_variant(CAPITAL_VARIANT, PluralWords::new("Ref.~", "Refs.~"));
180    style
181}
182
183/// Reads the citation counter style from settings data over [`default_style`],
184/// keeping its name; refuses a map that writes `name`.
185fn read_style<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<CounterStyleDecl, D::Error> {
186    use serde::de::Error;
187    let written = match serde_json::Value::deserialize(deserializer)? {
188        serde_json::Value::Object(written) => written,
189        other => return Err(D::Error::custom(format!(
190            "the option `style` of the feature `citations` must be a map, not `{other}`"
191        ))),
192    };
193    if written.contains_key("name") {
194        return Err(D::Error::custom(
195            "the option `style` of the feature `citations` may not set `name`",
196        ));
197    }
198    named::read_fields_over(&default_style(), written).map_err(D::Error::custom)
199}
200
201impl Default for CitationsConfig {
202    fn default() -> CitationsConfig {
203        CitationsConfig {
204            placement: CitationPlacement::default(),
205            mark: MarkForm::default(),
206            style: default_style(),
207            heading_title: Some("References".to_string()),
208            heading_level: 2,
209            note_separator: "; ".to_string(),
210        }
211    }
212}
213
214impl CitationsConfig {
215    /// Returns the default configuration: the citation entries listed, the
216    /// bracketed form, the default citation counter style ([`default_style`]), the
217    /// title `References` at level 2, and `; ` before a note.
218    pub fn new() -> CitationsConfig {
219        CitationsConfig::default()
220    }
221
222    /// Builder: sets [`placement`](CitationsConfig::placement).
223    pub fn placement(mut self, placement: CitationPlacement) -> CitationsConfig {
224        self.placement = placement;
225        self
226    }
227
228    /// Builder: sets [`mark`](CitationsConfig::mark).
229    pub fn mark(mut self, mark: MarkForm) -> CitationsConfig {
230        self.mark = mark;
231        self
232    }
233
234    /// Builder: sets [`style`](CitationsConfig::style), the citation counter style.
235    /// The name of `style` is used as given.
236    pub fn style(mut self, style: CounterStyleDecl) -> CitationsConfig {
237        self.style = style;
238        self
239    }
240
241    /// Builder: sets [`heading_title`](CitationsConfig::heading_title), the
242    /// title of the heading above the list of cited works.
243    pub fn heading_title(mut self, title: impl Into<String>) -> CitationsConfig {
244        self.heading_title = Some(title.into());
245        self
246    }
247
248    /// Builder: no heading above the list of the cited works.
249    pub fn without_heading(mut self) -> CitationsConfig {
250        self.heading_title = None;
251        self
252    }
253
254    /// Builder: sets [`heading_level`](CitationsConfig::heading_level).
255    pub fn heading_level(mut self, level: u8) -> CitationsConfig {
256        self.heading_level = level;
257        self
258    }
259
260    /// Builder: sets [`note_separator`](CitationsConfig::note_separator).
261    pub fn note_separator(mut self, separator: impl Into<String>) -> CitationsConfig {
262        self.note_separator = separator.into();
263        self
264    }
265
266    /// Returns the bytes the feature gives to the registry digest
267    /// ([`FeatureBuilder::digest_input`](crate::core::registry::FeatureBuilder::digest_input)):
268    /// the placement, the form, every field of the citation counter style as the
269    /// numbering feature writes a counter style's, whether the list has a
270    /// heading and its title, the note separator and the heading's level, each
271    /// text preceded by its length.
272    pub fn digest_bytes(&self) -> Vec<u8> {
273        // Taken apart by name, so a field added and not written here fails
274        // to compile.
275        let CitationsConfig { placement, mark, style, heading_title, heading_level, note_separator } = self;
276        let mut out = vec![placement.digest_byte(), mark.digest_byte()];
277        digest_style(&mut out, style);
278        let text = |out: &mut Vec<u8>, text: &String| {
279            out.extend_from_slice(&(text.len() as u64).to_le_bytes());
280            out.extend_from_slice(text.as_bytes());
281        };
282        match heading_title {
283            Some(title) => {
284                out.push(1);
285                text(&mut out, title);
286            }
287            None => out.push(0),
288        }
289        text(&mut out, note_separator);
290        out.push(*heading_level);
291        out
292    }
293}
294
295impl Hash for CitationsConfig {
296    fn hash<H: Hasher>(&self, state: &mut H) {
297        state.write(&self.digest_bytes());
298    }
299}