flm_core/stdlib/features/annotations/config.rs
1//! The configuration of the `annotations` feature, the annotators, each with
2//! the command they write and the initials shown at the start of their
3//! annotations; and the render option that hides every annotation.
4//!
5//! The configuration ([`AnnotationsConfig`]) is the value the feature is
6//! constructed from, fixed when the registry is built; the render option
7//! ([`AnnotationsRenderOptions`]) is set per render request
8//! ([settings, options and configuration](crate::guide::concepts_overview#settings-options-and-configuration)).
9
10/// One annotator: a reviewer who highlights passages and writes remarks in a
11/// document, with the command they write and the initials shown at the start
12/// of each of their annotations.
13///
14/// - [`command`](Annotator::command) — the name of the annotator's command,
15/// without the backslash: `phf` makes `\phf{…}` (a highlight), `\phf[…]` (a
16/// comment) and `\phf … \endphf` (a highlight). It must be made of ASCII
17/// letters only, like every command name of the language written with
18/// letters, and must be neither `begin` nor `end`, which open and close
19/// environments ([`Annotator::validate`]).
20/// - [`initials`](Annotator::initials) — the short text shown where each of
21/// the annotator's highlights and comments starts (in the margin, on an
22/// output that has one), such as `PhF`; `None` for an annotator whose
23/// annotations show no initials. The text is shown as written, never read
24/// as markup.
25///
26/// An annotator's **number** is its position in
27/// [`AnnotationsConfig::annotators`], counting from zero. The configuration
28/// specifies no color: an output that shows colors chooses one per number
29/// (the HTML stylesheet `flm.annotations.style` and the `phfcc` LaTeX package
30/// give the first eight numbers their own colors).
31///
32/// # Examples
33///
34/// ```
35/// use flm_core::stdlib::features::annotations::Annotator;
36///
37/// let reviewer = Annotator::new("phf").initials("PhF");
38/// assert_eq!(reviewer.command, "phf");
39/// assert_eq!(reviewer.initials.as_deref(), Some("PhF"));
40/// assert_eq!(Annotator::new("abc").initials, None);
41/// ```
42#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Deserialize, serde::Serialize)]
43#[derive(schemars::JsonSchema)]
44#[serde(deny_unknown_fields)]
45pub struct Annotator {
46 /// The command's name, without the backslash: `phf`. In settings, it is
47 /// written as the key of the annotator's entry, not as a field.
48 #[schemars(skip)]
49 pub command: String,
50 /// The initials shown at the start of the annotator's annotations, such as
51 /// `PhF`; `None` for none.
52 pub initials: Option<String>,
53}
54
55impl Annotator {
56 /// Returns an annotator whose command is `command` (without the
57 /// backslash), with no initials.
58 pub fn new(command: impl Into<String>) -> Annotator {
59 Annotator { command: command.into(), initials: None }
60 }
61
62 /// Builder: sets the initials shown at the start of the annotator's
63 /// annotations, and returns the annotator.
64 pub fn initials(mut self, initials: impl Into<String>) -> Annotator {
65 self.initials = Some(initials.into());
66 self
67 }
68
69 /// Returns the name of the command that closes a passage the annotator
70 /// highlights in the third form, `\phf … \endphf`: `end` followed by the
71 /// command's name, `endphf`.
72 pub fn end_command(&self) -> String {
73 format!("end{}", self.command)
74 }
75
76 /// Checks the annotator on its own.
77 ///
78 /// # Errors
79 ///
80 /// Returns a sentence that identifies the annotator and states the
81 /// problem: a command that is empty, holds a character other than an
82 /// ASCII letter, or is `begin` or `end` (none of which the language could
83 /// read as the annotator's command); or initials that are empty or made
84 /// only of whitespace (an annotator whose annotations show no initials has
85 /// `None`).
86 pub fn validate(&self) -> Result<(), String> {
87 let command = self.command.as_str();
88 if command.is_empty() || !command.chars().all(|ch| ch.is_ascii_alphabetic()) {
89 return Err(format!(
90 "the annotator command name `{command}` must be one or more ASCII letters, \
91 without the backslash"
92 ));
93 }
94 if command == "begin" || command == "end" {
95 return Err(format!(
96 "the annotator command name may not be `{command}`, since `\\{command}` starts or ends \
97 an environment"
98 ));
99 }
100 // Refused rather than read as none: blank initials show nothing,
101 // and a host meaning "no initials" writes `None`.
102 if self.initials.as_deref().is_some_and(|initials| initials.trim().is_empty()) {
103 return Err(format!(
104 "the initials of the annotator `\\{command}` may not be empty or only \
105 whitespace (leave them unset for no initials)"
106 ));
107 }
108 Ok(())
109 }
110}
111
112/// The configuration of the `annotations` feature: the annotators, in order.
113///
114/// Each annotator declares one command, written in three forms: `\phf{…}`
115/// and `\phf … \endphf` mark a passage (a **highlight**), and `\phf[…]`
116/// writes a remark (a **comment**). The order numbers the annotators from
117/// zero; an output that shows colors chooses one per number. The default
118/// configuration declares **no annotator**, and the feature then declares no
119/// command at all: `\phf` is an unknown command until a host configures it.
120///
121/// # Examples
122///
123/// ```
124/// use flm_core::stdlib::features::annotations::{AnnotationsConfig, Annotator};
125///
126/// let config = AnnotationsConfig::new()
127/// .annotator(Annotator::new("phf").initials("PhF"))
128/// .annotator(Annotator::new("abc"));
129/// assert_eq!(config.annotators.len(), 2);
130/// assert_eq!(config.number_of("abc"), Some(1));
131/// assert_eq!(config.validate(), Ok(()));
132/// assert!(AnnotationsConfig::new().annotators.is_empty());
133/// ```
134///
135/// The value is what
136/// [`AnnotationsFeature::new`](super::AnnotationsFeature::new) takes; a host
137/// using the standard features passes it with
138/// [`StdlibConfig::annotations`](crate::stdlib::StdlibConfig::annotations).
139/// The configuration is fixed when the registry is built, before any document
140/// is parsed
141/// ([configuration](crate::guide::concepts_overview#settings-options-and-configuration)),
142/// because the commands are part of the language. The feature therefore
143/// feeds [`digest_bytes`](AnnotationsConfig::digest_bytes) into the registry
144/// digest ([digests](crate::model::digest)), the fingerprint that decides
145/// whether a cached result may be reused.
146///
147/// The feature checks the configuration when the registry is built
148/// ([`AnnotationsConfig::validate`]): every annotator on its own
149/// ([`Annotator::validate`]), then two annotators with the same command are
150/// refused. A command that another feature also declares, such as `emph`,
151/// makes the registry build fail, as any two declarations of one name do.
152///
153/// The configuration refers to no output, HTML tag or class. Whether
154/// annotations are shown at all is decided per render, not by the
155/// configuration: [`AnnotationsRenderOptions`].
156#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, serde::Deserialize)]
157#[derive(schemars::JsonSchema)]
158#[serde(default, deny_unknown_fields)]
159pub struct AnnotationsConfig {
160 /// The annotators, in order: the first is annotator 0. In settings, a map
161 /// from each annotator's command name to its other fields.
162 #[serde(deserialize_with = "crate::core::settings::named::deserialize")]
163 #[schemars(
164 transform = crate::core::settings::named::map_schema,
165 with = "std::collections::BTreeMap<String, Annotator>"
166 )]
167 pub annotators: Vec<Annotator>,
168}
169
170impl AnnotationsConfig {
171 /// Returns the default configuration: no annotator.
172 pub fn new() -> AnnotationsConfig {
173 AnnotationsConfig::default()
174 }
175
176 /// Builder: adds `annotator` after the annotators already declared, and
177 /// returns the configuration; the new annotator's number is the count of
178 /// those already declared.
179 pub fn annotator(mut self, annotator: Annotator) -> AnnotationsConfig {
180 self.annotators.push(annotator);
181 self
182 }
183
184 /// Returns the number of the annotator whose command is `command`, or
185 /// `None` when there is none.
186 pub fn number_of(&self, command: &str) -> Option<usize> {
187 self.annotators.iter().position(|annotator| annotator.command == command)
188 }
189
190 /// Checks the configuration, as the feature does when it registers.
191 ///
192 /// # Errors
193 ///
194 /// Returns a sentence that states the first problem found: one of
195 /// [`Annotator::validate`]'s, or two annotators with the same command.
196 pub fn validate(&self) -> Result<(), String> {
197 for (at, annotator) in self.annotators.iter().enumerate() {
198 annotator.validate()?;
199 if self.annotators[..at].iter().any(|earlier| earlier.command == annotator.command) {
200 return Err(format!(
201 "the command `\\{}` may not be declared for two annotators",
202 annotator.command
203 ));
204 }
205 }
206 Ok(())
207 }
208
209 /// Returns the canonical byte form of the configuration, which the feature
210 /// feeds into the registry digest: every annotator in order, every field
211 /// of it, each text preceded by its length. Two configurations therefore
212 /// have the same byte form exactly when they are equal.
213 pub fn digest_bytes(&self) -> Vec<u8> {
214 let mut out = Vec::new();
215 push_len(&mut out, self.annotators.len());
216 for annotator in &self.annotators {
217 // Taken apart by name, so a field added and not written here fails
218 // to compile.
219 let Annotator { command, initials } = annotator;
220 push_text(&mut out, command);
221 match initials {
222 None => out.push(0),
223 Some(initials) => {
224 out.push(1);
225 push_text(&mut out, initials);
226 }
227 }
228 }
229 out
230 }
231}
232
233/// Writes a count as eight little-endian bytes.
234fn push_len(out: &mut Vec<u8>, len: usize) {
235 out.extend_from_slice(&(len as u64).to_le_bytes());
236}
237
238/// Writes a text as its length and its bytes.
239fn push_text(out: &mut Vec<u8>, text: &str) {
240 push_len(out, text.len());
241 out.extend_from_slice(text.as_bytes());
242}
243
244/// The render options of the `annotations` feature: an option type whose
245/// values are set on a render request ([`crate::model::options`]), in the
246/// plan request's overrides ([`Overrides`](crate::core::plan::Overrides)), as
247/// the example shows.
248///
249/// When [`hidden`](AnnotationsRenderOptions::hidden) is true, every annotation is
250/// left out of the output on every backend: a highlight is shown as its
251/// passage alone and a comment as nothing. This gives a clean copy of an
252/// annotated document without any change to its source.
253///
254/// # Examples
255///
256/// ```
257/// use flm_core::core::plan::Overrides;
258/// use flm_core::model::options::OptionValues;
259/// use flm_core::stdlib::features::annotations::AnnotationsRenderOptions;
260///
261/// let clean_copy = Overrides {
262/// render_options: OptionValues::new().with(AnnotationsRenderOptions { hidden: true }),
263/// ..Overrides::none()
264/// };
265/// # let _ = clean_copy;
266/// assert!(!AnnotationsRenderOptions::default().hidden);
267/// ```
268#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, serde::Deserialize)]
269#[derive(schemars::JsonSchema)]
270#[serde(default, deny_unknown_fields)]
271pub struct AnnotationsRenderOptions {
272 /// Whether every annotation is left out of the output, each highlight
273 /// shown as its passage alone and each comment not at all. `false` by
274 /// default.
275 pub hidden: bool,
276}
277
278
279/// In settings, an annotator is written under its command's name, as one
280/// entry of the map [`AnnotationsConfig::annotators`].
281impl crate::core::settings::named::NamedEntry for Annotator {
282 fn read_entry(name: &str, data: serde_json::Value) -> Result<Annotator, String> {
283 crate::core::settings::named::read_with_name("command", name, data)
284 }
285}
286
287#[cfg(test)]
288mod tests {
289 use super::*;
290
291 #[test]
292 fn a_command_is_ascii_letters_and_no_environment_word() {
293 for command in ["", "ph f", "phf1", "é", "p-f", "begin", "end"] {
294 assert!(Annotator::new(command).validate().is_err(), "{command}");
295 }
296 assert_eq!(Annotator::new("PhF").validate(), Ok(()));
297 assert_eq!(Annotator::new("endphf").validate(), Ok(()));
298 }
299
300 #[test]
301 fn blank_initials_are_refused_and_two_annotators_of_one_command_too() {
302 for initials in ["", " ", "\t"] {
303 assert!(Annotator::new("phf").initials(initials).validate().is_err(), "{initials:?}");
304 }
305 assert_eq!(Annotator::new("phf").initials(" P ").validate(), Ok(()));
306 let config = AnnotationsConfig::new()
307 .annotator(Annotator::new("phf"))
308 .annotator(Annotator::new("phf").initials("X"));
309 assert!(config.validate().is_err());
310 }
311
312 #[test]
313 fn the_digest_tells_every_field_apart() {
314 let one = AnnotationsConfig::new().annotator(Annotator::new("phf"));
315 let with_initials = AnnotationsConfig::new().annotator(Annotator::new("phf").initials("PhF"));
316 let other = AnnotationsConfig::new().annotator(Annotator::new("abc"));
317 let two = one.clone().annotator(Annotator::new("abc"));
318 let reordered = AnnotationsConfig::new().annotator(Annotator::new("abc")).annotator(Annotator::new("phf"));
319 let digests = [
320 AnnotationsConfig::new().digest_bytes(),
321 one.digest_bytes(),
322 with_initials.digest_bytes(),
323 other.digest_bytes(),
324 two.digest_bytes(),
325 reordered.digest_bytes(),
326 ];
327 for (at, digest) in digests.iter().enumerate() {
328 for other in &digests[..at] {
329 assert_ne!(digest, other);
330 }
331 }
332 assert_eq!(one.digest_bytes(), AnnotationsConfig::new().annotator(Annotator::new("phf")).digest_bytes());
333 }
334}