Skip to main content

flm_core/stdlib/features/verbatim/
latex.rs

1//! The recomposition rules of the [`verbatim`](super) feature for the
2//! `latex-recomposed` backend: the five verbatim commands written back as LaTeX.
3//!
4//! Verbatim content must reach LaTeX unchanged, including inside a *moving
5//! argument*, such as a section title or a caption, which LaTeX writes to an
6//! auxiliary file and reads back, and where LaTeX's own `\verb` cannot be used.
7//! Both rules therefore write what the `\EscVerb` command of the `fvextra`
8//! package reads: an ordinary braced argument in which every printable ASCII
9//! character other than a letter, a digit or `@` is preceded by a backslash
10//! (`fvextra` rejects `\@`; see
11//! [`escverb_encode`](crate::stdlib::backends::latex::sink::escverb_encode)). The
12//! rules do not encode the content themselves: they stage (build into the
13//! lowered tree; see [`Lowerer`]) the content
14//! unchanged in an argument of the shape [`EscVerb`](LatexArgShape::EscVerb), and
15//! the backend's emitter writes it in that encoding.
16//!
17//! | written | rule | LaTeX |
18//! |---|---|---|
19//! | `\verbtext{…}`, `\verbcode[lang]{…}`, `\verba[lang]{…}` | [`MACRO_LATEX_RULE`] | `\EscVerb[fontfamily=\flmVRBFamily,formatcom=\flmFmtVRB{<kind>}]{<content>}` |
20//! | `{verbatimtext}` (inline) | [`ENVIRONMENT_LATEX_RULE`] | the same, with `<kind>` = `verbtext` |
21//! | `{verbatimcode}[lang]` (a block) | [`ENVIRONMENT_LATEX_RULE`] | `\begin{flmVerbatimCode}[<lang>]`, the content on lines of its own, `\end{flmVerbatimCode}` |
22//!
23//! `<kind>` is `verbtext`, `verbcode` or `verba`, after the macro of the verbatim
24//! kind. `\flmFmtVRB{<kind>}` runs that kind's formatting hook,
25//! `\flmFmtVRB<kind>`, which a user redefines to change how that kind is set (see
26//! [`verbatim`](super), *What a verbatim command becomes on each backend*). The
27//! option `fontfamily=\flmVRBFamily` makes `fancyvrb` keep the font family of the
28//! surrounding text, so that the formatting hook alone sets the font of each
29//! kind: `\verbtext` content looks like the surrounding text, `\verba` content is
30//! in italics and `\verbcode` content is in the typewriter family. The
31//! language of a block is written as the optional argument of `flmVerbatimCode`,
32//! which hands it to the LaTeX hook `\flmVerbatimCodeSetup{<lang>}`. The language
33//! of `\verbcode[lang]` and `\verba[lang]` is not written.
34//!
35//! The formatting hooks, `\flmVRBFamily`, the environment `flmVerbatimCode` and
36//! `\flmVerbatimCodeSetup` are defined by the definition piece
37//! [`VERBATIM`](crate::stdlib::backends::latex::preamble::VERBATIM)
38//! (`flm.latex.def.verbatim`; a definition piece is a unit of LaTeX definitions
39//! written to the style file when a rule requires it, see
40//! [`LatexPreambleDef`](crate::stdlib::backends::latex::LatexPreambleDef)). Both
41//! rules require that piece and request the LaTeX package `fvextra`
42//! ([`FVEXTRA`](packages::FVEXTRA); a package request, see [`packages`]).
43//!
44//! The options `fontfamily=\flmVRBFamily,formatcom=\flmFmtVRB{<kind>}` are staged
45//! as one raw node, a construct element whose text the emitter writes byte for
46//! byte ([`flm.pres.latex.raw`](crate::stdlib::backends::latex::construct::RAW)),
47//! because they are a list of keys and values that LaTeX must read without a
48//! brace group around it. Both rules are the default on the `latex-recomposed` backend
49//! only.
50//!
51//! The feature does not own the backend or the three construct elements the
52//! rules stage. [`register`] declares them as peer declarations
53//! ([`PeerName`](crate::core::registry::PeerName)), so that a registry without
54//! the LaTeX features still builds; the two rules are then set aside (excluded
55//! from rule selection; see [`PeerName`](crate::core::registry::PeerName)).
56
57use std::sync::Arc;
58
59use techy::core::node::{BuildId, NodeRef};
60
61use crate::core::lowering::{
62    DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
63};
64use crate::core::registry::{BuildError, FeatureBuilder};
65use crate::lang::{Flm, FlmGroupType};
66use crate::model::element::element_value;
67use crate::model::names::{ElementName, Name};
68use crate::stdlib::backends::latex::construct::{
69    ARG_SLOT, ENVIRONMENT as LATEX_ENVIRONMENT, MACRO, RAW,
70};
71use crate::stdlib::backends::latex::{
72    LatexArgShape, LatexEnvironmentPayload, LatexMacroPayload, LatexRawPayload, packages,
73    preamble,
74};
75use crate::stdlib::backends::latex_recomposed::BACKEND;
76use crate::stdlib::backends::lowering::{copy_subtree_verbatim, stage_verbatim_content};
77use crate::stdlib::backends::pres::{BODY_SLOT, VerbatimKind};
78
79use super::{CONTENT_ARG, ENVIRONMENT, LANG_ARG, MACRO as VERBATIM_MACRO, VerbatimCallable};
80
81/// The name of the recomposition rule of `flm.verbatim.macro`,
82/// `flm.verbatim.macro.lower.latex-recomposed`, whose body is
83/// [`MacroLatexRule`].
84pub const MACRO_LATEX_RULE: &str = "flm.verbatim.macro.lower.latex-recomposed";
85
86/// The name of the recomposition rule of `flm.verbatim.environment`,
87/// `flm.verbatim.environment.lower.latex-recomposed`, whose body is
88/// [`EnvironmentLatexRule`].
89pub const ENVIRONMENT_LATEX_RULE: &str = "flm.verbatim.environment.lower.latex-recomposed";
90
91/// Records the two requirements of every verbatim command: the package
92/// request `fvextra` and the definition piece `flm.latex.def.verbatim`.
93fn require_verbatim(lw: &mut dyn Lowerer) {
94    lw.require(&Name::from(packages::FVEXTRA));
95    lw.require(&Name::from(preamble::VERBATIM));
96}
97
98/// Stages `\EscVerb[fontfamily=\flmVRBFamily,formatcom=\flmFmtVRB{<kind>}]{<content>}`
99/// over `content`, for the verbatim kind `kind`.
100fn escverb(
101    cx: &mut LowerCx<'_>,
102    lw: &mut dyn Lowerer,
103    kind: VerbatimKind,
104    content: Vec<BuildId>,
105) -> Result<BuildId, LowerError> {
106    let options = lw.pres_with(
107        cx,
108        &ElementName::from(RAW),
109        LatexRawPayload::new(preamble::escverb_options(kind)),
110        Vec::new(),
111    )?;
112    lw.pres_slots_with(
113        cx,
114        &ElementName::from(MACRO),
115        LatexMacroPayload::new(preamble::ESCVERB, [LatexArgShape::Optional, LatexArgShape::EscVerb]),
116        vec![(String::from(ARG_SLOT), vec![options]), (String::from(ARG_SLOT), content)],
117    )
118}
119
120/// The body of [`MACRO_LATEX_RULE`]: `\EscVerb` over the characters of the
121/// macro's content argument.
122///
123/// When the content argument is missing (a parse recovery left it absent and
124/// the parse reported it), `\EscVerb` is written with an empty argument and
125/// nothing more is reported. The rule returns a [`LowerError`] when the node
126/// carries no [`VerbatimCallable`] or when a node could not be staged.
127#[derive(Debug, Default, Clone, Copy)]
128pub struct MacroLatexRule;
129
130impl Lower for MacroLatexRule {
131    fn lower(
132        &self,
133        node: NodeRef<'_, Flm>,
134        cx: &mut LowerCx<'_>,
135        lw: &mut dyn Lowerer,
136    ) -> Result<Lowering, LowerError> {
137        let value = element_value::<VerbatimCallable>(&node)
138            .ok_or_else(|| LowerError::structure("a verbatim node without its element's data"))?;
139        let content = match node.argument_content_nodes_named(CONTENT_ARG) {
140            Ok(Some(content)) => stage_verbatim_content(&node, content, cx, lw)?,
141            _ => Vec::new(),
142        };
143        require_verbatim(lw);
144        Ok(Lowering::Emit(vec![escverb(cx, lw, value.kind, content)?]))
145    }
146}
147
148/// The body of [`ENVIRONMENT_LATEX_RULE`]: `\EscVerb` over the body of an
149/// inline environment (`{verbatimtext}`), the environment `flmVerbatimCode`
150/// over the body of a block (`{verbatimcode}`).
151///
152/// The body of a verbatim environment holds the group node of the verbatim
153/// class that the parse puts around every verbatim run; the rule copies that
154/// group's children, not the group itself. The rule returns a [`LowerError`]
155/// when the node carries no [`VerbatimCallable`] or when a node could not be
156/// staged.
157#[derive(Debug, Default, Clone, Copy)]
158pub struct EnvironmentLatexRule;
159
160impl Lower for EnvironmentLatexRule {
161    fn lower(
162        &self,
163        node: NodeRef<'_, Flm>,
164        cx: &mut LowerCx<'_>,
165        lw: &mut dyn Lowerer,
166    ) -> Result<Lowering, LowerError> {
167        let value = element_value::<VerbatimCallable>(&node)
168            .ok_or_else(|| LowerError::structure("a verbatim node without its element's data"))?;
169        let mut content = Vec::new();
170        if let Some(body) = node.body() {
171            for child in body.iter() {
172                if child.group_type() == Some(FlmGroupType::Verbatim) {
173                    content.extend(stage_verbatim_content(&node, child.children(), cx, lw)?);
174                } else {
175                    content.push(copy_subtree_verbatim(cx, child)?);
176                }
177            }
178        }
179        require_verbatim(lw);
180        if !value.block {
181            return Ok(Lowering::Emit(vec![escverb(cx, lw, value.kind, content)?]));
182        }
183        // The optional argument is always written, `[<lang>]` or `[]`.
184        // LaTeX looks for an absent optional argument by reading ahead past
185        // spaces, and the line end after `\begin{flmVerbatimCode}` is one:
186        // without the brackets that lookahead swallows it, and `fancyvrb`,
187        // which needs the verbatim content to begin on the next line, stops
188        // with "Extraneous input ... between \begin{flmVerbatimCode}[<key=value>]
189        // and line end". One shape for every block also makes a user's own
190        // `flmVerbatimCode`, defined the natural way with an optional
191        // argument, work.
192        let shapes = vec![LatexArgShape::Optional];
193        let mut slots = Vec::new();
194        let lang = language_slot(&node, cx, lw)?;
195        slots.push((String::from(ARG_SLOT), lang));
196        slots.push((String::from(BODY_SLOT), content));
197        let block = lw.pres_slots_with(
198            cx,
199            &ElementName::from(LATEX_ENVIRONMENT),
200            LatexEnvironmentPayload::new(preamble::VERBATIM_CODE_ENVIRONMENT, shapes).verbatim(),
201            slots,
202        )?;
203        Ok(Lowering::Emit(vec![block]))
204    }
205}
206
207/// The content of the optional argument of `flmVerbatimCode`: the language
208/// the document wrote, trimmed, or the content a user definition's template
209/// wrote there.
210///
211/// A language the document writes is plain text. It is written as
212/// [`language_of`](super::language_of) reads it, trimmed of the whitespace
213/// around it, a blank language being no language at all; every other backend
214/// reads it through the same function, so one document gives one language on
215/// every backend.
216///
217/// A language argument holding anything other than text comes from the
218/// template of a user definition kept as a LaTeX definition, which may place
219/// one of the definition's arguments there (`\begin{verbatimcode}[#{lang}]`).
220/// Such an argument is lowered as content, so that the placeholder is written
221/// as the definition's parameter and the language reaches the environment
222/// where the definition is called; read as text, it would be written as
223/// nothing and the language would be lost. The rest of what the template
224/// wrote in the argument is written as the template wrote it.
225///
226/// An absent argument gives an empty argument. The caller writes the brackets
227/// in every case.
228fn language_slot(
229    node: &NodeRef<'_, Flm>,
230    cx: &mut LowerCx<'_>,
231    lw: &mut dyn Lowerer,
232) -> Result<Vec<BuildId>, LowerError> {
233    let Ok(Some(content)) = node.argument_content_nodes_named(LANG_ARG) else {
234        return Ok(Vec::new());
235    };
236    if content.iter().all(|child| child.chars().is_some()) {
237        return match super::language_of(node) {
238            Some(lang) => Ok(vec![lw.text(cx, &lang)?]),
239            None => Ok(Vec::new()),
240        };
241    }
242    lw.lower_nodes(cx, content)
243}
244
245/// The two recomposition rules, ready to be registered: each produces the
246/// macro, environment and raw constructs and is the default on the
247/// `latex-recomposed` backend only.
248pub fn latex_rules() -> Vec<LoweringRule> {
249    let decl = || LoweringDecl::new().produces(MACRO).produces(LATEX_ENVIRONMENT).produces(RAW);
250    let on_this_backend = || DefaultMark::OnBackends(vec![BACKEND.into()]);
251    vec![
252        LoweringRule::new(
253            MACRO_LATEX_RULE,
254            VERBATIM_MACRO,
255            decl(),
256            Arc::new(MacroLatexRule),
257            on_this_backend(),
258        )
259        .docs(
260            "a verbatim macro lowers to `\\EscVerb` over its content, in the encoding \
261             `\\EscVerb` reads",
262        ),
263        LoweringRule::new(
264            ENVIRONMENT_LATEX_RULE,
265            ENVIRONMENT,
266            decl(),
267            Arc::new(EnvironmentLatexRule),
268            on_this_backend(),
269        )
270        .docs(
271            "an inline verbatim environment lowers to `\\EscVerb` over its content; a block \
272             lowers to the `flmVerbatimCode` environment over its content",
273        ),
274    ]
275}
276
277/// Registers what the `verbatim` feature contributes to the
278/// `latex-recomposed` backend: a peer declaration
279/// ([`PeerName`](crate::core::registry::PeerName)) of the backend and of the
280/// macro, environment and raw constructs, each with its payload type, then
281/// [`latex_rules`].
282///
283/// In a registry without the LaTeX features the peer declarations resolve to
284/// nothing and the rules are set aside (excluded from rule selection); the
285/// registry still builds.
286///
287/// # Errors
288///
289/// Returns the [`BuildError`] the feature builder raises, for instance for a
290/// rule already registered under the same name.
291pub fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
292    b.peer_backend(
293        BACKEND,
294        "the latex-recomposed backend, on which the recomposition rules of the verbatim \
295         commands are the default",
296    )?;
297    b.peer_element::<LatexMacroPayload>(
298        MACRO,
299        "the LaTeX family's macro construct, which the recomposition rules of the verbatim \
300         commands stage",
301    )?;
302    b.peer_element::<LatexEnvironmentPayload>(
303        LATEX_ENVIRONMENT,
304        "the LaTeX family's environment construct, which the recomposition rules of the \
305         verbatim commands stage",
306    )?;
307    b.peer_element::<LatexRawPayload>(
308        RAW,
309        "the LaTeX family's raw construct, which the recomposition rules of the verbatim \
310         commands stage",
311    )?;
312    for rule in latex_rules() {
313        b.lowering_rule(rule)?;
314    }
315    Ok(())
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321
322    #[test]
323    fn both_rules_are_the_default_on_the_recomposed_backend_only() {
324        let rules = latex_rules();
325        assert_eq!(rules[0].name, MACRO_LATEX_RULE);
326        assert_eq!(rules[0].element, VERBATIM_MACRO);
327        assert_eq!(rules[1].name, ENVIRONMENT_LATEX_RULE);
328        assert_eq!(rules[1].element, ENVIRONMENT);
329        for rule in &rules {
330            assert!(rule.default.is_specific_to(&BACKEND.into()));
331            assert_eq!(rule.decl.produces.len(), 3);
332        }
333    }
334}