use std::collections::BTreeSet;
use untechxt::preamble::{Engine, EngineSet};
use crate::model::digest::Fnv1a64;
use super::escape::Declared;
use super::names::{LatexDefinitionMode, mode_of_twin_name};
use super::packages::{ENGINES, PackageRequest};
use super::preamble::LatexPreambleDef;
pub const FONTENC: &str = "fontenc";
pub const IFTEX: &str = "iftex";
pub const DEFAULT_ENCODING_8BIT: &str = "T1";
pub const DEFAULT_ENCODING_UNICODE: &str = "TU";
pub fn default_encoding(engine: Engine) -> &'static str {
if EngineSet::UNICODE.contains(engine) {
DEFAULT_ENCODING_UNICODE
} else {
DEFAULT_ENCODING_8BIT
}
}
pub fn default_encoding_command(encoding: &str) -> String {
format!("\\renewcommand{{\\encodingdefault}}{{{encoding}}}")
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RecomposedDefinition {
pub name: String,
pub source_name: String,
pub text: String,
pub robust: bool,
pub feature: Option<String>,
pub declaration: bool,
}
impl RecomposedDefinition {
pub fn new(
name: impl Into<String>,
source_name: impl Into<String>,
text: impl Into<String>,
) -> RecomposedDefinition {
RecomposedDefinition {
name: name.into(),
source_name: source_name.into(),
text: text.into(),
robust: false,
feature: None,
declaration: false,
}
}
pub fn of_feature(mut self, feature: impl Into<String>) -> RecomposedDefinition {
self.feature = Some(feature.into());
self
}
pub fn robust(mut self) -> RecomposedDefinition {
self.robust = true;
self
}
pub fn declaration(mut self) -> RecomposedDefinition {
self.declaration = true;
self
}
}
fn one_line(text: &str) -> String {
text.chars().map(|ch| if ch == '\n' || ch == '\r' { ' ' } else { ch }).collect()
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, serde::Deserialize)]
#[derive(schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct ExtraPreamble {
pub before_packages: String,
pub after_packages: String,
pub at_end: String,
}
impl ExtraPreamble {
pub fn is_empty(&self) -> bool {
self.before_packages.is_empty()
&& self.after_packages.is_empty()
&& self.at_end.is_empty()
}
}
fn write_author_piece(out: &mut String, heading: &str, text: &str) {
if text.is_empty() {
return;
}
out.push_str(heading);
out.push_str(text);
if !text.ends_with('\n') {
out.push('\n');
}
}
type ByEngine = [Option<String>; 3];
const PDFLATEX: usize = 0;
const LUALATEX: usize = 1;
const XELATEX: usize = 2;
#[derive(Clone, Copy, PartialEq, Eq)]
enum Split {
Same,
Test(&'static str, usize),
Each,
}
impl Split {
fn of(entry: &ByEngine) -> Split {
let [pdflatex, lualatex, xelatex] = entry;
match (pdflatex == lualatex, lualatex == xelatex, pdflatex == xelatex) {
(true, true, _) => Split::Same,
(false, true, _) => Split::Test("\\iftutex", LUALATEX),
(true, false, _) => Split::Test("\\ifxetex", XELATEX),
(false, false, true) => Split::Test("\\ifluatex", LUALATEX),
(false, false, false) => Split::Each,
}
}
}
fn write_by_engine(out: &mut String, entries: &[ByEngine]) {
for run in entries.chunk_by(|a, b| Split::of(a) == Split::of(b)) {
match Split::of(&run[0]) {
Split::Same => write_branch(out, run, PDFLATEX),
Split::Test(test, at) => write_conditional(out, run, &[(test, at)]),
Split::Each => write_conditional(
out,
run,
&[("\\ifluatex", LUALATEX), ("\\ifxetex", XELATEX)],
),
}
}
}
fn write_conditional(out: &mut String, run: &[ByEngine], tests: &[(&str, usize)]) {
for (number, (test, at)) in tests.iter().enumerate() {
if number > 0 {
out.push_str("\\else");
}
out.push_str(test);
out.push('\n');
write_branch(out, run, *at);
}
if run.iter().any(|entry| entry[PDFLATEX].is_some()) {
out.push_str("\\else\n");
write_branch(out, run, PDFLATEX);
}
for _ in tests {
out.push_str("\\fi");
}
out.push('\n');
}
fn write_branch(out: &mut String, run: &[ByEngine], at: usize) {
for text in run.iter().filter_map(|entry| entry[at].as_deref()) {
out.push_str(text);
}
}
pub fn style_body(
packages: &[PackageRequest],
declared: &Declared,
pieces: &[&LatexPreambleDef],
definitions: &[RecomposedDefinition],
extra_preamble: &ExtraPreamble,
) -> String {
let mut out = String::new();
write_author_piece(
&mut out,
"% --- the author's own preamble: before the packages ---\n",
&extra_preamble.before_packages,
);
let items: Vec<ByEngine> = packages
.iter()
.map(|request| {
ENGINES.map(|engine| {
let line = request.for_engine(engine)?;
let named: Vec<String> = line.ids.iter().map(|id| one_line(id.as_str())).collect();
let requirepackage = request.requirepackage_line(engine)?;
Some(format!("% {}\n{requirepackage}\n", named.join(", ")))
})
})
.collect();
let commands: ByEngine = ENGINES.map(|engine| {
let encoding = default_encoding(engine);
packages
.iter()
.any(|request| {
request.package == FONTENC
&& request
.for_engine(engine)
.is_some_and(|line| line.options.iter().any(|option| option == encoding))
})
.then(|| format!("{}\n", default_encoding_command(encoding)))
});
if !items.is_empty() {
out.push_str("% --- packages ---\n");
if items.iter().chain([&commands]).any(|item| Split::of(item) != Split::Same) {
out.push_str(
"% Some lines below differ by TeX engine. They are written inside tests of the\n\
% engine, which the package iftex defines: \\iftutex is true under LuaLaTeX and\n\
% XeLaTeX, \\ifluatex under LuaLaTeX, and \\ifxetex under XeLaTeX. The last\n\
% branch of a test is for pdfLaTeX and any other engine.\n",
);
out.push_str(&format!("\\RequirePackage{{{IFTEX}}}\n"));
}
write_by_engine(&mut out, &items);
if commands.iter().any(Option::is_some) {
out.push_str("% --- the default font encoding ---\n");
out.push_str(
"% fontenc makes the last encoding of its option list the default, but the\n\
% options above may be merged from several requests, so their order carries\n\
% no meaning. The line below therefore sets the default for each engine whose\n\
% own encoding the request loads: T1 under pdfLaTeX, TU under LuaLaTeX and\n\
% XeLaTeX. A letter of another encoding switches to that encoding by itself.\n",
);
write_by_engine(&mut out, std::slice::from_ref(&commands));
}
}
write_author_piece(
&mut out,
"% --- the author's own preamble: after the packages ---\n",
&extra_preamble.after_packages,
);
if !declared.chars().is_empty() {
out.push_str("% --- unicode characters written as UTF-8 ---\n");
for (ch, spelling) in declared.chars() {
out.push_str("\\newunicodechar{");
out.push(*ch);
out.push_str("}{");
out.push_str(spelling);
out.push_str("}\n");
}
}
let mut seen = BTreeSet::new();
let pieces: Vec<&LatexPreambleDef> =
pieces.iter().copied().filter(|def| seen.insert(def.id.clone())).collect();
if !pieces.is_empty() {
out.push_str("% --- commands and environments the library defines for the document ---\n");
for def in pieces {
out.push_str("% ");
out.push_str(def.id.as_str());
out.push('\n');
out.push_str(&def.content);
if !def.content.ends_with('\n') {
out.push('\n');
}
}
}
let (by_features, by_document): (Vec<&RecomposedDefinition>, Vec<&RecomposedDefinition>) =
definitions.iter().partition(|definition| definition.feature.is_some());
if !by_features.is_empty() {
out.push_str("% --- definitions written from the configuration of FLM features ---\n");
for definition in by_features {
let RecomposedDefinition { name, text, robust, feature, declaration, .. } =
definition;
let renew = match (name.starts_with('\\'), robust) {
(true, false) => "\\renewcommand",
(true, true) => "\\RenewDocumentCommand",
(false, _) => "\\RenewDocumentEnvironment",
};
out.push_str("% ");
out.push_str(name);
out.push_str(" (the ");
out.push_str(feature.as_deref().unwrap_or_default());
if *declaration {
out.push_str(" feature's, written from its configuration): declared unless \\");
out.push_str(name);
out.push_str(" is already defined, so a definition made earlier under that name is kept\n");
} else {
out.push_str(
" feature's, written from its configuration): defined unless the name is \
already taken, so a definition of it made before this file is loaded wins; ",
);
out.push_str(renew);
out.push_str(" after loading this file changes it\n");
}
out.push_str(text);
if !text.ends_with('\n') {
out.push('\n');
}
}
}
if !by_document.is_empty() {
out.push_str("% --- user definitions ---\n");
for definition in by_document {
let RecomposedDefinition { name, source_name, text, robust, .. } = definition;
let is_macro = name.starts_with('\\');
let renew = match (is_macro, robust) {
(true, false) => "\\renewcommand",
(true, true) => "\\RenewDocumentCommand",
(false, _) => "\\RenewDocumentEnvironment",
};
let bare = source_name == name;
out.push_str("% ");
out.push_str(name);
if !bare {
out.push_str(" (the document's ");
out.push_str(&one_line(source_name));
match mode_of_twin_name(name.strip_prefix('\\').unwrap_or(name)) {
Some(LatexDefinitionMode::Text) => out.push_str(", in text"),
Some(LatexDefinitionMode::Mathematics) => out.push_str(", in mathematics"),
Some(LatexDefinitionMode::Single) | None => {}
}
out.push(')');
}
if bare {
out.push_str(
": defined unconditionally, under the name the document spells, as the \
render option bare_names asked; ",
);
} else {
out.push_str(
": defined unless the name is already taken, so a definition of it made \
before this file is loaded wins; ",
);
}
out.push_str(renew);
out.push_str(" after loading this file changes it\n");
out.push_str(text);
if !text.ends_with('\n') {
out.push('\n');
}
}
}
write_author_piece(
&mut out,
"% --- the author's own preamble: at the end ---\n",
&extra_preamble.at_end,
);
out.push_str("\\endinput\n");
out
}
pub fn content_hash(body: &str) -> String {
let mut hasher = Fnv1a64::new();
hasher.write_bytes(body.as_bytes());
format!("{:016x}", hasher.value())[..8].to_string()
}
pub fn with_header(name: &str, body: &str) -> String {
format!("\\NeedsTeXFormat{{LaTeX2e}}\n\\ProvidesPackage{{{name}}}\n{body}")
}
pub fn assemble_style(
name: &str,
packages: &[PackageRequest],
declared: &Declared,
pieces: &[&LatexPreambleDef],
definitions: &[RecomposedDefinition],
extra_preamble: &ExtraPreamble,
) -> String {
with_header(name, &style_body(packages, declared, pieces, definitions, extra_preamble))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::names::Name;
use crate::stdlib::backends::latex::escape::{EscapeConfig, UnicodeMode, escape_into};
use crate::stdlib::backends::latex::packages::{
self, LatexPackageDef, merge_requests, standard_packages,
};
use crate::stdlib::backends::latex::preamble::{self, standard_pieces};
fn merged(defs: &[&LatexPackageDef]) -> Vec<PackageRequest> {
let (requests, conflicts) = merge_requests(defs.iter().copied());
assert!(conflicts.is_empty(), "{conflicts:?}");
requests
}
#[test]
fn an_empty_requirement_set_gives_a_header_and_endinput() {
let style = assemble_style("flmrecomposed.00000000", &[], &Declared::new(), &[], &[], &ExtraPreamble::default());
assert_eq!(
style,
"\\NeedsTeXFormat{LaTeX2e}\n\\ProvidesPackage{flmrecomposed.00000000}\n\\endinput\n"
);
}
#[test]
fn the_blocks_come_in_order_and_a_duplicate_is_written_once() {
let roster = standard_packages();
let amsmath = roster.iter().find(|d| d.id.as_str() == packages::AMSMATH).unwrap();
let pieces = standard_pieces();
let math = pieces.iter().find(|p| p.id.as_str() == preamble::MATH_ENVIRONMENT).unwrap();
let mut declared = Declared::new();
escape_into(&mut String::new(), "é", &EscapeConfig::new(UnicodeMode::Declare), &mut declared);
let body = style_body(
&merged(&[amsmath, amsmath]),
&declared,
&[math, math],
&[
RecomposedDefinition::new(
"\\flmUDhello",
"\\hello",
"\\providecommand\\flmUDhello{hi}",
),
RecomposedDefinition::new("\\bare", "\\bare", "\\long\\def\\bare{hi}"),
RecomposedDefinition::new(
"\\flmUDfirm",
"\\firm",
"\\ProvideDocumentCommand\\flmUDfirm{+m}{hi#1}",
)
.robust(),
],
&ExtraPreamble::default(),
);
let package_at = body.find("% --- packages ---").unwrap();
let chars_at = body.find("% --- unicode characters").unwrap();
let pieces_at = body
.find("% --- commands and environments the library defines for the document ---")
.unwrap();
let defs_at = body.find("% --- user definitions ---").unwrap();
assert!(package_at < chars_at && chars_at < pieces_at && pieces_at < defs_at);
assert_eq!(body.matches("\\RequirePackage{amsmath}").count(), 1);
assert_eq!(body.matches("\\ProvideDocumentCommand\\flmMathEnvironment").count(), 1);
assert!(body.contains("\\newunicodechar{é}{\\'e}\n"));
assert!(body.contains(
"% \\flmUDhello (the document's \\hello): defined unless the name is already \
taken, so a definition of it made before this file is loaded wins; \
\\renewcommand after loading this file changes \
it\n\\providecommand\\flmUDhello{hi}\n"
));
assert!(body.contains(
"% \\bare: defined unconditionally, under the name the document spells, as the \
render option bare_names asked; \\renewcommand after loading this file \
changes it\n\\long\\def\\bare{hi}\n"
));
assert!(body.contains(
"% \\flmUDfirm (the document's \\firm): defined unless the name is already \
taken, so a definition of it made before this file is loaded wins; \
\\RenewDocumentCommand after loading this file changes \
it\n\\ProvideDocumentCommand\\flmUDfirm{+m}{hi#1}\n"
));
assert!(body.ends_with("\\endinput\n"));
}
#[test]
fn one_package_is_one_line_naming_every_identifier_behind_it() {
let plain = LatexPackageDef::new("amsmath", "the author's");
let under_another_id = LatexPackageDef::new("amsmath", "a feature's").id("flm.x.amsmath");
let with_options = LatexPackageDef::new("amsmath", "the author's")
.id("flm.y.amsmath")
.options(["fleqn"]);
let body = style_body(
&merged(&[&plain, &under_another_id, &with_options]),
&Declared::new(),
&[],
&[],
&ExtraPreamble::default(),
);
assert_eq!(
body,
"% --- packages ---\n\
% flm.latex.pkg.amsmath, flm.x.amsmath, flm.y.amsmath\n\
\\RequirePackage[fleqn]{amsmath}\n\
\\endinput\n"
);
}
const IFTEX_REQUEST: &str = "% Some lines below differ by TeX engine. They are written inside tests of the\n\
% engine, which the package iftex defines: \\iftutex is true under LuaLaTeX and\n\
% XeLaTeX, \\ifluatex under LuaLaTeX, and \\ifxetex under XeLaTeX. The last\n\
% branch of a test is for pdfLaTeX and any other engine.\n\
\\RequirePackage{iftex}\n";
const ENCODING_HEADING: &str = "% --- the default font encoding ---\n\
% fontenc makes the last encoding of its option list the default, but the\n\
% options above may be merged from several requests, so their order carries\n\
% no meaning. The line below therefore sets the default for each engine whose\n\
% own encoding the request loads: T1 under pdfLaTeX, TU under LuaLaTeX and\n\
% XeLaTeX. A letter of another encoding switches to that encoding by itself.\n";
#[test]
fn the_default_encoding_command_follows_each_engine_s_own_fontenc_line() {
let roster = standard_packages();
let fontenc: Vec<&LatexPackageDef> = roster
.iter()
.filter(|def| def.package == FONTENC)
.collect();
assert_eq!(fontenc.len(), 13);
let body = style_body(&merged(&fontenc), &Declared::new(), &[], &[], &ExtraPreamble::default());
assert!(body.starts_with(&format!("% --- packages ---\n{IFTEX_REQUEST}")), "{body}");
assert_eq!(body.matches("{fontenc}\n").count(), 2, "{body}");
assert!(body.contains("\\RequirePackage[T2A,TU,X2,T2B,T2C,OT2,T2D]{fontenc}\n"), "{body}");
assert!(body.contains("\\RequirePackage[T2A,T1,X2,T2B,T2C,OT2,T2D]{fontenc}\n"), "{body}");
let commands = format!(
"{ENCODING_HEADING}\\iftutex\n\\renewcommand{{\\encodingdefault}}{{TU}}\n\\else\n\
\\renewcommand{{\\encodingdefault}}{{T1}}\n\\fi\n"
);
assert!(body.ends_with(&format!("{commands}\\endinput\n")), "{body}");
let amsmath = roster.iter().find(|d| d.id.as_str() == packages::AMSMATH).unwrap();
let body = style_body(&merged(&[amsmath]), &Declared::new(), &[], &[], &ExtraPreamble::default());
assert!(!body.contains("iftex"), "{body}");
assert!(!body.contains("\\if"), "{body}");
assert!(!body.contains("\\encodingdefault"), "{body}");
let other = LatexPackageDef::new(FONTENC, "the author's own").options(["T2A"]);
let body = style_body(&merged(&[&other]), &Declared::new(), &[], &[], &ExtraPreamble::default());
assert!(!body.contains("\\encodingdefault"), "{body}");
let t1 = LatexPackageDef::new(FONTENC, "the author's own").options(["T1"]);
let body = style_body(&merged(&[&t1]), &Declared::new(), &[], &[], &ExtraPreamble::default());
assert_eq!(
body,
format!(
"% --- packages ---\n{IFTEX_REQUEST}% flm.latex.pkg.fontenc\n\
\\RequirePackage[T1]{{fontenc}}\n{ENCODING_HEADING}\\iftutex\n\\else\n\
\\renewcommand{{\\encodingdefault}}{{T1}}\n\\fi\n\\endinput\n"
)
);
let both = LatexPackageDef::new(FONTENC, "the author's own").options(["T1,TU"]);
let body = style_body(&merged(&[&both]), &Declared::new(), &[], &[], &ExtraPreamble::default());
assert!(body.ends_with(&format!("{commands}\\endinput\n")), "{body}");
}
#[test]
fn a_request_that_differs_by_engine_is_written_inside_an_iftex_test() {
let roster = standard_packages();
let by_id = |id: &Name| -> Vec<&LatexPackageDef> {
roster.iter().filter(|def| def.id == *id).collect()
};
let mut defs = by_id(&Name::from(packages::NEWUNICODECHAR));
defs.extend(by_id(&packages::chunk_package_id("fontenc-t1")));
defs.extend(by_id(&packages::chunk_package_id("fontenc-t2a")));
assert_eq!(defs.len(), 4);
let body = style_body(&merged(&defs), &Declared::new(), &[], &[], &ExtraPreamble::default());
assert_eq!(
body,
format!(
"% --- packages ---\n{IFTEX_REQUEST}\
% flm.latex.pkg.newunicodechar\n\
\\RequirePackage{{newunicodechar}}\n\
\\iftutex\n\
% flm.latex.pkg.untechxt.fontenc-t2a\n\
\\RequirePackage[T2A,TU]{{fontenc}}\n\
\\else\n\
% flm.latex.pkg.untechxt.fontenc-t1, flm.latex.pkg.untechxt.fontenc-t2a\n\
\\RequirePackage[T1,T2A]{{fontenc}}\n\
\\fi\n\
{ENCODING_HEADING}\
\\iftutex\n\
\\renewcommand{{\\encodingdefault}}{{TU}}\n\
\\else\n\
\\renewcommand{{\\encodingdefault}}{{T1}}\n\
\\fi\n\
\\endinput\n"
)
);
}
#[test]
fn the_three_way_case_nests_ifluatex_and_ifxetex() {
let x = |options: &'static str, engines: EngineSet| {
LatexPackageDef::new("x", "a test's").options([options]).engines(engines)
};
let (a, b, c) = (
x("a", EngineSet::PDFLATEX),
x("b", EngineSet::LUALATEX),
x("c", EngineSet::XELATEX),
);
let body = style_body(&merged(&[&a, &b, &c]), &Declared::new(), &[], &[], &ExtraPreamble::default());
assert_eq!(
body,
format!(
"% --- packages ---\n{IFTEX_REQUEST}\
\\ifluatex\n% flm.latex.pkg.x\n\\RequirePackage[b]{{x}}\n\
\\else\\ifxetex\n% flm.latex.pkg.x\n\\RequirePackage[c]{{x}}\n\
\\else\n% flm.latex.pkg.x\n\\RequirePackage[a]{{x}}\n\
\\fi\\fi\n\\endinput\n"
)
);
let unicode = x("b", EngineSet::UNICODE);
let body = style_body(&merged(&[&unicode]), &Declared::new(), &[], &[], &ExtraPreamble::default());
assert_eq!(
body,
format!(
"% --- packages ---\n{IFTEX_REQUEST}\
\\iftutex\n% flm.latex.pkg.x\n\\RequirePackage[b]{{x}}\n\\fi\n\\endinput\n"
)
);
}
#[test]
fn neighbors_that_differ_alike_share_one_test() {
let split = |package: &'static str| {
[
LatexPackageDef::new(package, "the Unicode engines'")
.options(["u"])
.engines(EngineSet::UNICODE),
LatexPackageDef::new(package, "pdfLaTeX's")
.options(["p"])
.engines(!EngineSet::UNICODE),
]
};
let [a_u, a_p] = split("a");
let [b_u, b_p] = split("b");
let same = LatexPackageDef::new("same", "every engine's");
let body = style_body(
&merged(&[&a_u, &a_p, &b_u, &b_p, &same]),
&Declared::new(),
&[],
&[],
&ExtraPreamble::default(),
);
assert_eq!(
body,
format!(
"% --- packages ---\n{IFTEX_REQUEST}\
\\iftutex\n\
% flm.latex.pkg.a\n\\RequirePackage[u]{{a}}\n\
% flm.latex.pkg.b\n\\RequirePackage[u]{{b}}\n\
\\else\n\
% flm.latex.pkg.a\n\\RequirePackage[p]{{a}}\n\
% flm.latex.pkg.b\n\\RequirePackage[p]{{b}}\n\
\\fi\n\
% flm.latex.pkg.same\n\\RequirePackage{{same}}\n\
\\endinput\n"
)
);
let body = style_body(
&merged(&[&a_u, &a_p, &same, &b_u, &b_p]),
&Declared::new(),
&[],
&[],
&ExtraPreamble::default(),
);
assert_eq!(body.matches("\\iftutex\n").count(), 2, "{body}");
}
#[test]
fn the_engine_positions_index_the_family_s_engines() {
assert_eq!(ENGINES[PDFLATEX], Engine::PdfLatex);
assert_eq!(ENGINES[LUALATEX], Engine::LuaLatex);
assert_eq!(ENGINES[XELATEX], Engine::XeLatex);
assert_eq!(default_encoding(Engine::PdfLatex), "T1");
assert_eq!(default_encoding(Engine::LuaLatex), "TU");
assert_eq!(default_encoding(Engine::XeLatex), "TU");
}
#[test]
fn a_feature_declaration_is_written_in_the_feature_block_under_its_test() {
let body = style_body(
&[],
&Declared::new(),
&[],
&[
RecomposedDefinition::new("\\flmUDa", "\\a", "\\providecommand\\flmUDa{hi}"),
RecomposedDefinition::new(
"lemma",
"lemma",
"\\ifcsname lemma\\endcsname\\else\\newtheorem{lemma}[theorem]{Lemma}\\fi",
)
.of_feature("theorems")
.declaration(),
],
&ExtraPreamble::default(),
);
let expected = "% --- definitions written from the configuration of FLM features ---\n\
% lemma (the theorems feature's, written from its configuration): declared unless \
\\lemma is already defined, so a definition made earlier under that name is kept\n\
\\ifcsname lemma\\endcsname\\else\\newtheorem{lemma}[theorem]{Lemma}\\fi\n\
% --- user definitions ---\n";
assert!(body.contains(expected), "{body}");
}
#[test]
fn a_line_break_in_an_identifier_cannot_end_the_comment_line() {
let def = LatexPackageDef::new("two\nlines", "the author's");
let body = style_body(&merged(&[&def]), &Declared::new(), &[], &[], &ExtraPreamble::default());
assert!(body.contains("% flm.latex.pkg.two lines\n"), "{body}");
assert!(body.contains("\\RequirePackage{two\nlines}\n"), "{body}");
}
#[test]
fn the_three_preamble_pieces_stand_in_their_places_byte_for_byte() {
let roster = standard_packages();
let amsmath = roster.iter().find(|d| d.id.as_str() == packages::AMSMATH).unwrap();
let block = "\\newcommand\\mine{% not a comment line of ours\n \\textbf{x}}";
let author = ExtraPreamble {
before_packages: String::from("\\PassOptionsToPackage{fleqn}{amsmath}"),
after_packages: String::from("\\ProvideDocumentCommand\\flmRef{O{} m}{#2}"),
at_end: String::from(block),
};
let body = style_body(
&merged(&[amsmath]),
&Declared::new(),
&[],
&[RecomposedDefinition::new("\\flmUDa", "\\a", "\\providecommand\\flmUDa{hi}")],
&author,
);
let before_at = body.find("% --- the author's own preamble: before the packages ---\n\\PassOptionsToPackage{fleqn}{amsmath}\n").unwrap();
let packages_at = body.find("% --- packages ---").unwrap();
let after_at = body.find("% --- the author's own preamble: after the packages ---\n\\ProvideDocumentCommand\\flmRef{O{} m}{#2}\n").unwrap();
let definitions_at = body.find("% --- user definitions ---").unwrap();
let end_at = body.find("% --- the author's own preamble: at the end ---").unwrap();
assert!(before_at < packages_at, "{body}");
assert!(packages_at < after_at && after_at < definitions_at, "{body}");
assert!(definitions_at < end_at, "{body}");
assert!(body.ends_with(&format!("{block}\n\\endinput\n")), "{body}");
let only_before = ExtraPreamble {
before_packages: String::from("\\relax\n"),
..ExtraPreamble::default()
};
assert_eq!(
style_body(&[], &Declared::new(), &[], &[], &only_before),
"% --- the author's own preamble: before the packages ---\n\\relax\n\\endinput\n"
);
let ends_in_break =
ExtraPreamble { at_end: String::from("\\relax\n"), ..ExtraPreamble::default() };
let body = style_body(&[], &Declared::new(), &[], &[], &ends_in_break);
assert!(body.ends_with("\\relax\n\\endinput\n"), "{body}");
let body = style_body(&[], &Declared::new(), &[], &[], &ExtraPreamble::default());
assert_eq!(body, "\\endinput\n");
}
#[test]
fn the_content_hash_names_the_body_and_ignores_the_header() {
let body = style_body(&[], &Declared::new(), &[], &[], &ExtraPreamble::default());
let hash = content_hash(&body);
let style = with_header(&format!("stem.{hash}"), &body);
assert!(style.starts_with("\\NeedsTeXFormat{LaTeX2e}\n\\ProvidesPackage{stem."));
assert_eq!(content_hash(&style[style.find("\\endinput").unwrap()..]), hash);
assert_ne!(content_hash("other"), hash);
}
}