Skip to main content

flm_core/stdlib/features/graphics/
latex.rs

1//! The lowering rule of the [`graphics`](super) feature for the
2//! `latex-recomposed` backend, which writes an image as the LaTeX hook
3//! `\flmIncludeGraphics`, and the feature's definition piece, which defines
4//! that hook.
5//!
6//! | written | LaTeX |
7//! |---|---|
8//! | `\includegraphics{figures/plot.png}` | `\flmIncludeGraphics{figures/plot.png}` |
9//! | `\includegraphics[width=5cm]{plot.png}` | `\flmIncludeGraphics[width=5cm]{plot.png}` (with no inspector) |
10//! | `\includegraphics[width=10pt]{plot.png}` | `\flmIncludeGraphics[width=10bp]{plot.png}` (with no inspector) |
11//!
12//! # The LaTeX hook
13//!
14//! A LaTeX hook is a macro that the recomposed LaTeX writes and the style
15//! file defines with a plain default, which a user redefines in the
16//! document's preamble ([LaTeX hooks](crate::stdlib::backends::latex::preamble);
17//! [the LaTeX hooks](crate::guide::rendering#the-latex-hooks) in the rendering
18//! guide). The rule [`LATEX_RULE`] ([`ImageLatexRule`]) writes an image as
19//! `\flmIncludeGraphics[<keys>]{<path>}` ([`HOOK_COMMAND`]):
20//!
21//! - `<keys>` are `width=<length>` and `height=<length>` where the image is
22//!   shown at a set size, the size being decided as on every output
23//!   ([`shown_size`](super::rules::shown_size)): the options, one dimension
24//!   scaled from the inspected size where only the other is given, else the
25//!   inspected size, each multiplied by the output's magnification. Each length is written by [`stage_length`], the LaTeX
26//!   family's only way of writing a length, which writes a point (1/72 inch)
27//!   as LaTeX's big point `bp`. The optional argument is left out where there
28//!   is no key.
29//! - `<path>` is the published address (the path as written, under the
30//!   strategy `reference`), escaped as the LaTeX family escapes an address
31//!   ([`escape_url`]).
32//!
33//! The path is read as characters, so a user definition whose template holds
34//! a placeholder in a path is not written as a LaTeX definition: each of its
35//! use sites is expanded instead. The alternative text is not written,
36//! because LaTeX's `\includegraphics` has no place for it.
37//!
38//! # The definition piece
39//!
40//! A definition piece ([`LatexPreambleDef`]) is a unit of LaTeX definitions
41//! that a feature registers under an identifier `flm.latex.def.<name>`; a
42//! lowering rule requires it by identifier, and the style file holds the text
43//! of every piece the document requires. The feature's piece, [`PIECE`]
44//! (`flm.latex.def.graphics`, [`definition_piece`]), defines the LaTeX hook with
45//! `\ProvideDocumentCommand` as `\includegraphics[max width=\linewidth,#1]{#2}`,
46//! so that an image is never wider than the line. The piece requests the
47//! LaTeX packages `graphicx` and `adjustbox`, the latter with its option
48//! `export`, which makes `max width` a key of `\includegraphics` ([package
49//! requests](crate::stdlib::backends::latex::packages)). A user who wants
50//! another default redefines the LaTeX hook, before or after loading the style
51//! file. The rendering guide shows the result ([images in the recomposed
52//! LaTeX](crate::guide::rendering#images-in-the-recomposed-latex)).
53
54use std::sync::Arc;
55
56use techy::core::node::{BuildId, NodeRef};
57
58use crate::core::lowering::{
59    DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
60};
61use crate::core::registry::{BuildError, FeatureBuilder};
62use crate::lang::Flm;
63use crate::model::names::{ElementName, Name};
64use crate::stdlib::backends::latex::construct::{ARG_SLOT, MACRO, RAW};
65use crate::stdlib::backends::latex::preamble::stage_length;
66use crate::stdlib::backends::latex::{
67    LatexArgShape, LatexMacroPayload, LatexPreambleDef, LatexRawPayload, escape_url, packages,
68    preamble,
69};
70use crate::stdlib::backends::latex_recomposed::BACKEND;
71use crate::stdlib::backends::pres::Length;
72
73use super::inspect::INFO;
74use super::options::{HEIGHT_KEY, WIDTH_KEY};
75use super::publish::published_table;
76use super::rules::read_image;
77use super::strategy::GraphicsRenderOptions;
78use super::IMAGE_ELEMENT;
79
80/// The name of the image's rule on the `latex-recomposed` backend,
81/// `flm.graphics.image.lower.latex-recomposed`, whose body is
82/// [`ImageLatexRule`].
83pub const LATEX_RULE: &str = "flm.graphics.image.lower.latex-recomposed";
84
85/// The name of the feature's definition piece, `graphics`; its identifier is
86/// `flm.latex.def.graphics` ([`PIECE`]).
87pub const PIECE_NAME: &str = "graphics";
88
89/// The identifier of the feature's definition piece, `flm.latex.def.graphics`
90/// ([`definition_piece`]).
91pub const PIECE: &str = "flm.latex.def.graphics";
92
93/// The name of the LaTeX hook an image is written as, `flmIncludeGraphics`.
94pub const HOOK_COMMAND: &str = "flmIncludeGraphics";
95
96/// Returns the feature's definition piece, `flm.latex.def.graphics`, which
97/// defines the LaTeX hook `\flmIncludeGraphics[<keys>]{<path>}` with
98/// `\ProvideDocumentCommand` as
99/// `\includegraphics[max width=\linewidth,#1]{#2}`. It requests the LaTeX
100/// packages `graphicx` ([`packages::GRAPHICX`]) and `adjustbox` with its
101/// option `export` ([`packages::ADJUSTBOX`]). Redefine the LaTeX hook, before or
102/// after loading the style file, to show images another way.
103pub fn definition_piece() -> LatexPreambleDef {
104    LatexPreambleDef::new(
105        PIECE_NAME,
106        "\
107% An image, as FLM's \\includegraphics writes it:
108% \\flmIncludeGraphics[<keys>]{<path>}, <keys> being width=<length> and
109% height=<length> where the image is shown at a set size, <path> an ordinary
110% argument in which the characters # % \\ are written \\# \\% \\\\.
111% The image never runs wider than the line (max width, a key adjustbox adds to
112% \\includegraphics). Redefine the hook to show images another way.
113\\ProvideDocumentCommand\\flmIncludeGraphics{O{} m}{\\includegraphics[max width=\\linewidth,#1]{#2}}
114",
115        "`\\flmIncludeGraphics[keys]{path}`: the LaTeX hook an image is written as, \
116         `\\includegraphics` kept within the line's width",
117    )
118    .requires([packages::GRAPHICX, packages::ADJUSTBOX])
119}
120
121/// The body of [`LATEX_RULE`]: it stages the LaTeX hook `\flmIncludeGraphics`, with
122/// the image's size as keys where the image has one, and its published
123/// address escaped by [`escape_url`]. See the [module documentation](self).
124#[derive(Debug, Default, Clone, Copy)]
125pub struct ImageLatexRule;
126
127impl Lower for ImageLatexRule {
128    fn lower(
129        &self,
130        node: NodeRef<'_, Flm>,
131        cx: &mut LowerCx<'_>,
132        lw: &mut dyn Lowerer,
133    ) -> Result<Lowering, LowerError> {
134        let (src, (width, height)) = {
135            let Some(image) = read_image(&node, BACKEND, lw)? else {
136                return Ok(Lowering::Emit(Vec::new()));
137            };
138            (image.published.src.clone(), image.size)
139        };
140        let mut shapes = Vec::new();
141        let mut slots = Vec::new();
142        let keys = keys(cx, lw, width.as_ref(), height.as_ref())?;
143        if !keys.is_empty() {
144            shapes.push(LatexArgShape::Optional);
145            slots.push(keys);
146        }
147        shapes.push(LatexArgShape::Mandatory);
148        slots.push(raw(cx, lw, &escape_url(&src))?);
149        lw.require(&Name::from(PIECE));
150        let hook = lw.pres_slots_with(
151            cx,
152            &ElementName::from(MACRO),
153            LatexMacroPayload::new(HOOK_COMMAND, shapes),
154            slots.into_iter().map(|slot| (String::from(ARG_SLOT), slot)).collect(),
155        )?;
156        Ok(Lowering::Emit(vec![hook]))
157    }
158}
159
160/// Stages `text` as one raw node (`flm.pres.latex.raw`); stages nothing
161/// where `text` is empty.
162fn raw(cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer, text: &str) -> Result<Vec<BuildId>, LowerError> {
163    if text.is_empty() {
164        return Ok(Vec::new());
165    }
166    Ok(vec![lw.pres_with(cx, &ElementName::from(RAW), LatexRawPayload::new(text), Vec::new())?])
167}
168
169/// Stages the keys of the LaTeX hook `\flmIncludeGraphics`: `width=<length>`
170/// and `height=<length>` for those set, separated by a comma, each length
171/// written by [`stage_length`].
172fn keys(
173    cx: &mut LowerCx<'_>,
174    lw: &mut dyn Lowerer,
175    width: Option<&Length>,
176    height: Option<&Length>,
177) -> Result<Vec<BuildId>, LowerError> {
178    let mut nodes = Vec::new();
179    for (key, length) in [(WIDTH_KEY, width), (HEIGHT_KEY, height)] {
180        let Some(length) = length else { continue };
181        let lead = if nodes.is_empty() { format!("{key}=") } else { format!(",{key}=") };
182        nodes.extend(raw(cx, lw, &lead)?);
183        nodes.push(stage_length(cx, lw, length)?);
184    }
185    Ok(nodes)
186}
187
188/// Returns the image's rule on the `latex-recomposed` backend,
189/// [`LATEX_RULE`], the default on that backend only. It reads the table of
190/// records [`INFO`], the backend's published table and the render options
191/// [`GraphicsRenderOptions`] (for the magnification).
192pub fn latex_rule() -> LoweringRule {
193    LoweringRule::new(
194        LATEX_RULE,
195        IMAGE_ELEMENT,
196        LoweringDecl::new()
197            .reads(INFO)
198            .reads(published_table(BACKEND))
199            .option::<GraphicsRenderOptions>()
200            .produces(MACRO)
201            .produces(RAW),
202        Arc::new(ImageLatexRule),
203        DefaultMark::OnBackends(vec![BACKEND.into()]),
204    )
205    .docs(
206        "an image lowers to the LaTeX hook `\\flmIncludeGraphics`, with its size as keys where it \
207         has one, and its escaped address",
208    )
209}
210
211/// Registers the image's rule on the `latex-recomposed` backend and
212/// contributes the definition piece to the service slot of definition pieces
213/// ([`preamble::SLOT`]), with peer declarations of the names that the LaTeX
214/// features own (the backend, the macro construct and the raw construct). A
215/// peer declaration ([`PeerName`](crate::core::registry::PeerName)) tells the
216/// registry build that another feature owns a name, so the feature builds in
217/// a registry without the LaTeX features, with its rule set aside (excluded
218/// from rule selection; see [`PeerName`](crate::core::registry::PeerName)).
219///
220/// # Errors
221///
222/// The [`BuildError`] of the registry builder when a declaration is made
223/// outside the registration round that accepts it (see
224/// [`Finalizer`](crate::core::registry::Finalizer)).
225pub(super) fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
226    b.peer_backend(
227        BACKEND,
228        "the latex-recomposed backend, on which the image's LaTeX rule is the default",
229    )?;
230    b.peer_element::<LatexMacroPayload>(
231        MACRO,
232        "the LaTeX family's macro-call construct, which the image's LaTeX rule stages for the \
233         LaTeX hook `\\flmIncludeGraphics`",
234    )?;
235    b.peer_element::<LatexRawPayload>(
236        RAW,
237        "the LaTeX family's raw construct, whose raw nodes hold the keys and the address",
238    )?;
239    b.peer_slot::<LatexPreambleDef>(preamble::SLOT, Arc::new(definition_piece()))?;
240    b.lowering_rule(latex_rule())
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246    use crate::stdlib::backends::latex::preamble::piece_id;
247
248    #[test]
249    fn the_piece_defines_the_hook_and_requests_the_two_packages() {
250        let piece = definition_piece();
251        assert_eq!(piece.id, piece_id(PIECE_NAME));
252        assert_eq!(piece.id.as_str(), PIECE);
253        assert_eq!(piece.requires, [Name::from(packages::GRAPHICX), Name::from(packages::ADJUSTBOX)]);
254        assert!(piece.content.contains(
255            "\\ProvideDocumentCommand\\flmIncludeGraphics{O{} m}{\\includegraphics[max \
256             width=\\linewidth,#1]{#2}}"
257        ));
258    }
259
260    #[test]
261    fn the_rule_is_the_default_on_the_recomposed_backend_only() {
262        let rule = latex_rule();
263        assert_eq!(rule.element, IMAGE_ELEMENT);
264        assert!(rule.default.is_specific_to(&BACKEND.into()));
265    }
266}