Skip to main content

flm_core/stdlib/features/floats/
config.rs

1//! The configuration of the [`floats`](super) feature: the float types
2//! ([`FloatType`]), collected in a [`FloatsConfig`], each with its numbering
3//! policy ([`FloatNumbering`]), its caption name (written before its number
4//! in the line under its content), its number format, the words a reference
5//! writes before its number, the content handlers it accepts, the scoped
6//! packages available in its body and the label types it accepts.
7//!
8//! A feature's configuration is the plain Rust value the feature is
9//! constructed from; it is fixed when the registry is built and cannot vary
10//! per document or per render ([settings, options and
11//! configuration](crate::guide::concepts_overview#settings-options-and-configuration)).
12//!
13//! The module also holds the names by which the two shipped float types refer
14//! to the `graphics` and `cells` features: [`INCLUDEGRAPHICS_PACKAGE`],
15//! [`INCLUDEGRAPHICS_HANDLER`], [`CELLS_PACKAGE`] and [`CELLS_HANDLER`]. The
16//! `floats` feature does not depend on those features: a name that no
17//! registered feature declares has no effect.
18
19use std::hash::{Hash, Hasher};
20
21use crate::core::settings::named::{self, NamedEntry};
22use crate::model::names::Name;
23use crate::stdlib::features::numbering::{NumberTemplate, PluralWords, PrefixWords};
24use crate::stdlib::features::refs::CAPITAL_VARIANT;
25
26use super::{ANY_HANDLER, RESERVED_KINDS};
27
28/// The name of the scoped package holding `\includegraphics`,
29/// `flm.graphics.includegraphics`, which the `graphics` feature declares. The
30/// shipped types [`FloatType::figure`] and [`FloatType::table`] list it among
31/// their [`scoped_packages`](FloatType::scoped_packages), so that
32/// `\includegraphics` can be written in their bodies.
33pub const INCLUDEGRAPHICS_PACKAGE: &str = "flm.graphics.includegraphics";
34
35/// The name of the content handler that accepts exactly one image,
36/// `includegraphics`, which the `graphics` feature contributes. The shipped
37/// types [`FloatType::figure`] and [`FloatType::table`] list it among their
38/// [`handlers`](FloatType::handlers).
39pub const INCLUDEGRAPHICS_HANDLER: &str = "includegraphics";
40
41/// The name of the scoped package holding the `cells` environment,
42/// `flm.cells.environment`, which the `cells` feature declares. The shipped
43/// type [`FloatType::table`] lists it among its
44/// [`scoped_packages`](FloatType::scoped_packages), so that a table of cells
45/// can be written in its body.
46pub const CELLS_PACKAGE: &str = "flm.cells.environment";
47
48/// The name of the content handler that accepts exactly one table of cells,
49/// `cells`, which the `cells` feature contributes. The shipped type
50/// [`FloatType::table`] lists it among its [`handlers`](FloatType::handlers).
51pub const CELLS_HANDLER: &str = "cells";
52
53/// The **numbering policy** of a float type: when the floats of the type are
54/// numbered.
55///
56/// A float is numbered in its type's counter or not at all. The policy and the
57/// float's own `\label` and `\nonumber` decide which
58/// ([`numbers`](FloatNumbering::numbers)); where the numbering feature is not
59/// registered, a float that the policy numbers is reported
60/// ([`NoNumbering`](super::NoNumbering)) and shown without a number, except on
61/// the recomposed LaTeX, where LaTeX numbers it. In settings, the policy is written
62/// `numbered`, `unnumbered` or `auto-numbered`.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Deserialize, serde::Serialize)]
64#[derive(schemars::JsonSchema)]
65#[serde(rename_all = "kebab-case")]
66pub enum FloatNumbering {
67    /// Every float of the type is numbered, unless it carries `\nonumber`, as
68    /// a displayed equation is.
69    Numbered,
70    /// No float of the type is numbered, regardless of its `\label` and
71    /// `\nonumber`; a `\nonumber` in one changes nothing and is reported
72    /// with a Note.
73    Unnumbered,
74    /// A float of the type is numbered when it carries a `\label` and no
75    /// `\nonumber`; a `\nonumber` in a float with no `\label` changes nothing
76    /// and is reported with a Note. The default.
77    #[default]
78    AutoNumbered,
79}
80
81impl FloatNumbering {
82    /// Returns the policy's stable name, as settings write it: `numbered`,
83    /// `unnumbered` or `auto-numbered`.
84    pub fn as_str(self) -> &'static str {
85        match self {
86            FloatNumbering::Numbered => "numbered",
87            FloatNumbering::Unnumbered => "unnumbered",
88            FloatNumbering::AutoNumbered => "auto-numbered",
89        }
90    }
91
92    /// Returns whether a float under this policy is numbered, given whether it
93    /// carries a `\label` (`labeled`) and whether it carries a `\nonumber`
94    /// (`nonumber`).
95    pub fn numbers(self, labeled: bool, nonumber: bool) -> bool {
96        match self {
97            FloatNumbering::Numbered => !nonumber,
98            FloatNumbering::Unnumbered => false,
99            FloatNumbering::AutoNumbered => labeled && !nonumber,
100        }
101    }
102}
103
104/// One **float type**: one environment an author writes, such as `figure`,
105/// `table`, or a `diagram` that a host configures. A float type has a
106/// numbering policy, a caption name (written before its number in the line
107/// under its content), a number format, the words a reference writes before
108/// its number, the content handlers it accepts, the scoped packages available
109/// in its body and the label types it accepts.
110///
111/// [`FloatType::new`] gives a type the defaults its name implies: numbered
112/// when it carries a `\label` ([`FloatNumbering::AutoNumbered`]), the number
113/// written in arabic digits, the caption name and the words derived from the
114/// capitalized name (`diagram` gives the caption name `Diagram` and the
115/// words `Diagram~`, `Diagrams~`, with the same pair as the variant
116/// `capital`), no scoped package, and one accepted label type, the type's own
117/// name (`\label{diagram:x}`). The
118/// builder methods change each field. [`FloatType::figure`] and
119/// [`FloatType::table`] are the two shipped types.
120///
121/// A float type is declared through the configuration ([`FloatsConfig`]) or by
122/// another feature through [`contribute_type`](super::contribute_type). Its
123/// name must consist of ASCII letters and must not be one of the reserved kind
124/// tokens ([`validate`](FloatType::validate)).
125///
126/// In settings, a float type is one entry of the map `types`, under its name;
127/// `handlers` must be written, and every other field takes the default that
128/// [`FloatType::new`] gives for that name and those handlers.
129///
130/// # Examples
131///
132/// ```
133/// use flm_core::stdlib::features::floats::{FloatNumbering, FloatType};
134///
135/// // A diagram holding anything, every one numbered.
136/// let diagram = FloatType::new("diagram", ["any"]).numbering(FloatNumbering::Numbered);
137/// assert_eq!(diagram.caption_name, "Diagram");
138/// assert_eq!(diagram.words.base.one, "Diagram~");
139/// assert_eq!(diagram.label_types, ["diagram"]);
140///
141/// // A figure also accepting labels written `fig:…`.
142/// let figure = FloatType::figure().label_types(["figure", "fig"]);
143/// assert_eq!(figure.words.base.one, "Fig.~");
144/// ```
145#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
146#[derive(schemars::JsonSchema)]
147#[serde(deny_unknown_fields)]
148#[schemars(transform = float_type_schema)]
149pub struct FloatType {
150    /// The type's name: the environment's name, the reference kind of the
151    /// float's reference point, the prefix of its anchor (`figure-1`) and one
152    /// of the kind tokens of the lowered float. ASCII letters only. In
153    /// settings, the name is the entry's key, not a field.
154    #[schemars(skip)]
155    pub name: Name,
156    /// The word written before the number in the line under a numbered
157    /// float's content: `Figure` in `Figure 1: A photo`. Plain text, shown as
158    /// written.
159    pub caption_name: String,
160    /// When a float of the type is numbered: `numbered`, `unnumbered` or
161    /// `auto-numbered` (numbered when it carries a `\label`; the default).
162    pub numbering: FloatNumbering,
163    /// How the number is written, as a number template of the numbering
164    /// feature (a text in the template language, such as `#{roman}`);
165    /// `#{arabic}` by default.
166    pub number_format: NumberTemplate,
167    /// The words a reference writes before the number (`Fig.~` in `Fig.~1`),
168    /// singular and plural, with their variants (`Figure~` in `Figure~1`,
169    /// written by `\ref[S]{…}`). FLM markup.
170    pub words: PrefixWords,
171    /// The names of the content handlers the type accepts, tried in this
172    /// order: the first that accepts a float's content decides. A handler that
173    /// no registered feature contributes accepts nothing. At least one name;
174    /// `any` accepts any content.
175    pub handlers: Vec<String>,
176    /// The names of the scoped packages available in the body of a float of
177    /// the type, besides the package of `\caption`, `\label` and
178    /// `\nonumber`: they make the commands of the type's content available
179    /// there (`\includegraphics` in a `figure`). A package that no registered
180    /// feature declares makes nothing available.
181    pub scoped_packages: Vec<Name>,
182    /// The label types a `\label` in a float of the type may have (the part
183    /// before the colon); by default the type's own name.
184    pub label_types: Vec<String>,
185}
186
187
188/// Adjusts the JSON Schema of a float type: only `handlers` is required,
189/// since an entry is read over the type [`FloatType::new`] makes from the
190/// entry's name and its `handlers`.
191fn float_type_schema(schema: &mut schemars::Schema) {
192    crate::core::settings::named::require_only(schema, &["handlers"]);
193}
194impl FloatType {
195    /// Returns the float type `name` that accepts the content handlers
196    /// `handlers`, with the defaults its name implies (see the type's
197    /// documentation).
198    pub fn new(
199        name: impl Into<Name>,
200        handlers: impl IntoIterator<Item = impl Into<String>>,
201    ) -> FloatType {
202        let name = name.into();
203        let caption_name = capitalized(name.as_str());
204        let one = format!("{caption_name}~");
205        let other = format!("{caption_name}s~");
206        let words = PrefixWords::new(one.clone(), other.clone())
207            .with_variant(CAPITAL_VARIANT, PluralWords::new(one, other));
208        FloatType {
209            label_types: vec![name.to_string()],
210            name,
211            caption_name,
212            numbering: FloatNumbering::default(),
213            number_format: NumberTemplate::formats("#{arabic}"),
214            words,
215            handlers: handlers.into_iter().map(Into::into).collect(),
216            scoped_packages: Vec::new(),
217        }
218    }
219
220    /// Returns the shipped type `figure`: numbered when it carries a `\label`,
221    /// caption name `Figure`, the words `Fig.~`, `Figs.~` with the variant
222    /// `capital` `Figure~`, `Figures~`, accepting exactly one image (the handler
223    /// [`INCLUDEGRAPHICS_HANDLER`]), with `\includegraphics` available in its
224    /// body (the package [`INCLUDEGRAPHICS_PACKAGE`]).
225    pub fn figure() -> FloatType {
226        FloatType::new("figure", [INCLUDEGRAPHICS_HANDLER])
227            .words(
228                PrefixWords::new("Fig.~", "Figs.~")
229                    .with_variant(CAPITAL_VARIANT, PluralWords::new("Figure~", "Figures~")),
230            )
231            .scoped_packages([INCLUDEGRAPHICS_PACKAGE])
232    }
233
234    /// Returns the shipped type `table`: numbered when it carries a `\label`,
235    /// caption name `Table`, the words `Tab.~`, `Tabs.~` with the variant
236    /// `capital` `Table~`, `Tables~`, accepting exactly one table of cells (the handler [`CELLS_HANDLER`]) or
237    /// exactly one image ([`INCLUDEGRAPHICS_HANDLER`]), with the `cells`
238    /// environment and `\includegraphics` available in its body (the packages
239    /// [`CELLS_PACKAGE`] and [`INCLUDEGRAPHICS_PACKAGE`]).
240    pub fn table() -> FloatType {
241        FloatType::new("table", [CELLS_HANDLER, INCLUDEGRAPHICS_HANDLER])
242            .words(
243                PrefixWords::new("Tab.~", "Tabs.~")
244                    .with_variant(CAPITAL_VARIANT, PluralWords::new("Table~", "Tables~")),
245            )
246            .scoped_packages([CELLS_PACKAGE, INCLUDEGRAPHICS_PACKAGE])
247    }
248
249    /// Builder: sets the caption name.
250    pub fn caption_name(mut self, caption_name: impl Into<String>) -> FloatType {
251        self.caption_name = caption_name.into();
252        self
253    }
254
255    /// Builder: sets the numbering policy.
256    pub fn numbering(mut self, numbering: FloatNumbering) -> FloatType {
257        self.numbering = numbering;
258        self
259    }
260
261    /// Builder: sets the number format.
262    pub fn number_format(mut self, number_format: NumberTemplate) -> FloatType {
263        self.number_format = number_format;
264        self
265    }
266
267    /// Builder: sets the words a reference writes before the number.
268    pub fn words(mut self, words: PrefixWords) -> FloatType {
269        self.words = words;
270        self
271    }
272
273    /// Builder: sets the content handlers, in the order they are tried.
274    pub fn handlers(mut self, handlers: impl IntoIterator<Item = impl Into<String>>) -> FloatType {
275        self.handlers = handlers.into_iter().map(Into::into).collect();
276        self
277    }
278
279    /// Builder: sets the scoped packages available in the body.
280    pub fn scoped_packages(
281        mut self,
282        scoped_packages: impl IntoIterator<Item = impl Into<Name>>,
283    ) -> FloatType {
284        self.scoped_packages = scoped_packages.into_iter().map(Into::into).collect();
285        self
286    }
287
288    /// Builder: sets the accepted label types.
289    pub fn label_types(mut self, label_types: impl IntoIterator<Item = impl Into<String>>) -> FloatType {
290        self.label_types = label_types.into_iter().map(Into::into).collect();
291        self
292    }
293
294    /// Checks the type on its own, as [`contribute_type`](super::contribute_type)
295    /// does before declaring anything.
296    ///
297    /// # Errors
298    ///
299    /// A sentence that describes the first problem found: a name that is empty
300    /// or holds anything but ASCII letters; a name that is one of the kind
301    /// tokens a float reserves ([`RESERVED_KINDS`]); an empty list of content
302    /// handlers.
303    pub fn validate(&self) -> Result<(), String> {
304        let name = self.name.as_str();
305        if name.is_empty() || !name.chars().all(|ch| ch.is_ascii_alphabetic()) {
306            return Err(format!("the float type name `{name}` must consist of ASCII letters only"));
307        }
308        if RESERVED_KINDS.contains(&name) {
309            let reserved: Vec<String> = RESERVED_KINDS.iter().map(|kind| format!("`{kind}`")).collect();
310            return Err(format!(
311                "a float type may not be named `{name}`: the names {} are reserved",
312                reserved.join(" and ")
313            ));
314        }
315        if self.handlers.is_empty() {
316            return Err(format!(
317                "the float type `{name}` must list at least one content handler (`{ANY_HANDLER}` \
318                 accepts any content)"
319            ));
320        }
321        Ok(())
322    }
323
324    /// Writes every field of the type into `out`, each text preceded by its
325    /// length: the type's part of [`FloatsConfig::digest_bytes`].
326    fn push_digest(&self, out: &mut Vec<u8>) {
327        let FloatType {
328            name,
329            caption_name,
330            numbering,
331            number_format,
332            words,
333            handlers,
334            scoped_packages,
335            label_types,
336        } = self;
337        push_text(out, name.as_str());
338        push_text(out, caption_name);
339        push_text(out, numbering.as_str());
340        match number_format {
341            NumberTemplate::Formats(text) => {
342                out.push(0);
343                push_text(out, text);
344            }
345            NumberTemplate::Initial(text) => {
346                out.push(1);
347                push_text(out, text);
348            }
349        }
350        push_plural(out, &words.base);
351        push_len(out, words.variants.len());
352        for (variant, plural) in &words.variants {
353            push_text(out, variant);
354            push_plural(out, plural);
355        }
356        push_len(out, handlers.len());
357        for handler in handlers {
358            push_text(out, handler);
359        }
360        push_len(out, scoped_packages.len());
361        for package in scoped_packages {
362            push_text(out, package.as_str());
363        }
364        push_len(out, label_types.len());
365        for label_type in label_types {
366            push_text(out, label_type);
367        }
368    }
369}
370
371/// The configuration of the [`Floats`](super::Floats) feature: the float
372/// types it declares, in order.
373///
374/// The default ([`FloatsConfig::new`]) declares the two shipped types,
375/// [`figure`](FloatType::figure) and [`table`](FloatType::table), both
376/// numbered. A caller replaces a type by declaring one of the same name
377/// ([`float_type`](FloatsConfig::float_type)), removes one
378/// ([`without_type`](FloatsConfig::without_type)), adds its own, or starts
379/// from [`FloatsConfig::empty`]:
380///
381/// ```
382/// use flm_core::stdlib::features::floats::{FloatNumbering, FloatType, FloatsConfig};
383///
384/// let config = FloatsConfig::new()
385///     .float_type(FloatType::figure().numbering(FloatNumbering::Numbered))
386///     .float_type(FloatType::new("diagram", ["any"]));
387/// assert_eq!(config.types.len(), 3);
388/// assert!(config.validate().is_ok());
389/// ```
390///
391/// A float type is document structure (a numbered series and the word under
392/// its content), not a property of the content that fills it. The two shipped
393/// types are therefore declared here, and they refer to the content handlers
394/// they accept by name. A feature that brings a float type together with its
395/// own content declares the type through
396/// [`contribute_type`](super::contribute_type) instead.
397///
398/// The value is what [`Floats::new`](super::Floats::new) takes; the standard
399/// package takes it through
400/// [`StdlibConfig::floats`](crate::stdlib::StdlibConfig::floats). It is a
401/// configuration, fixed when the registry is built: the environments are part
402/// of the language, and the counters and counter styles are built from it. The
403/// feature therefore adds [`digest_bytes`](FloatsConfig::digest_bytes) to the
404/// registry digest. The feature checks it when it registers
405/// ([`validate`](FloatsConfig::validate)).
406#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
407#[derive(schemars::JsonSchema)]
408#[serde(default, deny_unknown_fields)]
409pub struct FloatsConfig {
410    /// The float types, in order; no two have the same name. In settings, a
411    /// map from each type's name to its fields.
412    #[serde(deserialize_with = "crate::core::settings::named::deserialize")]
413    #[schemars(
414        transform = crate::core::settings::named::map_schema,
415        with = "std::collections::BTreeMap<String, FloatType>"
416    )]
417    pub types: Vec<FloatType>,
418}
419
420impl Default for FloatsConfig {
421    fn default() -> FloatsConfig {
422        FloatsConfig::new()
423    }
424}
425
426impl FloatsConfig {
427    /// Returns the configuration with the two shipped types, `figure` then
428    /// `table`.
429    pub fn new() -> FloatsConfig {
430        FloatsConfig { types: vec![FloatType::figure(), FloatType::table()] }
431    }
432
433    /// Returns a configuration that declares no float type.
434    pub fn empty() -> FloatsConfig {
435        FloatsConfig { types: Vec::new() }
436    }
437
438    /// Builder: declares `float_type`, replacing the type of that name in
439    /// its place if there is one, and adding it at the end otherwise.
440    pub fn float_type(mut self, float_type: FloatType) -> FloatsConfig {
441        match self.types.iter_mut().find(|known| known.name == float_type.name) {
442            Some(known) => *known = float_type,
443            None => self.types.push(float_type),
444        }
445        self
446    }
447
448    /// Builder: removes the type `name`, if there is one.
449    pub fn without_type(mut self, name: &str) -> FloatsConfig {
450        self.types.retain(|known| known.name.as_str() != name);
451        self
452    }
453
454    /// Returns the type `name`, if the configuration declares it.
455    pub fn get(&self, name: &str) -> Option<&FloatType> {
456        self.types.iter().find(|known| known.name.as_str() == name)
457    }
458
459    /// Checks the configuration, as the feature does when it registers.
460    ///
461    /// # Errors
462    ///
463    /// A sentence that describes the first problem found: a type that fails
464    /// [`FloatType::validate`], or two types of one name.
465    pub fn validate(&self) -> Result<(), String> {
466        for (at, float_type) in self.types.iter().enumerate() {
467            float_type.validate()?;
468            if self.types[..at].iter().any(|earlier| earlier.name == float_type.name) {
469                return Err(format!(
470                    "the float type `{}` may not be declared twice",
471                    float_type.name
472                ));
473            }
474        }
475        Ok(())
476    }
477
478    /// Returns the configuration written out as bytes: what the feature adds
479    /// to the registry digest, and what `Hash` hashes.
480    ///
481    /// Every type is written out in order, with every one of its fields, each
482    /// text preceded by its length. Two configurations give the same bytes
483    /// exactly when they are equal. The code takes the fields apart by name,
484    /// so a field added to a type and not written here fails to compile.
485    pub fn digest_bytes(&self) -> Vec<u8> {
486        let FloatsConfig { types } = self;
487        let mut out = Vec::new();
488        push_len(&mut out, types.len());
489        for float_type in types {
490            float_type.push_digest(&mut out);
491        }
492        out
493    }
494}
495
496impl Hash for FloatsConfig {
497    fn hash<H: Hasher>(&self, state: &mut H) {
498        state.write(&self.digest_bytes());
499    }
500}
501
502/// Returns `text` with its first letter capitalized.
503fn capitalized(text: &str) -> String {
504    let mut chars = text.chars();
505    match chars.next() {
506        Some(first) => first.to_uppercase().chain(chars).collect(),
507        None => String::new(),
508    }
509}
510
511/// Writes a count as eight little-endian bytes.
512fn push_len(out: &mut Vec<u8>, len: usize) {
513    out.extend_from_slice(&(len as u64).to_le_bytes());
514}
515
516/// Writes a text as its length and its bytes.
517fn push_text(out: &mut Vec<u8>, text: &str) {
518    push_len(out, text.len());
519    out.extend_from_slice(text.as_bytes());
520}
521
522/// Writes a pair of words.
523fn push_plural(out: &mut Vec<u8>, plural: &PluralWords) {
524    push_text(out, &plural.one);
525    push_text(out, &plural.other);
526}
527
528/// Reads a float type from settings: an entry of the map
529/// [`FloatsConfig::types`], under the type's name. The entry is read over the
530/// type that [`FloatType::new`] makes for that name and the entry's
531/// `handlers`, which must be written.
532impl NamedEntry for FloatType {
533    fn read_entry(name: &str, data: serde_json::Value) -> Result<FloatType, String> {
534        let handlers: Vec<String> = named::required(name, &data, "handlers")?;
535        named::read_over(&FloatType::new(name, handlers), "name", name, data)
536    }
537}
538
539#[cfg(test)]
540mod tests {
541    use super::*;
542
543    #[test]
544    fn a_type_takes_its_defaults_from_its_name() {
545        let diagram = FloatType::new("diagram", ["any"]);
546        assert_eq!(diagram.caption_name, "Diagram");
547        assert_eq!(diagram.words.base, PluralWords::new("Diagram~", "Diagrams~"));
548        assert_eq!(diagram.words.variants[CAPITAL_VARIANT], PluralWords::new("Diagram~", "Diagrams~"));
549        assert_eq!(diagram.numbering, FloatNumbering::AutoNumbered);
550        assert_eq!(FloatType::figure().numbering, FloatNumbering::AutoNumbered);
551        assert_eq!(FloatType::table().numbering, FloatNumbering::AutoNumbered);
552        assert_eq!(diagram.number_format, NumberTemplate::formats("#{arabic}"));
553        assert_eq!(diagram.label_types, ["diagram"]);
554        assert!(diagram.scoped_packages.is_empty());
555    }
556
557    #[test]
558    fn the_shipped_types_carry_the_words_handlers_and_package() {
559        let figure = FloatType::figure();
560        assert_eq!(figure.caption_name, "Figure");
561        assert_eq!(figure.words.base, PluralWords::new("Fig.~", "Figs.~"));
562        assert_eq!(figure.words.variants[CAPITAL_VARIANT], PluralWords::new("Figure~", "Figures~"));
563        assert_eq!(figure.handlers, ["includegraphics"]);
564        assert_eq!(figure.scoped_packages, [Name::from(INCLUDEGRAPHICS_PACKAGE)]);
565        assert_eq!(
566            FloatType::table().scoped_packages,
567            [Name::from(CELLS_PACKAGE), Name::from(INCLUDEGRAPHICS_PACKAGE)]
568        );
569        let table = FloatType::table();
570        assert_eq!(table.caption_name, "Table");
571        assert_eq!(table.words.base, PluralWords::new("Tab.~", "Tabs.~"));
572        assert_eq!(table.handlers, ["cells", "includegraphics"]);
573        assert_eq!(FloatsConfig::new().validate(), Ok(()));
574    }
575
576    #[test]
577    fn the_policy_decides_the_number_from_the_fields() {
578        use FloatNumbering::*;
579        assert!(Numbered.numbers(false, false) && !Numbered.numbers(true, true));
580        assert!(!Unnumbered.numbers(true, false));
581        assert!(AutoNumbered.numbers(true, false));
582        assert!(!AutoNumbered.numbers(false, false) && !AutoNumbered.numbers(true, true));
583    }
584
585    #[test]
586    fn a_name_an_empty_handler_list_and_a_repeated_type_are_refused() {
587        let refused = |config: FloatsConfig| config.validate().is_err();
588        assert!(refused(FloatsConfig::empty().float_type(FloatType::new("my-float", ["any"]))));
589        assert!(refused(FloatsConfig::empty().float_type(FloatType::new("", ["any"]))));
590        assert!(refused(FloatsConfig::empty().float_type(FloatType::new("numbered", ["any"]))));
591        assert!(refused(FloatsConfig::empty().float_type(FloatType::new("unnumbered", ["any"]))));
592        assert!(refused(FloatsConfig::empty().float_type(FloatType::new("x", Vec::<String>::new()))));
593        let twice = FloatsConfig { types: vec![FloatType::figure(), FloatType::figure()] };
594        assert!(refused(twice));
595    }
596
597    #[test]
598    fn declaring_a_type_of_a_known_name_replaces_it_in_place() {
599        let config = FloatsConfig::new().float_type(FloatType::figure().caption_name("Fig"));
600        assert_eq!(config.types.len(), 2);
601        assert_eq!(config.types[0].caption_name, "Fig");
602        assert_eq!(FloatsConfig::new().without_type("figure").types.len(), 1);
603    }
604
605    #[test]
606    fn the_digest_bytes_change_with_every_field() {
607        let base = FloatsConfig::new();
608        let figure = FloatType::figure;
609        let changed = [
610            base.clone().without_type("table"),
611            base.clone().float_type(FloatType::new("diagram", ["any"])),
612            base.clone().float_type(figure().caption_name("Fig")),
613            base.clone().float_type(figure().numbering(FloatNumbering::Numbered)),
614            base.clone().float_type(figure().numbering(FloatNumbering::Unnumbered)),
615            base.clone().float_type(figure().number_format(NumberTemplate::formats("#{roman}"))),
616            base.clone().float_type(figure().number_format(NumberTemplate::initial("#{arabic}"))),
617            base.clone().float_type(figure().words(PrefixWords::new("Fig.~", "Figs.~"))),
618            base.clone().float_type(figure().handlers(["any"])),
619            base.clone().float_type(figure().scoped_packages(Vec::<Name>::new())),
620            base.clone().float_type(figure().label_types(["figure", "fig"])),
621        ];
622        for other in &changed {
623            assert_ne!(other.digest_bytes(), base.digest_bytes(), "{other:?}");
624        }
625        assert_eq!(FloatsConfig::new().digest_bytes(), base.digest_bytes());
626    }
627}