Skip to main content

flm_core/stdlib/features/annotations/
mod.rs

1//! The `annotations` feature: a reviewer's marks in a document, passages
2//! highlighted and remarks written into the text, under commands that a host
3//! configures, one per reviewer.
4//!
5//! # What an author writes
6//!
7//! An **annotator** is one reviewer, configured with a command name and
8//! optional initials ([`Annotator`], [`AnnotationsConfig`]). The annotators
9//! are numbered from zero in configuration order, and an output can give
10//! each number its own color. The default configuration declares no
11//! annotator, and the feature then declares no command: `\phf` is an unknown
12//! command until a host configures an annotator whose command is `phf`.
13//!
14//! Each annotator's command writes two kinds of annotation:
15//!
16//! - a **highlight**, a passage the annotator marks, which stays part of the
17//!   text: written `\phf{…}`, or `\phf … \endphf`;
18//! - a **comment**, a remark the annotator writes into the text, which is not
19//!   part of it: written `\phf[…]`. (A comment in this sense is a reviewer's
20//!   remark, not a source comment written with `%`.)
21//!
22//! ```text
23//! The result \phf{holds in every case}, as \phf[cite the lemma here] shown.
24//! \phf The second form needs no braces, which helps
25//! with a long passage.\endphf
26//! ```
27//!
28//! The command takes **one argument**, read by the feature's own parser
29//! ([`AnnotationParser`]), which chooses the form by what follows the command
30//! (past any whitespace and source comments): a `{` begins a braced group, a
31//! `[` a bracketed group, and anything else begins a passage that ends at
32//! `\endphf` (`end` followed by the command's name). The argument holds
33//! inline content or paragraphs, as written. `\phf{x}[y]` is a highlight of
34//! `x` followed by the text `[y]`.
35//! The function [`form_of`] reads which form an annotation was written in.
36//! The guide for authors describes annotations under
37//! [Annotations](crate::guide::language_syntax#annotations).
38//!
39//! An annotation never becomes a block that holds paragraphs. A blank line
40//! inside it is a paragraph break of the text around it, and the annotation
41//! continues in the next paragraph; a list inside it is a block of the text
42//! around it, still part of the annotation (a cut part around that block, see
43//! below), and a displayed formula inside it stays in the inline content the
44//! annotation spans. The annotator's initials are shown at the start of the
45//! annotation only.
46//!
47//! # What the feature provides to the pipeline
48//!
49//! **The element.** Every annotator's command is one element value of the
50//! element type [`ANNOTATION`] (`flm.annotations.annotation`), carrying an
51//! [`AnnotationElement`]: a macro with one argument, [`TEXT_ARG`], declared in
52//! text mode.
53//!
54//! **Cut parts.** The element is *block-transparent*: its content is laid
55//! out as if it were written directly in the content around it
56//! ([block-transparent elements](crate::guide::concepts_overview#block-transparent-elements)).
57//! Before any paragraph is built, the block-structure pass
58//! ([`blocks`](crate::lang::rewrites::blocks)) cuts an
59//! annotation whose argument crosses a paragraph break or holds a block into
60//! **cut parts**: one node of the annotation's element around each stretch of
61//! inline content between paragraph breaks and blocks, and one around each
62//! block. Each cut part carries an [`AnnotationPiece`] record, its
63//! continuation record, which says which cut part of how many it is. The
64//! lowering rules read it to show the initials on the first cut part only,
65//! and the `text` backend's rule reads it to open a comment's bracket on the
66//! first cut part and close it on the last.
67//!
68//! **Lowering rules.** A lowering rule ([`LoweringRule`]) says how an element
69//! becomes output on a backend. The feature registers these rules. A rule
70//! marked as the default for one backend ranks above a rule marked as the
71//! default everywhere ([`DefaultMark`]):
72//!
73//! - [`RULE`] ([`AnnotationRule`]), the default on every backend that has no
74//!   rule of its own for an annotation: an
75//!   annotation, or a cut part of one, lowers to a `flm.pres.span` of the
76//!   role [`HIGHLIGHT_ROLE`] or [`COMMENT_ROLE`] (a `flm.pres.block` of that
77//!   role for a cut part around a block placed among blocks), with the kind
78//!   tokens `<command>` and `annotator-<n>` ([`annotator_kind`]). A role is a
79//!   feature-owned dotted name on a presentation payload that says what a
80//!   container is, and kind tokens classify it further
81//!   ([`payload`](crate::stdlib::backends::pres::payload)). A cut part also
82//!   carries the kind token [`MARK_CONTINUES_KIND`] when a cut part follows
83//!   it and [`MARK_CONTINUED_KIND`] when one precedes it. The annotator's
84//!   initials are a margin decoration at the start of the annotation, holding
85//!   a span of the role [`INITIALS_ROLE`]; a decoration is a node that the
86//!   lowering driver moves out of the content into an attached slot of the
87//!   enclosing presentation node
88//!   ([`Decoration`](crate::stdlib::backends::pres::Decoration)).
89//! - [`TEXT_RULE`] ([`AnnotationTextRule`]), the default on the `text`
90//!   backend: it lowers an annotation as the general rule does, except that a
91//!   comment is written with its brackets and initials as text and no
92//!   decoration: `[PhF: remark]` for an annotator with the initials `PhF`.
93//!   The text backend prints a highlight as `[PhF] passage`.
94//! - On the `html` backend, the feature's stylesheet `flm.annotations.style`
95//!   ([`html`]), which colors each annotation by its annotator's number; the
96//!   general rule and the `text` backend's rule require it wherever they
97//!   write an annotation.
98//! - On the `latex-rendered` backend, the definition piece
99//!   `flm.latex.def.flmx.annotations` ([`latex_rendered`]), which the same
100//!   requirement brings into the style file.
101//! - [`latex::LATEX_RULE`] ([`latex::AnnotationLatexRule`]), the default on
102//!   the `latex-recomposed` backend: it writes the command back as the author
103//!   wrote it, over the LaTeX package `phfcc`, which makes each annotator's
104//!   command ([`latex`]).
105//!
106//! **Settings.** The feature's configuration, [`AnnotationsConfig`], is the
107//! value the feature is constructed from; it is fixed when the registry is
108//! built
109//! ([configuration](crate::guide::concepts_overview#settings-options-and-configuration)),
110//! because the commands are part of the language. Written as data, its
111//! settings key `annotators` maps each command name to the annotator's other
112//! fields, and a host that combines several sources of settings combines
113//! that map one annotator at a time. The feature feeds the configuration
114//! into the [registry digest](crate::model::digest), the number that changes
115//! whenever something about the registry that can change what processing
116//! produces changes ([`FeatureBuilder::digest_input`]);
117//! [`AnnotationsConfig::digest_bytes`] gives the bytes. The feature also
118//! declares one option type, [`AnnotationsRenderOptions`], set per render
119//! request: when its field [`hidden`](AnnotationsRenderOptions::hidden) is
120//! true, every rule leaves every
121//! annotation out of the output, for a clean copy: a highlight is shown as
122//! its passage alone and a comment as nothing (the recomposed LaTeX keeps the
123//! paragraph breaks a comment held).
124//!
125//! # Errors
126//!
127//! A passage opened by `\phf` and not closed by `\endphf` is reported as
128//! [`Unterminated`] (`flm.annotations.unterminated`) while the document is
129//! parsed. An unknown command (a stray `\endphf`, or `\phf` with no
130//! annotator configured) and an unclosed group are reported by the language
131//! itself.
132//!
133//! # Interactions with other features
134//!
135//! - **Block structure.** The element carries the block-transparent aspect
136//!   ([`BlockTransparent`]) and a block role per occurrence
137//!   ([`BlockRoleAspect`]); the block-structure pass
138//!   ([`blocks`](crate::lang::rewrites::blocks)) cuts it into cut parts.
139//! - **Text of a title.** The element carries the aspect [`ApartFromText`]:
140//!   a comment's remark is not part of the text around it, so that reading
141//!   the plain text of a run (for example to give an unlabeled heading an
142//!   identifier from its title) leaves the remark out. A highlight's passage
143//!   is part of the text.
144//! - **Decorations.** The initials are a margin decoration
145//!   (`flm.pres.deco.margin`); each backend writes it as it writes every
146//!   margin decoration.
147//! - **The `latex-recomposed` backend** lowers the tree before the
148//!   block-structure pass, so an annotation reaches its rule uncut and is
149//!   written back as one invocation ([`latex`]).
150//! - **The standard features.** The [standard features](crate::stdlib)
151//!   include the feature under the configuration
152//!   [`StdlibConfig::annotations`](crate::stdlib::StdlibConfig::annotations).
153//!
154//! # Items
155//!
156//! - [`AnnotationsFeature`] and [`feature`] — the feature, under a
157//!   configuration or the default one.
158//! - [`AnnotationsConfig`], [`Annotator`] — the configuration;
159//!   [`AnnotationsRenderOptions`] — the render option.
160//! - [`AnnotationElement`] — the data of each element value of
161//!   [`ANNOTATION`].
162//! - [`AnnotationParser`], [`Form`], [`form_of`] — the argument's parser and
163//!   the reading of an annotation's form.
164//! - [`AnnotationPiece`], [`payload_readers`] — the continuation record of a
165//!   cut part, and its reader for serialized trees.
166//! - [`AnnotationRule`], [`AnnotationTextRule`] — the general rule and the
167//!   `text` backend's rule; [`html`] and [`latex`] — the rules of the `html`
168//!   and `latex-recomposed` backends.
169//! - [`Unterminated`] — the one condition the feature reports.
170//! - The names: [`FEATURE`], [`ANNOTATION`], [`TEXT_ARG`], [`RULE`],
171//!   [`TEXT_RULE`], the roles [`HIGHLIGHT_ROLE`], [`COMMENT_ROLE`],
172//!   [`INITIALS_ROLE`], and the kind tokens [`annotator_kind`],
173//!   [`MARK_CONTINUES_KIND`], [`MARK_CONTINUED_KIND`].
174
175mod config;
176mod cut;
177mod diagnostics;
178pub mod html;
179pub mod latex;
180pub mod latex_rendered;
181mod lower;
182mod parser;
183
184use std::sync::Arc;
185
186use techy::core::node::NodeRef;
187
188use crate::core::settings::SettingsDecl;
189use crate::core::lowering::{DefaultMark, LoweringRule};
190use crate::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature};
191use crate::lang::Flm;
192use crate::lang::mint::{ArgDef, ArgLayout, ElementDef, SyntaxDef};
193use crate::lang::rewrites::blocks::BlockTransparent;
194use crate::model::aspects::{ApartFromText, BlockRoleAspect, ContentRef};
195use crate::model::element::ElementSpec;
196use crate::model::names::{FeatureName, Name};
197use crate::model::options::Bind;
198use crate::stdlib::backends::text;
199
200pub use config::{AnnotationsConfig, AnnotationsRenderOptions, Annotator};
201pub use cut::{payload_readers, AnnotationPiece};
202pub use diagnostics::Unterminated;
203pub use lower::{AnnotationRule, AnnotationTextRule};
204pub use parser::{form_of, AnnotationParser, Form};
205
206/// The feature's registered name, `annotations`.
207pub const FEATURE: &str = "annotations";
208
209/// The declaration of the feature's settings ([`crate::core::settings`]): the
210/// fields of [`AnnotationsConfig`] and of [`AnnotationsRenderOptions`] are its
211/// settings keys, and the key `annotators` is combined one annotator at a
212/// time.
213fn settings() -> SettingsDecl {
214    SettingsDecl::new(FEATURE)
215        .config::<AnnotationsConfig>(
216            "The annotators, in order, the first numbered 0: for each, the name of its command \
217            (without the backslash) and the initials shown at the start of its annotations. \
218            Fixed when the registry is built: it cannot vary per document or per render.",
219        )
220        .options::<AnnotationsRenderOptions>(
221            Bind::Render,
222            "Whether every annotation is left out of the output, each highlight shown as its \
223            passage alone and each comment not at all (`hidden`, false by default). Set per \
224            render request.",
225        )
226        .merge_entries("annotators", || crate::core::settings::named::to_data(&AnnotationsConfig::default().annotators, "command"))
227        .remove_false("annotators")
228}
229
230/// The element type of an annotation, `flm.annotations.annotation`: one
231/// element value per configured annotator, each carrying an
232/// [`AnnotationElement`].
233pub const ANNOTATION: &str = "flm.annotations.annotation";
234
235/// The name of an annotation's one argument, `text`: the highlighted passage
236/// or the written remark, read by the [`AnnotationParser`].
237pub const TEXT_ARG: &str = "text";
238
239/// The role of the span or block a highlight is staged as,
240/// `flm.annotations.highlight`.
241pub const HIGHLIGHT_ROLE: &str = "flm.annotations.highlight";
242
243/// The role of the span or block a comment is staged as,
244/// `flm.annotations.comment`.
245pub const COMMENT_ROLE: &str = "flm.annotations.comment";
246
247/// The role of the span that holds an annotator's initials inside the margin
248/// decoration at the start of a highlight or a comment,
249/// `flm.annotations.initials`.
250pub const INITIALS_ROLE: &str = "flm.annotations.initials";
251
252/// The name of the general lowering rule of the element [`ANNOTATION`],
253/// `flm.annotations.annotation.lower.default` ([`AnnotationRule`]), the
254/// default on every backend.
255pub const RULE: &str = "flm.annotations.annotation.lower.default";
256
257/// The name of the lowering rule of the element [`ANNOTATION`] on the `text`
258/// backend, `flm.annotations.annotation.lower.text` ([`AnnotationTextRule`]),
259/// which writes a comment's brackets and initials as text.
260pub const TEXT_RULE: &str = "flm.annotations.annotation.lower.text";
261
262/// Returns the kind token of the annotator numbered `number`,
263/// `annotator-<n>`: the second kind token of every annotation's span or block
264/// and of its initials' span, after the command's name. A stylesheet selects
265/// an annotator's color by this token.
266pub fn annotator_kind(number: usize) -> Name {
267    Name::from(format!("annotator-{number}"))
268}
269
270/// The kind token `mark-continues`, carried by every cut part of a cut
271/// annotation except the last: the annotation continues in a later cut part.
272/// With [`MARK_CONTINUED_KIND`], it lets a stylesheet draw what opens an
273/// annotation on its first cut part only and what closes it on its last cut
274/// part only. An annotation that was not cut carries neither token.
275///
276/// A kind token has a meaning only together with the role's class, so the
277/// same token on another feature's element is a different token. The kind
278/// tokens of a cut part also hold the annotator's command name, which is made
279/// of letters only; because of the hyphen, no command name can equal either
280/// token.
281pub const MARK_CONTINUES_KIND: &str = "mark-continues";
282
283/// The kind token `mark-continued`, carried by every cut part of a cut
284/// annotation except the first: the annotation began in an earlier cut part.
285/// See [`MARK_CONTINUES_KIND`].
286pub const MARK_CONTINUED_KIND: &str = "mark-continued";
287
288/// The data that each element value of [`ANNOTATION`] carries: the annotator
289/// whose command writes the annotation, and the annotator's number, its
290/// position in the configuration counted from zero.
291///
292/// The element value also carries three aspects, each implemented on this
293/// type: the block role ([`BlockRoleAspect`]) and the cut into cut parts
294/// ([`BlockTransparent`]), described at [`AnnotationPiece`], and the content
295/// apart from the text ([`ApartFromText`]).
296#[derive(Debug, Clone, PartialEq, Eq)]
297pub struct AnnotationElement {
298    /// The annotator.
299    pub annotator: Annotator,
300    /// The annotator's number.
301    pub number: usize,
302}
303
304/// A comment is not part of the text around it: its remark, the argument
305/// [`TEXT_ARG`], is the annotator's. The plain text of a heading's title that
306/// holds a comment therefore leaves the remark out, and so does the
307/// identifier made from that text. A highlight's passage is part of the
308/// text, so a highlight returns no content reference.
309impl ApartFromText for AnnotationElement {
310    fn apart_from_text(&self, node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
311        match form_of(node) {
312            Some(Form::Comment) => vec![ContentRef::ArgumentNamed(TEXT_ARG.to_string())],
313            Some(Form::Highlight) | None => Vec::new(),
314        }
315    }
316}
317
318/// Returns the element value of the annotator numbered `number`.
319fn annotation_element(annotator: &Annotator, number: usize) -> Arc<ElementSpec> {
320    let value = Arc::new(AnnotationElement { annotator: annotator.clone(), number });
321    Arc::new(
322        ElementSpec::new(ANNOTATION)
323            .docs(format!(
324                "`\\{0}{{…}}`, `\\{0}[…]`, `\\{0} … \\end{0}`: an annotation of annotator {1}.",
325                annotator.command, number
326            ))
327            .with::<dyn BlockRoleAspect>(Arc::clone(&value) as Arc<dyn BlockRoleAspect>)
328            .with::<dyn BlockTransparent>(Arc::clone(&value) as Arc<dyn BlockTransparent>)
329            .with::<dyn ApartFromText>(Arc::clone(&value) as Arc<dyn ApartFromText>)
330            .with_value(value),
331    )
332}
333
334/// Returns the declaration of the command of the annotator numbered `number`:
335/// a macro of one argument, [`TEXT_ARG`], read by the feature's
336/// [`AnnotationParser`] and laid out as inline content or as paragraphs and
337/// blocks, according to its content; declared in text mode.
338fn annotation_def(owner: &FeatureName, annotator: &Annotator, number: usize) -> ElementDef {
339    let command = annotator.command.as_str();
340    ElementDef::new(
341        owner.clone(),
342        [command],
343        SyntaxDef::Macro {
344            args: vec![ArgDef::named(TEXT_ARG, AnnotationParser::new(command))
345                .layout(ArgLayout::InlineOrBlocks)
346                .docs("The passage highlighted, or the remark written.")],
347        },
348        annotation_element(annotator, number),
349    )
350    .docs(format!(
351        "Marks a passage or writes a remark, as annotator {number}: written with braces, or \
352         as `\\{command}` followed by the passage and `\\end{command}`, it highlights the \
353         passage; written with brackets, it writes the remark."
354    ))
355}
356
357/// The `annotations` feature ([`FlmFeature`]), constructed from an
358/// [`AnnotationsConfig`]: it declares one command per annotator and the
359/// lowering rules of an annotation. See the [module documentation](self).
360#[derive(Debug, Clone, Default)]
361pub struct AnnotationsFeature {
362    config: AnnotationsConfig,
363}
364
365impl AnnotationsFeature {
366    /// Returns the feature constructed from `config`, which stays fixed for
367    /// the life of the registry the feature is registered into.
368    ///
369    /// The configuration is checked when the feature registers: an invalid
370    /// one ([`AnnotationsConfig::validate`]) makes the registry build fail
371    /// with a [`BuildError::Feature`].
372    pub fn new(config: AnnotationsConfig) -> AnnotationsFeature {
373        AnnotationsFeature { config }
374    }
375
376    /// Returns the configuration this feature was constructed from.
377    pub fn config(&self) -> &AnnotationsConfig {
378        &self.config
379    }
380}
381
382impl FlmFeature for AnnotationsFeature {
383    fn info(&self) -> FeatureInfo {
384        FeatureInfo::new(FEATURE, "Annotations").docs(
385            "A reviewer's marks: one command per configured annotator, written `\\phf{…}` or \
386             `\\phf … \\endphf` for a highlighted passage and `\\phf[…]` for a remark, with \
387             `phf` the annotator's command.",
388        )
389    }
390
391    fn settings(&self) -> Option<SettingsDecl> {
392        Some(settings())
393    }
394
395    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
396        let owner = b.feature().clone();
397        self.config
398            .validate()
399            .map_err(|detail| BuildError::Feature { feature: owner.clone(), detail })?;
400        for (number, annotator) in self.config.annotators.iter().enumerate() {
401            b.element(annotation_def(&owner, annotator, number))?;
402        }
403        if !self.config.annotators.is_empty() {
404            b.element_type_text(
405                ANNOTATION,
406                "A reviewer's mark: a passage highlighted or a remark written, by one of the \
407                 configured annotators.",
408            )?;
409        }
410        // The element exists only where an annotator is configured, and a
411        // rule names a registered element.
412        if !self.config.annotators.is_empty() {
413            b.lowering_rule(
414                LoweringRule::new(RULE, ANNOTATION, lower::decl(), Arc::new(AnnotationRule), DefaultMark::Everywhere)
415                    .docs(
416                        "an annotation lowers to a `flm.pres.span` (or, for a cut part around one \
417                         block, a `flm.pres.block`) of the role `flm.annotations.highlight` or \
418                         `flm.annotations.comment`, with the kind tokens `<command>` and \
419                         `annotator-<n>`, holding the initials in a `flm.pres.deco.margin` on a \
420                         first cut part, then the passage or the remark; when annotations are hidden \
421                         (`hidden`), a highlight lowers to its passage alone and a comment to \
422                         nothing",
423                    ),
424            )?;
425            b.peer_backend(
426                text::BACKEND,
427                "the text backend, on which the annotation's rule \
428                 `flm.annotations.annotation.lower.text` is the default",
429            )?;
430            b.lowering_rule(
431                LoweringRule::new(
432                    TEXT_RULE,
433                    ANNOTATION,
434                    lower::decl(),
435                    Arc::new(AnnotationTextRule),
436                    DefaultMark::OnBackends(vec![text::BACKEND.into()]),
437                )
438                .docs(
439                    "an annotation lowers as under the general rule, except a comment: `[`, the \
440                     initials and `: ` are written as text before the remark and `]` after it, \
441                     with no decoration",
442                ),
443            )?;
444            html::register(b)?;
445            latex_rendered::register(b)?;
446            latex::register(b, &self.config.annotators)?;
447        }
448        b.digest_input(&self.config.digest_bytes())?;
449        Ok(())
450    }
451}
452
453/// Returns the [`AnnotationsFeature`] under the default configuration (no
454/// annotator, so no command), ready to be listed in a package entry.
455///
456/// To list the feature under an [`AnnotationsConfig`] of your own, use
457/// `Arc::new(AnnotationsFeature::new(config))`, or pass the configuration to
458/// the standard features with
459/// [`StdlibConfig::annotations`](crate::stdlib::StdlibConfig::annotations).
460pub fn feature() -> Arc<dyn FlmFeature> {
461    Arc::new(AnnotationsFeature::default())
462}