Skip to main content

flm_core/stdlib/features/metadata/
latex.rs

1//! The lowering rules of the metadata's pieces on the `latex-recomposed` backend: the
2//! title, the authors and the date written back as the LaTeX text that a LaTeX
3//! document passes to `\title`, `\author` and `\date`.
4//!
5//! - The title and the date are their content, written back as LaTeX
6//!   ([`MetaTextLatexRule`]): `On \emph{flexible} markup`.
7//! - The authors are each author as a LaTeX author types one in `\author` with the
8//!   standard classes, the authors joined by LaTeX's `\and` ([`AuthorLatexRule`]).
9//!   An author ([`EntryLatexRule`]) is the name, then `\thanks{…}` for each note,
10//!   then each affiliation and the email address, each on a line of its own after
11//!   `\\`:
12//!
13//!   ```latex
14//!   Ada Lovelace\thanks{Corresponding author} \\ University of X \\ ada@example.com \and Grace Hopper
15//!   ```
16//!
17//!   The name and an affiliation are their content, written back as LaTeX
18//!   ([`MetaTextLatexRule`]); a note is `\thanks` around its content
19//!   ([`NoteLatexRule`]); the email address is its text ([`EmailLatexRule`]).
20//!
21//! The rules are the defaults on the `latex-recomposed` backend only. That backend
22//! places a piece only where the render options of the `pieces` feature list it, and
23//! leaves the piece out of its entry artifact (the file that stands for the output;
24//! [`ArtifactSet`](crate::core::artifact::ArtifactSet)) for the program to place ([pieces in the
25//! recomposed LaTeX](crate::guide::rendering#pieces-in-the-recomposed-latex)).
26//!
27//! The feature registers the rules with a peer declaration
28//! ([`PeerName`](crate::core::registry::PeerName)) of the backend and of the macro
29//! construct `flm.pres.latex.macro` the rules of the authors stage, so that a registry
30//! without the LaTeX features still builds, with the rules set aside (excluded from
31//! rule selection).
32
33use std::sync::Arc;
34
35use techy::core::node::{BuildId, NodeRef};
36
37use crate::core::lowering::{
38    DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
39};
40use crate::core::registry::{BuildError, FeatureBuilder};
41use crate::lang::Flm;
42use crate::model::names::ElementName;
43use crate::stdlib::backends::latex::construct::{ARG_SLOT, MACRO};
44use crate::stdlib::backends::latex::{LatexArgShape, LatexMacroPayload};
45use crate::stdlib::backends::latex_recomposed::BACKEND;
46
47use super::rules::{each_child, email_of, inline_content};
48use super::{AUTHOR, AUTHOR_AFFILIATION, AUTHOR_EMAIL, AUTHOR_ENTRY, AUTHOR_NAME, AUTHOR_NOTE, DATE, TITLE};
49
50/// The command that ends a line of an author, `\\`, without its backslash.
51const LINE_BREAK: &str = "\\";
52
53/// The command around a note about an author, `\thanks`, without its backslash.
54const THANKS: &str = "thanks";
55
56/// Returns the name of the lowering rule of the element `element` on the
57/// `latex-recomposed` backend, `<element>.lower.latex-recomposed`.
58pub fn latex_rule_name(element: &str) -> String {
59    format!("{element}.lower.latex-recomposed")
60}
61
62/// Returns a call of the command `name` with no argument.
63fn command(cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer, name: &str) -> Result<BuildId, LowerError> {
64    lw.pres_slots_with(cx, &ElementName::from(MACRO), LatexMacroPayload::new(name, []), Vec::new())
65}
66
67/// The lowering rule of the title, of the date, of an author's name and of an
68/// affiliation on the `latex-recomposed` backend: the content, written back as
69/// LaTeX.
70#[derive(Debug, Default)]
71pub struct MetaTextLatexRule;
72
73impl Lower for MetaTextLatexRule {
74    fn lower(
75        &self,
76        node: NodeRef<'_, Flm>,
77        cx: &mut LowerCx<'_>,
78        lw: &mut dyn Lowerer,
79    ) -> Result<Lowering, LowerError> {
80        Ok(Lowering::Emit(inline_content(&node, cx, lw)?))
81    }
82}
83
84/// The lowering rule of the authors on the `latex-recomposed` backend: each
85/// author, lowered through its rule ([`EntryLatexRule`]), the authors joined by
86/// ` \and `.
87#[derive(Debug, Default)]
88pub struct AuthorLatexRule;
89
90impl Lower for AuthorLatexRule {
91    fn lower(
92        &self,
93        node: NodeRef<'_, Flm>,
94        cx: &mut LowerCx<'_>,
95        lw: &mut dyn Lowerer,
96    ) -> Result<Lowering, LowerError> {
97        let mut joined = Vec::new();
98        for one in each_child(&node)? {
99            if !joined.is_empty() {
100                joined.push(lw.text(cx, " ")?);
101                joined.push(command(cx, lw, "and")?);
102                joined.push(lw.text(cx, " ")?);
103            }
104            joined.extend(lw.lower_nodes(cx, one)?);
105        }
106        Ok(Lowering::Emit(joined))
107    }
108}
109
110/// The lowering rule of one author on the `latex-recomposed` backend: the name,
111/// then each note, then each affiliation and the email address after ` \\ `, each
112/// part lowered through its rule.
113#[derive(Debug, Default)]
114pub struct EntryLatexRule;
115
116impl Lower for EntryLatexRule {
117    fn lower(
118        &self,
119        node: NodeRef<'_, Flm>,
120        cx: &mut LowerCx<'_>,
121        lw: &mut dyn Lowerer,
122    ) -> Result<Lowering, LowerError> {
123        let mut name = Vec::new();
124        let mut notes = Vec::new();
125        let mut lines = Vec::new();
126        for (one, child) in each_child(&node)?.into_iter().zip(node.children().iter()) {
127            let part = lw.lower_nodes(cx, one)?;
128            match child.ext().element.name.as_str() {
129                AUTHOR_NOTE => notes.extend(part),
130                AUTHOR_AFFILIATION | AUTHOR_EMAIL => lines.push(part),
131                _ => name.extend(part),
132            }
133        }
134        let mut written = name;
135        written.extend(notes);
136        for line in lines {
137            written.push(lw.text(cx, " ")?);
138            written.push(command(cx, lw, LINE_BREAK)?);
139            written.push(lw.text(cx, " ")?);
140            written.extend(line);
141        }
142        Ok(Lowering::Emit(written))
143    }
144}
145
146/// The lowering rule of a note about an author on the `latex-recomposed` backend:
147/// `\thanks{…}` around the note's content, written back as LaTeX.
148#[derive(Debug, Default)]
149pub struct NoteLatexRule;
150
151impl Lower for NoteLatexRule {
152    fn lower(
153        &self,
154        node: NodeRef<'_, Flm>,
155        cx: &mut LowerCx<'_>,
156        lw: &mut dyn Lowerer,
157    ) -> Result<Lowering, LowerError> {
158        let content = inline_content(&node, cx, lw)?;
159        let thanks = LatexMacroPayload::new(THANKS, [LatexArgShape::Mandatory]);
160        let call = lw.pres_slots_with(cx, &ElementName::from(MACRO), thanks, vec![(String::from(ARG_SLOT), content)])?;
161        Ok(Lowering::Emit(vec![call]))
162    }
163}
164
165/// The lowering rule of an author's email address on the `latex-recomposed`
166/// backend: the address, as text.
167#[derive(Debug, Default)]
168pub struct EmailLatexRule;
169
170impl Lower for EmailLatexRule {
171    fn lower(
172        &self,
173        node: NodeRef<'_, Flm>,
174        cx: &mut LowerCx<'_>,
175        lw: &mut dyn Lowerer,
176    ) -> Result<Lowering, LowerError> {
177        let address = email_of(&node)?;
178        Ok(Lowering::Emit(vec![lw.text(cx, address)?]))
179    }
180}
181
182/// Registers the rules, with the peer declarations of the backend and of the macro
183/// construct they need.
184pub(super) fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
185    b.peer_backend(
186        BACKEND,
187        "the latex-recomposed backend, on which the metadata's LaTeX rules are the default",
188    )?;
189    b.peer_element::<LatexMacroPayload>(
190        MACRO,
191        "the LaTeX family's macro-call construct, which the rules of the authors stage for `\\and`, `\\\\` \
192         and `\\thanks`",
193    )?;
194    let on_backend = || DefaultMark::OnBackends(vec![BACKEND.into()]);
195    for element in [TITLE, DATE, AUTHOR_NAME, AUTHOR_AFFILIATION] {
196        b.lowering_rule(
197            LoweringRule::new(
198                latex_rule_name(element),
199                element,
200                LoweringDecl::new(),
201                Arc::new(MetaTextLatexRule),
202                on_backend(),
203            )
204            .docs(format!("on the recomposed LaTeX, `{element}` is its content, written back as LaTeX")),
205        )?;
206    }
207    let rules: [(&str, Arc<dyn Lower>, &str); 4] = [
208        (AUTHOR, Arc::new(AuthorLatexRule), "on the recomposed LaTeX, the authors are each author, joined by `\\and`"),
209        (
210            AUTHOR_ENTRY,
211            Arc::new(EntryLatexRule),
212            "on the recomposed LaTeX, an author is the name, each note, then each affiliation and the email \
213             address after `\\\\`",
214        ),
215        (AUTHOR_NOTE, Arc::new(NoteLatexRule), "on the recomposed LaTeX, a note is `\\thanks` around its content"),
216        (AUTHOR_EMAIL, Arc::new(EmailLatexRule), "on the recomposed LaTeX, an email address is its text"),
217    ];
218    for (element, rule, docs) in rules {
219        let decl = if element == AUTHOR_EMAIL { LoweringDecl::new() } else { LoweringDecl::new().produces(MACRO) };
220        b.lowering_rule(LoweringRule::new(latex_rule_name(element), element, decl, rule, on_backend()).docs(docs))?;
221    }
222    Ok(())
223}