Skip to main content

flm_core/stdlib/features/href/
latex.rs

1//! The hyperlinks on the `latex-recomposed` backend: each command of the
2//! [`href`](super) feature written back as a LaTeX hook, a macro that the recomposed
3//! LaTeX writes and the style file defines with a plain default, which a user
4//! redefines in the document's preamble
5//! ([`latex::preamble`](crate::stdlib::backends::latex::preamble); see [the LaTeX
6//! hooks](crate::guide::rendering#the-latex-hooks)).
7//!
8//! | written | LaTeX |
9//! |---|---|
10//! | `\href{https://example.com}{Example link}` | `\flmHref{https://example.com}{Example link}` |
11//! | `\url{https://example.com/}` | `\flmUrl{https://example.com/}` |
12//! | `\email{a@b.com}` | `\flmEmail{a@b.com}` |
13//! | `\url{https://x.org/a%20b#c}` | `\flmUrl{https://x.org/a\%20b\#c}` |
14//!
15//! # The three hooks
16//!
17//! The rule [`LATEX_RULE`] writes one hook per command. Each hook takes ordinary LaTeX
18//! arguments (no argument is read with changed character codes), so that a hook still
19//! works in a *moving argument*, such as the title of a heading that LaTeX writes to
20//! the table of contents and reads back:
21//!
22//! - `\flmHref{<address>}{<text>}`, like the `\href` of the `hyperref` package, the
23//!   text lowered as content through the ordinary lowering rules;
24//! - `\flmUrl{<address>}`, linked through `\href` and showing the address's display,
25//!   which the hook derives itself (below), typeset with the `\nolinkurl` of
26//!   `hyperref`, the way `\url` typesets an address: in `\UrlFont`, with the line
27//!   breaks of the `url` package;
28//! - `\flmEmail{<address>}`, linked through `\href` with `mailto:` before the address,
29//!   and showing the display of that target (the address without `mailto:`), derived
30//!   and typeset the same way.
31//!
32//! The address is written through the LaTeX family's escaping of an address,
33//! [`escape_url`]: `#`, `%` and `\` each preceded by a backslash, every other
34//! character as it is. The address is read as characters
35//! ([`chars_at_lowering`](crate::core::lowering::chars_at_lowering)), so a user
36//! definition whose template holds a placeholder inside an address
37//! (`\href{https://doi.org/#1}{#1}`, `\url{#1}`) is not written back as a LaTeX
38//! definition: each of its use sites is expanded, and the rule writes the address the
39//! use site supplies.
40//!
41//! # The display, derived in LaTeX
42//!
43//! What a `\url` or an `\email` shows is presentation, so on the recomposed LaTeX the
44//! hook derives it instead of receiving it: the rule writes the address alone, and the
45//! internal macro `\flm@href@display{<address>}` of the feature's definition piece
46//! computes the display from it, with the same result as the feature's [`display`]:
47//! the escaping backslashes removed, then one leading `http://`, `https://` or
48//! `mailto:`, then the trailing run of `/`, `#` and `?`. So
49//! `\flmUrl{https://example.com/?\#}` shows `example.com`, as the HTML page does, and
50//! a LaTeX author who redefines `\flmUrl` receives the address and chooses what to
51//! show. The internal macro is not meant to be redefined: a user redefines the hooks.
52//!
53//! # The definition piece in the style file
54//!
55//! A *definition piece* is a unit of LaTeX definitions that a feature registers under
56//! an identifier `flm.latex.def.<name>`, which a lowering rule requires and the style
57//! file then holds ([`LatexPreambleDef`]). The three hooks are defined by the
58//! feature's definition piece ([`definition_piece`], `flm.latex.def.href`), each with
59//! `\ProvideDocumentCommand`, so that a definition the user's document class or
60//! preamble made first takes precedence. The piece requests the `hyperref` package,
61//! because the hooks' defaults are that package's own macros `\href` and `\nolinkurl`.
62//! A recomposed document that holds a hyperlink therefore loads `hyperref`, and every
63//! reference written through the LaTeX hook `\flmHyperref` (a reference that displays
64//! the author's own words) then becomes a link as well. A document that loads
65//! `hyperref` itself, with options of its own, after the style file, must list the
66//! package in the render option
67//! [`skip_packages`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::skip_packages),
68//! which removes the request; otherwise LaTeX stops with an option clash. The piece
69//! also says what each hook contributes to a PDF bookmark (its text or its display
70//! alone), at the beginning of the document and only where `hyperref` is loaded, so
71//! that this works whether the package was loaded before the style file or after it.
72//!
73//! An address that is not characters is reported
74//! ([`AddressNotCharacters`](super::AddressNotCharacters)), as on every output, and
75//! what the link would have shown is written alone.
76//!
77//! # Registration without the LaTeX features
78//!
79//! The feature registers the rule with a peer declaration
80//! ([`PeerName`](crate::core::registry::PeerName)) of each name it uses that the LaTeX
81//! features own: the backend `latex-recomposed`, the macro construct
82//! `flm.pres.latex.macro`, the raw construct `flm.pres.latex.raw` (a raw node holds
83//! LaTeX text written as it is) and the service slot of the definition pieces. A
84//! registry without the LaTeX features therefore still builds, with the rule set aside
85//! (excluded from rule selection).
86
87use std::sync::Arc;
88
89use techy::core::node::{BuildId, NodeRef};
90
91use crate::core::lowering::{
92    DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
93};
94use crate::core::registry::{BuildError, FeatureBuilder};
95use crate::lang::Flm;
96use crate::model::names::{ElementName, Name};
97use crate::stdlib::backends::latex::construct::{ARG_SLOT, MACRO, RAW};
98use crate::stdlib::backends::latex::{
99    LatexArgShape, LatexMacroPayload, LatexPreambleDef, LatexRawPayload, escape_url, packages,
100    preamble,
101};
102use crate::stdlib::backends::latex_recomposed::BACKEND;
103use crate::stdlib::backends::lowering::lower_arg_named_or_nothing;
104
105use super::{
106    Address, HrefCommand, LINK_ELEMENT, TEXT_ARG, command_of, display, read_address,
107    report_not_characters,
108};
109
110/// The name of the lowering rule of [`LINK_ELEMENT`] on the `latex-recomposed`
111/// backend, `flm.href.link.lower.latex-recomposed`, implemented by
112/// [`LinkLatexRule`].
113pub const LATEX_RULE: &str = "flm.href.link.lower.latex-recomposed";
114
115/// The name of the feature's definition piece, `href`; its identifier is
116/// `flm.latex.def.href` ([`PIECE`]).
117pub const PIECE_NAME: &str = "href";
118
119/// The identifier of the feature's definition piece, `flm.latex.def.href`
120/// ([`definition_piece`]).
121pub const PIECE: &str = "flm.latex.def.href";
122
123/// The name of the LaTeX hook that `\href` is written as, `flmHref`.
124pub const HREF_COMMAND: &str = "flmHref";
125
126/// The name of the LaTeX hook that `\url` is written as, `flmUrl`.
127pub const URL_COMMAND: &str = "flmUrl";
128
129/// The name of the LaTeX hook that `\email` is written as, `flmEmail`.
130pub const EMAIL_COMMAND: &str = "flmEmail";
131
132/// Returns the name of the LaTeX hook that `command` is written as.
133pub fn hook_of(command: HrefCommand) -> &'static str {
134    match command {
135        HrefCommand::Href => HREF_COMMAND,
136        HrefCommand::Url => URL_COMMAND,
137        HrefCommand::Email => EMAIL_COMMAND,
138    }
139}
140
141/// Returns the feature's definition piece, `flm.latex.def.href`: the three LaTeX
142/// hooks `\flmHref{<address>}{<text>}`, `\flmUrl{<address>}` and
143/// `\flmEmail{<address>}`, each defined with `\ProvideDocumentCommand` over the
144/// `\href` of `hyperref` (the display of the last two derived by the piece's
145/// internal macro, with the same result as [`display`], and typeset with
146/// `\nolinkurl`), and what each contributes to a PDF bookmark: its text or its
147/// display alone.
148///
149/// The piece requests the `hyperref` package ([`packages::HYPERREF`]), whose
150/// macros the hooks' defaults use; a document that loads that package itself
151/// lists it in the render option `skip_packages` (see the [module
152/// documentation](self)).
153///
154/// Redefine a hook, before loading the style file or after it, to link or to
155/// typeset that command's links another way.
156pub fn definition_piece() -> LatexPreambleDef {
157    LatexPreambleDef::new(
158        PIECE_NAME,
159        "\
160% Links to an address outside the document, one hook per FLM command:
161% \\flmHref{<address>}{<text>}: <text>, linked to <address>, as \\href does.
162% \\flmUrl{<address>}: the display of <address>, linked to <address> and
163%   typeset the way \\url typesets an address.
164% \\flmEmail{<address>}: the display of mailto:<address> -- the address --
165%   linked to mailto:<address> and typeset the same way.
166% The display is what the other outputs of FLM show of such a link: its target
167% without one leading http://, https:// or mailto: and without the trailing
168% run of the characters / # ? -- https://example.com/?# shows example.com.
169% Every argument is an ordinary one: in <address> the characters # % \\ are
170% written \\# \\% \\\\. Redefine a hook to link or typeset differently.
171%
172% The display is derived by \\flm@href@display{<address>}, written in expl3,
173% LaTeX's programming layer, which is part of the format and needs no package;
174% its names read only between \\ExplSyntaxOn and \\ExplSyntaxOff. It reads the
175% address as a string of characters (\\tl_to_str:n), drops the backslash of
176% each \\# \\% \\\\, then the prefix, then the trailing run, one character at a
177% time. It works by expansion alone and leaves the display and nothing else,
178% so that it serves where a hook is typeset and where hyperref builds a PDF
179% bookmark by expansion. The macros with @ in their names are internals, not a
180% customization point: redefine a hook, not its parts.
181\\ExplSyntaxOn
182\\def\\flm@href@display#1{\\exp_args:Ne \\flm@href@trim
183  {\\exp_args:Ne \\flm@href@unprefix
184    {\\exp_args:Ne \\flm@href@unescape {\\tl_to_str:n {#1}}}}}
185% Every character, a backslash dropped and the character after it kept.
186\\def\\flm@href@unescape#1{\\str_if_empty:nF {#1}
187  {\\str_if_eq:eeTF {\\str_head:n {#1}} {\\c_backslash_str}
188    {\\exp_args:Ne \\flm@href@unescape@one {\\str_tail:n {#1}}}
189    {\\flm@href@unescape@one {#1}}}}
190\\def\\flm@href@unescape@one#1{\\str_head:n {#1}
191  \\exp_args:Ne \\flm@href@unescape {\\str_tail:n {#1}}}
192% The first of the three prefixes the string begins with, taken off.
193\\def\\flm@href@unprefix#1{\\flm@href@unprefix@try {#1} {http://}
194  {\\flm@href@unprefix@try {#1} {https://}
195    {\\flm@href@unprefix@try {#1} {mailto:} {#1}}}}
196\\def\\flm@href@unprefix@try#1#2#3{\\str_if_eq:eeTF
197  {\\str_range:nnn {#1} {1} {\\str_count:n {#2}}} {#2}
198  {\\str_range:nnn {#1} {\\str_count:n {#2} + 1} {-1}} {#3}}
199% The last character taken off while it is one of / # ?.
200\\def\\flm@href@trim#1{\\exp_args:Ne \\flm@href@trim@last {\\str_item:nn {#1} {-1}} {#1}}
201\\def\\flm@href@trim@last#1#2{\\bool_lazy_any:nTF
202  {{\\str_if_eq_p:nn {#1} {/}} {\\str_if_eq_p:ee {#1} {\\c_hash_str}} {\\str_if_eq_p:nn {#1} {?}}}
203  {\\exp_args:Ne \\flm@href@trim {\\str_range:nnn {#2} {1} {-2}}} {#2}}
204% The display of <target>, typeset by \\nolinkurl.
205\\def\\flm@href@show#1{\\exp_args:Ne \\nolinkurl {\\flm@href@display {#1}}}
206\\ExplSyntaxOff
207\\ProvideDocumentCommand\\flmHref{m m}{\\href{#1}{#2}}
208\\ProvideDocumentCommand\\flmUrl{m}{\\href{#1}{\\flm@href@show{#1}}}
209\\ProvideDocumentCommand\\flmEmail{m}{\\href{mailto:#1}{\\flm@href@show{mailto:#1}}}
210% What such a link contributes to a PDF bookmark: its text or its display
211% alone. The hook runs when the document begins, so that it also holds where
212% the document loads hyperref itself, after this file, having named it in the
213% render option skip_packages; it does nothing where hyperref is absent.
214\\AtBeginDocument{\\ifdefined\\pdfstringdefDisableCommands
215  \\pdfstringdefDisableCommands{%
216    \\def\\flmHref#1#2{#2}%
217    \\def\\flmUrl#1{\\flm@href@display{#1}}%
218    \\def\\flmEmail#1{\\flm@href@display{mailto:#1}}%
219  }\\fi}
220",
221        "`\\flmHref{address}{text}`, `\\flmUrl{address}` and `\\flmEmail{address}`: the LaTeX \
222         hooks of the three hyperlink commands, linked through `hyperref`, the display of the last \
223         two derived in LaTeX",
224    )
225    .requires([packages::HYPERREF])
226}
227
228/// The implementation of the lowering rule [`LATEX_RULE`]: it stages the
229/// command's LaTeX hook ([`hook_of`]) with the address, escaped with
230/// [`escape_url`], as its first argument and, for `\href`, the text lowered as
231/// content as its second, and requires the definition piece [`PIECE`]. The
232/// display of a `\url` or an `\email` is not written: the hook derives it. See
233/// the [module documentation](self).
234#[derive(Debug, Default, Clone, Copy)]
235pub struct LinkLatexRule;
236
237impl Lower for LinkLatexRule {
238    fn lower(
239        &self,
240        node: NodeRef<'_, Flm>,
241        cx: &mut LowerCx<'_>,
242        lw: &mut dyn Lowerer,
243    ) -> Result<Lowering, LowerError> {
244        let command = command_of(&node)?;
245        let address = match read_address(&node)? {
246            Address::Read(text) => text,
247            Address::NotCharacters(words) => {
248                report_not_characters(&node, command, lw);
249                return Ok(Lowering::Emit(unlinked(cx, lw, &node, command, &words)?));
250            }
251        };
252        // The address alone: the display of a `\url` or an `\email` is
253        // presentation of the address, which the hook derives in LaTeX, and an
254        // author who redefines the hook decides what it shows.
255        let mut slots = vec![escaped(cx, lw, &address)?];
256        if command.has_text() {
257            slots.push(lower_arg_named_or_nothing(cx, lw, &node, TEXT_ARG)?);
258        }
259        lw.require(&Name::from(PIECE));
260        let shapes = vec![LatexArgShape::Mandatory; slots.len()];
261        let hook = lw.pres_slots_with(
262            cx,
263            &ElementName::from(MACRO),
264            LatexMacroPayload::new(hook_of(command), shapes),
265            slots.into_iter().map(|slot| (String::from(ARG_SLOT), slot)).collect(),
266        )?;
267        Ok(Lowering::Emit(vec![hook]))
268    }
269}
270
271/// Stages `text`, escaped with [`escape_url`], as one raw node
272/// (`flm.pres.latex.raw`, LaTeX text written as it is); nothing where `text` is
273/// empty.
274fn escaped(
275    cx: &mut LowerCx<'_>,
276    lw: &mut dyn Lowerer,
277    text: &str,
278) -> Result<Vec<BuildId>, LowerError> {
279    if text.is_empty() {
280        return Ok(Vec::new());
281    }
282    let raw = LatexRawPayload::new(escape_url(text));
283    Ok(vec![lw.pres_with(cx, &ElementName::from(RAW), raw, Vec::new())?])
284}
285
286/// Stages what a link whose address is not characters shows, alone: the text of
287/// `\href` lowered as content, or the display of the address's words as document
288/// text.
289fn unlinked(
290    cx: &mut LowerCx<'_>,
291    lw: &mut dyn Lowerer,
292    node: &NodeRef<'_, Flm>,
293    command: HrefCommand,
294    words: &str,
295) -> Result<Vec<BuildId>, LowerError> {
296    if command.has_text() {
297        return lower_arg_named_or_nothing(cx, lw, node, TEXT_ARG);
298    }
299    let shown = display(&format!("{}{words}", command.prefix()));
300    if shown.is_empty() {
301        return Ok(Vec::new());
302    }
303    Ok(vec![lw.text(cx, &shown)?])
304}
305
306/// Returns the lowering rule [`LATEX_RULE`], the default on the
307/// `latex-recomposed` backend only.
308pub fn latex_rule() -> LoweringRule {
309    LoweringRule::new(
310        LATEX_RULE,
311        LINK_ELEMENT,
312        LoweringDecl::new().produces(MACRO).produces(RAW),
313        Arc::new(LinkLatexRule),
314        DefaultMark::OnBackends(vec![BACKEND.into()]),
315    )
316    .docs(
317        "a hyperlink lowers to its LaTeX hook, `\\flmHref`, `\\flmUrl` or `\\flmEmail`, over its \
318         escaped address and, for `\\href`, its text",
319    )
320}
321
322/// Registers the rule [`LATEX_RULE`] and contributes the definition piece to the
323/// service slot of the definition pieces ([`preamble::SLOT`]), with peer
324/// declarations ([`PeerName`](crate::core::registry::PeerName)) of the names they
325/// use that the LaTeX features own (the backend, the macro construct and the raw
326/// construct), so that the feature builds in a registry without the LaTeX
327/// features, with its rule set aside (excluded from rule selection).
328///
329/// # Errors
330///
331/// [`BuildError::ContributionAfterAssembly`] when called from a
332/// [`Finalizer`](crate::core::registry::Finalizer), the second registration round, in
333/// which a feature may no longer contribute to a service slot
334/// ([`FeatureBuilder`]).
335pub(super) fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
336    b.peer_backend(
337        BACKEND,
338        "the latex-recomposed backend, on which the recomposition rule of a hyperlink is the \
339         default",
340    )?;
341    b.peer_element::<LatexMacroPayload>(
342        MACRO,
343        "the LaTeX family's macro-call construct, which the recomposition rule stages for a LaTeX \
344         hook",
345    )?;
346    b.peer_element::<LatexRawPayload>(
347        RAW,
348        "the LaTeX family's raw construct (LaTeX text written as it is), in which the rule \
349         writes an escaped address",
350    )?;
351    b.peer_slot::<LatexPreambleDef>(preamble::SLOT, Arc::new(definition_piece()))?;
352    b.lowering_rule(latex_rule())
353}
354
355#[cfg(test)]
356mod tests {
357    use super::*;
358    use crate::stdlib::backends::latex::preamble::piece_id;
359
360    #[test]
361    fn the_piece_is_named_as_its_identifier_says_and_requests_hyperref() {
362        let piece = definition_piece();
363        assert_eq!(piece.id, piece_id(PIECE_NAME));
364        assert_eq!(piece.id.as_str(), PIECE);
365        assert_eq!(piece.requires, [Name::from(packages::HYPERREF)]);
366        for hook in [HREF_COMMAND, URL_COMMAND, EMAIL_COMMAND] {
367            assert!(piece.content.contains(&format!("\\ProvideDocumentCommand\\{hook}")));
368        }
369        // The bookmark block is asked when the document begins, so that it
370        // holds where the document loads `hyperref` itself, after the style
371        // file, having skipped the request.
372        assert!(
373            piece.content.contains("\\AtBeginDocument{\\ifdefined\\pdfstringdefDisableCommands"),
374            "{}",
375            piece.content
376        );
377    }
378
379    #[test]
380    fn the_rule_is_the_default_on_the_recomposed_backend_only() {
381        let rule = latex_rule();
382        assert_eq!(rule.element, LINK_ELEMENT);
383        assert!(rule.default.is_specific_to(&BACKEND.into()));
384    }
385}