flm_core/stdlib/features/xnotes/latex_rendered.rs
1//! The [`xnotes`](super) feature on the `latex-rendered` backend: its
2//! definition piece, `flm.latex.def.flmx.xnotes` ([`piece`]), and the one
3//! rule of the standard features written for this backend alone, the
4//! xnote's rule [`RULE`] ([`XnoteRenderedRule`]).
5//!
6//! # The rule
7//!
8//! An xnote kind's `placement` decides how its xnotes are written, as on
9//! every backend. For a kind placed in a list, the rule stages exactly what
10//! the general rule stages: the mark, through
11//! [`stage_mark`](super::stage_mark), a superscript span of role
12//! `flm.xnotes.xnote.mark` holding a link of kind `xnote` to the xnote's
13//! entry in the kind's list. For a kind placed in place, it stages the macro
14//! construct `\flmxXnote` with three arguments, so that LaTeX receives the
15//! mark and the content apart (LaTeX's `\footnote` takes them apart):
16//!
17//! ```latex
18//! \flmxXnote[kind=footnote, anchor=footnote-3, doc-role=footnote]{<mark>}{<content>}
19//! ```
20//!
21//! The optional argument is a raw node holding the keys: the kind's name,
22//! the xnote's anchor where the plan computes one, and the document role.
23//! The first mandatory argument is the mark, the span of role
24//! `flm.xnotes.xnote.mark` carrying the mark's anchor and holding the mark
25//! text, with no link (the content is beside it); the second is the xnote's
26//! content lowered through the rules, as blocks where it holds paragraphs.
27//! The brackets the general rule writes around an xnote in place are not
28//! written: the LaTeX definition decides the look. The rule reports what the
29//! general rule reports: the refused content of the optional argument, an
30//! empty xnote and a missing entry.
31//!
32//! # The piece
33//!
34//! The piece is the LaTeX text of the fragment `sty/xnotes.sty`, included at
35//! compile time. It defines `\flmxXnote`, which dispatches on the key `kind`
36//! (`\flmxDefineXnote{<kind>}{…}`) and whose default sets a footnote at the
37//! bottom of the page carrying FLM's mark (not LaTeX's footnote counter),
38//! the note's text beginning with the target of its anchor. It registers
39//! the block of every kind's list under the kind token `xnotes` (a block of
40//! paragraphs, the target of its anchor first) and the link kinds `xnote`
41//! and `xnote-back` as the links chunk's default link. The marks' spans are
42//! left to the span's default, the superscript of their style. Its comment
43//! block says how a template registers another look.
44//!
45//! It delivers the feature's style identifier [`STYLE`](super::STYLE),
46//! which the feature's rules require at every xnote and every list: a
47//! `latex-rendered` document holding an xnote holds the piece in its style
48//! file, and one that does not, does not.
49//!
50//! The feature contributes the piece to the LaTeX family's preamble slot
51//! ([`preamble::SLOT`]) and registers the rule under peer declarations of
52//! the backend and of the construct elements, so that a registry without
53//! the LaTeX backends still builds.
54
55use std::sync::Arc;
56
57use techy::core::node::{BuildId, NodeRef};
58
59use crate::core::lowering::{
60 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringRule,
61};
62use crate::core::registry::{BuildError, FeatureBuilder};
63use crate::lang::Flm;
64use crate::model::element::element_value;
65use crate::model::names::{ElementName, Name};
66use crate::stdlib::backends::latex::construct::{ARG_SLOT, MACRO, RAW};
67use crate::stdlib::backends::latex::preamble::{self, LatexPreambleDef};
68use crate::stdlib::backends::latex::{LatexArgShape, LatexMacroPayload, LatexRawPayload};
69use crate::stdlib::backends::latex_rendered::BACKEND;
70use crate::stdlib::backends::latex_rendered::contract::{CORE_CHUNK, LINKS_CHUNK};
71use crate::stdlib::backends::latex_rendered::emit::{anchor_spelling, is_bare_name};
72use crate::stdlib::backends::lowering::{lower_blocks_with_edges, lower_run};
73
74use super::config::{XnoteKind, XnotePlacement};
75use super::lower::{
76 Brackets, Content, Mark, find, identifiers, lower_xnote, report_empty, report_labels,
77 report_missing, write_mark,
78};
79use super::{XNOTE, XnoteElement, xnote_decl};
80
81/// The piece's identifier, `flm.latex.def.flmx.xnotes`.
82pub const PIECE: &str = "flm.latex.def.flmx.xnotes";
83
84/// The name of the xnote's rule on the `latex-rendered` backend,
85/// `flm.xnotes.xnote.lower.latex-rendered` ([`XnoteRenderedRule`]).
86pub const RULE: &str = "flm.xnotes.xnote.lower.latex-rendered";
87
88/// The LaTeX command, without the backslash, that the rule writes for an
89/// xnote of a kind placed in place, `flmxXnote`.
90pub const COMMAND: &str = "flmxXnote";
91
92/// The feature's definition piece on the `latex-rendered` backend, [`PIECE`]:
93/// the text of `sty/xnotes.sty`, requiring the links chunk, whose default
94/// link its link kinds use. See the [module documentation](self).
95pub fn piece() -> LatexPreambleDef {
96 LatexPreambleDef::new(
97 "flmx.xnotes",
98 include_str!("sty/xnotes.sty"),
99 "notes: `\\flmxXnote`, the lists of notes and the links of notes",
100 )
101 .requires([CORE_CHUNK, LINKS_CHUNK])
102 .delivering([super::STYLE])
103}
104
105/// The xnote's rule on the `latex-rendered` backend, [`RULE`]: for a kind
106/// placed in a list, the general rule's staging (the mark); for a kind
107/// placed in place, the construct `\flmxXnote`. See the
108/// [module documentation](self).
109#[derive(Debug, Default, Clone, Copy)]
110pub struct XnoteRenderedRule;
111
112impl Lower for XnoteRenderedRule {
113 fn lower(
114 &self,
115 node: NodeRef<'_, Flm>,
116 cx: &mut LowerCx<'_>,
117 lw: &mut dyn Lowerer,
118 ) -> Result<Lowering, LowerError> {
119 let value = element_value::<XnoteElement>(&node)
120 .ok_or_else(|| LowerError::structure("an xnote without its element's data"))?;
121 let kind = Arc::clone(&value.kind);
122 if matches!(kind.placement, XnotePlacement::List) {
123 // Exactly the general rule, so that the two cannot differ.
124 return lower_xnote(&node, cx, lw, Brackets::Text);
125 }
126 lw.require(&Name::from(super::STYLE));
127 report_labels(lw, &node, &kind);
128 // The element carries one xnote, the first of its kind.
129 Ok(Lowering::Emit(stage_rendered(cx, lw, &node, &kind, 0)?))
130 }
131}
132
133/// Stages the `nth` xnote of the kind `kind` that `node` carries as the
134/// construct `\flmxXnote[<keys>]{<mark>}{<content>}`: the keys as a raw
135/// node, the mark as [`write_mark`] stages it (anchored, not linked), the
136/// content lowered through the rules, as blocks where it holds paragraphs.
137/// An xnote the table does not record is written as nothing and reported as
138/// `flm.run.missing-entry`; an empty one is reported as
139/// [`Empty`](super::Empty).
140///
141/// # Errors
142///
143/// [`LowerError`] when `node` is not a node of the tree being lowered, when
144/// the calling rule did not declare what it reads or produces, and from the
145/// lowering of the content.
146fn stage_rendered(
147 cx: &mut LowerCx<'_>,
148 lw: &mut dyn Lowerer,
149 node: &NodeRef<'_, Flm>,
150 kind: &XnoteKind,
151 nth: usize,
152) -> Result<Vec<BuildId>, LowerError> {
153 let Some(record) = find(lw, node, kind, nth)? else {
154 report_missing(lw, node);
155 return Ok(Vec::new());
156 };
157 report_empty(lw, node, kind, nth)?;
158 let (_, anchor) = identifiers(lw, &record)?;
159 let keys = keys(kind.name.as_str(), anchor.as_deref());
160 let keys = lw.pres_with(cx, &ElementName::from(RAW), LatexRawPayload::new(keys), Vec::new())?;
161 let mark = write_mark(cx, lw, kind, &record, Mark { anchored: true, linked: false })?;
162 let content = Content::of(node, kind, nth);
163 let body = if content.holds_blocks(node) {
164 lower_blocks_with_edges(cx, lw, content.nodes(), Vec::new(), Vec::new())?
165 } else {
166 lower_run(cx, lw, content.nodes())?
167 };
168 let payload = LatexMacroPayload::new(
169 COMMAND,
170 vec![LatexArgShape::Optional, LatexArgShape::Mandatory, LatexArgShape::Mandatory],
171 );
172 let slots = vec![
173 (ARG_SLOT.to_string(), vec![keys]),
174 (ARG_SLOT.to_string(), vec![mark]),
175 (ARG_SLOT.to_string(), body),
176 ];
177 Ok(vec![lw.pres_slots_with(cx, &ElementName::from(MACRO), payload, slots)?])
178}
179
180/// The keys of `\flmxXnote`, written as the backend writes an element's
181/// keys: `kind=<kind>, anchor=<anchor>, doc-role=footnote`, the anchor left
182/// out where there is none, bare where it may stand bare
183/// ([`is_bare_name`]) and otherwise braced and spelled as an address
184/// ([`anchor_spelling`]), so that it reads back as itself.
185fn keys(kind: &str, anchor: Option<&str>) -> String {
186 let mut keys = format!("kind={kind}");
187 if let Some(anchor) = anchor {
188 if is_bare_name(anchor) {
189 keys.push_str(&format!(", anchor={anchor}"));
190 } else {
191 keys.push_str(&format!(", anchor={{{}}}", anchor_spelling(anchor)));
192 }
193 }
194 keys.push_str(", doc-role=footnote");
195 keys
196}
197
198/// The xnote's rule on the `latex-rendered` backend, [`RULE`]
199/// ([`XnoteRenderedRule`]), marked default on that backend only.
200pub fn rule() -> LoweringRule {
201 LoweringRule::new(
202 RULE,
203 XNOTE,
204 xnote_decl().produces(MACRO).produces(RAW),
205 Arc::new(XnoteRenderedRule),
206 DefaultMark::OnBackends(vec![BACKEND.into()]),
207 )
208 .docs(
209 "an xnote lowers as under the general rule for a listed xnote kind; for an in-place \
210 kind, to the macro construct `\\flmxXnote[<keys>]{<mark>}{<content>}`, its keys as a \
211 raw node, its mark unlinked, its content lowered through the rules",
212 )
213}
214
215/// Contributes [`piece`] to the preamble slot, and, where the configuration
216/// declares an xnote kind with a command (where the element [`XNOTE`]
217/// exists), registers [`rule`], under peer declarations of the backend and
218/// of the macro and raw construct elements.
219///
220/// # Errors
221///
222/// The [`BuildError`] of the registry builder when a declaration is made
223/// outside the registration round that accepts it.
224pub(super) fn register(b: &mut FeatureBuilder<'_>, with_element: bool) -> Result<(), BuildError> {
225 b.peer_slot::<LatexPreambleDef>(preamble::SLOT, Arc::new(piece()))?;
226 if !with_element {
227 return Ok(());
228 }
229 b.peer_backend(
230 BACKEND,
231 "the latex-rendered backend, on which the xnote's rule for this backend is the default",
232 )?;
233 b.peer_element::<LatexMacroPayload>(
234 MACRO,
235 "the LaTeX family's macro-call construct, which the rule stages for `\\flmxXnote`",
236 )?;
237 b.peer_element::<LatexRawPayload>(
238 RAW,
239 "the LaTeX family's raw node construct, which holds the keys of `\\flmxXnote`",
240 )?;
241 b.lowering_rule(rule())
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247
248 #[test]
249 fn the_piece_names_itself_and_requires_the_links_chunk() {
250 let piece = piece();
251 assert_eq!(piece.id.as_str(), PIECE);
252 assert!(piece.requires.iter().any(|id| id.as_str() == LINKS_CHUNK));
253 assert_eq!(piece.delivers, [Name::from(super::super::STYLE)]);
254 assert!(piece.content.starts_with(&format!("% {PIECE} -- ")), "{}", piece.content);
255 }
256
257 #[test]
258 fn the_keys_are_spelled_as_the_backend_spells_an_element_s_keys() {
259 assert_eq!(
260 keys("footnote", Some("footnote-3")),
261 "kind=footnote, anchor=footnote-3, doc-role=footnote"
262 );
263 assert_eq!(keys("footnote", None), "kind=footnote, doc-role=footnote");
264 assert_eq!(
265 keys("note", Some("a#b~c")),
266 "kind=note, anchor={a\\#b\\string~c}, doc-role=footnote"
267 );
268 }
269}