use techy::core::node::BuildId;
use std::collections::BTreeSet;
use crate::core::lowering::{LowerCx, LowerError, Lowerer};
use crate::core::services::Services;
use untechxt::preamble::ChunkPreamble;
use crate::model::names::{ElementName, Name};
use crate::stdlib::backends::pres::{Length, LengthUnit, VerbatimKind};
use super::construct::{LatexRawPayload, RAW};
use super::packages;
pub const SLOT: &str = "flm.latex.preamble";
pub const ID_PREFIX: &str = "flm.latex.def.";
pub fn split_requirements<'n>(
ids: impl IntoIterator<Item = &'n Name>,
) -> (BTreeSet<Name>, BTreeSet<Name>) {
ids.into_iter().cloned().partition(|id| id.as_str().starts_with(ID_PREFIX))
}
pub const REFS: &str = "flm.latex.def.refs";
pub const HYPERREF: &str = "flm.latex.def.hyperref";
pub const LABEL_DISPLAY_TEXT: &str = "flm.latex.def.label-display-text";
pub const ZREF_CLEVER_TYPE: &str = "flm.latex.def.zref-clever-type";
pub const LABELS: &str = "flm.latex.def.labels";
pub const HEADING: &str = "flm.latex.def.heading";
pub const VERBATIM: &str = "flm.latex.def.verbatim";
pub const MATH_ENVIRONMENT: &str = "flm.latex.def.math-environment";
pub const IF_BLANK: &str = "flm.latex.def.ifblank";
pub const USER_ARGS: &str = "flm.latex.def.userargs";
pub const TAB_WIDTH: &str = "flm.latex.def.tab-width";
pub const TAB_WIDTH_LENGTH: &str = "flmTabWidth";
pub fn stage_length(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
length: &Length,
) -> Result<BuildId, LowerError> {
if length.unit == LengthUnit::Tabs {
lw.require(&Name::from(TAB_WIDTH));
}
lw.pres_with(cx, &ElementName::from(RAW), LatexRawPayload::new(latex_length(length)), Vec::new())
}
fn latex_length(length: &Length) -> String {
let amount = length.amount_decimal();
match length.unit {
LengthUnit::Tabs => format!("{amount}\\{TAB_WIDTH_LENGTH}"),
LengthUnit::Points => format!("{amount}bp"),
LengthUnit::Ems | LengthUnit::Millimeters | LengthUnit::Centimeters | LengthUnit::Inches => {
length.to_string()
}
}
}
pub fn piece_id(name: &str) -> Name {
Name::from(format!("{ID_PREFIX}{name}"))
}
pub const CHUNK_ID_PREFIX: &str = "flm.latex.def.untechxt.";
pub fn chunk_piece_id(chunk_id: &str) -> Name {
Name::from(format!("{CHUNK_ID_PREFIX}{chunk_id}"))
}
pub const ESCVERB: &str = "EscVerb";
pub const HEADING_COMMAND: &str = "flmHeading";
pub const LABELS_COMMAND: &str = "flmLabels";
pub const LABELS_WITH_DISPLAY_TEXT_COMMAND: &str = "flmLabelsWithDisplayText";
pub const PHANTOMSECTION_COMMAND: &str = "phantomsection";
pub const REF_COMMAND: &str = "flmRef";
pub const HYPERREF_COMMAND: &str = "flmHyperref";
pub const HYPERREF_PACKAGE_COMMAND: &str = "hyperref";
pub const INTERNAL_REF_COUNTER: &str = "flm@internal@refcnt";
pub const INTERNAL_REF_TYPE: &str = "flm--internal--ref";
pub const NO_CASE_CHANGE: &str = "NoCaseChange";
pub const BLANK_COMMAND: &str = "flmIfBlankTF";
pub const ARG_COMMAND: &str = "flmArg";
pub const IF_ARG_COMMAND: &str = "flmIfArgTF";
pub const IF_ARG_BLANK_COMMAND: &str = "flmIfArgBlankTF";
pub const FMT_VRB: &str = "flmFmtVRB";
pub const VRB_FAMILY: &str = "flmVRBFamily";
pub const VERBATIM_CODE_ENVIRONMENT: &str = "flmVerbatimCode";
pub const VERBATIM_TEXT_ENVIRONMENT: &str = "flmVerbatimText";
pub const VERBATIM_BLOCK_COMMAND: &str = "flmVerbatimBlock";
pub fn verbatim_hook(kind: VerbatimKind) -> &'static str {
match kind {
VerbatimKind::Text => "verbtext",
VerbatimKind::Code => "verbcode",
VerbatimKind::Identifier => "verba",
}
}
pub fn escverb_options(kind: VerbatimKind) -> String {
format!("fontfamily=\\{VRB_FAMILY},formatcom=\\{FMT_VRB}{{{}}}", verbatim_hook(kind))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LatexPreambleDef {
pub id: Name,
pub requires: Vec<Name>,
pub content: String,
pub docs: String,
pub delivers: Vec<Name>,
}
impl LatexPreambleDef {
pub fn new(name: &str, content: impl Into<String>, docs: impl Into<String>) -> Self {
LatexPreambleDef {
id: piece_id(name),
requires: Vec::new(),
content: content.into(),
docs: crate::kept_docs(docs),
delivers: Vec::new(),
}
}
pub fn requires(mut self, ids: impl IntoIterator<Item = impl Into<Name>>) -> Self {
self.requires = ids.into_iter().map(Into::into).collect();
self
}
pub fn delivering(mut self, ids: impl IntoIterator<Item = impl Into<Name>>) -> Self {
self.delivers = ids.into_iter().map(Into::into).collect();
self
}
}
pub fn pieces(services: &Services) -> impl Iterator<Item = &LatexPreambleDef> + '_ {
services.services_named::<LatexPreambleDef>(SLOT)
}
pub fn definitions(services: &Services) -> Vec<&LatexPreambleDef> {
let mut chosen: Vec<&LatexPreambleDef> = Vec::new();
for piece in services.services_by_precedence_named::<LatexPreambleDef>(SLOT) {
if !chosen.iter().any(|seen| seen.id == piece.id) {
chosen.push(piece);
}
}
let mut placed: BTreeSet<&Name> = BTreeSet::new();
pieces(services)
.filter(|piece| chosen.iter().any(|kept| std::ptr::eq(*kept, *piece)) && placed.insert(&piece.id))
.collect()
}
pub fn piece_named<'s>(services: &'s Services, id: &str) -> Option<&'s LatexPreambleDef> {
services.services_by_precedence_named::<LatexPreambleDef>(SLOT).find(|def| def.id.as_str() == id)
}
pub fn refs_piece() -> LatexPreambleDef {
LatexPreambleDef::new(
"refs",
"\
% \\flmRef[<options>]{<label>}: a reference that gives the name of its target
% (\"Section 2\"), set by \\zcref of the zref-clever package.
%
% The options are the ones the document wrote, in FLM's own vocabulary. This
% definition translates each of them by its key -- a value written after the
% key is ignored, as in FLM -- and drops every key it has no translation for:
%
% noprefix -> noname the number or title alone, with no
% name before it (\"2\", not
% \"Section 2\")
% S -> S the first name capitalized and
% unabbreviated, for a reference that
% opens a sentence
% capital -> cap=true,abbrev=false the names capitalized (\"Lemma 1\")
% lowercase -> cap=false,abbrev=false the names in lowercase (\"lemma 1\")
% abbreviated -> abbrev=true the abbreviated names (\"Lem. 1\")
% where the reference type declares
% them, the full names otherwise
% anything else -> dropped the default wording; a variant of
% your own naming has no counterpart
% in zref-clever, which would stop on
% a key it does not know
%
% Redefine \\flmRef to set references differently -- another package, another
% wording, your own variants, no link. Your definition sees the options as the
% document wrote them, in FLM's vocabulary, and maps them as it likes.
%
% The translation uses expl3, LaTeX's programming layer, which is part of the
% format and needs no package; its names read only between \\ExplSyntaxOn and
% \\ExplSyntaxOff. \\keyval_parse:NNn reads the option list as LaTeX reads any
% key-value list: it hands a key written alone to the first macro below and a
% key with its value to the second, which drops the value. \\str_case:nnF looks
% the key up in the table and appends what \\zcref is to be given, or nothing.
% The macros with @ in their names are internals, not a customization point:
% redefine \\flmRef, not its parts.
\\ExplSyntaxOn
\\def\\flm@ref@add#1{\\tl_put_right:Nn \\flm@ref@options {#1,}}
\\def\\flm@ref@key#1{\\str_case:nnF {#1}
{{noprefix}{\\flm@ref@add{noname}}
{S}{\\flm@ref@add{S}}
{capital}{\\flm@ref@add{cap=true,abbrev=false}}
{lowercase}{\\flm@ref@add{cap=false,abbrev=false}}
{abbreviated}{\\flm@ref@add{abbrev=true}}}
{}}
\\def\\flm@ref@pair#1#2{\\flm@ref@key{#1}}
\\def\\flm@ref@zcref#1#2{\\zcref[#1]{#2}}
\\ProvideDocumentCommand\\flmRef{O{} m}{%
\\def\\flm@ref@options{}%
\\keyval_parse:NNn \\flm@ref@key \\flm@ref@pair {#1}%
\\exp_args:No \\flm@ref@zcref {\\flm@ref@options} {#2}}
\\ExplSyntaxOff
",
"`\\flmRef[options]{label}`, the LaTeX hook every reference is written with: sets the \
reference with `\\zcref`, translating the reference options into those of \
`zref-clever`; needed by every reference",
)
.requires([packages::ZREF_CLEVER])
}
pub fn hyperref_piece() -> LatexPreambleDef {
LatexPreambleDef::new(
"hyperref",
"\
% \\flmHyperref{<label>}{<text>}: <text>, shown as a link to the place <label>
% refers to.
%
% Making a link in a PDF takes the hyperref package, and loading it changes a
% whole document -- every reference becomes a link, bookmarks are built. That
% is the author's decision, not this file's, so this file neither loads
% hyperref nor asks for it: the definition below links through it where the
% document loaded it and prints the text alone where it did not, so the
% document compiles either way. The question is about this document's own
% preamble, so the answer is the same wherever the document is compiled; it is
% asked here, at the reference, so it is right whether this file was loaded
% before hyperref or after it.
%
% Redefine \\flmHyperref to link differently -- another package, a footnote
% with the target's number, no link at all.
\\ProvideDocumentCommand\\flmHyperref{m m}{%
\\IfPackageLoadedTF{hyperref}{\\hyperref[{#1}]{#2}}{#2}}
% What such a reference contributes to a PDF bookmark: the text alone. A
% bookmark is plain text and carries no link, and without this line the label
% would appear in it beside the text. The hook runs when the document begins
% and does nothing where hyperref is absent.
\\AtBeginDocument{\\ifdefined\\pdfstringdefDisableCommands
\\pdfstringdefDisableCommands{%
\\def\\flmHyperref#1#2{#2}%
}\\fi}
",
"`\\flmHyperref{label}{text}`, the LaTeX hook of a reference that shows the author's own \
words: a link through `hyperref` where the document loaded it, the text alone \
otherwise; needed by such references",
)
}
pub fn label_display_text_piece() -> LatexPreambleDef {
LatexPreambleDef::new(
"label-display-text",
"\
% \\flmLabelsWithDisplayText{<text>}{<labels>}: makes <labels> refer to this
% place, with <text> as what a reference to them prints. It is the only
% command for that: a heading the class did not number uses it, and so does
% anything else that has a name but no number.
%
% It places no anchor of its own. Under hyperref a sectioning command, starred
% or not, already places one at the title; a \\label after it points there.
% \\refstepcounter would place a second anchor here, below the title, and a
% link would lead below the heading. So the counter is stepped with
% the plain \\stepcounter and the two things this needs are set here:
% \\@currentlabel, which is what a \\label records, and \\@currentcounter,
% which is what zref-clever reads to give the label its reference type. The
% group keeps every change local.
%
% <text> is expanded to make \\@currentlabel, and \\label does not survive that
% expansion; so a \\label inside <text> (for example a footnote's) is dropped
% from the label's text only. At its own place in the document it still makes
% its own label.
%
% A caller with no sectioning command before it -- for example a defined term
% in running text -- writes \\phantomsection at its own place, so that a link
% has an anchor of its own to lead to.
%
% Redefine \\flmLabelsWithDisplayText to change how such labels are made.
\\ifcsname c@flm@internal@refcnt\\endcsname\\else\\newcounter{flm@internal@refcnt}\\fi
\\ProvideDocumentCommand\\flmLabelsWithDisplayText{m m}{%
\\begingroup
\\stepcounter{flm@internal@refcnt}%
{\\let\\label\\@gobble\\protected@xdef\\flm@lwdt@text{#1}}%
\\let\\@currentlabel\\flm@lwdt@text
\\def\\@currentcounter{flm@internal@refcnt}%
#2%
\\endgroup}
",
"`\\flmLabelsWithDisplayText{text}{labels}`: makes labels refer to the current \
place, with `text` as what a reference to them prints; needed by unnumbered headings, \
defined terms and the labeled captions of unnumbered floats",
)
}
pub fn zref_clever_type_piece() -> LatexPreambleDef {
LatexPreambleDef::new(
"zref-clever-type",
"\
% The zref-clever reference type of the counter \\flmLabelsWithDisplayText
% steps, with every name prefix empty, so that a reference to such a label
% prints its text alone (\"Introduction\", not \"Section Introduction\").
% Every other label keeps the name its own type gives it. Redefine these
% settings, or the type of the counter, to put something before the text.
\\zcsetup{countertype={flm@internal@refcnt=flm--internal--ref}}
\\zcRefTypeSetup{flm--internal--ref}{Name-sg = , name-sg = , Name-pl = , name-pl = ,}
",
"the `zref-clever` reference type with which a reference to a label made by \
`\\flmLabelsWithDisplayText` prints its text alone; needed by unnumbered headings, \
defined terms and the labeled captions of unnumbered floats",
)
.requires([packages::ZREF_CLEVER, LABEL_DISPLAY_TEXT])
}
pub fn labels_piece() -> LatexPreambleDef {
LatexPreambleDef::new(
"labels",
"\
% \\flmLabels{<\\label commands>}: the labels of one place in the document.
% In text it runs them as written. On a line of a display-math
% environment, where amsmath keeps the last label of a line and loses the
% ones before it, it runs the first and records every further one as an alias:
% a line per alias is written to the .aux file after the last page and read on
% the next run, making the alias refer to what the first label refers to
% (for \\ref and for \\zcref alike). Redefine \\flmLabels to change what a
% group of labels does; \\def\\flmLabels#1{#1} restores plain LaTeX behavior,
% amsmath's \"Multiple \\label's\" message included.
\\ProvideDocumentCommand\\flmLabels{m}{%
\\ifmmode\\expandafter\\flm@labels@math\\else\\expandafter\\@firstofone\\fi{#1}}
% Reading the group: the first \\label as written, the rest as aliases of it.
\\def\\flm@labels@math#1{\\def\\flm@lbl@first{}\\flm@lbl@scan#1\\flm@lbl@stop}
\\def\\flm@lbl@scan{\\@ifnextchar\\label\\flm@lbl@take\\flm@lbl@rest}
\\def\\flm@lbl@take\\label#1{%
\\ifx\\flm@lbl@first\\@empty
\\def\\flm@lbl@first{#1}%
\\label{#1}%
\\else
\\expandafter\\flm@recordalias\\expandafter{\\flm@lbl@first}{#1}%
\\fi
\\flm@lbl@scan}
\\def\\flm@lbl@rest#1\\flm@lbl@stop{#1}
% Collecting the aliases. A name is recorded once however often the line is
% typeset (amsmath measures a line before setting it).
\\def\\flm@aliaslist{}
\\def\\flm@recordalias#1#2{%
\\ifcsname flm@alias@#2\\endcsname\\else
\\expandafter\\gdef\\csname flm@alias@#2\\endcsname{}%
\\g@addto@macro\\flm@aliaslist{\\flm@alias@entry{#2}{#1}}%
\\fi}
% Writing them, from the hook that runs after the last page has been shipped
% out: every \\newlabel of that page has reached the .aux file by then, so the
% alias lines come after them. \\AtEndDocument would run too early.
\\def\\flm@alias@write#1#2{\\immediate\\write\\@auxout{\\string\\flm@aliaslabel{#1}{#2}}}
\\AddToHook{enddocument/afterlastpage}{\\let\\flm@alias@entry\\flm@alias@write\\flm@aliaslist}
% Reading them back: the alias refers to what the original refers to. The
% assignments are global because the .aux file is read inside a group.
\\def\\flm@aliaslabel#1#2{%
\\ifcsname r@#2\\endcsname
\\global\\expandafter\\let\\csname r@#1\\expandafter\\endcsname\\csname r@#2\\endcsname
\\fi
\\ifcsname Z@R@#2\\endcsname
\\global\\expandafter\\let\\csname Z@R@#1\\expandafter\\endcsname\\csname Z@R@#2\\endcsname
\\fi}
",
"`\\flmLabels{...}`, the LaTeX hook every group of labels is written with: makes every \
label on a line of display mathematics resolve; needed by every label",
)
}
pub fn heading_piece() -> LatexPreambleDef {
LatexPreambleDef::new(
"heading",
"\
% \\flmHeading[<keys>]<sectioning command><star>{<title>}{<labels>}: a heading
% and the labels that refer to it, written on two lines for readability, as in
% \\flmHeading[toc=true]
% \\section*{Title}{\\flmLabels{\\label{ref1}}}
% It runs the sectioning command as written, then makes the labels refer to
% the heading: by its number when the class numbered it, by its title when it
% did not (a starred heading, or a level below secnumdepth). It finds out
% which without patching anything: a class numbers a heading through
% \\refstepcounter, which records the counter's name in \\@currentcounter.
%
% The optional argument is a key-value list. It is written here, on the hook,
% and never on the sectioning command: a starred sectioning command takes no
% optional argument, and giving one to \\section* is not an error, it is
% silently wrong -- \\section*[Short]{Long} takes one token as its heading,
% so the opening bracket alone becomes the heading and Short, the closing
% bracket and Long all run together into the following paragraph. Two keys
% are defined:
%
% toc=true|false whether the heading is listed in the table of contents.
% Absent, it is listed as LaTeX lists it. After a starred
% sectioning command with toc=true, which LaTeX never
% lists, \\addcontentsline{toc}{<level>}{<entry>} adds it:
% <level> is the command's own name (section for
% \\section), <entry> the alternative title if alt was
% written, else the title; under hyperref the starred
% command has already placed the anchor the line links
% to. On an unstarred heading toc=false is not honored:
% the heading stays listed and a warning says so.
%
% alt={Short title} an alternative title: what goes into the table of
% contents, the running head and the PDF bookmark, while
% the page keeps the full title. It is handed to the
% sectioning command as its own optional argument, so it
% does what \\section[Short title]{Full title} does, and
% nothing else: a reference to an unnumbered heading still
% prints the full title. A starred heading does not hand
% it to the sectioning command; where it is written
% toc=true, alt is its line in the table of contents.
%
% What counts is whether the key was written, not what it holds. alt={} is an
% empty alternative title and is handed over as \\section[]{Full title}, which
% is how LaTeX asks for an empty table-of-contents entry; no optional argument
% at all, and an empty one ([]), hand nothing over and leave the sectioning
% command exactly as it was. Writing alt with no value is LaTeX's own error,
% as is a key that is not defined here, and a value of toc other than true or
% false. The values and the record that alt was written are cleared at every
% call, so one heading's keys never reach the next. The recomposed LaTeX writes
% toc on every heading and alt where the heading was given an alternative
% title; both keys are also there for a document written by hand and for a
% user who redefines the hook.
%
% Redefine \\flmHeading to change what a heading does. The block below uses
% expl3, LaTeX's programming layer, which is part of the format and needs no
% package; its names read only between \\ExplSyntaxOn and \\ExplSyntaxOff.
% \\keys_define:nn declares the keys and \\keys_set:nn reads a list of them;
% \\bool_if:NTF asks whether the key was written. The three declarations are
% guarded on their own names, as every declaration in this file is, so that two
% of these style files can be loaded in one LaTeX run. The macros with @ in
% their names are internals, not a customization point: redefine \\flmHeading,
% not its parts.
\\ExplSyntaxOn
\\ifcsname flm@heading@alt\\endcsname\\else\\tl_new:N \\flm@heading@alt\\fi
\\ifcsname flm@heading@given\\endcsname\\else\\bool_new:N \\flm@heading@given\\fi
\\ifcsname flm@heading@toc\\endcsname\\else\\tl_new:N \\flm@heading@toc\\fi
\\keys_define:nn {flm/heading}
{alt .code:n = {\\tl_set:Nn \\flm@heading@alt {#1}
\\bool_set_true:N \\flm@heading@given} ,
alt .value_required:n = true ,
toc .choices:nn = {true, false} {\\tl_set_eq:NN \\flm@heading@toc \\l_keys_choice_tl} ,
toc .value_required:n = true}
\\def\\flm@heading@withalt#1#2#3{#2[#1]{#3}}
% The contents line of a starred heading: <level> then <entry>.
\\def\\flm@heading@addtoc#1#2{\\addcontentsline{toc}{#1}{#2}}
% toc=false on an unstarred heading: the heading stays listed.
\\def\\flm@heading@notoc#1{\\PackageWarning{flm}{toc=false~on~the~unstarred~
\\string#1~is~not~honored~by~the~default~\\string\\flmHeading;~the~heading~
stays~in~the~table~of~contents}}
\\ProvideDocumentCommand\\flmHeading{O{} m s m m}{%
\\tl_clear:N \\flm@heading@alt
\\bool_set_false:N \\flm@heading@given
\\tl_clear:N \\flm@heading@toc
\\keys_set:nn {flm/heading} {#1}%
\\def\\@currentcounter{}%
\\IfBooleanTF{#3}
{#2*{#4}%
\\str_if_eq:VnT \\flm@heading@toc {true}
{\\edef\\flm@heading@level{\\cs_to_str:N #2}%
\\bool_if:NTF \\flm@heading@given
{\\exp_args:NVV \\flm@heading@addtoc \\flm@heading@level \\flm@heading@alt}
{\\exp_args:NV \\flm@heading@addtoc \\flm@heading@level {#4}}}}
{\\str_if_eq:VnT \\flm@heading@toc {false} {\\flm@heading@notoc{#2}}%
\\bool_if:NTF \\flm@heading@given
{\\exp_args:NV \\flm@heading@withalt \\flm@heading@alt #2{#4}}
{#2{#4}}}%
\\ifx\\@currentcounter\\@empty
\\flmLabelsWithDisplayText{#4}{#5}%
\\else
#5%
\\fi}
\\ExplSyntaxOff
",
"`\\flmHeading[toc=...,alt={...}]`, the LaTeX hook written before every sectioning \
command: makes a reference to an unnumbered heading print its title, lists a starred \
heading written with `toc=true` in the table of contents, and takes an alternative \
title for the table of contents and the PDF bookmark; needed by every heading",
)
.requires([LABELS, LABEL_DISPLAY_TEXT, ZREF_CLEVER_TYPE])
}
pub fn verbatim_piece() -> LatexPreambleDef {
LatexPreambleDef::new(
"verbatim",
"\
% Verbatim content. Inline content is written as
% \\EscVerb[fontfamily=\\flmVRBFamily,formatcom=\\flmFmtVRB{<kind>}]{<escaped content>}
% and block content as the flmVerbatimCode environment. \\EscVerb comes with
% fvextra 1.5 (2022) and later, which this file requires.
% \\flmVRBFamily, the font family of the surrounding text, is given to fancyvrb
% as fontfamily: fancyvrb keeps that family, and each kind's hook alone sets the
% font. It is expandable, as fancyvrb's fontfamily needs.
\\providecommand\\flmVRBFamily{\\f@family}
% \\flmFmtVRB{<kind>} runs the hook \\flmFmtVRB<kind>; redefine
% \\flmFmtVRBverbtext, \\flmFmtVRBverbcode or \\flmFmtVRBverba to change how
% that kind of verbatim content is set.
\\ProvideDocumentCommand\\flmFmtVRBverbtext{}{}
\\ProvideDocumentCommand\\flmFmtVRBverbcode{}{\\ttfamily}
\\ProvideDocumentCommand\\flmFmtVRBverba{}{\\itshape}
\\ProvideDocumentCommand\\flmFmtVRB{m}{\\csname flmFmtVRB#1\\endcsname}
% \\flmVerbatimCodeSetup{<lang>} runs at the start of a flmVerbatimCode
% environment with its language tag (empty when none was given); redefine
% it to attach syntax highlighting. It runs before the Verbatim environment
% opens, so it must not open a group or an environment of its own.
\\ProvideDocumentCommand\\flmVerbatimCodeSetup{m}{}
% flmVerbatimCode[<lang>]: a block of code, set with the verbcode hook. The
% recomposed LaTeX always writes the brackets, [<lang>] or [], because LaTeX's
% lookahead for an absent optional argument swallows the line end that the
% verbatim content must begin after. Define the environment before loading
% this file to replace it.
\\ProvideDocumentEnvironment{flmVerbatimCode}{O{}}{%
\\flmVerbatimCodeSetup{#1}%
\\VerbatimEnvironment
\\begin{Verbatim}[formatcom=\\flmFmtVRB{verbcode}]}%
{\\end{Verbatim}}
% flmVerbatimText[<lang>]: a block of plain verbatim text, set with the
% verbtext hook in the font family of the surrounding text. It takes the same
% optional argument as flmVerbatimCode and ignores it, so that one command
% (\\flmVerbatimBlock below), which always writes the brackets, serves either
% environment.
\\ProvideDocumentEnvironment{flmVerbatimText}{O{}}{%
\\VerbatimEnvironment
\\begin{Verbatim}[fontfamily=\\flmVRBFamily,formatcom=\\flmFmtVRB{verbtext}]}%
{\\end{Verbatim}}
% \\flmVerbatimBlock[<options>]{<environment>}{<lines>}: one block of verbatim
% content written as a single macro call, for the places a block cannot be
% written out in full -- inside an argument of a call, inside the body a
% body-grabbing environment hands over, inside a definition's own body -- where
% LaTeX has read the characters long before anything can say they are verbatim.
% The three arguments:
% <options> the block environment's own optional argument, always
% written, [<lang>] or [];
% <environment> the environment's name, flmVerbatimCode for a code block;
% <lines> one brace group per line of the block, and inside each line
% one brace group per tab-separated segment, every segment
% written in the encoding \\EscVerb reads (a backslash before
% every printable ASCII character that is not a letter or a
% digit). The line and segment structure is carried by braces
% rather than by characters because a line feed written into an
% auxiliary file comes back from it as a space, and a tab
% inside an argument is a space before anything can look at it;
% brace groups survive both.
% The command un-escapes every segment with fvextra's own un-escaper, joins the
% segments of a line with a tab and the lines with a line feed, and hands
% \\begin{<environment>}[<options>] ... \\end{<environment>} to \\scantokens,
% which offers that text to TeX as if it were a file: the environment is
% entered for real, and fancyvrb reads its lines the way it reads them out of
% any file. This is the only place this file uses \\scantokens, and it is the
% whole mechanism -- nothing is saved anywhere, no name is made up, nothing
% outlives the call. The \\begin and the \\end are written as plain characters
% (\\string\\begin\\string{...) because \\scantokens puts a space after every
% control word, and fancyvrb looks for the exact characters \\end{ on a line:
% written as control words they would read \\end {...} and the environment
% would never close.
% The call leaves the mode it found. A block is vertical material, so the
% environment leaves TeX in vertical mode regardless of what came before; a
% block that ends a section title would then leave hyperref's link open in
% vertical mode, which pdfTeX refuses on the run that reads the table of
% contents back. Called
% where a paragraph was under way, the command therefore begins one again
% (\\leavevmode); called where TeX was already in vertical mode, it does not,
% because starting a paragraph there would add an empty line the same block
% written out in full does not add.
\\begingroup
\\catcode`\\^^J=12 \\catcode`\\^^I=12
\\gdef\\flm@vrb@nl{^^J}\\gdef\\flm@vrb@tab{^^I}
\\endgroup
\\let\\flm@vrb@stop\\relax
\\let\\flm@vrb@leave\\relax
\\ProvideDocumentCommand\\flmVerbatimBlock{O{} m m}{%
\\ifhmode\\let\\flm@vrb@leave\\leavevmode\\else\\let\\flm@vrb@leave\\relax\\fi
\\begingroup
\\gdef\\flm@vrb@acc{}\\def\\flm@vrb@lsep{}%
\\flm@vrb@lines#3\\flm@vrb@stop
\\xdef\\flm@vrb@src{%
\\string\\begin\\string{#2\\string}[#1]\\flm@vrb@nl
\\flm@vrb@acc\\flm@vrb@nl\\string\\end\\string{#2\\string}}%
\\endgroup
\\edef\\flm@vrb@restorenl{\\newlinechar=\\the\\newlinechar\\relax}%
\\newlinechar=`\\^^J\\relax
\\expandafter\\scantokens\\expandafter{\\flm@vrb@src}%
\\flm@vrb@restorenl
\\ifvmode\\flm@vrb@leave\\fi}
% The walk over the lines and their segments: one line group at a time, one
% segment at a time, the segments of a line joined with a tab and the lines
% with a line feed. \\FVExtraDetokenizeREscVArg is fvextra's own un-escaper,
% the macro \\EscVerb itself calls, so that inline verbatim content and a block
% share one escaping; it is also the only safe route for text that is not
% ASCII.
\\def\\flm@vrb@lines{\\@ifnextchar\\bgroup\\flm@vrb@line\\flm@vrb@linesdone}
\\def\\flm@vrb@line#1{%
\\xdef\\flm@vrb@acc{\\flm@vrb@acc\\flm@vrb@lsep}\\let\\flm@vrb@lsep\\flm@vrb@nl
\\def\\flm@vrb@ssep{}\\flm@vrb@segs#1\\flm@vrb@stop\\flm@vrb@lines}
\\def\\flm@vrb@linesdone#1\\flm@vrb@stop{}
\\def\\flm@vrb@segs{\\@ifnextchar\\bgroup\\flm@vrb@seg\\flm@vrb@segsdone}
\\def\\flm@vrb@seg#1{\\FVExtraDetokenizeREscVArg{\\flm@vrb@addseg}{#1}\\flm@vrb@segs}
\\def\\flm@vrb@segsdone#1\\flm@vrb@stop{}
\\def\\flm@vrb@addseg#1{%
\\xdef\\flm@vrb@acc{\\flm@vrb@acc\\flm@vrb@ssep#1}\\let\\flm@vrb@ssep\\flm@vrb@tab}
% What a PDF bookmark holds where a heading contains verbatim content. A
% bookmark is plain text: it can carry neither the setting of inline verbatim
% content nor a block at all, so hyperref is told what to put there instead.
% Inline content gives its text -- without this, fvextra disables \\EscVerb
% without removing its optional argument and the option list appears in the
% bookmark -- and a block gives its content run together, with no line breaks
% and no separator between the lines. The two definitions are in a hook that
% runs when the document begins and does nothing where hyperref is absent, so
% this file neither requires hyperref nor cares whether it is loaded before or
% after it.
\\AtBeginDocument{\\ifdefined\\pdfstringdefDisableCommands
\\pdfstringdefDisableCommands{%
\\def\\EscVerb[#1]#2{#2}%
\\def\\flmVerbatimBlock[#1]#2#3{#3}%
}\\fi}
",
"`\\flmFmtVRB` and its per-kind LaTeX hooks, the environments `flmVerbatimCode` and \
`flmVerbatimText`, and `\\flmVerbatimBlock`; needed by verbatim content",
)
.requires([packages::FVEXTRA])
}
pub fn math_environment_piece() -> LatexPreambleDef {
LatexPreambleDef::new(
"math-environment",
"\
% \\flmMathEnvironment{<env>}{<args>}{<body>}: a display-math environment
% written as one macro call. Redefine it to set the environments differently.
\\ProvideDocumentCommand\\flmMathEnvironment{m m m}{\\begin{#1}#2#3\\end{#1}}
",
"`\\flmMathEnvironment{env}{args}{body}`: a display-math environment written as one \
macro call; needed where display mathematics is written that way",
)
.requires([packages::AMSMATH])
}
pub fn if_blank_piece() -> LatexPreambleDef {
LatexPreambleDef::new(
"ifblank",
"\
% \\flmIfBlankTF{<content>}{<then>}{<else>}: the branch a user definition's own
% \"is this blank?\" test selects — <then> where <content> holds nothing at
% all, <else> otherwise. Not a customization point: change your own
% definition, not this. It is long, so that an argument holding a paragraph
% break is tested rather than stopping the compilation, and expandable, so
% that the test never stops the expansion of a definition that has to expand.
%
% This block uses expl3, LaTeX's programming layer, which
% is part of the format and needs no package; its names read only between
% \\ExplSyntaxOn and \\ExplSyntaxOff. \\tl_if_empty:nTF is true exactly when its
% argument holds no token at all, which is the condition FLM's own blank test
% asks: a single space is content, and a comment is gone before the argument
% exists.
\\ExplSyntaxOn
\\providecommand\\flmIfBlankTF[3]{\\tl_if_empty:nTF {#1} {#2} {#3}}
\\ExplSyntaxOff
",
"`\\flmIfBlankTF{content}{then}{else}`: tests whether an argument is blank; needed \
where one of the document's own definitions tests an argument that way",
)
}
pub fn user_args_piece() -> LatexPreambleDef {
LatexPreambleDef::new(
"userargs",
"\
% \\flmArg{<n>}{<arguments>}, \\flmIfArgTF{<n>}{<arguments>}{<then>}{<else>} and
% \\flmIfArgBlankTF{<n>,...}{<arguments>}{<then>}{<else>}: reading one argument of
% a user definition that takes more than nine of them. Such a definition is
% called with all its arguments in one group, one pair of braces around each
% ( \\flmUDbig{{a}{b}{c}...} ), because a macro body has nine parameters; its
% body reads part <n> of that group through these. \\flmArg gives the argument's
% content, \\flmIfArgTF asks whether the argument holds \\BooleanTrue, and
% \\flmIfArgBlankTF asks whether the listed arguments hold nothing at all between
% them. Not a customization point: change your own definition, not this. Long,
% so that an argument holding a paragraph break is read rather than stopping the
% compilation, and expandable, so that reading an argument never stops the
% expansion of a definition that has to expand.
%
% \\tl_item:nn is the LaTeX kernel's own: it picks part <n>, counting from one,
% and strips the braces around it. A test never reads a part directly --
% \\IfBooleanTF{\\flmArg{2}{#1}} stops with \"Invalid argument\" and
% \\flmIfBlankTF{\\flmArg{2}{#1}} answers the wrong branch without a word, since
% both look at the accessor's own tokens -- so the two tests expand the accessor
% first with \\exp_args:Ne, which needs the \\expanded primitive: every TeX engine
% has carried it since 2019, so it is older than the LaTeX this file asks for.
% What the part itself holds is left untouched: a space in an argument stays
% content, and a command in one is not expanded early.
%
% \\flmIfArgBlankTF asks its question through \\flmIfBlankTF, the block above,
% rather than spelling the test again: what \"blank\" means is written in one
% place regardless of a definition's size. A definition taking more than nine
% arguments therefore always brings that block into this file along with this
% one, whether or not it asks a blank test.
\\ExplSyntaxOn
\\providecommand\\flmArg[2]{\\tl_item:nn {#2} {#1}}
\\providecommand\\flmIfArgTF[4]{\\exp_args:Ne \\IfBooleanTF {\\tl_item:nn {#2} {#1}} {#3} {#4}}
\\providecommand\\flmIfArgBlankTF[4]{\\exp_args:Ne \\flmIfBlankTF {\\clist_map_tokens:nn {#1} {\\tl_item:nn {#2}}} {#3} {#4}}
\\ExplSyntaxOff
",
"`\\flmArg{n}{arguments}`, `\\flmIfArgTF` and `\\flmIfArgBlankTF`: read one argument \
of a document's own definition that takes more than nine; needed by such a \
definition",
)
.requires([IF_BLANK])
}
pub fn tab_width_piece() -> LatexPreambleDef {
LatexPreambleDef::new(
"tab-width",
"\
% \\flmTabWidth: the width of one tab, the unit a length in tabs is written in
% (1\\flmTabWidth, 2\\flmTabWidth) -- the indentation of a line of a quotation.
% Change it with \\setlength{\\flmTabWidth}{...}.
\\ifcsname flmTabWidth\\endcsname\\else\\newlength{\\flmTabWidth}\\setlength{\\flmTabWidth}{2em}\\fi
",
"`\\flmTabWidth`: the width of one tab, `2em` by default; needed where the recomposed \
LaTeX writes a length in tabs, such as the indentation of a line of a quotation",
)
}
pub fn standard_pieces() -> Vec<LatexPreambleDef> {
let mut pieces = vec![
refs_piece(),
hyperref_piece(),
label_display_text_piece(),
zref_clever_type_piece(),
labels_piece(),
heading_piece(),
verbatim_piece(),
math_environment_piece(),
if_blank_piece(),
user_args_piece(),
tab_width_piece(),
];
pieces.extend(chunk_pieces());
pieces
}
pub fn chunk_pieces() -> Vec<LatexPreambleDef> {
packages::table_chunks()
.into_iter()
.filter(|chunk| !packages::is_package_chunk(chunk))
.map(|chunk| {
let latex = match chunk.cases() {
[case]
if packages::ENGINES
.iter()
.all(|engine| case.engines().contains(*engine)) =>
{
match case.preamble() {
ChunkPreamble::Snippet(latex) => latex,
_ => unreachable!("a declaration chunk's one case is declarations"),
}
}
_ => panic!(
"the chunk {} is not one block of declarations for every engine; a \
declaration is written with no test of the engine",
chunk.id()
),
};
let guard = guard_name(latex).unwrap_or_else(|| {
panic!("the chunk {} declares no name to guard on", chunk.id())
});
let content = format!(
"% Declarations some characters of the document need. Declared only when \
nothing of that name exists, so that two style files in one LaTeX run do not \
clash.\n\
\\ifcsname {guard}\\endcsname\\else\n{latex}\n\\fi\n"
);
LatexPreambleDef {
id: chunk_piece_id(chunk.id()),
requires: Vec::new(),
content,
docs: crate::kept_docs(format!(
"declarations needed by characters of the document whose LaTeX spelling \
uses them (chunk `{}` of untechxt's Unicode-to-LaTeX table)",
chunk.id()
)),
delivers: Vec::new(),
}
})
.collect()
}
fn guard_name(latex: &str) -> Option<String> {
for line in latex.lines() {
for (prefix, sym) in [
("\\DeclareMathAlphabet{\\", false),
("\\DeclareMathSymbol{\\", false),
("\\DeclareTextSymbol{\\", false),
("\\DeclareSymbolFont{", true),
] {
if let Some(rest) = line.strip_prefix(prefix) {
let name = rest.split('}').next().unwrap_or_default();
if !name.is_empty() {
return Some(if sym { format!("sym{name}") } else { name.to_string() });
}
}
}
}
None
}
#[cfg(test)]
mod tests {
use super::super::names::USER_DEFINITION_PREFIX;
use super::*;
#[test]
fn a_length_is_spelled_as_a_latex_dimension() {
assert_eq!(latex_length(&Length::tabs(2)), "2\\flmTabWidth");
assert_eq!(latex_length(&Length::parse("1.5tab").unwrap()), "1.5\\flmTabWidth");
assert_eq!(latex_length(&Length::parse("10pt").unwrap()), "10bp");
for spelled in ["1.5em", "3mm", "2cm", "0.25in"] {
assert_eq!(latex_length(&Length::parse(spelled).unwrap()), spelled);
}
}
fn definitions(content: &str) -> String {
content.lines().filter(|line| !line.trim_start().starts_with('%')).collect::<Vec<_>>().join("\n")
}
fn definitions_outside_the_pdf_string_hook(content: &str) -> String {
let text = definitions(content);
let mut kept = Vec::new();
let mut inside = false;
for line in text.lines() {
if line.trim_start().starts_with("\\AtBeginDocument{\\ifdefined\\pdfstringdefDisableCommands")
{
inside = true;
}
if !inside {
kept.push(line);
}
if inside && line.trim_end().ends_with("\\fi}") {
inside = false;
}
}
assert!(!inside, "an unterminated \\pdfstringdefDisableCommands hook");
kept.join("\n")
}
#[test]
fn the_standard_pieces_carry_their_identifiers_and_requirements() {
let pieces = standard_pieces();
let ids: Vec<&str> = pieces.iter().map(|p| p.id.as_str()).collect();
assert_eq!(&ids[..8], [
REFS,
HYPERREF,
LABEL_DISPLAY_TEXT,
ZREF_CLEVER_TYPE,
LABELS,
HEADING,
VERBATIM,
MATH_ENVIRONMENT
]);
let by_id = |id: &str| pieces.iter().find(|p| p.id.as_str() == id).unwrap();
assert_eq!(by_id(REFS).requires, [Name::from(packages::ZREF_CLEVER)]);
assert!(by_id(HYPERREF).requires.is_empty());
assert!(by_id(LABEL_DISPLAY_TEXT).requires.is_empty());
assert_eq!(by_id(ZREF_CLEVER_TYPE).requires, [
Name::from(packages::ZREF_CLEVER),
Name::from(LABEL_DISPLAY_TEXT)
]);
assert!(by_id(LABELS).requires.is_empty());
assert_eq!(by_id(HEADING).requires, [
Name::from(LABELS),
Name::from(LABEL_DISPLAY_TEXT),
Name::from(ZREF_CLEVER_TYPE)
]);
assert_eq!(by_id(VERBATIM).requires, [Name::from(packages::FVEXTRA)]);
assert_eq!(by_id(MATH_ENVIRONMENT).requires, [Name::from(packages::AMSMATH)]);
assert!(by_id(IF_BLANK).requires.is_empty());
assert_eq!(by_id(USER_ARGS).requires, [Name::from(IF_BLANK)]);
}
#[test]
fn the_chunk_pieces_follow_the_chunk_table_and_are_guarded() {
let declarations: Vec<&untechxt::preamble::Chunk> = packages::table_chunks()
.into_iter()
.filter(|chunk| !packages::is_package_chunk(chunk))
.collect();
for chunk in &declarations {
let [case] = chunk.cases() else {
panic!("the chunk {} does not have exactly one case", chunk.id());
};
for engine in packages::ENGINES {
assert!(case.engines().contains(engine), "{} under {engine:?}", chunk.id());
}
}
let pieces = chunk_pieces();
assert_eq!(
pieces.iter().map(|piece| piece.id.clone()).collect::<Vec<_>>(),
declarations.iter().map(|chunk| chunk_piece_id(chunk.id())).collect::<Vec<_>>()
);
assert!(pieces.iter().all(|piece| piece.id.as_str().starts_with(CHUNK_ID_PREFIX)));
let standard: Vec<Name> = standard_pieces().iter().map(|p| p.id.clone()).collect();
assert_eq!(&standard[standard.len() - pieces.len()..],
&pieces.iter().map(|p| p.id.clone()).collect::<Vec<_>>()[..]);
for piece in &pieces {
assert!(piece.content.contains("\\ifcsname "), "{}", piece.id);
assert!(piece.content.ends_with("\\fi\n"), "{}", piece.id);
}
assert_eq!(guard_name(r"\DeclareMathAlphabet{\UnxTBbold}{U}{bbold}{m}{n}").as_deref(),
Some("UnxTBbold"));
assert_eq!(guard_name("\\DeclareFontEncoding{LS1}{}{}\n\\DeclareSymbolFont{UnxTx}{LS1}{a}{m}{n}")
.as_deref(),
Some("symUnxTx"));
}
#[test]
fn a_piece_requires_packages_and_pieces_told_apart_by_their_prefix() {
for piece in standard_pieces() {
for id in &piece.requires {
let known = id.as_str().starts_with(ID_PREFIX)
|| id.as_str().starts_with(packages::ID_PREFIX);
assert!(known, "{}: {id}", piece.id);
}
}
}
fn every_registered_piece() -> Vec<LatexPreambleDef> {
use crate::core::registry::{PackageEntry, RegistryBuilder, RegistryInputs};
use crate::stdlib::{self, StdlibConfig};
let mut builder = RegistryBuilder::new();
builder.use_package(stdlib::add_features(PackageEntry::new("std"), StdlibConfig::new()));
let registry = builder.build(&RegistryInputs::new()).expect("the standard registry builds");
let registered: Vec<LatexPreambleDef> = pieces(registry.services()).cloned().collect();
for piece in standard_pieces() {
assert!(registered.iter().any(|p| p.id == piece.id), "{}", piece.id);
}
registered
}
#[test]
fn every_piece_is_complete_lines_with_one_guard_spelling_per_kind() {
for piece in every_registered_piece() {
assert!(piece.content.ends_with('\n'), "{}", piece.id);
assert!(piece.content.starts_with('%'), "{}", piece.id);
if piece.id.as_str().starts_with("flm.latex.def.flmx.") {
continue;
}
for line in definitions_outside_the_pdf_string_hook(&piece.content).lines() {
for definer in [
"\\NewExpandableDocumentCommand",
"\\DeclareExpandableDocumentCommand",
"\\RenewExpandableDocumentCommand",
"\\ProvideExpandableDocumentCommand",
"\\newcommand",
"\\renewcommand",
"\\newenvironment",
"\\renewenvironment",
"\\DeclareRobustCommand",
"\\NewDocumentCommand",
"\\DeclareDocumentCommand",
"\\NewDocumentEnvironment",
"\\DeclareDocumentEnvironment",
] {
assert!(!line.contains(definer), "{}: {definer} in {line}", piece.id);
}
if let Some(rest) = line.trim_start().strip_prefix("\\def\\") {
let name: String =
rest.chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '@').collect();
assert!(name.contains('@'), "{}: \\def of the public {name}", piece.id);
}
}
let text = definitions_outside_the_pdf_string_hook(&piece.content);
for forbidden in [
"\\ifdefined",
"\\@ifundefined",
"\\@ifpackageloaded",
"\\@ifclassloaded",
"\\IfPackageLoadedWithOptionsTF",
"\\IfClassLoadedTF",
"\\IfClassLoadedWithOptionsTF",
"\\IfFormatAtLeastTF",
"\\IfPackageAtLeastTF",
"\\IfFileExists",
"\\IfFontExistsTF",
"_if_exist:",
"\\ifpdf",
"\\ifxetex",
"\\ifluatex",
"\\ifPDFTeX",
"\\ifXeTeX",
"\\ifLuaTeX",
"\\sys_if_engine",
"\\sys_if_output",
] {
assert!(!text.contains(forbidden), "{}: {forbidden}", piece.id);
}
if text.contains(ASKING_WHAT_THE_DOCUMENT_LOADED) {
assert!(
ASK_WHAT_THE_DOCUMENT_LOADED.contains(&piece.id.as_str()),
"{}: {ASKING_WHAT_THE_DOCUMENT_LOADED} asked by a piece that is not one of \
the pieces allowed to ask it, {ASK_WHAT_THE_DOCUMENT_LOADED:?}; a piece that \
needs the question is a decision to be recorded, not a line of LaTeX",
piece.id
);
let asked_of_hyperref =
format!("{ASKING_WHAT_THE_DOCUMENT_LOADED}{{{HYPERREF_PACKAGE_COMMAND}}}");
assert!(
!text.replace(&asked_of_hyperref, "").contains(ASKING_WHAT_THE_DOCUMENT_LOADED),
"{}: the question is asked of a package other than \
`{HYPERREF_PACKAGE_COMMAND}`",
piece.id
);
}
}
let pieces = standard_pieces();
let asking: Vec<&str> = pieces
.iter()
.filter(|piece| {
definitions_outside_the_pdf_string_hook(&piece.content)
.contains(ASKING_WHAT_THE_DOCUMENT_LOADED)
})
.map(|piece| piece.id.as_str())
.collect();
assert_eq!(asking, ASK_WHAT_THE_DOCUMENT_LOADED);
}
const ASKING_WHAT_THE_DOCUMENT_LOADED: &str = "\\IfPackageLoadedTF";
const ASK_WHAT_THE_DOCUMENT_LOADED: &[&str] = &[HYPERREF];
#[test]
fn no_piece_defines_a_name_under_a_user_definitions_prefix() {
for piece in standard_pieces() {
for line in definitions(&piece.content).lines() {
assert!(
!line.contains(USER_DEFINITION_PREFIX),
"{}: the name space `{USER_DEFINITION_PREFIX}` belongs to the document's own \
definitions, and this line reaches into it: {line}",
piece.id
);
}
}
for package in packages::standard_packages() {
assert!(!package.package.contains(USER_DEFINITION_PREFIX), "{}", package.id);
assert!(
!package.options.iter().any(|option| option.contains(USER_DEFINITION_PREFIX)),
"{}",
package.id
);
}
}
#[test]
fn the_hooks_are_defined_under_the_names_the_rules_write() {
let by_id = |id: &str| {
standard_pieces().into_iter().find(|p| p.id.as_str() == id).unwrap().content
};
assert!(by_id(REFS).contains(&format!("\\ProvideDocumentCommand\\{REF_COMMAND}{{O{{}} m}}")));
assert!(by_id(LABELS).contains(&format!("\\ProvideDocumentCommand\\{LABELS_COMMAND}{{m}}")));
assert!(
by_id(LABEL_DISPLAY_TEXT)
.contains(&format!("\\ProvideDocumentCommand\\{LABELS_WITH_DISPLAY_TEXT_COMMAND}"))
);
assert!(
by_id(HEADING)
.contains(&format!("\\ProvideDocumentCommand\\{HEADING_COMMAND}{{O{{}} m s m m}}"))
);
assert!(by_id(HEADING).contains("{#2*{#4}%"));
assert!(by_id(HEADING).contains("\\ifx\\@currentcounter\\@empty"));
assert!(by_id(LABEL_DISPLAY_TEXT).contains(&format!("\\newcounter{{{INTERNAL_REF_COUNTER}}}")));
assert!(by_id(ZREF_CLEVER_TYPE)
.contains(&format!("countertype={{{INTERNAL_REF_COUNTER}={INTERNAL_REF_TYPE}}}")));
}
#[test]
fn the_heading_hook_takes_two_keys_and_never_stars_an_optional_argument() {
let heading = definitions(&heading_piece().content);
assert!(heading.contains("\\keys_define:nn {flm/heading}"));
assert!(heading.contains("alt .code:n = {\\tl_set:Nn \\flm@heading@alt {#1}"));
assert!(heading.contains("\\bool_set_true:N \\flm@heading@given"));
assert!(heading.contains("\\keys_set:nn {flm/heading} {#1}"));
assert!(heading.contains("\\tl_clear:N \\flm@heading@alt"));
assert!(heading.contains("\\bool_set_false:N \\flm@heading@given"));
assert!(heading.contains("\\tl_clear:N \\flm@heading@toc"));
assert_eq!(heading.matches(".code:n").count(), 1);
assert_eq!(heading.matches(".choices:nn").count(), 1);
assert_eq!(heading.matches("\\keys_define:nn").count(), 1);
assert!(heading.contains("alt .value_required:n = true"));
assert!(heading.contains("toc .choices:nn = {true, false}"));
assert!(heading.contains("toc .value_required:n = true"));
assert!(heading.contains("\\def\\flm@heading@addtoc#1#2{\\addcontentsline{toc}{#1}{#2}}"));
assert!(heading.contains("\\edef\\flm@heading@level{\\cs_to_str:N #2}"));
assert!(heading.contains("\\str_if_eq:VnT \\flm@heading@toc {true}"));
assert!(heading.contains("\\str_if_eq:VnT \\flm@heading@toc {false} {\\flm@heading@notoc{#2}}"));
assert!(heading.contains("\\PackageWarning{flm}"));
assert!(heading.contains("{#2*{#4}%"));
assert!(!heading.contains("#2*["));
assert!(heading.contains("{#2{#4}}"));
assert!(heading.contains("\\def\\flm@heading@withalt#1#2#3{#2[#1]{#3}}"));
assert!(heading.contains("\\bool_if:NTF \\flm@heading@given"));
assert!(!heading.contains("\\tl_if_empty:NTF \\flm@heading@alt"));
for name in ["flm@heading@alt", "flm@heading@given", "flm@heading@toc"] {
assert!(
heading.contains(&format!("\\ifcsname {name}\\endcsname\\else")),
"the declaration of {name} is not guarded: {heading}"
);
}
}
#[test]
fn the_alias_line_is_written_after_the_last_page_and_read_back_globally() {
let labels = definitions(&labels_piece().content);
assert!(labels.contains("\\AddToHook{enddocument/afterlastpage}"));
assert!(!labels.contains("\\AtEndDocument"));
assert!(labels.contains("\\global\\expandafter\\let\\csname r@#1"));
assert!(labels.contains("\\global\\expandafter\\let\\csname Z@R@#1"));
}
#[test]
fn the_names_written_by_the_rules_are_the_ones_the_verbatim_piece_defines() {
let content = definitions(&verbatim_piece().content);
for kind in [VerbatimKind::Text, VerbatimKind::Code, VerbatimKind::Identifier] {
let hook = format!("\\{FMT_VRB}{}", verbatim_hook(kind));
assert!(content.contains(&hook), "{hook}");
}
assert!(
content.contains(&format!("\\ProvideDocumentEnvironment{{{VERBATIM_CODE_ENVIRONMENT}}}"))
);
assert!(
content.contains(&format!("\\ProvideDocumentEnvironment{{{VERBATIM_TEXT_ENVIRONMENT}}}"))
);
assert!(
content.contains(&format!("\\ProvideDocumentCommand\\{VERBATIM_BLOCK_COMMAND}{{O{{}} m m}}"))
);
let outside = definitions_outside_the_pdf_string_hook(&verbatim_piece().content);
assert!(!outside.contains(&format!("\\{ESCVERB}")));
assert!(content.contains(&format!("\\providecommand\\{VRB_FAMILY}")));
assert_eq!(
escverb_options(VerbatimKind::Code),
"fontfamily=\\flmVRBFamily,formatcom=\\flmFmtVRB{verbcode}"
);
}
#[test]
fn the_pdf_string_hook_says_what_verbatim_content_contributes_to_a_bookmark() {
let content = definitions(&verbatim_piece().content);
assert!(content.contains(&format!("\\def\\{ESCVERB}[#1]#2{{#2}}")));
assert!(content.contains(&format!("\\def\\{VERBATIM_BLOCK_COMMAND}[#1]#2#3{{#3}}")));
assert!(content.contains("\\AtBeginDocument{\\ifdefined\\pdfstringdefDisableCommands"));
assert_eq!(content.matches("\\ifdefined").count(), 1);
let with_a_hook: Vec<String> = standard_pieces()
.iter()
.filter(|piece| {
definitions(&piece.content).contains("\\pdfstringdefDisableCommands")
})
.map(|piece| piece.id.to_string())
.collect();
assert_eq!(with_a_hook, [String::from(HYPERREF), String::from(VERBATIM)]);
}
#[test]
fn the_hyperref_piece_asks_what_the_document_loaded_and_says_what_a_bookmark_holds() {
let content = definitions(&hyperref_piece().content);
assert!(content.contains(&format!(
"\\ProvideDocumentCommand\\{HYPERREF_COMMAND}{{m m}}"
)));
let linked = format!("\\{HYPERREF_PACKAGE_COMMAND}[{{#1}}]{{#2}}");
assert!(content.contains(&format!(
"\\IfPackageLoadedTF{{{HYPERREF_PACKAGE_COMMAND}}}{{{linked}}}{{#2}}"
)));
assert!(!content.contains("\\RequirePackage"));
assert!(content.contains("\\AtBeginDocument{\\ifdefined\\pdfstringdefDisableCommands"));
assert!(content.contains(&format!("\\def\\{HYPERREF_COMMAND}#1#2{{#2}}")));
assert_eq!(content.matches("\\ifdefined").count(), 1);
}
#[test]
fn the_escaped_block_is_the_style_file_s_only_use_of_scantokens() {
let uses = |piece: &LatexPreambleDef| {
definitions(&piece.content).matches("\\scantokens").count()
};
let pieces = standard_pieces();
assert_eq!(pieces.iter().map(uses).sum::<usize>(), 1);
assert_eq!(uses(&verbatim_piece()), 1);
}
}