flm_core/stdlib/features/annotations/latex.rs
1//! The recomposition rule of the [`annotations`](super) feature on the
2//! `latex-recomposed` backend: an annotation is written back as the author
3//! wrote it, over the LaTeX package `phfcc`, which defines a reviewer's
4//! commands.
5//!
6//! | written | LaTeX |
7//! |---|---|
8//! | `\phf{a passage}` | `\phf{a passage}` |
9//! | `\phf[a remark]` | `\phf[a remark]` |
10//! | `\phf a passage\endphf` | `\phf a passage\endphf` |
11//! | `\phf[one⏎⏎two]` | `\phf[one⏎⏎two]`, one invocation |
12//!
13//! The rendering guide describes the same output for readers of the
14//! recomposed LaTeX
15//! ([Annotations in the recomposed LaTeX](crate::guide::rendering#annotations-in-the-recomposed-latex)).
16//!
17//! # The invocation as written
18//!
19//! The rule [`LATEX_RULE`] ([`AnnotationLatexRule`]) writes the command as it
20//! was written: the backslash and the name, and the whitespace that ended
21//! the name; then the whitespace and source comments written between the
22//! command and its opening `{` or `[`, the opening delimiter, the argument's
23//! content lowered through the ordinary rules, and the closing delimiter:
24//! `}`, `]`, or `\endphf` with the whitespace it read. A passage that was not
25//! closed is written with no closing command, as it was written. The
26//! delimiters are the ones the argument's group records (the annotation's
27//! [form](super::form_of) is read from the same record), so that the three
28//! forms come back as the author typed them. The command, the whitespace
29//! after it and the delimiters are written as raw nodes
30//! (`flm.pres.latex.raw`, LaTeX text written byte for byte).
31//!
32//! **An annotation across a paragraph break is one invocation.** The
33//! `latex-recomposed` backend lowers the tree before the block-structure
34//! pass, the pass that cuts an annotation into cut parts at its paragraph
35//! breaks and blocks. An annotation written across a paragraph
36//! break, or around a list, therefore reaches this rule as one node, with its
37//! paragraph breaks and blocks inside its argument, and is written back as
38//! typed: `\phf[A comment.⏎⏎With more.]` byte for byte, and `phfcc` colors
39//! the whole of it.
40//!
41//! # The commands, made by `phfcc`
42//!
43//! The rule requires the package request `flm.latex.pkg.phfcc`
44//! ([`packages::PHFCC`], with no option; a LaTeX package that a rule
45//! requires by identifier, [`packages`]). It also writes into the [style
46//! file](crate::stdlib::backends::latex::style),
47//! from the configuration, one declaration per configured annotator, in
48//! configuration order:
49//!
50//! ```latex
51//! \ifcsname phf\endcsname\else\phfMakeCommentingCommand[initials={PhF}]{phf}\fi
52//! \ifcsname abc\endcsname\else\phfMakeCommentingCommand[formatinitials=hide]{abc}\fi
53//! ```
54//!
55//! The package assigns its colors in the order in which the commands are
56//! made, so the declarations follow the annotators' numbers, the numbers by
57//! which the HTML stylesheet chooses its colors, and every configured
58//! annotator is declared, whether the document uses it or not. An annotator
59//! with initials passes them with the key `initials`, written as text; an
60//! annotator with none is made with `formatinitials=hide`, since the package
61//! would otherwise show the command's name. Each declaration is guarded on
62//! the command it makes ([`LatexDefinitionKind::Declaration`]): where the
63//! author's preamble already made a command of that name, that command is
64//! kept and the declaration does nothing. No LaTeX hook of the LaTeX family
65//! is involved: the package defines the commands.
66//!
67//! # Output when every annotation is hidden
68//!
69//! When [`AnnotationsRenderOptions::hidden`] is true, the rule writes no command, no
70//! package request and no declaration: a highlight lowers to its passage, and
71//! a comment to nothing but the paragraph breaks it held, so that the text
72//! around a comment written across a paragraph break remains two paragraphs.
73//! Hiding does not use the package's own switch,
74//! `\phfDisableCommentingCommands`: that switch makes every use of a
75//! commenting command an error, for a final version that must contain none,
76//! whereas hiding leaves the text clean.
77
78use std::sync::Arc;
79
80use techy::core::node::{BuildId, NodeRef};
81use techy::latexlike::InvocationSyntaxData;
82
83use crate::core::lowering::{
84 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
85};
86use crate::core::registry::{BuildError, FeatureBuilder};
87use crate::lang::{structural, Flm};
88use crate::model::element::element_value;
89use crate::model::names::{ElementName, Name};
90use crate::stdlib::backends::latex::construct::{DEFINITION, RAW};
91use crate::stdlib::backends::latex::{
92 packages, LatexDefinitionKind, LatexDefinitionPayload, LatexRawPayload,
93};
94use crate::stdlib::backends::latex_recomposed::BACKEND;
95use crate::stdlib::backends::lowering::lower_run;
96use crate::stdlib::backends::pres::BODY_SLOT;
97
98use super::config::{AnnotationsRenderOptions, Annotator};
99use super::parser::{delimiters_of, form_of, Form};
100use super::{AnnotationElement, ANNOTATION, FEATURE, TEXT_ARG};
101
102/// The name of the lowering rule of an annotation on the `latex-recomposed`
103/// backend, `flm.annotations.annotation.lower.latex-recomposed`
104/// ([`AnnotationLatexRule`]).
105pub const LATEX_RULE: &str = "flm.annotations.annotation.lower.latex-recomposed";
106
107/// The name of the command of the `phfcc` package that makes a reviewer's
108/// commenting command, `phfMakeCommentingCommand`.
109pub const MAKE_COMMAND: &str = "phfMakeCommentingCommand";
110
111/// The implementation of the lowering rule [`LATEX_RULE`], the default on the
112/// `latex-recomposed` backend: it writes an annotation back as the author
113/// wrote it, and stages the declarations of every configured annotator's
114/// command for the style file. See the [module documentation](self).
115///
116/// # Errors
117///
118/// [`LowerError`] when the node carries no [`AnnotationElement`] or no
119/// argument group, and
120/// any error from reading the render option or lowering the content.
121#[derive(Debug, Clone)]
122pub struct AnnotationLatexRule {
123 annotators: Arc<[Annotator]>,
124}
125
126impl AnnotationLatexRule {
127 /// Returns the rule for the configured `annotators`, given in
128 /// configuration order.
129 pub fn new(annotators: impl Into<Arc<[Annotator]>>) -> AnnotationLatexRule {
130 AnnotationLatexRule { annotators: annotators.into() }
131 }
132
133 /// Stages the declarations of every configured annotator's command, in
134 /// configuration order, each guarded on the command's name.
135 fn declarations(&self, cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer) -> Result<Vec<BuildId>, LowerError> {
136 let mut staged = Vec::with_capacity(self.annotators.len());
137 for annotator in self.annotators.iter() {
138 let command = annotator.command.as_str();
139 let body = match annotator.initials.as_deref() {
140 Some(initials) => vec![
141 raw(cx, lw, &format!("\\{MAKE_COMMAND}[initials={{"))?,
142 lw.text(cx, initials)?,
143 raw(cx, lw, &format!("}}]{{{command}}}"))?,
144 ],
145 None => vec![raw(cx, lw, &format!("\\{MAKE_COMMAND}[formatinitials=hide]{{{command}}}"))?],
146 };
147 let payload = LatexDefinitionPayload::new(LatexDefinitionKind::Declaration, command, 0)
148 .of_feature(FEATURE);
149 staged.push(lw.pres_slots_with(
150 cx,
151 &ElementName::from(DEFINITION),
152 payload,
153 vec![(String::from(BODY_SLOT), body)],
154 )?);
155 }
156 Ok(staged)
157 }
158}
159
160impl Lower for AnnotationLatexRule {
161 fn lower(
162 &self,
163 node: NodeRef<'_, Flm>,
164 cx: &mut LowerCx<'_>,
165 lw: &mut dyn Lowerer,
166 ) -> Result<Lowering, LowerError> {
167 if element_value::<AnnotationElement>(&node).is_none() {
168 return Err(LowerError::structure("an annotation without its element's data"));
169 }
170 let form = form_of(&node).ok_or_else(|| LowerError::structure("an annotation without its argument"))?;
171 if lw.option::<AnnotationsRenderOptions>()?.hidden {
172 return Ok(Lowering::Emit(match form {
173 Form::Highlight => lw.lower_arg_named(cx, &node, TEXT_ARG)?,
174 Form::Comment => paragraph_breaks(&node, cx, lw)?,
175 }));
176 }
177 let (open, close) =
178 delimiters_of(&node).ok_or_else(|| LowerError::structure("an annotation without its argument"))?;
179 lw.require(&Name::from(packages::PHFCC));
180 // Every annotation stages the declarations of every configured
181 // annotator; the emitter records each declaration once, so the style
182 // file holds them in configuration order whatever the document uses
183 // first.
184 let mut staged = self.declarations(cx, lw)?;
185 staged.push(raw(cx, lw, &command_as_written(&node))?);
186 staged.extend(before_group(&node, cx, lw)?);
187 if !open.is_empty() {
188 staged.push(raw(cx, lw, open)?);
189 }
190 staged.extend(lw.lower_arg_named(cx, &node, TEXT_ARG)?);
191 if !close.is_empty() {
192 staged.push(raw(cx, lw, close)?);
193 }
194 Ok(Lowering::Emit(staged))
195 }
196}
197
198/// Stages a raw node (`flm.pres.latex.raw`): LaTeX text written byte for
199/// byte.
200fn raw(cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer, text: &str) -> Result<BuildId, LowerError> {
201 lw.pres_with(cx, &ElementName::from(RAW), LatexRawPayload::new(text), Vec::new())
202}
203
204/// Returns the command of the annotation `node` as it was written: the escape
205/// character and the name, followed by the whitespace that ended the name,
206/// which belongs to the command (it separates the name from a passage that
207/// begins with a letter, `\phf passage`).
208fn command_as_written(node: &NodeRef<'_, Flm>) -> String {
209 let name = node.name().unwrap_or_default();
210 match node.invocation_syntax() {
211 Some(InvocationSyntaxData::Macro { escape_char, post_space }) => {
212 format!("{escape_char}{name}{}", post_space.resolve(node.span().source()))
213 }
214 _ => format!("\\{name}"),
215 }
216}
217
218/// Lowers what is written in the argument before its group, the whitespace
219/// and source comments between the command and an opening `{` or `[`, as the
220/// recomposed LaTeX writes whitespace and source comments anywhere.
221fn before_group(node: &NodeRef<'_, Flm>, cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer) -> Result<Vec<BuildId>, LowerError> {
222 let Some(region) = node.arguments().and_then(|arguments| arguments.get_named(TEXT_ARG)?.region.as_ref())
223 else {
224 return Ok(Vec::new());
225 };
226 let group = region.content_parent();
227 let noise: Vec<NodeRef<'_, Flm>> = node
228 .argument_nodes_named(TEXT_ARG)
229 .ok()
230 .flatten()
231 .map(|nodes| nodes.iter().take_while(|written| written.id() != group).collect())
232 .unwrap_or_default();
233 lower_run(cx, lw, &noise)
234}
235
236/// Lowers the paragraph breaks written directly in the argument of the
237/// comment `node`: what a hidden comment leaves of itself, so that the text
238/// around a comment written across a paragraph break remains two
239/// paragraphs.
240fn paragraph_breaks(node: &NodeRef<'_, Flm>, cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer) -> Result<Vec<BuildId>, LowerError> {
241 let Some(content) = node.argument_content_nodes_named(TEXT_ARG).ok().flatten() else {
242 return Ok(Vec::new());
243 };
244 let mut staged = Vec::new();
245 for written in content.iter() {
246 if written.ext().element.name.as_str() == structural::PARBREAK {
247 staged.extend(lower_run(cx, lw, std::slice::from_ref(&written))?);
248 }
249 }
250 Ok(staged)
251}
252
253/// Returns the lowering rule [`LATEX_RULE`], the default on the
254/// `latex-recomposed` backend only, which declares the commands of
255/// `annotators` in the style file.
256pub fn latex_rule(annotators: impl Into<Arc<[Annotator]>>) -> LoweringRule {
257 LoweringRule::new(
258 LATEX_RULE,
259 ANNOTATION,
260 LoweringDecl::new()
261 .option::<AnnotationsRenderOptions>()
262 .produces(DEFINITION)
263 .produces(RAW),
264 Arc::new(AnnotationLatexRule::new(annotators)),
265 DefaultMark::OnBackends(vec![BACKEND.into()]),
266 )
267 .docs(
268 "an annotation lowers to its invocation as written (the command, the opening delimiter, \
269 the content and the closing delimiter), one invocation even across a paragraph break, \
270 since the backend lowers the tree before the block-structure pass; it requires the \
271 `phfcc` package, and the style file makes every configured annotator's command with \
272 `\\phfMakeCommentingCommand`, guarded on its name; when annotations are hidden \
273 (`hidden`), a highlight lowers to its passage alone and a comment to its paragraph \
274 breaks",
275 )
276}
277
278/// Registers the lowering rule [`latex_rule`], the default on the
279/// `latex-recomposed` backend only, after a peer declaration
280/// ([`PeerName`](crate::core::registry::PeerName)) of the backend and of each
281/// construct element the rule stages, so that a registry without the LaTeX
282/// features still builds, with the rule set aside (excluded from rule
283/// selection; see [`PeerName`](crate::core::registry::PeerName)).
284///
285/// # Errors
286///
287/// The [`BuildError`] of the registry builder.
288pub(super) fn register(b: &mut FeatureBuilder<'_>, annotators: &[Annotator]) -> Result<(), BuildError> {
289 b.peer_backend(
290 BACKEND,
291 "the latex-recomposed backend, on which the annotation's rule \
292 `flm.annotations.annotation.lower.latex-recomposed` is the default",
293 )?;
294 b.peer_element::<LatexDefinitionPayload>(
295 DEFINITION,
296 "the LaTeX family's definition construct, which the annotation's rule stages for the \
297 declaration of each annotator's command",
298 )?;
299 b.peer_element::<LatexRawPayload>(
300 RAW,
301 "the LaTeX family's raw construct, in which the annotation's rule writes the command and \
302 the delimiters as written",
303 )?;
304 b.lowering_rule(latex_rule(annotators.to_vec()))
305}
306
307#[cfg(test)]
308mod tests {
309 use super::*;
310
311 #[test]
312 fn the_rule_is_the_default_on_the_latex_recomposed_backend_only() {
313 let rule = latex_rule(vec![Annotator::new("phf")]);
314 assert_eq!(rule.element, ANNOTATION);
315 assert!(rule.default.is_specific_to(&BACKEND.into()));
316 }
317}