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::preamble::{self, LatexPreambleDef};
use crate::stdlib::backends::latex::{LatexArgShape, LatexMacroPayload, LatexRawPayload};
use crate::stdlib::backends::latex_recomposed::BACKEND;
use crate::stdlib::backends::lowering::lower_run;
use crate::stdlib::backends::pres;
use super::bibliography::{BIBLIOGRAPHY, BIBLIOGRAPHY_ENTRY};
use super::config::CAPITAL_VARIANT;
use super::diagnostics::NoCitation;
use super::elements::{calls, leading_call, read_call, Chunk, Reading, CITE, NOTE_ARG, REFCITE};
use super::mark::{read_flags, report_mistakes, stage_dropped, MarkSettings};
pub const CITE_LATEX_RULE: &str = "flm.citations.cite.lower.latex-recomposed";
pub const REFCITE_LATEX_RULE: &str = "flm.citations.refcite.lower.latex-recomposed";
pub const PIECE_NAME: &str = "citations";
pub const PIECE: &str = "flm.latex.def.citations";
pub const CITE_COMMAND: &str = "flmCite";
pub const PRE_SPACE_COMMAND: &str = "flmCitePreSpace";
pub const REF_CITE_COMMAND: &str = "flmRefCite";
pub fn definition_piece() -> LatexPreambleDef {
LatexPreambleDef::new(
PIECE_NAME,
"\
% Citations, written as the document wrote them. The list of the cited works
% is LaTeX's own (thebibliography, BibTeX, biblatex), built from your
% database.
% \\flmCite[<note>]{<keys>}: one citation, its keys as written, separated by
% commas, and its note where it has one; by default LaTeX's \\cite. To show
% the entries in place, redefine it, with biblatex's \\fullcite for instance.
% \\flmCitePreSpace: written before citations attached to the text before
% them; by default \\unskip~, a space that does not break. For superscript
% citations, redefine it to \\unskip.
% \\flmRefCite{<word>}{<citations>}: citations used as a noun of the sentence,
% with the word written before them (refs.~, Refs.~, or nothing); by
% default the word, then the citations.
% A change of case (\\MakeUppercase) leaves the keys of \\flmCite unchanged and
% changes its note, as it does for \\cite; as for \\cite, it protects the
% first brace group after the command, so where the note holds one
% ([{...}], \\emph{...}) the keys are changed too.
\\ProvideDocumentCommand\\flmCite{o m}{\\IfValueTF{#1}{\\cite[{#1}]{#2}}{\\cite{#2}}}
\\ProvideDocumentCommand\\flmCitePreSpace{}{\\unskip~}
\\ProvideDocumentCommand\\flmRefCite{m m}{#1#2}
% What a citation contributes to a PDF bookmark: nothing. The \\AtBeginDocument
% block below runs when the document begins, so that it also applies where
% hyperref is loaded after this file; it does nothing without hyperref.
% \\flm@cite@bookmark, defined first, reads \\flmCite's optional note, if any,
% then its keys, and writes nothing.
\\def\\flm@cite@bookmark#1{\\ifx[#1\\expandafter\\flm@cite@bookmark@note\\fi}
\\def\\flm@cite@bookmark@note#1]#2{}
\\AtBeginDocument{\\ifdefined\\pdfstringdefDisableCommands
\\pdfstringdefDisableCommands{%
\\def\\flmCitePreSpace{}%
\\let\\flmCite\\flm@cite@bookmark
\\def\\flmRefCite#1#2{}%
}\\fi}
\\ExplSyntaxOn
\\tl_if_in:NnF \\l_text_case_exclude_arg_tl { \\flmCite } { \\tl_put_right:Nn \\l_text_case_exclude_arg_tl { \\flmCite } }
\\ExplSyntaxOff
",
"the LaTeX hooks of a citation: `\\flmCite[note]{keys}` (LaTeX's `\\cite` by default), \
`\\flmCitePreSpace` and `\\flmRefCite{word}{citations}`; a change of case leaves the \
keys of `\\flmCite` unchanged",
)
}
fn stage_calls<'t>(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
node: &NodeRef<'t, Flm>,
) -> Result<(Vec<BuildId>, Chunk<'t>), LowerError> {
let mut all = Chunk::default();
let mut out = Vec::new();
for call in calls(node) {
let before = all.items.len();
read_call(&call, Reading::AtLowering, &mut all)?;
let keys: Vec<&str> = all.items[before..].iter().map(|item| item.key.as_str()).collect();
if keys.is_empty() {
continue;
}
let note: Vec<NodeRef<'t, Flm>> = match call.argument_content_nodes_named(NOTE_ARG) {
Ok(Some(content)) => content.iter().collect(),
_ => Vec::new(),
};
let mut shapes = Vec::with_capacity(2);
let mut slots = Vec::with_capacity(2);
if !note.is_empty() {
shapes.push(LatexArgShape::Optional);
slots.push((ARG_SLOT.to_string(), lower_run(cx, lw, ¬e)?));
}
let raw = LatexRawPayload::new(keys.join(","));
shapes.push(LatexArgShape::Mandatory);
slots.push((ARG_SLOT.to_string(), vec![lw.pres_with(cx, &ElementName::from(RAW), raw, Vec::new())?]));
out.push(lw.pres_slots_with(
cx,
&ElementName::from(MACRO),
LatexMacroPayload::new(CITE_COMMAND, shapes),
slots,
)?);
}
report_mistakes(lw, &all);
if !out.is_empty() {
lw.require(&Name::from(PIECE));
}
Ok((out, all))
}
fn bare_hook(cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer, name: &str) -> Result<BuildId, LowerError> {
lw.pres_slots_with(cx, &ElementName::from(MACRO), LatexMacroPayload::new(name, []), Vec::new())
}
#[derive(Debug, Default, Clone, Copy)]
pub struct CiteLatexRule;
impl Lower for CiteLatexRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let (cites, chunk) = stage_calls(cx, lw, &node)?;
if cites.is_empty() {
return Ok(Lowering::Emit(vec![stage_dropped(cx, lw, &chunk, false)?]));
}
let mut out = vec![bare_hook(cx, lw, PRE_SPACE_COMMAND)?];
out.extend(cites);
Ok(Lowering::Emit(out))
}
}
#[derive(Debug)]
pub struct RefCiteLatexRule {
settings: Arc<MarkSettings>,
}
impl Lower for RefCiteLatexRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let flags = read_flags(&node, lw)?;
if leading_call(&node).is_none() {
lw.error(NoCitation, node.span().clone());
}
let (cites, chunk) = stage_calls(cx, lw, &node)?;
if cites.is_empty() {
return Ok(Lowering::Emit(vec![stage_dropped(cx, lw, &chunk, false)?]));
}
let items = chunk.items.len();
let mut word = Vec::new();
if flags.word {
let variant = flags.capital.then_some(CAPITAL_VARIANT);
if let Some(text) = self.settings.style()?.word_text(items, variant) {
word = lw.splice(cx, text)?;
}
}
let hook = lw.pres_slots_with(
cx,
&ElementName::from(MACRO),
LatexMacroPayload::new(REF_CITE_COMMAND, [LatexArgShape::Mandatory, LatexArgShape::Mandatory]),
vec![(ARG_SLOT.to_string(), word), (ARG_SLOT.to_string(), cites)],
)?;
Ok(Lowering::Emit(vec![hook]))
}
}
fn decl() -> LoweringDecl {
LoweringDecl::new().produces(MACRO).produces(RAW).produces(pres::DROPPED)
}
pub(super) fn latex_rules(settings: &Arc<MarkSettings>) -> Vec<LoweringRule> {
vec![
LoweringRule::new(
CITE_LATEX_RULE,
CITE,
decl(),
Arc::new(CiteLatexRule),
DefaultMark::OnBackends(vec![BACKEND.into()]),
)
.docs(
"a citation chunk lowers to `\\flmCitePreSpace` and one `\\flmCite[note]{keys}` per \
call, the keys written unescaped",
),
LoweringRule::new(
REFCITE_LATEX_RULE,
REFCITE,
decl(),
Arc::new(RefCiteLatexRule { settings: Arc::clone(settings) }),
DefaultMark::OnBackends(vec![BACKEND.into()]),
)
.docs(
"a citation chunk written with `\\R` lowers to `\\flmRefCite{word}{…}` holding the \
citation counter style's word and one `\\flmCite[note]{keys}` per call, with no \
`\\flmCitePreSpace`",
),
]
}
pub(super) fn register(b: &mut FeatureBuilder<'_>, settings: &Arc<MarkSettings>) -> Result<(), BuildError> {
b.peer_backend(
BACKEND,
"the latex-recomposed backend, on which the citations feature's rules of the recomposed \
LaTeX are the defaults",
)?;
b.peer_element::<LatexMacroPayload>(
MACRO,
"the LaTeX family's macro-call construct, which the citations feature's rules stage for \
each LaTeX hook",
)?;
b.peer_element::<LatexRawPayload>(
RAW,
"the LaTeX family's raw construct, in which the citation keys of a call are written",
)?;
b.peer_slot::<LatexPreambleDef>(preamble::SLOT, Arc::new(definition_piece()))?;
register_list(b)?;
for rule in latex_rules(settings) {
b.lowering_rule(rule)?;
}
Ok(())
}
#[derive(Debug, Default)]
pub struct ListNotWritten;
impl Lower for ListNotWritten {
fn lower(
&self,
_node: NodeRef<'_, Flm>,
_cx: &mut LowerCx<'_>,
_lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
Ok(Lowering::Emit(Vec::new()))
}
}
fn register_list(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
let rules = [
(BIBLIOGRAPHY, "flm.citations.bibliography.lower.latex-recomposed"),
(BIBLIOGRAPHY_ENTRY, "flm.citations.bibliography.entry.lower.latex-recomposed"),
];
for (element, rule) in rules {
b.lowering_rule(
LoweringRule::new(
rule,
element,
LoweringDecl::new(),
Arc::new(ListNotWritten),
DefaultMark::OnBackends(vec![BACKEND.into()]),
)
.docs(
"on the recomposed LaTeX, nothing is written for the list of the cited works: \
LaTeX writes its own",
),
)?;
}
Ok(())
}
#[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_no_package() {
let piece = definition_piece();
assert_eq!(piece.id, piece_id(PIECE_NAME));
assert_eq!(piece.id.as_str(), PIECE);
assert!(piece.requires.is_empty());
for hook in [CITE_COMMAND, PRE_SPACE_COMMAND, REF_CITE_COMMAND] {
assert!(piece.content.contains(&format!("\\ProvideDocumentCommand\\{hook}{{")), "{hook}");
}
assert!(piece.content.contains("\\tl_put_right:Nn \\l_text_case_exclude_arg_tl { \\flmCite }"));
for line in ["\\def\\flmCitePreSpace{}%", "\\let\\flmCite\\flm@cite@bookmark", "\\def\\flmRefCite#1#2{}%"] {
assert!(piece.content.contains(line), "{line}");
}
}
}