flm_core/stdlib/features/href/mod.rs
1//! This module defines the `href` feature ([`Href`]), which provides three commands
2//! that insert a link to an address outside the document:
3//!
4//! | written | links to | shows |
5//! |---|---|---|
6//! | `\href{https://example.com}{Click here}` | `https://example.com` | `Click here` |
7//! | `\url{https://example.com/}` | `https://example.com/` | `example.com` |
8//! | `\email{someone@example.com}` | `mailto:someone@example.com` | `someone@example.com` |
9//!
10//! The first argument of each command is the *address*, as the author wrote it. The
11//! *target* of a link is the address to which the link points: for `\email`, the
12//! address preceded by `mailto:`, and for `\href` and `\url`, the address itself
13//! ([`HrefCommand::prefix`]). A link written with `\href` shows its second argument.
14//! A link written with `\url` or `\email` shows the *display* of its target, that is,
15//! the target without a leading `http://`, `https://` or `mailto:`, and without
16//! trailing `/`, `#` and `?` characters ([`display`]).
17//!
18//! The three commands can be written only in text mode. The feature has no
19//! configuration. The language guide describes the commands for authors
20//! ([hyperlinks](crate::guide::language_syntax#hyperlinks)).
21//!
22//! # The address
23//!
24//! The address argument is read as raw text up to the matching `}`
25//! ([`ArgStdKind::Verbatim`]). Every character before this brace is part of the
26//! address, including `%`, `#`, `\`, `~` and nested braces. For instance,
27//! `\url{https://example.com/a%20b#top}` links to `https://example.com/a%20b#top`.
28//!
29//! In the template of a user definition, a placeholder in an address is replaced by
30//! the corresponding argument of the call, and a literal `#` is written `##`, as
31//! everywhere in a template. For instance, if the template of `\doi` is
32//! `\href{https://doi.org/#1}{#1}`, the call `\doi{10.1000/xyz}` links to
33//! `https://doi.org/10.1000/xyz`. The argument of the call must be plain text.
34//! Otherwise, the error [`AddressNotCharacters`] is reported and no link is made.
35//!
36//! The feature does not validate or normalize addresses. A backend can refuse an
37//! address when it writes a link. For instance, the HTML backend refuses an address
38//! whose scheme is not allowed by the render option
39//! [`HtmlAllowedUrlSchemes`](crate::stdlib::backends::html::HtmlAllowedUrlSchemes).
40//! The HTML backend then writes the link without an `href` attribute, and reports
41//! the error `flm.html.refused-address`.
42//!
43//! # The element and the lowering rules
44//!
45//! The three commands share one element type, [`LINK_ELEMENT`] (`flm.href.link`).
46//! Each command has its own element value, whose data is an [`HrefCommand`].
47//!
48//! The feature registers two lowering rules for this element type:
49//!
50//! - The default rule [`RULE`] ([`LinkRule`]) is used on every backend except
51//! `latex-recomposed`. It lowers a link to a
52//! [`flm.pres.link`](crate::stdlib::backends::pres::LINK) node of kind
53//! [`LINK_KIND`] (`url`), which points to the target of the link. The node
54//! contains the text argument of `\href`, or the display of the target for `\url`
55//! and `\email`.
56//! - The rule [`latex::LATEX_RULE`] is used on the `latex-recomposed` backend. It
57//! writes each link as a call of a *LaTeX hook*, that is, a macro that is defined
58//! in the style file and that a user can redefine: `\flmHref{address}{text}`,
59//! `\flmUrl{address}` or `\flmEmail{address}`. The hooks `\flmUrl` and `\flmEmail`
60//! compute the display in LaTeX, with the same result as [`display`]. See the
61//! module [`latex`].
62//!
63//! Each backend writes a `flm.pres.link` node in its own format. For instance, the
64//! HTML backend writes an `<a>` element whose `href` attribute is the target
65//! ([hyperlinks in HTML](crate::guide::rendering#hyperlinks-in-html)). The `text`
66//! backend writes what the link shows, followed by the target between angle
67//! brackets, as in `Click here <https://example.com>`. By default, the `text`
68//! backend omits the target after a link written with `\url` or `\email`, since such
69//! a link already shows its address. The render options
70//! [`link_addresses`](crate::stdlib::backends::text::TextRenderOptions::link_addresses)
71//! and
72//! [`link_addresses_when_shown`](crate::stdlib::backends::text::TextRenderOptions::link_addresses_when_shown)
73//! change this behavior. The `text` backend recognizes such a link by the field
74//! [`LinkPayload::shows_target`], which the default rule sets for `\url` and `\email`.
75
76pub mod latex;
77
78use std::sync::Arc;
79
80use techy::core::node::{BuildId, NodeRef};
81use techy::error::{Diagnostic, DiagnosticInfo};
82
83use crate::core::lowering::{
84 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
85 chars_at_lowering,
86};
87use crate::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature};
88use crate::lang::mint::{ArgDef, ArgStdKind, ElementDef, SyntaxDef};
89use crate::lang::text::plain_text_of;
90use crate::lang::Flm;
91use crate::model::aspects::{
92 ApartFromText, BlockRole, BlockRoleAspect, ContentRef, FixedBlockRole,
93};
94use crate::model::element::{ElementSpec, element_value};
95use crate::model::names::{ElementName, FeatureName};
96use crate::stdlib::backends::lowering::lower_arg_named_or_nothing;
97use crate::stdlib::backends::pres::{self, LinkPayload};
98
99/// The feature's registered name, `href`.
100pub const FEATURE: &str = "href";
101
102/// The name of the element type of `\href`, `\url` and `\email`, `flm.href.link`.
103/// Each of the three commands has its own element value of this type, whose data
104/// is an [`HrefCommand`].
105pub const LINK_ELEMENT: &str = "flm.href.link";
106
107/// The name of the default lowering rule of [`LINK_ELEMENT`],
108/// `flm.href.link.lower.default`. The rule is implemented by [`LinkRule`], and is
109/// used on every backend except `latex-recomposed`. On the `latex-recomposed`
110/// backend, the rule [`latex::LATEX_RULE`] is used instead.
111pub const RULE: &str = "flm.href.link.lower.default";
112
113/// The link kind of the links that the default rule [`RULE`] builds, `url`
114/// ([`LinkPayload::kind`]). This kind marks a link to an address outside the
115/// document. The HTML backend writes it as the attribute `data-flm-kind="url"`.
116pub const LINK_KIND: &str = "url";
117
118/// The name of the address argument, `address`.
119pub const ADDRESS_ARG: &str = "address";
120
121/// The name of the argument role `flm.href.address`, which marks an argument that
122/// contains the address of a link. The address argument [`ADDRESS_ARG`] of `\href`,
123/// `\url` and `\email` has this role
124/// ([`ArgDef::role`](crate::lang::mint::ArgDef::role)).
125pub const ADDRESS_ARG_ROLE: &str = "flm.href.address";
126
127/// The name of the text argument of `\href`, `text`.
128pub const TEXT_ARG: &str = "text";
129
130/// The prefixes that [`display`] removes from the start of a link target:
131/// `http://`, `https://` and `mailto:`. At most one prefix is removed.
132pub const DISPLAY_PREFIXES: [&str; 3] = ["http://", "https://", "mailto:"];
133
134/// The characters that [`display`] removes from the end of a link target: `/`,
135/// `#` and `?`. All of these characters at the end of the target are removed, in
136/// any number and in any order.
137pub const DISPLAY_TRAILING: [char; 3] = ['/', '#', '?'];
138
139/// The command with which a link is written: `\href`, `\url` or `\email`.
140///
141/// An `HrefCommand` is the data of each element value of [`LINK_ELEMENT`]. A
142/// lowering rule reads it from a node with [`element_value`]. The methods of
143/// `HrefCommand` return the properties of the command that a lowering rule needs:
144/// whether the command has a text argument ([`has_text`](Self::has_text)), and the
145/// prefix of the link target ([`prefix`](Self::prefix)). A lowering rule therefore
146/// does not need to compare the names of the commands.
147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148pub enum HrefCommand {
149 /// The command `\href{address}{text}`. The link shows `text`.
150 Href,
151 /// The command `\url{address}`. The link shows the display of the address
152 /// ([`display`]).
153 Url,
154 /// The command `\email{address}`. The link points to `mailto:` followed by
155 /// the address, and shows the address.
156 Email,
157}
158
159impl HrefCommand {
160 /// The three commands, in the order `\href`, `\url`, `\email`.
161 pub const ALL: [HrefCommand; 3] = [HrefCommand::Href, HrefCommand::Url, HrefCommand::Email];
162
163 /// Returns the command's name, without the backslash: `href`, `url`,
164 /// `email`.
165 pub fn name(self) -> &'static str {
166 match self {
167 HrefCommand::Href => "href",
168 HrefCommand::Url => "url",
169 HrefCommand::Email => "email",
170 }
171 }
172
173 /// Returns whether the command has a text argument after the address. Only
174 /// `\href` has one. The link of a command without a text argument shows the
175 /// display of its target ([`display`]).
176 pub fn has_text(self) -> bool {
177 matches!(self, HrefCommand::Href)
178 }
179
180 /// Returns the prefix that is placed before the address to form the link
181 /// target: `mailto:` for `\email`, and an empty string for `\href` and
182 /// `\url`.
183 pub fn prefix(self) -> &'static str {
184 match self {
185 HrefCommand::Email => "mailto:",
186 HrefCommand::Href | HrefCommand::Url => "",
187 }
188 }
189}
190
191/// Returns the display of the link target `target`, that is, the text that a
192/// link written with `\url` or `\email` shows.
193///
194/// The display is the target without a leading prefix from [`DISPLAY_PREFIXES`]
195/// (`http://`, `https://` or `mailto:`), and without the trailing characters from
196/// [`DISPLAY_TRAILING`] (`/`, `#` and `?`). The prefixes are compared exactly,
197/// including the letter case. The display can be empty, as for `https://`.
198///
199/// The LaTeX hooks of the `latex-recomposed` backend compute the same display in
200/// LaTeX ([`latex`]).
201///
202/// # Examples
203///
204/// ```
205/// use flm_core::stdlib::features::href::display;
206///
207/// assert_eq!(display("https://example.com/?#"), "example.com");
208/// assert_eq!(display("mailto:a@b.c"), "a@b.c");
209/// assert_eq!(display("ftp://example.com/"), "ftp://example.com");
210/// ```
211pub fn display(target: &str) -> String {
212 let rest = DISPLAY_PREFIXES
213 .iter()
214 .find_map(|prefix| target.strip_prefix(prefix))
215 .unwrap_or(target);
216 rest.trim_end_matches(DISPLAY_TRAILING).to_string()
217}
218
219/// The error that is reported when the address of `\href`, `\url` or `\email` is
220/// not plain text (`flm.href.address-not-characters`).
221///
222/// The address that an author writes in one of these commands is always plain
223/// text, because the address argument is read as raw text. Other content gets
224/// into an address through a user definition whose template places one of its
225/// arguments in the address. A call of such a definition must pass plain text in
226/// this argument. For instance, if the template of `\doi` is
227/// `\href{https://doi.org/#1}{#1}`, the call can be `\doi{10.1000/xyz}`.
228///
229/// Reported by the lowering rule of the command when it is invoked. No link is
230/// made. `\href` expands to its text argument. `\url` and `\email` expand to the
231/// display ([`display`]) of the address, computed from the text of the address
232/// without its markup.
233#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
234#[diagnostic(
235 id = "flm.href.address-not-characters",
236 message = "Invalid address in ‘\\{command}’: the address must be plain text"
237)]
238pub struct AddressNotCharacters {
239 /// The name of the command, without the backslash: `href`, `url` or `email`.
240 pub command: String,
241}
242
243/// The address of a link, as returned by [`read_address`].
244pub(crate) enum Address {
245 /// The address is plain text. The string contains its characters, without
246 /// the prefix of the command ([`HrefCommand::prefix`]).
247 Read(String),
248 /// The address contains content that is not plain text. The string contains
249 /// the text of the address without its markup ([`plain_text_of`]), and
250 /// without the prefix of the command. After reporting
251 /// [`AddressNotCharacters`], the lowering rules compute the display of a
252 /// `\url` or an `\email` from this text.
253 NotCharacters(String),
254}
255
256/// Reads the address argument of the link node `node` with
257/// [`chars_at_lowering`].
258///
259/// Returns [`Address::Read`] when the address is plain text, and
260/// [`Address::NotCharacters`] otherwise. When the node has no address argument,
261/// the address is empty.
262///
263/// # Errors
264///
265/// Returns [`LowerError::PlaceholderCharacters`] when the address contains a
266/// placeholder of a user definition's template. This happens only when the
267/// template is lowered without being expanded, which is the case on the
268/// `latex-recomposed` backend for a definition that is written as a LaTeX
269/// definition. The user-definitions feature then expands every use site of the
270/// definition ([`LowerError::PlaceholderCharacters`]).
271pub(crate) fn read_address(node: &NodeRef<'_, Flm>) -> Result<Address, LowerError> {
272 let Ok(Some(content)) = node.argument_content_nodes_named(ADDRESS_ARG) else {
273 return Ok(Address::Read(String::new()));
274 };
275 Ok(match chars_at_lowering(content.iter())? {
276 Ok(text) => Address::Read(text),
277 Err(_) => Address::NotCharacters(plain_text_of(content.iter())),
278 })
279}
280
281/// Returns the command with which the link node `node` was written, from the data
282/// of the element of the node.
283///
284/// # Errors
285///
286/// Returns a [`LowerError::Structure`] error when the data of the element is not
287/// an [`HrefCommand`].
288pub(crate) fn command_of(node: &NodeRef<'_, Flm>) -> Result<HrefCommand, LowerError> {
289 element_value::<HrefCommand>(node)
290 .copied()
291 .ok_or_else(|| {
292 LowerError::structure("missing ‘HrefCommand’ data on the element of the node")
293 })
294}
295
296/// Reports [`AddressNotCharacters`] at `node`.
297pub(crate) fn report_not_characters(
298 node: &NodeRef<'_, Flm>,
299 command: HrefCommand,
300 lw: &mut dyn Lowerer,
301) {
302 lw.diagnose(Diagnostic::error(
303 AddressNotCharacters { command: command.name().to_string() },
304 node.span().clone(),
305 ));
306}
307
308/// Excludes the address argument [`ADDRESS_ARG`] of a link from the plain text of
309/// the content around the link ([`plain_text_of`]).
310///
311/// For instance, when the identifier of a heading is computed from its title, the
312/// address of a link in the title is left out. The text argument of `\href` is
313/// part of the plain text. The display of a `\url` or an `\email` is computed
314/// only when the link is lowered, so it is not part of the plain text either.
315impl ApartFromText for HrefCommand {
316 fn apart_from_text(&self, _node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
317 vec![ContentRef::ArgumentNamed(ADDRESS_ARG.to_string())]
318 }
319}
320
321/// Returns the element value of the command `command`. The element is inline
322/// content, its data is `command`, and its [`ApartFromText`] aspect excludes the
323/// address from the plain text.
324fn element(command: HrefCommand) -> Arc<ElementSpec> {
325 Arc::new(
326 ElementSpec::new(LINK_ELEMENT)
327 .docs(match command {
328 HrefCommand::Href => {
329 "A link to an address outside the document, shown as the text written for it."
330 }
331 HrefCommand::Url => {
332 "A link to an address outside the document, shown as the address."
333 }
334 HrefCommand::Email => "A link to an email address, shown as the address.",
335 })
336 .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT)))
337 .with::<dyn ApartFromText>(Arc::new(command))
338 .with_value(Arc::new(command)),
339 )
340}
341
342/// Returns the arguments of a command: the verbatim address, then, for `\href`,
343/// the text.
344fn arguments(command: HrefCommand) -> Vec<ArgDef> {
345 let address = match command {
346 HrefCommand::Email => "The email address, as in `someone@example.com`.",
347 HrefCommand::Href | HrefCommand::Url => {
348 "The address of the link, as in `https://example.com/a%20b`."
349 }
350 };
351 let mut args = vec![ArgDef::named(
352 ADDRESS_ARG,
353 ArgStdKind::Verbatim { delimiters: Some(('{', '}')) },
354 )
355 .docs(format!(
356 "{address} The address is raw text up to the matching `}}`: the characters `%`, `#`, \
357 `\\`, `~` and nested braces are part of the address."
358 ))
359 .role(ADDRESS_ARG_ROLE)];
360 if command.has_text() {
361 args.push(
362 ArgDef::mandatory(TEXT_ARG).docs("The text that the link shows, as in `Click here`."),
363 );
364 }
365 args
366}
367
368// The recovery of an unreadable address is one rule for the three commands:
369// what the link would show is shown alone, so that a reader still sees what the
370// author meant to show.
371
372/// The implementation of the default lowering rule [`RULE`] of `\href`, `\url`
373/// and `\email`.
374///
375/// The rule lowers a link to a
376/// [`flm.pres.link`](crate::stdlib::backends::pres::LINK) node of kind
377/// [`LINK_KIND`] (`url`), whose field [`LinkPayload::href`] is the link target.
378/// For `\href`, the node contains the text argument, lowered as content. For
379/// `\url` and `\email`, the node contains a text node with the display of the
380/// target ([`display`]), and the rule sets the field
381/// [`LinkPayload::shows_target`].
382///
383/// When the address is not plain text, the rule reports [`AddressNotCharacters`]
384/// and builds no link node. It then returns only the content that the link would
385/// have contained.
386#[derive(Debug, Default, Clone, Copy)]
387pub struct LinkRule;
388
389impl Lower for LinkRule {
390 fn lower(
391 &self,
392 node: NodeRef<'_, Flm>,
393 cx: &mut LowerCx<'_>,
394 lw: &mut dyn Lowerer,
395 ) -> Result<Lowering, LowerError> {
396 let command = command_of(&node)?;
397 let (target, linked) = match read_address(&node)? {
398 Address::Read(text) => (text, true),
399 Address::NotCharacters(words) => {
400 report_not_characters(&node, command, lw);
401 (words, false)
402 }
403 };
404 let target = format!("{}{target}", command.prefix());
405 let content = shown(cx, lw, &node, command, &target)?;
406 if !linked {
407 return Ok(Lowering::Emit(content));
408 }
409 let payload = LinkPayload {
410 href: target,
411 kind: LINK_KIND.into(),
412 doc_role: None,
413 label: None,
414 shows_target: !command.has_text(),
415 };
416 let link = lw.pres_with(cx, &ElementName::from(pres::LINK), payload, content)?;
417 Ok(Lowering::Emit(vec![link]))
418 }
419}
420
421/// Lowers the content of a link, and returns the lowered nodes. For `\href`, the
422/// content is the text argument of `node`. For `\url` and `\email`, the content is
423/// one text node with the display of `target`, or no node when the display is
424/// empty.
425fn shown(
426 cx: &mut LowerCx<'_>,
427 lw: &mut dyn Lowerer,
428 node: &NodeRef<'_, Flm>,
429 command: HrefCommand,
430 target: &str,
431) -> Result<Vec<BuildId>, LowerError> {
432 if command.has_text() {
433 return lower_arg_named_or_nothing(cx, lw, node, TEXT_ARG);
434 }
435 let display = display(target);
436 if display.is_empty() {
437 return Ok(Vec::new());
438 }
439 Ok(vec![lw.text(cx, &display)?])
440}
441
442/// Returns the default lowering rule [`RULE`] of [`LINK_ELEMENT`], implemented by
443/// [`LinkRule`].
444///
445/// The rule is marked as the default on every backend
446/// ([`DefaultMark::Everywhere`]). On the `latex-recomposed` backend, the rule
447/// returned by [`latex::latex_rule`] is selected instead, because it is marked as
448/// the default for this backend.
449pub fn rule() -> LoweringRule {
450 LoweringRule::new(
451 RULE,
452 LINK_ELEMENT,
453 LoweringDecl::new().produces(pres::LINK),
454 Arc::new(LinkRule),
455 DefaultMark::Everywhere,
456 )
457 .docs(
458 "Lowers a link to a `flm.pres.link` node of kind `url`, which points to the address of \
459 the link, preceded by `mailto:` for `\\email`. The node contains the text argument of \
460 `\\href`, or, for `\\url` and `\\email`, the address as these commands show it.",
461 )
462}
463
464/// The `href` feature, which provides the commands `\href`, `\url` and `\email`
465/// for links to addresses outside the document. See the [module
466/// documentation](self).
467///
468/// The feature registers the three commands, the argument role
469/// [`ADDRESS_ARG_ROLE`], the default lowering rule [`RULE`], and the lowering rule
470/// [`latex::LATEX_RULE`] of the `latex-recomposed` backend.
471#[derive(Debug, Default, Clone, Copy)]
472pub struct Href;
473
474impl FlmFeature for Href {
475 fn info(&self) -> FeatureInfo {
476 FeatureInfo::new(FEATURE, "Hyperlinks").docs(
477 "Links to addresses outside the document, inserted with `\\href{address}{text}`, \
478 `\\url{address}` and `\\email{address}`.",
479 )
480 }
481
482 fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
483 let owner: FeatureName = b.feature().clone();
484 b.argument_role(
485 ADDRESS_ARG_ROLE,
486 "The address of a link: a URL, or an email address for `\\email`.",
487 )?;
488 for command in HrefCommand::ALL {
489 let name = command.name();
490 b.element(
491 ElementDef::new(
492 owner.clone(),
493 [name],
494 SyntaxDef::Macro { args: arguments(command) },
495 element(command),
496 )
497 .docs(match command {
498 HrefCommand::Href => "Inserts a link to `address`, shown as `text`.",
499 HrefCommand::Url => {
500 "Inserts a link to an address, shown as the address without a leading \
501 `http://`, `https://` or `mailto:` and without trailing `/`, `#` and `?` \
502 characters."
503 }
504 HrefCommand::Email => {
505 "Inserts a link to an email address, shown as the address. The link points \
506 to `mailto:` followed by the address."
507 }
508 }),
509 )?;
510 }
511 b.element_type_text(
512 LINK_ELEMENT,
513 "A link to an address outside the document, such as a web page or an email \
514 address. The link shows either the text written for it or the address.",
515 )?;
516 b.lowering_rule(rule())?;
517 latex::register(b)?;
518 Ok(())
519 }
520}
521
522/// Returns the [`Href`] feature, ready to be listed in a package entry.
523pub fn feature() -> Arc<dyn FlmFeature> {
524 Arc::new(Href)
525}
526
527#[cfg(test)]
528mod tests {
529 use super::*;
530
531 #[test]
532 fn the_display_drops_one_prefix_and_the_trailing_run() {
533 assert_eq!(display("https://example.com/?#"), "example.com");
534 assert_eq!(display("http://example.com/a/b//"), "example.com/a/b");
535 assert_eq!(display("mailto:a@b.c"), "a@b.c");
536 // One prefix only, the comparison exact.
537 assert_eq!(display("https://http://x"), "http://x");
538 assert_eq!(display("HTTPS://X.ORG"), "HTTPS://X.ORG");
539 assert_eq!(display("https://"), "");
540 assert_eq!(display("#?/"), "");
541 assert_eq!(display(""), "");
542 // A trailing character of the run inside the address stays.
543 assert_eq!(display("x.org/?a=1#b"), "x.org/?a=1#b");
544 }
545
546 #[test]
547 fn the_three_commands_say_what_they_take_and_what_they_put_before_the_address() {
548 let names: Vec<&str> = HrefCommand::ALL.iter().map(|command| command.name()).collect();
549 assert_eq!(names, ["href", "url", "email"]);
550 assert!(HrefCommand::Href.has_text());
551 assert!(!HrefCommand::Url.has_text() && !HrefCommand::Email.has_text());
552 assert_eq!(HrefCommand::Email.prefix(), "mailto:");
553 assert_eq!(HrefCommand::Url.prefix(), "");
554 }
555
556 #[test]
557 fn every_command_takes_a_braced_verbatim_address() {
558 for command in HrefCommand::ALL {
559 let args = arguments(command);
560 assert_eq!(args[0].name.as_deref(), Some(ADDRESS_ARG));
561 let braced = ArgDef::new(ArgStdKind::Verbatim { delimiters: Some(('{', '}')) });
562 assert_eq!(args[0].kind.identity(), braced.kind.identity());
563 assert_eq!(args.len(), if command.has_text() { 2 } else { 1 });
564 }
565 }
566}