pub mod latex;
use std::sync::Arc;
use techy::core::node::{BuildId, NodeRef};
use techy::error::{Diagnostic, DiagnosticInfo};
use crate::core::lowering::{
DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
chars_at_lowering,
};
use crate::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature};
use crate::lang::mint::{ArgDef, ArgStdKind, ElementDef, SyntaxDef};
use crate::lang::text::plain_text_of;
use crate::lang::Flm;
use crate::model::aspects::{
ApartFromText, BlockRole, BlockRoleAspect, ContentRef, FixedBlockRole,
};
use crate::model::element::{ElementSpec, element_value};
use crate::model::names::{ElementName, FeatureName};
use crate::stdlib::backends::lowering::lower_arg_named_or_nothing;
use crate::stdlib::backends::pres::{self, LinkPayload};
pub const FEATURE: &str = "href";
pub const LINK_ELEMENT: &str = "flm.href.link";
pub const RULE: &str = "flm.href.link.lower.default";
pub const LINK_KIND: &str = "url";
pub const ADDRESS_ARG: &str = "address";
pub const ADDRESS_ARG_ROLE: &str = "flm.href.address";
pub const TEXT_ARG: &str = "text";
pub const DISPLAY_PREFIXES: [&str; 3] = ["http://", "https://", "mailto:"];
pub const DISPLAY_TRAILING: [char; 3] = ['/', '#', '?'];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HrefCommand {
Href,
Url,
Email,
}
impl HrefCommand {
pub const ALL: [HrefCommand; 3] = [HrefCommand::Href, HrefCommand::Url, HrefCommand::Email];
pub fn name(self) -> &'static str {
match self {
HrefCommand::Href => "href",
HrefCommand::Url => "url",
HrefCommand::Email => "email",
}
}
pub fn has_text(self) -> bool {
matches!(self, HrefCommand::Href)
}
pub fn prefix(self) -> &'static str {
match self {
HrefCommand::Email => "mailto:",
HrefCommand::Href | HrefCommand::Url => "",
}
}
}
pub fn display(target: &str) -> String {
let rest = DISPLAY_PREFIXES
.iter()
.find_map(|prefix| target.strip_prefix(prefix))
.unwrap_or(target);
rest.trim_end_matches(DISPLAY_TRAILING).to_string()
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.href.address-not-characters",
message = "Invalid address in ‘\\{command}’: the address must be plain text"
)]
pub struct AddressNotCharacters {
pub command: String,
}
pub(crate) enum Address {
Read(String),
NotCharacters(String),
}
pub(crate) fn read_address(node: &NodeRef<'_, Flm>) -> Result<Address, LowerError> {
let Ok(Some(content)) = node.argument_content_nodes_named(ADDRESS_ARG) else {
return Ok(Address::Read(String::new()));
};
Ok(match chars_at_lowering(content.iter())? {
Ok(text) => Address::Read(text),
Err(_) => Address::NotCharacters(plain_text_of(content.iter())),
})
}
pub(crate) fn command_of(node: &NodeRef<'_, Flm>) -> Result<HrefCommand, LowerError> {
element_value::<HrefCommand>(node)
.copied()
.ok_or_else(|| {
LowerError::structure("missing ‘HrefCommand’ data on the element of the node")
})
}
pub(crate) fn report_not_characters(
node: &NodeRef<'_, Flm>,
command: HrefCommand,
lw: &mut dyn Lowerer,
) {
lw.diagnose(Diagnostic::error(
AddressNotCharacters { command: command.name().to_string() },
node.span().clone(),
));
}
impl ApartFromText for HrefCommand {
fn apart_from_text(&self, _node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
vec![ContentRef::ArgumentNamed(ADDRESS_ARG.to_string())]
}
}
fn element(command: HrefCommand) -> Arc<ElementSpec> {
Arc::new(
ElementSpec::new(LINK_ELEMENT)
.docs(match command {
HrefCommand::Href => {
"A link to an address outside the document, shown as the text written for it."
}
HrefCommand::Url => {
"A link to an address outside the document, shown as the address."
}
HrefCommand::Email => "A link to an email address, shown as the address.",
})
.with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT)))
.with::<dyn ApartFromText>(Arc::new(command))
.with_value(Arc::new(command)),
)
}
fn arguments(command: HrefCommand) -> Vec<ArgDef> {
let address = match command {
HrefCommand::Email => "The email address, as in `someone@example.com`.",
HrefCommand::Href | HrefCommand::Url => {
"The address of the link, as in `https://example.com/a%20b`."
}
};
let mut args = vec![ArgDef::named(
ADDRESS_ARG,
ArgStdKind::Verbatim { delimiters: Some(('{', '}')) },
)
.docs(format!(
"{address} The address is raw text up to the matching `}}`: the characters `%`, `#`, \
`\\`, `~` and nested braces are part of the address."
))
.role(ADDRESS_ARG_ROLE)];
if command.has_text() {
args.push(
ArgDef::mandatory(TEXT_ARG).docs("The text that the link shows, as in `Click here`."),
);
}
args
}
#[derive(Debug, Default, Clone, Copy)]
pub struct LinkRule;
impl Lower for LinkRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let command = command_of(&node)?;
let (target, linked) = match read_address(&node)? {
Address::Read(text) => (text, true),
Address::NotCharacters(words) => {
report_not_characters(&node, command, lw);
(words, false)
}
};
let target = format!("{}{target}", command.prefix());
let content = shown(cx, lw, &node, command, &target)?;
if !linked {
return Ok(Lowering::Emit(content));
}
let payload = LinkPayload {
href: target,
kind: LINK_KIND.into(),
doc_role: None,
label: None,
shows_target: !command.has_text(),
};
let link = lw.pres_with(cx, &ElementName::from(pres::LINK), payload, content)?;
Ok(Lowering::Emit(vec![link]))
}
}
fn shown(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
node: &NodeRef<'_, Flm>,
command: HrefCommand,
target: &str,
) -> Result<Vec<BuildId>, LowerError> {
if command.has_text() {
return lower_arg_named_or_nothing(cx, lw, node, TEXT_ARG);
}
let display = display(target);
if display.is_empty() {
return Ok(Vec::new());
}
Ok(vec![lw.text(cx, &display)?])
}
pub fn rule() -> LoweringRule {
LoweringRule::new(
RULE,
LINK_ELEMENT,
LoweringDecl::new().produces(pres::LINK),
Arc::new(LinkRule),
DefaultMark::Everywhere,
)
.docs(
"Lowers a link to a `flm.pres.link` node of kind `url`, which points to the address of \
the link, preceded by `mailto:` for `\\email`. The node contains the text argument of \
`\\href`, or, for `\\url` and `\\email`, the address as these commands show it.",
)
}
#[derive(Debug, Default, Clone, Copy)]
pub struct Href;
impl FlmFeature for Href {
fn info(&self) -> FeatureInfo {
FeatureInfo::new(FEATURE, "Hyperlinks").docs(
"Links to addresses outside the document, inserted with `\\href{address}{text}`, \
`\\url{address}` and `\\email{address}`.",
)
}
fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
let owner: FeatureName = b.feature().clone();
b.argument_role(
ADDRESS_ARG_ROLE,
"The address of a link: a URL, or an email address for `\\email`.",
)?;
for command in HrefCommand::ALL {
let name = command.name();
b.element(
ElementDef::new(
owner.clone(),
[name],
SyntaxDef::Macro { args: arguments(command) },
element(command),
)
.docs(match command {
HrefCommand::Href => "Inserts a link to `address`, shown as `text`.",
HrefCommand::Url => {
"Inserts a link to an address, shown as the address without a leading \
`http://`, `https://` or `mailto:` and without trailing `/`, `#` and `?` \
characters."
}
HrefCommand::Email => {
"Inserts a link to an email address, shown as the address. The link points \
to `mailto:` followed by the address."
}
}),
)?;
}
b.element_type_text(
LINK_ELEMENT,
"A link to an address outside the document, such as a web page or an email \
address. The link shows either the text written for it or the address.",
)?;
b.lowering_rule(rule())?;
latex::register(b)?;
Ok(())
}
}
pub fn feature() -> Arc<dyn FlmFeature> {
Arc::new(Href)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_display_drops_one_prefix_and_the_trailing_run() {
assert_eq!(display("https://example.com/?#"), "example.com");
assert_eq!(display("http://example.com/a/b//"), "example.com/a/b");
assert_eq!(display("mailto:a@b.c"), "a@b.c");
assert_eq!(display("https://http://x"), "http://x");
assert_eq!(display("HTTPS://X.ORG"), "HTTPS://X.ORG");
assert_eq!(display("https://"), "");
assert_eq!(display("#?/"), "");
assert_eq!(display(""), "");
assert_eq!(display("x.org/?a=1#b"), "x.org/?a=1#b");
}
#[test]
fn the_three_commands_say_what_they_take_and_what_they_put_before_the_address() {
let names: Vec<&str> = HrefCommand::ALL.iter().map(|command| command.name()).collect();
assert_eq!(names, ["href", "url", "email"]);
assert!(HrefCommand::Href.has_text());
assert!(!HrefCommand::Url.has_text() && !HrefCommand::Email.has_text());
assert_eq!(HrefCommand::Email.prefix(), "mailto:");
assert_eq!(HrefCommand::Url.prefix(), "");
}
#[test]
fn every_command_takes_a_braced_verbatim_address() {
for command in HrefCommand::ALL {
let args = arguments(command);
assert_eq!(args[0].name.as_deref(), Some(ADDRESS_ARG));
let braced = ArgDef::new(ArgStdKind::Verbatim { delimiters: Some(('{', '}')) });
assert_eq!(args[0].kind.identity(), braced.kind.identity());
assert_eq!(args.len(), if command.has_text() { 2 } else { 1 });
}
}
}