use std::sync::Arc;
use techy::core::node::{BuildId, NodeRef};
use techy::error::Diagnostic;
use crate::core::lowering::{
DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
};
use crate::core::registry::{BuildError, FeatureBuilder};
use crate::lang::Flm;
use crate::lang::structural::PARBREAK;
use crate::model::aspects::is_whitespace_of;
use crate::model::element::{element_of, element_value};
use crate::model::names::{ElementName, Name};
use crate::stdlib::backends::latex::construct::{
ARG_SLOT, ENVIRONMENT as ENVIRONMENT_CONSTRUCT, MACRO, RAW,
};
use crate::stdlib::backends::latex::preamble::stage_length;
use crate::stdlib::backends::latex::{
LatexArgShape, LatexEnvironmentPayload, LatexMacroPayload, LatexPreambleDef, LatexRawPayload,
preamble,
};
use crate::stdlib::backends::latex_recomposed::BACKEND;
use crate::stdlib::backends::lowering::{is_blank, lower_run, stage_trimmed_runs};
use crate::stdlib::backends::pres::BODY_SLOT;
use super::config::QuoteSection;
use super::elements::{QuoteElement, section_position};
use super::lower::{bare_content, is_content, is_line_command, is_linebreak, read_line};
use super::QUOTE;
pub const LATEX_RULE: &str = "flm.quote.lower.latex-recomposed";
pub const PIECE_NAME: &str = "quote";
pub const PIECE: &str = "flm.latex.def.quote";
pub const TEXT_HOOK: &str = "flmQuoteText";
pub const LINES_HOOK: &str = "flmQuoteLines";
pub const ATTRIBUTED_HOOK: &str = "flmQuoteAttributed";
pub const BLOCK_HOOK: &str = "flmQuoteBlock";
pub const INDENT_HOOK: &str = "flmIndent";
pub fn hook_of(section: QuoteSection) -> &'static str {
match section {
QuoteSection::Text => TEXT_HOOK,
QuoteSection::Lines => LINES_HOOK,
QuoteSection::Attributed => ATTRIBUTED_HOOK,
QuoteSection::Block => BLOCK_HOOK,
}
}
pub fn definition_piece() -> LatexPreambleDef {
LatexPreambleDef::new(
PIECE_NAME,
"\
% Quotations: one command for each kind of quotation section (a passage,
% lines, an attribution, a block), written between the environment's \\begin
% and \\end lines.
% \\flmQuoteText{<passage>}: a quoted passage, ending a paragraph.
% \\flmQuoteLines{<lines>}: lines set as written, each ended by \\\\\\relax, with no
% paragraph indentation; a line's indentation is \\flmIndent{<length>} at
% its start, a tab being \\flmTabWidth.
% \\flmQuoteAttributed{<attribution>}: the attribution, on a line of its own
% set to the right, after a dash.
% \\flmQuoteBlock{<paragraphs>}: paragraphs and blocks, indented as the one
% item of a list with no label, its left margin 4em.
% \\flmIndent{<length>}: space of <length> at the start of a line.
% Redefine one of these commands to set that kind of quotation section
% differently.
% The environments blockquote (set as \\flmQuoteBlock sets its paragraphs) and
% address (a group set in \\small), which standard LaTeX does not define, are
% defined below; a definition made before this file is loaded is kept.
\\ProvideDocumentCommand\\flmQuoteText{+m}{#1\\par}
\\ProvideDocumentCommand\\flmQuoteLines{+m}{\\par\\begingroup\\setlength{\\parindent}{0pt}\\leavevmode#1\\par\\endgroup}
\\ProvideDocumentCommand\\flmQuoteAttributed{+m}{\\par\\begingroup\\raggedleft---~#1\\par\\endgroup}
\\ProvideDocumentCommand\\flmQuoteBlock{+m}{\\par\\list{}{\\itemindent\\parindent\\leftmargin=4em\\relax}\\item\\relax #1\\endlist}
\\ProvideDocumentCommand\\flmIndent{m}{\\hspace*{#1}}
\\ProvideDocumentEnvironment{blockquote}{}{\\par\\list{}{\\itemindent\\parindent\\leftmargin=4em\\relax}\\item\\relax}{\\endlist}
\\ProvideDocumentEnvironment{address}{}{\\par\\begingroup\\small}{\\par\\endgroup}
",
"`\\flmQuoteText`, `\\flmQuoteLines`, `\\flmQuoteAttributed`, `\\flmQuoteBlock`: the \
LaTeX hooks of the four kinds of quotation section; `\\flmIndent{length}`: a line's \
indentation; the environments `blockquote` and `address`",
)
}
#[derive(Debug, Default, Clone, Copy)]
pub struct QuoteLatexRule;
impl Lower for QuoteLatexRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let value = element_value::<QuoteElement>(&node)
.ok_or_else(|| LowerError::structure("a quotation without its value"))?;
lw.require(&Name::from(PIECE));
let body: Vec<NodeRef<'_, Flm>> =
node.body().map(|body| body.iter().collect()).unwrap_or_default();
let mut content = Vec::new();
let mut start = 0;
for (at, child) in body.iter().enumerate() {
if let Some(position) = section_position(child) {
bare_run(cx, lw, value, &body[start..at], &mut content)?;
let section = match position.section {
QuoteSection::Lines => {
let nodes: Vec<NodeRef<'_, Flm>> = child
.argument_content_nodes(0)
.map(|nodes| nodes.iter().collect())
.unwrap_or_default();
stage_lines(cx, lw, &nodes)?
}
_ => lw.lower_arg(cx, child, 0)?,
};
content.push(hook(cx, lw, position.section, section)?);
start = at + 1;
}
}
bare_run(cx, lw, value, &body[start..], &mut content)?;
let environment = lw.pres_slots_with(
cx,
&ElementName::from(ENVIRONMENT_CONSTRUCT),
LatexEnvironmentPayload::new(value.name.as_str(), Vec::new()),
vec![(String::from(BODY_SLOT), content)],
)?;
Ok(Lowering::Emit(vec![environment]))
}
}
fn bare_run(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
value: &QuoteElement,
run: &[NodeRef<'_, Flm>],
out: &mut Vec<BuildId>,
) -> Result<(), LowerError> {
let Some(first) = run.iter().position(|node| !is_edge(node)) else {
out.extend(lower_edge(cx, lw, run)?);
return Ok(());
};
let last = run.iter().rposition(|node| !is_edge(node)).unwrap_or(first);
out.extend(lower_edge(cx, lw, &run[..first])?);
let core = &run[first..=last];
match value.environment.bare {
Some(QuoteSection::Lines) => {
let lines = stage_lines(cx, lw, core)?;
out.push(hook(cx, lw, QuoteSection::Lines, lines)?);
}
Some(kind) => {
let content = stage_trimmed_runs(cx, lw, &[core], is_line_command)?;
out.push(hook(cx, lw, kind, content)?);
}
None => {
lw.diagnose(Diagnostic::error(bare_content(value), core[0].span().clone()));
out.extend(lower_run(cx, lw, core)?);
}
}
out.extend(lower_edge(cx, lw, &run[last + 1..])?);
Ok(())
}
fn is_edge(node: &NodeRef<'_, Flm>) -> bool {
node.is_comment() || is_blank(node) || element_of(node).name.as_str() == PARBREAK
}
fn lower_edge(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
edge: &[NodeRef<'_, Flm>],
) -> Result<Vec<BuildId>, LowerError> {
let mut out = Vec::new();
for run in edge.split(is_whitespace_of) {
out.extend(lower_run(cx, lw, run)?);
}
Ok(out)
}
fn stage_lines(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
content: &[NodeRef<'_, Flm>],
) -> Result<Vec<BuildId>, LowerError> {
let mut out = Vec::new();
if !content.iter().any(|node| is_content(node) || is_linebreak(node)) {
return Ok(out);
}
for (index, line) in content.split(is_linebreak).enumerate() {
if index > 0 {
out.push(raw(cx, lw, "\\\\\\relax\n")?);
}
let (indent, runs) = read_line(lw, line);
if !indent.is_zero() {
let length = stage_length(cx, lw, &indent)?;
out.push(lw.pres_slots_with(
cx,
&ElementName::from(MACRO),
LatexMacroPayload::new(INDENT_HOOK, [LatexArgShape::Mandatory]),
vec![(String::from(ARG_SLOT), vec![length])],
)?);
}
out.extend(stage_trimmed_runs(cx, lw, &runs, is_line_command)?);
}
Ok(out)
}
fn hook(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
section: QuoteSection,
content: Vec<BuildId>,
) -> Result<BuildId, LowerError> {
lw.pres_slots_with(
cx,
&ElementName::from(MACRO),
LatexMacroPayload::new(hook_of(section), [LatexArgShape::Mandatory]),
vec![(String::from(ARG_SLOT), content)],
)
}
fn raw(cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer, text: &str) -> Result<BuildId, LowerError> {
lw.pres_with(cx, &ElementName::from(RAW), LatexRawPayload::new(text), Vec::new())
}
pub fn latex_rule() -> LoweringRule {
LoweringRule::new(
LATEX_RULE,
QUOTE,
LoweringDecl::new()
.produces(ENVIRONMENT_CONSTRUCT)
.produces(MACRO)
.produces(RAW),
Arc::new(QuoteLatexRule),
DefaultMark::OnBackends(vec![BACKEND.into()]),
)
.docs(
"a quotation lowers to the environment of its name, each quotation section through the \
LaTeX hook of its kind, and a line's indentation through `\\flmIndent`",
)
}
pub(super) fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
b.peer_backend(
BACKEND,
"the latex-recomposed backend, on which the quotation's rule \
`flm.quote.lower.latex-recomposed` is the default",
)?;
b.peer_element::<LatexEnvironmentPayload>(
ENVIRONMENT_CONSTRUCT,
"the LaTeX family's environment construct, which the recomposition rule stages",
)?;
b.peer_element::<LatexMacroPayload>(
MACRO,
"the LaTeX family's macro-call construct, which the recomposition rule stages for the \
LaTeX hooks of the quotation sections and of a line's indentation",
)?;
b.peer_element::<LatexRawPayload>(
RAW,
"the LaTeX family's raw node construct, in which the recomposition rule writes the \
line breaks between lines and the length of a line's indentation",
)?;
b.peer_slot::<LatexPreambleDef>(preamble::SLOT, Arc::new(definition_piece()))?;
b.lowering_rule(latex_rule())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_piece_provides_the_four_hooks_and_the_indentation() {
let piece = definition_piece();
assert_eq!(piece.id.as_str(), PIECE);
for hook in [TEXT_HOOK, LINES_HOOK, ATTRIBUTED_HOOK, BLOCK_HOOK, INDENT_HOOK] {
assert!(
piece.content.contains(&format!("\\ProvideDocumentCommand\\{hook}{{")),
"{hook}"
);
}
assert!(piece.requires.is_empty());
}
#[test]
fn the_piece_provides_only_the_two_environments_latex_lacks() {
let piece = definition_piece();
for name in ["blockquote", "address"] {
let definition = format!("\\ProvideDocumentEnvironment{{{name}}}{{}}");
assert_eq!(piece.content.matches(&definition).count(), 1, "{name}");
}
assert!(!piece.content.contains("Environment{quote}"));
}
}