use std::sync::Arc;
use techy::core::node::{BuildId, NodeRef};
use crate::core::lowering::{
DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
};
use crate::core::registry::{BuildError, FeatureBuilder};
use crate::lang::Flm;
use crate::model::names::{ElementName, Name};
use crate::stdlib::backends::latex::construct::{ARG_SLOT, MACRO, RAW};
use crate::stdlib::backends::latex::{
LatexArgShape, LatexMacroPayload, LatexPreambleDef, LatexRawPayload, escape_url, packages,
preamble,
};
use crate::stdlib::backends::latex_recomposed::BACKEND;
use crate::stdlib::backends::lowering::lower_arg_named_or_nothing;
use super::{
Address, HrefCommand, LINK_ELEMENT, TEXT_ARG, command_of, display, read_address,
report_not_characters,
};
pub const LATEX_RULE: &str = "flm.href.link.lower.latex-recomposed";
pub const PIECE_NAME: &str = "href";
pub const PIECE: &str = "flm.latex.def.href";
pub const HREF_COMMAND: &str = "flmHref";
pub const URL_COMMAND: &str = "flmUrl";
pub const EMAIL_COMMAND: &str = "flmEmail";
pub fn hook_of(command: HrefCommand) -> &'static str {
match command {
HrefCommand::Href => HREF_COMMAND,
HrefCommand::Url => URL_COMMAND,
HrefCommand::Email => EMAIL_COMMAND,
}
}
pub fn definition_piece() -> LatexPreambleDef {
LatexPreambleDef::new(
PIECE_NAME,
"\
% Links to an address outside the document, one hook per FLM command:
% \\flmHref{<address>}{<text>}: <text>, linked to <address>, as \\href does.
% \\flmUrl{<address>}: the display of <address>, linked to <address> and
% typeset the way \\url typesets an address.
% \\flmEmail{<address>}: the display of mailto:<address> -- the address --
% linked to mailto:<address> and typeset the same way.
% The display is what the other outputs of FLM show of such a link: its target
% without one leading http://, https:// or mailto: and without the trailing
% run of the characters / # ? -- https://example.com/?# shows example.com.
% Every argument is an ordinary one: in <address> the characters # % \\ are
% written \\# \\% \\\\. Redefine a hook to link or typeset differently.
%
% The display is derived by \\flm@href@display{<address>}, written in expl3,
% LaTeX's programming layer, which is part of the format and needs no package;
% its names read only between \\ExplSyntaxOn and \\ExplSyntaxOff. It reads the
% address as a string of characters (\\tl_to_str:n), drops the backslash of
% each \\# \\% \\\\, then the prefix, then the trailing run, one character at a
% time. It works by expansion alone and leaves the display and nothing else,
% so that it serves where a hook is typeset and where hyperref builds a PDF
% bookmark by expansion. The macros with @ in their names are internals, not a
% customization point: redefine a hook, not its parts.
\\ExplSyntaxOn
\\def\\flm@href@display#1{\\exp_args:Ne \\flm@href@trim
{\\exp_args:Ne \\flm@href@unprefix
{\\exp_args:Ne \\flm@href@unescape {\\tl_to_str:n {#1}}}}}
% Every character, a backslash dropped and the character after it kept.
\\def\\flm@href@unescape#1{\\str_if_empty:nF {#1}
{\\str_if_eq:eeTF {\\str_head:n {#1}} {\\c_backslash_str}
{\\exp_args:Ne \\flm@href@unescape@one {\\str_tail:n {#1}}}
{\\flm@href@unescape@one {#1}}}}
\\def\\flm@href@unescape@one#1{\\str_head:n {#1}
\\exp_args:Ne \\flm@href@unescape {\\str_tail:n {#1}}}
% The first of the three prefixes the string begins with, taken off.
\\def\\flm@href@unprefix#1{\\flm@href@unprefix@try {#1} {http://}
{\\flm@href@unprefix@try {#1} {https://}
{\\flm@href@unprefix@try {#1} {mailto:} {#1}}}}
\\def\\flm@href@unprefix@try#1#2#3{\\str_if_eq:eeTF
{\\str_range:nnn {#1} {1} {\\str_count:n {#2}}} {#2}
{\\str_range:nnn {#1} {\\str_count:n {#2} + 1} {-1}} {#3}}
% The last character taken off while it is one of / # ?.
\\def\\flm@href@trim#1{\\exp_args:Ne \\flm@href@trim@last {\\str_item:nn {#1} {-1}} {#1}}
\\def\\flm@href@trim@last#1#2{\\bool_lazy_any:nTF
{{\\str_if_eq_p:nn {#1} {/}} {\\str_if_eq_p:ee {#1} {\\c_hash_str}} {\\str_if_eq_p:nn {#1} {?}}}
{\\exp_args:Ne \\flm@href@trim {\\str_range:nnn {#2} {1} {-2}}} {#2}}
% The display of <target>, typeset by \\nolinkurl.
\\def\\flm@href@show#1{\\exp_args:Ne \\nolinkurl {\\flm@href@display {#1}}}
\\ExplSyntaxOff
\\ProvideDocumentCommand\\flmHref{m m}{\\href{#1}{#2}}
\\ProvideDocumentCommand\\flmUrl{m}{\\href{#1}{\\flm@href@show{#1}}}
\\ProvideDocumentCommand\\flmEmail{m}{\\href{mailto:#1}{\\flm@href@show{mailto:#1}}}
% What such a link contributes to a PDF bookmark: its text or its display
% alone. The hook runs when the document begins, so that it also holds where
% the document loads hyperref itself, after this file, having named it in the
% render option skip_packages; it does nothing where hyperref is absent.
\\AtBeginDocument{\\ifdefined\\pdfstringdefDisableCommands
\\pdfstringdefDisableCommands{%
\\def\\flmHref#1#2{#2}%
\\def\\flmUrl#1{\\flm@href@display{#1}}%
\\def\\flmEmail#1{\\flm@href@display{mailto:#1}}%
}\\fi}
",
"`\\flmHref{address}{text}`, `\\flmUrl{address}` and `\\flmEmail{address}`: the LaTeX \
hooks of the three hyperlink commands, linked through `hyperref`, the display of the last \
two derived in LaTeX",
)
.requires([packages::HYPERREF])
}
#[derive(Debug, Default, Clone, Copy)]
pub struct LinkLatexRule;
impl Lower for LinkLatexRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let command = command_of(&node)?;
let address = match read_address(&node)? {
Address::Read(text) => text,
Address::NotCharacters(words) => {
report_not_characters(&node, command, lw);
return Ok(Lowering::Emit(unlinked(cx, lw, &node, command, &words)?));
}
};
let mut slots = vec![escaped(cx, lw, &address)?];
if command.has_text() {
slots.push(lower_arg_named_or_nothing(cx, lw, &node, TEXT_ARG)?);
}
lw.require(&Name::from(PIECE));
let shapes = vec![LatexArgShape::Mandatory; slots.len()];
let hook = lw.pres_slots_with(
cx,
&ElementName::from(MACRO),
LatexMacroPayload::new(hook_of(command), shapes),
slots.into_iter().map(|slot| (String::from(ARG_SLOT), slot)).collect(),
)?;
Ok(Lowering::Emit(vec![hook]))
}
}
fn escaped(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
text: &str,
) -> Result<Vec<BuildId>, LowerError> {
if text.is_empty() {
return Ok(Vec::new());
}
let raw = LatexRawPayload::new(escape_url(text));
Ok(vec![lw.pres_with(cx, &ElementName::from(RAW), raw, Vec::new())?])
}
fn unlinked(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
node: &NodeRef<'_, Flm>,
command: HrefCommand,
words: &str,
) -> Result<Vec<BuildId>, LowerError> {
if command.has_text() {
return lower_arg_named_or_nothing(cx, lw, node, TEXT_ARG);
}
let shown = display(&format!("{}{words}", command.prefix()));
if shown.is_empty() {
return Ok(Vec::new());
}
Ok(vec![lw.text(cx, &shown)?])
}
pub fn latex_rule() -> LoweringRule {
LoweringRule::new(
LATEX_RULE,
LINK_ELEMENT,
LoweringDecl::new().produces(MACRO).produces(RAW),
Arc::new(LinkLatexRule),
DefaultMark::OnBackends(vec![BACKEND.into()]),
)
.docs(
"a hyperlink lowers to its LaTeX hook, `\\flmHref`, `\\flmUrl` or `\\flmEmail`, over its \
escaped address and, for `\\href`, its text",
)
}
pub(super) fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
b.peer_backend(
BACKEND,
"the latex-recomposed backend, on which the recomposition rule of a hyperlink is the \
default",
)?;
b.peer_element::<LatexMacroPayload>(
MACRO,
"the LaTeX family's macro-call construct, which the recomposition rule stages for a LaTeX \
hook",
)?;
b.peer_element::<LatexRawPayload>(
RAW,
"the LaTeX family's raw construct (LaTeX text written as it is), in which the rule \
writes an escaped address",
)?;
b.peer_slot::<LatexPreambleDef>(preamble::SLOT, Arc::new(definition_piece()))?;
b.lowering_rule(latex_rule())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::stdlib::backends::latex::preamble::piece_id;
#[test]
fn the_piece_is_named_as_its_identifier_says_and_requests_hyperref() {
let piece = definition_piece();
assert_eq!(piece.id, piece_id(PIECE_NAME));
assert_eq!(piece.id.as_str(), PIECE);
assert_eq!(piece.requires, [Name::from(packages::HYPERREF)]);
for hook in [HREF_COMMAND, URL_COMMAND, EMAIL_COMMAND] {
assert!(piece.content.contains(&format!("\\ProvideDocumentCommand\\{hook}")));
}
assert!(
piece.content.contains("\\AtBeginDocument{\\ifdefined\\pdfstringdefDisableCommands"),
"{}",
piece.content
);
}
#[test]
fn the_rule_is_the_default_on_the_recomposed_backend_only() {
let rule = latex_rule();
assert_eq!(rule.element, LINK_ELEMENT);
assert!(rule.default.is_specific_to(&BACKEND.into()));
}
}