use crate::stdlib::backends::latex::{ExtraPreamble, LatexPreambleDef, PackageRequest};
use crate::untechxt::preamble::Engine;
use super::emit::StagedDefinition;
pub const HYPERREF_OPTIONS: &str =
"colorlinks=true, linkcolor=flmxLinkColor, urlcolor=flmxUrlColor, citecolor=flmxCiteColor";
pub const FORMAT_DATE: &str = "2022/06/01";
#[derive(Debug, Clone, Copy)]
pub struct StyleParts<'a> {
pub packages: &'a [PackageRequest],
pub hyperref: bool,
pub pieces: &'a [&'a LatexPreambleDef],
pub definitions: &'a [StagedDefinition],
pub extra: &'a ExtraPreamble,
}
fn push_lines(out: &mut String, text: &str) {
if text.is_empty() {
return;
}
out.push_str(text);
if !text.ends_with('\n') {
out.push('\n');
}
}
pub fn style_body(parts: &StyleParts<'_>) -> String {
let mut out = String::new();
out.push_str("% the engine: LuaLaTeX\n\\RequirePackage{iftex}\n\\RequireLuaTeX\n");
if !parts.extra.before_packages.is_empty() {
out.push_str("% the author's text before the packages\n");
push_lines(&mut out, &parts.extra.before_packages);
}
out.push_str("% the packages\n");
for request in parts.packages {
let Some(line) = request.requirepackage_line(Engine::LuaLatex) else { continue };
let ids: Vec<&str> = request
.for_engine(Engine::LuaLatex)
.map(|line| line.ids.iter().map(|id| id.as_str()).collect())
.unwrap_or_default();
out.push_str(&format!("% {}\n{line}\n", ids.join(", ")));
}
if parts.hyperref {
out.push_str("% hyperref, loaded at the end of the preamble\n");
out.push_str(&format!(
"\\AddToHook{{begindocument/before}}{{\\RequirePackage[{HYPERREF_OPTIONS}]{{hyperref}}}}\n"
));
}
if !parts.extra.after_packages.is_empty() {
out.push_str("% the author's text after the packages\n");
push_lines(&mut out, &parts.extra.after_packages);
}
for piece in parts.pieces {
out.push_str(&format!("% {}\n", piece.id));
push_lines(&mut out, &piece.content);
}
if !parts.definitions.is_empty() {
out.push_str("% the definitions the document's rules staged\n");
for definition in parts.definitions {
push_lines(&mut out, &definition.text);
}
}
if !parts.extra.at_end.is_empty() {
out.push_str("% the author's text at the end\n");
push_lines(&mut out, &parts.extra.at_end);
}
out.push_str("\\endinput\n");
out
}
pub fn assemble(name: &str, body: &str) -> String {
format!(
"\\NeedsTeXFormat{{LaTeX2e}}[{FORMAT_DATE}]\n\\ProvidesPackage{{{name}}}\n\
% the definitions of a document written by FLM's latex-rendered backend\n{body}"
)
}