Skip to main content

latexml_core/binding/def/
dialect.rs

1use std::{borrow::Cow, rc::Rc, sync::LazyLock};
2
3use regex::Regex;
4use rustc_hash::FxHashMap as HashMap;
5
6// use crate::common::error::*;
7use crate::binding::content::{merge_font, merge_font_ref};
8use crate::{
9  BoxOps, Digested,
10  binding::{counter::dialect::step_counter, def::traits::IntoDigestedResult},
11  common::{
12    arena, arena::SymHashMap, def_parser::parse_parameters, error::*, font::Font, number::Number,
13    numeric_ops::NumericOps, object::Object,
14  },
15  definition::{
16    BeforeDigestClosure, ConditionalClosure, ConstructionClosure, DeclaredMode, Definition,
17    DigestionClosure, ExpansionBody, FontDirective, PrimitiveBody, ReplacementClosure, Reversion,
18    SizingClosure,
19    argument::ArgWrap,
20    conditional::{Conditional, ConditionalOptions, ConditionalType},
21    constructor::{Constructor, ConstructorOptions, TexGroup},
22    expandable::{Expandable, ExpandableOptions},
23    math_primitive::{MathPrimitive, MathPrimitiveOptions},
24    primitive::{Primitive, PrimitiveOptions},
25    register::{
26      Register, RegisterGetterClosure, RegisterSetterClosure, RegisterType, RegisterValue,
27    },
28  },
29  document::Document,
30  gullet, mouth,
31  parameter::{Parameter, Parameters},
32  pin,
33  state::*,
34  stomach::*,
35  tbox::Tbox,
36  token::*,
37  tokens::{TeXString, Tokens},
38  whatsit::Whatsit,
39};
40
41const MATH_CONSTRUCTOR_ATTRIBUTES: &[&str] = &[
42  "name",
43  "meaning",
44  "omcd",
45  "decl_id",
46  "mathstyle",
47  "lpadding",
48  "rpadding",
49];
50
51/// regex for the prefix of a conditional command sequence
52pub static CONDITIONAL_CS_RE: LazyLock<Regex> =
53  LazyLock::new(|| Regex::new(r"^\\(?:if(.*)|unless)$").unwrap());
54/// regex for the prefix of a protocol (such as literal:)
55pub static LEADING_PROTOCOL_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\w+:").unwrap());
56/// regex for a trailing slash (trivial, but aids replacement of said slash)
57pub static TRAILING_SLASH_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"/$").unwrap());
58/// regex for one-or-more spaces
59pub static SPACES_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\s+").unwrap());
60/// regex for ${}^{label}$
61pub static DIRTY_ID_IDIOM_RE: LazyLock<Regex> =
62  LazyLock::new(|| Regex::new(r"\$\{\}\^\{(?P<label>[^\}]*)\}\$").unwrap());
63/// regex for characters not expected in a usual id attribute
64pub static NON_ID_CHARSET_RE: LazyLock<Regex> =
65  LazyLock::new(|| Regex::new(r"[^\w_\-.]+").unwrap());
66/// regex for a strange noisy TeX `\\~{}`
67pub static TILDE_NOISE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\\~\{\}").unwrap());
68/// regex for a TeX argument specifier or any command sequence
69pub static HAS_ARG_OR_CS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"#\d|\\.").unwrap());
70/// regex for the usual argument placeholders `#1`-`#9`
71pub static ARG_HOLE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"#(\d)").unwrap());
72
73/// Is defined in the `LaTeX`-y sense of also not being let to \relax.
74pub fn is_defined(name: &str) -> bool {
75  let cs = T_CS!(name);
76  is_defined_token(&cs)
77}
78
79/// Token variant of `is_defined`. Defined in the LaTeX-y sense of also not being let to \relax.
80pub fn is_defined_token(cs: &Token) -> bool {
81  match lookup_meaning(cs) {
82    Some(store) => match store {
83      Stored::Token(_) => true,
84      Stored::Expandable(ref m) => m.get_cs_name() != "\\relax",
85      Stored::Primitive(ref m) => m.get_cs_name() != "\\relax",
86      Stored::Constructor(ref m) => m.get_cs_name() != "\\relax",
87      Stored::Register(ref m) => m.get_cs_name() != "\\relax",
88      Stored::Conditional(ref m) => m.get_cs_name() != "\\relax",
89      Stored::MathPrimitive(ref m) => m.get_cs_name() != "\\relax",
90      _ => true, // other stored values are considered defined
91    },
92    _ => false,
93  }
94}
95
96/// Check if the `token` is not yet defined, or let to `\relax`
97pub fn is_definable(token: &Token) -> bool {
98  // Non-CS / non-ACTIVE tokens (letters, digits, punctuation, etc.) have
99  // a trivial "self" meaning from `lookup_meaning` (= `Stored::Token(self)`).
100  // That's not a real `\def`/`\let` definition — kernel `\@ifdefinable`
101  // would treat them as not-yet-defined. Without this check, calls like
102  // `\@ifdefinable{Z@L@\foo}{…}` (zref-base.sty:118) get our DefToken
103  // reader's first-token-from-brace-group (the letter `Z`) and fail with
104  // "Command \Z already defined" because letter Z's lookup_meaning is
105  // non-None. Witness: arXiv:2504.18121 / 2504.17729 / 2504.17871 et al
106  // (Task #23 zref-base \Z collision cluster).
107  if !token.get_catcode().is_active_or_cs() {
108    return true;
109  }
110  let meaning = lookup_meaning(token);
111  token.with_str(|name| name != "\\relax" && !name.starts_with("\\end"))
112    && (meaning.is_none()
113      || (meaning == lookup_meaning(&TOKEN_RELAX))
114      || lookup_bool("2.09_COMPATIBILITY"))
115}
116
117//======================================================================
118// Defining Conditional Control Sequences.
119//======================================================================
120/// Define a conditional control sequence.
121///
122/// Its processing takes place in the Gullet.
123/// The test is applied to the arguments (if any),
124/// which determines which branch is executed.
125/// If the test is undefined, the conditional is a "user defined" one;
126/// Two additional primitives are defined \footrue and \foofalse;
127/// the test is then determined by the most recently called of those.
128///
129/// If you supply a skipper instead of a test, it is also applied to the arguments
130/// and should skip to the right place in the following \or, \else, \fi.
131pub fn def_conditional(
132  cs: Token,
133  paramlist: Option<Parameters>,
134  test: Option<ConditionalClosure>,
135  options: ConditionalOptions,
136) -> Result<()> {
137  if provide_only_declines(&cs) {
138    return Ok(());
139  }
140  let locked_key_opt = if let Some(true) = options.locked {
141    Some(arena::with(cs.get_sym(), |cs_name| s!("{cs_name}:locked")))
142  } else {
143    None
144  };
145  if cs.with_str(|cs_name| matches!(cs_name, "\\fi" | "\\else" | "\\or" | "\\unless")) {
146    install_definition(
147      Conditional {
148        origin: crate::definition::origin::current_origin(),
149        cs,
150        paramlist,
151        test,
152        conditional_type: cs.with_str(|cs_name| ConditionalType::from(cs_name)),
153        skipper: options.skipper,
154      },
155      options.scope,
156    )
157  } else {
158    // Perl Package.pm L1210-1219 — match `\<2chars><rest>` and warn (not
159    // error) when prefix is not `if`, but still proceed with user-defined
160    // conditional creation. Bug-for-bug compatible: e.g. `\newif\pgf@lib@svg@relative`
161    // (PGF library naming) creates `\f@lib@svg@relativetrue` etc. with the
162    // `pg` prefix consumed — package code that uses `\if\pgf@lib@svg@relative`
163    // still works because the Let to `\iffalse` runs unconditionally.
164    let (name_opt, warn_misnamed) = cs.with_str(|custom| {
165      // First try strict `\if<name>` / `\unless` — preferred path.
166      if let Some(captures) = CONDITIONAL_CS_RE.captures(custom) {
167        let name = captures.get(1).map_or("", |m| m.as_str()).to_string();
168        return (Some(name), false);
169      }
170      // Perl-loose fallback: `\<2chars><rest>` — capture rest as `name`,
171      // emit a `misdefined` Warn since prefix isn't `if`.
172      let bytes = custom.as_bytes();
173      if bytes.len() > 3 && bytes[0] == b'\\' {
174        let rest = std::str::from_utf8(&bytes[3..]).ok().map(str::to_string);
175        (rest, true)
176      } else {
177        (None, false)
178      }
179    });
180    if warn_misnamed {
181      let message = s!(
182        "The conditional {} is being defined but doesn't start with \\if",
183        cs
184      );
185      Warn!("misdefined", cs, message);
186    }
187    if let Some(name) = name_opt {
188      // Perl Package.pm:1220 `(defined $name) && ($name ne 'case') &&
189      // (!defined $test)`: an EMPTY name is defined too — `\newif\if西暦`
190      // (jsarticle.cls:1927; the kanji is catcode OTHER in both engines, so
191      // the DefToken argument is the bare `\if`) lets `\if` to `\iffalse`, a
192      // well-formed conditional; rejecting the empty name installed a
193      // test-less `Conditional` that errored on every later `\if`, and the
194      // tikz→pgf→pgfkeys load that follows is `\if`-heavy (jsarticle + tikz:
195      // 544 errors, Perl 28 — the pTeX residual).
196      if name != "case" && test.is_none() {
197        // user-defined conditional, like with \newif
198        // Note: setting up these macros is compile-time expensive, maybe there is some way to
199        // avoid...
200        // Note: the double clones are technically correct Rust if annoying to write and read.
201        //       first, we want to capture a cloned value of cs, to be able to keep using cs here.
202        // second, each invocation of the conditional macro needs to create new tokens to
203        // return,       hence a clone is required on each call.
204        def_macro(
205          T_CS!(s!("\\{}true", name)),
206          None,
207          Tokens!(T_CS!("\\let"), cs, T_CS!("\\iftrue")),
208          None,
209        )?;
210        def_macro(
211          T_CS!(s!("\\{}false", name)),
212          None,
213          Tokens!(T_CS!("\\let"), cs, T_CS!("\\iffalse")),
214          None,
215        )?;
216        let_i(&cs, &T_CS!("\\iffalse"), None);
217      } else {
218        //  For \ifcase, the parameter list better be a single Number !!
219        install_definition(
220          Conditional {
221            origin: crate::definition::origin::current_origin(),
222            cs,
223            paramlist,
224            test,
225            conditional_type: ConditionalType::If,
226            skipper: options.skipper,
227          },
228          options.scope,
229        );
230      }
231    } else {
232      let message = s!(
233        "The conditional {} is being defined but doesn't start with \\if",
234        cs
235      );
236      Error!("misdefined", cs, message);
237    }
238  }
239
240  if let Some(locked_key) = locked_key_opt {
241    assign_value(&locked_key, true, Some(Scope::Global));
242  }
243  Ok(())
244}
245
246/// Defines the macro expansion for a command sequence.
247///
248/// A macro control sequence that reads parameters
249/// as specified by `paramlist` and is expanded during macro expansion time in the `Gullet`.
250/// See `ExpansionBody` for the possible kinds of `expansion` material.
251pub fn def_macro<T: Into<Option<ExpansionBody>>>(
252  cs: Token,
253  paramlist: Option<Parameters>,
254  expansion: T,
255  options_opt: Option<ExpandableOptions>,
256) -> Result<()> {
257  let mut options = options_opt.unwrap_or_default();
258  if !options.extends && provide_only_declines(&cs) {
259    return Ok(());
260  }
261  let expansion_opt: Option<ExpansionBody> = expansion.into();
262  // TODO: The None case could be refactored to feel much cleaner.
263  // For now it's equivalent to Tokens!()
264  let scope = options.scope.take();
265  if options.mathactive && cs.with_str(|s| s.len()) == 1 {
266    assign_mathcode(
267      cs.with_str(|cstr| cstr.chars().next().unwrap()),
268      0x8000u16,
269      scope,
270    );
271  }
272  let locked_key_opt = if options.locked {
273    Some(format!("{cs}:locked"))
274  } else {
275    None
276  };
277  // A robust macro's body goes under `\cs␣` FIRST, its `\protect \cs␣` wrapper after — the reverse of Perl's
278  // DefMacroI (Package.pm:1166 calls `defRobustCS`, :1143-1149, before installing the body), unobservable otherwise:
279  // nothing reads the inner in between, and the wrapper's install can then judge what it wraps, so a document's
280  // `\DeclareRobustCommand\mathit[1]{…}` of a locked binding defines a command, not a value
281  // (`state::install_definition`; 2306.10719). The wrapper takes the definition's scope, as `defRobustCS` does
282  // (Package.pm:1148).
283  let (robust, locked) = (options.robust, options.locked);
284  let defcs = if robust {
285    T_CS!(cs.with_str(|cstr| format!("{cstr} ")))
286  } else {
287    cs
288  };
289  install_definition(
290    Expandable::new(defcs, paramlist, expansion_opt, Some(options))?,
291    scope,
292  );
293  if robust {
294    def_robust_cs(cs, locked, scope)?;
295  }
296  if let Some(locked_key) = locked_key_opt {
297    assign_value(&locked_key, true, Some(Scope::Global));
298    // A locked robust binding keeps its inner `\cs␣` against the class and package files (`:locked@files`): the
299    // wrapper calls that name, so a class's `\@namedef{cite }{…}` (cmfne.cls:1774, cite.sty's code copied) took over
300    // every `\cite`, and its `\@citex` reached our cite binding's `\citen` = `\cite` again (Fatal
301    // `Stomach:Recursion`, 2210.02246, 2303.09770). Perl locks the wrapper only (Package.pm DefMacroI), and the
302    // document's own definition of the inner (a `\DeclareRobustCommand\cite`) stays its own, as there.
303    // OXIDIZED_DESIGN #568; guard `perfect_kernel_batch66b::locked_robust_cite_keeps_its_inner_definition`.
304    if robust {
305      assign_value(&format!("{defcs}:locked@files"), true, Some(Scope::Global));
306    }
307  }
308  Ok(())
309}
310
311/// configuration for creating a new Register
312#[derive(Default)]
313pub struct RegisterOptions {
314  /// closure to obtain the current register value
315  pub getter:   Option<RegisterGetterClosure>,
316  /// closure to set the current register value
317  pub setter:   Option<RegisterSetterClosure>,
318  /// is this register meant as read-only? (default: false)
319  pub readonly: bool,
320  /// an optional name for the register (default: the cs)
321  pub address:  Option<String>,
322  /// an optional allocation for the register (default: None)
323  pub allocate: Option<String>,
324  /// install the control sequence in the current group, as a TeX shorthand definition does (tex.web §1224
325  /// `define`: `\countdef` & co. are local unless `\global`); default: global, as a binding's register
326  pub local:    bool,
327}
328
329/// Defines a register with an initial value.
330///
331/// (a Number, Dimension, Glue, MuGlue or Tokens --- I haven't handled Box's yet).
332/// Usually, the `prototype` is just the control sequence,
333/// but registers are also handled by prototypes like `\count{Number}`. `DefRegister` arranges
334/// that the register value can be accessed when a numeric, dimension, ... value is being read,
335/// and also defines the control sequence for assignment.
336pub fn def_register<T: Into<RegisterValue>>(
337  cs: Token,
338  parameters: Option<Parameters>,
339  value: T,
340  options: Option<RegisterOptions>,
341) -> Result<()> {
342  if provide_only_declines(&cs) {
343    return Ok(());
344  }
345  let mut options: RegisterOptions = options.unwrap_or_default();
346  let value: RegisterValue = value.into();
347  let has_address_option = options.address.is_some();
348  let mut address = match options.address.take() {
349    Some(v) => v,
350    None => match options.allocate {
351      Some(v) => allocate_register(&v, &cs.to_string())?.unwrap_or_default(),
352      None => String::new(),
353    },
354  };
355  // A bare re-definition of a register that is already allocated keeps its
356  // allocation: latex.ltx's `\newdimen\columnsep` is `\dimen124` (tex.web §1224),
357  // which the format dump records, and the post-dump pools re-`DefRegister!`
358  // ~54 kernel lengths only to give them their default values. Renamed to their
359  // own CS names, `\meaning\columnsep` printed `\columnsep`, so etoolbox's
360  // `\ifdefdimen` (a `\meaning` test, etoolbox.sty:443-456) said "not a length"
361  // (tudscrbase: tudscrartcl, tudscrbook, tudscrposter, tudscrreprt).
362  if address.is_empty()
363    && let Some(existing) = lookup_register_definition(&cs)
364    && is_allocated_register_address(&existing.address)
365  {
366    address = existing.address.to_string();
367  }
368  // by adding this check here, we no longer need to use Register::new in the Rust version
369  if address.is_empty() {
370    address = cs.to_string();
371  }
372  // Assign, but do not RE-assign
373  if !has_address_option || !has_value(&address) {
374    assign_value(&address, value.clone(), Some(Scope::Global));
375  }
376
377  let register_type: RegisterType = (&value).into();
378  install_definition(
379    Register {
380      cs,
381      address,
382      parameters,
383      register_type,
384      readonly: options.readonly,
385      getter: options.getter,
386      setter: options.setter,
387      default: Some(value),
388      value: None,
389      locator: gullet::get_locator(),
390      ..Register::default()
391    },
392    if options.local {
393      None
394    } else {
395      Some(Scope::Global)
396    },
397  );
398  Ok(())
399}
400
401/// The prologue a primitive's or constructor's mode options compile to (Perl `DefPrimitiveI`
402/// Package.pm:1294-1309, `DefConstructorI` :1456-1471): `mode => 'text'` is
403/// `restricted_horizontal` entered from horizontal mode, and `bounded` opens a group only when
404/// no mode is given. Returns the mode to begin, and the record the definer builds its prologue
405/// closures from.
406fn command_declared_mode(
407  mode: Option<String>,
408  enter_horizontal: bool,
409  leave_horizontal: bool,
410  bounded: bool,
411  require_math: bool,
412  forbid_math: bool,
413) -> (Option<String>, DeclaredMode) {
414  let text = mode.as_deref() == Some("text");
415  let restricted_box = mode.as_deref() == Some("restricted_horizontal");
416  let mode = if text {
417    Some("restricted_horizontal".to_string())
418  } else {
419    mode
420  };
421  let declared_mode = DeclaredMode {
422    mode: mode.as_deref().map(arena::pin),
423    enter_horizontal: enter_horizontal || text,
424    leave_horizontal,
425    bounded: mode.is_none() && bounded,
426    require_math,
427    forbid_math,
428    restricted_box,
429  };
430  (mode, declared_mode)
431}
432
433/// Defines a primitive control sequence
434///
435/// A primitive is processed during
436/// digestion (in the  `Stomach`), after macro expansion but before Construction time.
437/// Primitive control sequences generate Boxes or Lists, generally
438/// containing basic Unicode content, rather than structured XML.
439/// Primitive control sequences are also executed for side effect during digestion,
440/// effecting changes to the `State`.
441pub fn def_primitive(
442  cs: Token,
443  paramlist: Option<Parameters>,
444  compiled_replacement: Option<PrimitiveBody>,
445  options: PrimitiveOptions,
446) -> Result<()> {
447  if provide_only_declines(&cs) {
448    return Ok(());
449  }
450  let options_locked = options.locked;
451  let scope = options.scope;
452  let mut before_digest_env: Vec<BeforeDigestClosure> = Vec::new();
453  let cs_name = cs.with_cs_name(ToString::to_string);
454
455  // A string body enters horizontal mode (Primitive.pm:73 `enterHorizontal if defined
456  // $replacement`) — as the prologue, before a `bounded` group and its `font`, where LaTeX's
457  // `\UseTextSymbol` starts the paragraph (`\hmode@start@before@group`, latex.ltx:9967): the
458  // `\everypar` it fires (OXIDIZED_DESIGN #267) must not run inside the glyph's font and group.
459  let string_body = matches!(compiled_replacement, Some(PrimitiveBody::String(_)));
460  let enters_horizontal = options.enter_horizontal || (string_body && options.mode.is_none());
461  let (mode, declared_mode) = command_declared_mode(
462    options.mode,
463    enters_horizontal,
464    options.leave_horizontal,
465    options.bounded,
466    options.require_math,
467    options.forbid_math,
468  );
469
470  if declared_mode.require_math {
471    let cs_name_cloned = cs_name.clone();
472    let require_math_closure = before_digest_simple!({ requireMath!(cs_name_cloned) });
473    before_digest_env.push(require_math_closure);
474  }
475
476  if declared_mode.forbid_math {
477    let cs_name_cloned = cs_name.clone();
478    let forbid_math_closure = before_digest_simple!({ forbidMath!(cs_name_cloned) });
479    before_digest_env.push(forbid_math_closure);
480  }
481  if declared_mode.enter_horizontal {
482    before_digest_env.push(before_digest_simple!({
483      enter_horizontal();
484    }));
485  }
486  if declared_mode.leave_horizontal {
487    before_digest_env.push(before_digest_simple!({
488      leave_horizontal()?;
489    }));
490  }
491  if let Some(ref mode) = mode {
492    let mode_clone = mode.clone();
493    let begin_mode_closure = before_digest_simple!({
494      begin_mode(&mode_clone)?;
495    });
496    before_digest_env.push(begin_mode_closure);
497  } else if declared_mode.bounded {
498    let bgroup_closure = before_digest_simple!({
499      bgroup();
500      // tex.web §274 `new_save_level(c)`: the OPENER writes the group code
501      // on the save-stack level; the closer checks it (§1068 `cur_group`).
502      // The code here is this primitive's cs (`groupInitiator` is the
503      // INVOKING token, which an alias or `\csname` form can differ from).
504      assign_frame_value("lx@group@code", Stored::Token(cs));
505    });
506    before_digest_env.push(bgroup_closure);
507  }
508  // A parameterless pure size switch expands, as size10.clo's do (`\DeclareRobustCommand`s, and
509  // `\normalsize` made robust by `\MakeRobust`): `\small` is a macro for the primitive `\lx@size@small`, so the idiom that
510  // appends to it, `\expandafter\def\expandafter\normalsize\expandafter{\normalsize …}` (or etoolbox's
511  // `\appto`), keeps the switch rather than calling itself (witnesses 2605.03010, 2605.19623,
512  // 2605.30610: "\normalsize expands into itself" at `\begin{document}`'s `\normalsize`). No
513  // `\protect` (the primitive is unexpandable, safe in an `\edef`); the primitive reverts as `\small`.
514  // Perl's size primitives are unexpandable. Guard
515  // `perfect_kernel_batch58::size_commands_can_be_appended_to`.
516  let size_switch = paramlist.is_none()
517    && matches!(&options.font, Some(FontDirective::Asset(font))
518      if font.size.is_some() && font.family.is_none() && font.series.is_none() && font.shape.is_none());
519  let declared_font = options.font.clone();
520  match options.font {
521    Some(FontDirective::Asset(chosen_font)) => {
522      // A pure size switch (`\small` … `\Huge`, `font => {size => N}` in the
523      // class bindings) is LaTeX's `\@setfontsize` (latex.ltx:14103), whose
524      // first act is `\let\@currsize#1`: the size command's identity is
525      // TeX-visible state that packages test with `\ifx\@currsize\small`
526      // (ltugboat's `\SMC` cascade in latex-doc-ptr.sty:203-215, otherwise
527      // falling through to `\TBWarning`; `\@currsize` restores in many
528      // others). With the primitive alone `\@currsize` stayed the kernel's
529      // `\normalsize` macro (OXIDIZED_DESIGN #165) and never `\ifx`-matched
530      // any size. Guard: `perfect_kernel_batch54::size_switch_lets_currsize`.
531      let is_size_switch = chosen_font.size.is_some()
532        && chosen_font.family.is_none()
533        && chosen_font.series.is_none()
534        && chosen_font.shape.is_none();
535      // Perf: capture Rc<Font> directly; closure borrows through it.
536      // Previously: `(*chosen_font).clone()` cloned the Font per invocation.
537      // `\@setfontsize` goes on to `\fontsize{#2}{#3}\selectfont`. The merge
538      // records the size in `\f@size` (latex.ltx:12587; content.rs
539      // `merge_font_ref`), so a later `\fontsize{\f@size}{…}\selectfont`
540      // (line spacing) keeps the switched size (OXIDIZED_DESIGN_DIVERGENCES
541      // #288). The `\selectfont` puts the pending family, series and shape in
542      // force: doc.sty's `\MacroFont` (doc.sty:149-153) is `\fontfamily
543      // \ttdefault` … `\small` with no `\selectfont` of its own, so its
544      // macrocode came out roman (moloch, frankenstein, ftnxtra; Perl
545      // article.cls.ltxml:111 the same). It is read next, in this group, as
546      // whatever `\selectfont` means there — inside a pgf picture that is
547      // `\pgf@selectfont`, which returns to `\nullfont`
548      // (pgfcorescopes.code.tex:243, 309). In math the font in force is the
549      // math font, which `\selectfont` does not choose (`\@nomath` only
550      // warns there): math keeps it.
551      // A switch with parameters reads them after this step, so it would take
552      // the `\selectfont` as its argument; only the parameterless one reads it.
553      let ends_in_selectfont = is_size_switch && paramlist.is_none();
554      let merge_font_closure = before_digest_simple!({
555        merge_font_ref(&chosen_font);
556        if is_size_switch {
557          let_i(&T_CS!("\\@currsize"), &cs, None);
558        }
559        if ends_in_selectfont && !lookup_bool_sym(pin!("IN_MATH")) {
560          let selectfont = T_CS!("\\selectfont");
561          if lookup_definition(&selectfont)?.is_some() {
562            gullet::unread_one(selectfont);
563            // `\@setfontsize#1#2#3` is `\fontsize{#2}{#3}\selectfont`: the switch sets the leading
564            // too, `\baselineskip` = #3 × `\baselinestretch` (the kernel's `\size@update`). The
565            // bindings' size switches are size10.clo's, so its leading: a preamble
566            // `\setlength{\baselineskip}{1.5cm}` otherwise stood for every size, and a tikz
567            // node's `\small` lines stacked 2.5× too far apart (witness 2605.29990 S4.F7.pic1).
568            // Guard `perfect_kernel_batch58::size_switches_set_the_leading`.
569            let fontsize = T_CS!("\\fontsize");
570            if let Some(size) = chosen_font.size
571              && lookup_definition(&fontsize)?.is_some()
572            {
573              let leading = size10_leading(size);
574              let mut tokens = vec![fontsize, T_BEGIN!()];
575              tokens.extend(Explode!(s!("{size}")));
576              tokens.extend([T_END!(), T_BEGIN!()]);
577              tokens.extend(Explode!(s!("{leading}")));
578              tokens.push(T_END!());
579              gullet::unread(Tokens::new(tokens));
580            }
581          }
582        }
583      });
584      before_digest_env.push(merge_font_closure);
585    },
586    Some(FontDirective::Closure(font_closure)) => {
587      let execute_font_closure = before_digest_simple!({
588        merge_font(font_closure(None)?);
589      });
590      before_digest_env.push(execute_font_closure);
591    },
592    None => {},
593  }
594  before_digest_env.extend(options.before_digest);
595
596  let mut after_digest_env: Vec<DigestionClosure> = options.after_digest;
597  if let Some(ref mode_str) = mode {
598    let mode_clone = mode_str.clone();
599    let end_mode_closure: DigestionClosure = after_digest_simple!(_whatsit, {
600      end_mode(&mode_clone)?;
601    });
602    after_digest_env.push(end_mode_closure);
603  } else if declared_mode.bounded {
604    let egroup_closure: DigestionClosure = after_digest_simple!(_whatsit, {
605      // tex.web closes a group only through a closer whose handler finds the
606      // matching group code on top of the save stack (§1068 `cur_group`);
607      // `lx@group@code`, written by the opener above, is that code. If the top frame was
608      // not opened by this primitive — `\end{document}` inside the body
609      // abandoned it (§1335; an unbalanced `\abstract{…`, screenplay-pkg.tex:
610      // 67) — there is nothing of ours to close; closing the document frame
611      // instead was the "Attempt to close a group that switched to mode
612      // internal_vertical" error. Nested invocations of one primitive close
613      // innermost-first, as group codes need not be unique in TeX either.
614      let mine = is_value_bound("lx@group@code", Some(0))
615        && lookup_token("lx@group@code").is_some_and(|t| t == cs);
616      if mine {
617        egroup()?;
618      }
619    });
620    after_digest_env.push(egroup_closure);
621  }
622  //  Not sure robust entirely makes sense for Primitives, other than LaTeXML vs LaTeX mismatch
623  let mut alias = options.alias;
624  let defcs = if options.robust {
625    def_robust_cs(cs, options.locked, scope)?
626  } else if size_switch {
627    if alias.is_none() {
628      alias = Some(cs_name.clone());
629    }
630    def_switch_alias(cs, options.locked, scope)?
631  } else {
632    cs
633  };
634
635  install_definition(
636    Primitive {
637      origin: crate::definition::origin::current_origin(),
638      cs: defcs,
639      paramlist,
640      replacement: compiled_replacement,
641      before_digest: before_digest_env,
642      after_digest: after_digest_env,
643      alias,
644      nargs: options.nargs,
645      is_prefix: options.is_prefix,
646      reversion: options.reversion,
647      font_id: options.font_id,
648      declared_mode: Some(declared_mode),
649      font: declared_font,
650    },
651    scope,
652  );
653  if options_locked {
654    assign_value(&s!("{}:locked", cs_name), true, Some(Scope::Global));
655  }
656  Ok(())
657}
658
659/// Advanced math replacements require a XMDual representation
660pub fn def_math_dual(
661  cs: Token,
662  paramlist: Option<Parameters>,
663  presentation: String,
664  options: MathPrimitiveOptions,
665) -> Result<()> {
666  let (cont_cs_str, pres_cs_str) =
667    cs.with_str(|csname| (s!("{csname}@content"), s!("{csname}@presentation")));
668  let cont_cs = T_CS!(cont_cs_str);
669  let pres_cs = T_CS!(pres_cs_str);
670  let defcs = if options.robust {
671    def_robust_cs(cs, options.locked, options.scope)?
672  } else {
673    cs
674  };
675  let presentation_toks = mouth::tokenize_internal(TeXString::assembled(presentation.clone()));
676
677  // Make the original CS expand into a DUAL invoking a presentation macro and content constructor
678  let captured_role = options.role.clone();
679  let captured_revert_as = options.revert_as.clone();
680  let captured_cont_cs = cont_cs;
681  let captured_pres_cs = pres_cs;
682  let captured_pres = presentation.clone();
683  install_definition(
684    Expandable::new(
685      defcs,
686      paramlist.clone(),
687      Some(ExpansionBody::Closure(Rc::new(move |args| {
688        let args_opt_tks = args
689          .into_iter()
690          .map(|arg| arg.into())
691          .collect::<Vec<Option<Tokens>>>();
692        let (cargs, pargs) = dualize_arglist(&captured_pres, args_opt_tks)?;
693
694        let mut dtks = vec![T_CS!("\\lx@dual")];
695        // optional keyval arg
696        if captured_role.is_some() || captured_revert_as.is_some() {
697          dtks.push(T_OTHER!("["));
698          if let Some(ref role) = captured_role {
699            dtks.extend(vec![T_OTHER!("role"), T_OTHER!("="), T_OTHER!(role)]);
700            if let Some(ref _revert_as) = captured_revert_as {
701              dtks.push(T_OTHER!(","));
702            }
703          }
704          if let Some(ref revert_as) = captured_revert_as {
705            dtks.extend(vec![
706              T_OTHER!("revert_as"),
707              T_OTHER!("="),
708              T_OTHER!(revert_as),
709            ]);
710          }
711          dtks.push(T_OTHER!("]"));
712        }
713        // end optional keyval arg
714        // Perl: Invocation($content_cs, @content_args) wraps each arg in braces.
715        // If no args (no params), just emit the CS without braces.
716        dtks.push(T_BEGIN!());
717        dtks.push(captured_cont_cs);
718        for carg in cargs.into_iter().flatten() {
719          dtks.push(T_BEGIN!());
720          dtks.extend(carg.unlist());
721          dtks.push(T_END!());
722        }
723        dtks.push(T_END!());
724        dtks.push(T_BEGIN!());
725        dtks.push(captured_pres_cs);
726        for parg in pargs.into_iter().flatten() {
727          dtks.push(T_BEGIN!());
728          dtks.extend(parg.unlist());
729          dtks.push(T_END!());
730        }
731        dtks.push(T_END!());
732
733        Ok(Tokens::new(dtks))
734      }))),
735      Some(ExpandableOptions {
736        protected: options.protected,
737        ..ExpandableOptions::default()
738      }),
739    )?,
740    options.scope,
741  );
742
743  // Make the presentation macro.
744  install_definition(
745    Expandable::new(
746      pres_cs,
747      paramlist.clone(),
748      Some(ExpansionBody::Tokens(presentation_toks)),
749      Some(ExpandableOptions {
750        protected: options.protected,
751        ..ExpandableOptions::default()
752      }),
753    )?,
754    options.scope,
755  );
756
757  // content: Make the content constructor
758  // content: build the replacement closure
759  let nargs = paramlist
760    .as_ref()
761    .map(|pl| pl.get_parameters().len())
762    .unwrap_or(0);
763  let content_closure: ReplacementClosure = if nargs == 0 {
764    Rc::new(|document, _args, props| {
765      let mut attrs = HashMap::default();
766      for key in ["role", "scriptpos", "stretchy"] {
767        if let Some(v) = props.get(key) {
768          attrs.insert(key.to_owned(), v.to_string());
769        }
770      }
771      for key in MATH_CONSTRUCTOR_ATTRIBUTES {
772        if let Some(v) = props.get(key) {
773          attrs.insert(key.to_string(), v.to_string());
774        }
775      }
776      document.insert_element("ltx:XMTok", Vec::new(), Some(attrs))?;
777      Ok(())
778    })
779  } else {
780    Rc::new(|document, args, props| {
781      let mut app_attrs = HashMap::default();
782      for key in ["role", "scriptpos"] {
783        if let Some(v) = props.get(key) {
784          app_attrs.insert(key.to_owned(), v.to_string());
785        }
786      }
787      document.open_element("ltx:XMApp", Some(app_attrs), None)?;
788      let mut op_attrs = HashMap::default();
789      if let Some(v) = props.get("operator_stretchy") {
790        op_attrs.insert("stretchy".to_owned(), v.to_string());
791      }
792      if let Some(v) = props.get("operator_role") {
793        op_attrs.insert("role".to_owned(), v.to_string());
794      }
795      if let Some(v) = props.get("operator_scriptpos") {
796        op_attrs.insert("scriptpos".to_owned(), v.to_string());
797      }
798      for key in MATH_CONSTRUCTOR_ATTRIBUTES {
799        if let Some(v) = props.get(key) {
800          op_attrs.insert(key.to_string(), v.to_string());
801        }
802      }
803      // operator
804      document.insert_element("ltx:XMTok", Vec::new(), Some(op_attrs))?;
805      // arguments
806      // TODO: options.reorder?
807      for arg in args.iter().flatten() {
808        document.absorb(arg, None)?;
809      }
810      document.close_element("ltx:XMApp")?;
811      Ok(())
812    })
813  };
814  // content: install the constructor
815  let mut content_constructor = Constructor {
816    cs: cont_cs,
817    paramlist,
818    replacement: Some(content_closure),
819    ..Constructor::default()
820  };
821  let scope = options.scope;
822  transfer_common_constructor_options(&cs, &presentation, options, &mut content_constructor);
823  install_definition(content_constructor, scope);
824  Ok(())
825}
826
827/// Perl `defmath_wrapped` (Package.pm:1786-1813): no arguments, but a presentation naming control
828/// sequences. `\cs` expands to `\cs@wrapper{\cs@presentation}`, the presentation macro holds the
829/// tokens as given, and the wrapper constructor puts their digested form in an `XMWrap` carrying the
830/// DefMath's attributes (name, meaning, role, scriptpos, stretchy, …), which the math parser moves
831/// onto the parsed content (MathParser.pm:333-360, `parser.rs`). It reverts as its argument, or as
832/// `\cs` in a dual's content branch.
833pub fn def_math_wrapped(
834  cs: Token,
835  presentation: Tokens,
836  options: MathPrimitiveOptions,
837) -> Result<()> {
838  let (wrap_cs_str, pres_cs_str) =
839    cs.with_str(|csname| (s!("{csname}@wrapper"), s!("{csname}@presentation")));
840  let wrap_cs = T_CS!(wrap_cs_str);
841  let pres_cs = T_CS!(pres_cs_str);
842  let defcs = if options.robust {
843    def_robust_cs(cs, options.locked, options.scope)?
844  } else {
845    cs
846  };
847  install_definition(
848    Expandable::new(
849      defcs,
850      None,
851      Some(ExpansionBody::Tokens(Tokens::new(vec![
852        wrap_cs,
853        T_BEGIN!(),
854        pres_cs,
855        T_END!(),
856      ]))),
857      Some(ExpandableOptions {
858        protected: options.protected,
859        ..ExpandableOptions::default()
860      }),
861    )?,
862    options.scope,
863  );
864  install_definition(
865    Expandable::new(
866      pres_cs,
867      None,
868      Some(ExpansionBody::Tokens(presentation.clone())),
869      Some(ExpandableOptions {
870        protected: options.protected,
871        ..ExpandableOptions::default()
872      }),
873    )?,
874    options.scope,
875  );
876  let replacement: ReplacementClosure = Rc::new(|document, args, props| {
877    let mut attrs = HashMap::default();
878    for key in ["role", "scriptpos", "stretchy"] {
879      if let Some(v) = props.get(key) {
880        attrs.insert(key.to_owned(), v.to_string());
881      }
882    }
883    for key in MATH_CONSTRUCTOR_ATTRIBUTES {
884      if let Some(v) = props.get(key) {
885        attrs.insert(key.to_string(), v.to_string());
886      }
887    }
888    document.open_element("ltx:XMWrap", Some(attrs), None)?;
889    for arg in args.iter().flatten() {
890      document.absorb(arg, None)?;
891    }
892    document.close_element("ltx:XMWrap")?;
893    Ok(())
894  });
895  let mut wrapper = Constructor {
896    cs: wrap_cs,
897    paramlist: parse_parameters("{}", &wrap_cs, true)?,
898    replacement: Some(replacement),
899    ..Constructor::default()
900  };
901  let scope = options.scope;
902  transfer_common_constructor_options(&cs, &presentation.to_string(), options, &mut wrapper);
903  wrapper.reversion = Some(Reversion::Closure(Rc::new(move |_whatsit, args| {
904    if get_dual_branch() == Some("content") {
905      return Ok(Tokens::new(vec![cs]));
906    }
907    match args.first().and_then(Option::as_ref) {
908      Some(arg) => arg.revert(),
909      None => Ok(Tokens::new(Vec::new())),
910    }
911  })));
912  install_definition(wrapper, scope);
913  Ok(())
914}
915
916/// EXPERIMENT: Introduce an intermediate case for simple symbols
917/// Define a primitive that will create a Tbox with the appropriate set of XMTok attributes.
918pub fn def_math_primitive(
919  cs: Token,
920  _paramlist: Option<Parameters>,
921  presentation: String,
922  options: MathPrimitiveOptions,
923) {
924  let scope = options.scope;
925  let reqfont_opt = options.font.clone();
926  // Perf: wrap options in Rc to avoid per-invocation clone of a 30+ field struct.
927  // Previously cloned `MathPrimitiveOptions` (20+ Option<String>, 4 Vecs) on every
928  // DefMath invocation (e.g. 1000 math tokens = 1000 full clones). Now the closure
929  // reads fields through the Rc and applies overrides via a dedicated method.
930  let shared_options = Rc::new(options.clone());
931  let variablesize_op = shared_options.variablesize_op;
932  let dynamic_scriptpos = shared_options.dynamic_scriptpos;
933  let letters_class = shared_options.letters_class;
934  // Perl defmath_prim (Package.pm:1831): the box reverts to the alias when there is one
935  // (`\{` is `\lx@math@lbrace` with alias `\{`).
936  let reversion_cs = options.alias.as_deref().map_or(cs, Token::from);
937
938  install_definition(
939    MathPrimitive {
940      cs,
941      paramlist: None, // never any parameters, this is intentional
942      replacement: Some(Rc::new(move |_args| {
943        let locator = gullet::get_locator();
944        // Perl: defmath_prim L1810 — `my $mode = LookupValue('MODE');`
945        // The Tbox records the CURRENT digestion mode so that Box::isMath
946        // (mode =~ /math$/) returns false inside \text{} (restricted_horizontal),
947        // making `?#isMath` template fall through to the text branch.
948        let cur_mode = lookup_string_from_sym(pin!("MODE"));
949        let mode_static: &'static str = match cur_mode.as_str() {
950          "math" => "math",
951          "display_math" => "display_math",
952          "inline_math" => "inline_math",
953          "vertical" => "vertical",
954          "internal_vertical" => "internal_vertical",
955          "horizontal" => "horizontal",
956          "restricted_horizontal" => "restricted_horizontal",
957          _ => "math",
958        };
959        let state_font = lookup_font().unwrap();
960        // Dynamic mathstyle: doVariablesizeOp — "display" in display, "text" otherwise
961        let mathstyle_override: Option<&'static str> = if variablesize_op {
962          let is_display = state_font
963            .get_mathstyle()
964            .is_some_and(|s| s.as_ref() == "display");
965          Some(if is_display { "display" } else { "text" })
966        } else {
967          None
968        };
969        // Dynamic scriptpos: doScriptpos — "mid" in display, "post" otherwise
970        let scriptpos_override: Option<&'static str> = if dynamic_scriptpos {
971          let is_display = state_font
972            .get_mathstyle()
973            .is_some_and(|s| s.as_ref() == "display");
974          Some(if is_display { "mid" } else { "post" })
975        } else {
976          None
977        };
978        // A glyph declared from the `letters` symbol font takes its class's shape (`Font::specialize_letters`).
979        let specialize = |font: &Font| match letters_class {
980          Some(class) => font.specialize_letters(&presentation, class),
981          None => font.specialize(&presentation),
982        };
983        let font = Rc::new(if let Some(ref reqfont) = reqfont_opt {
984          let this_reqfont = reqfont.get_font(None)?;
985          specialize(&state_font.merge_ref(&this_reqfont))
986        } else {
987          specialize(&state_font)
988        });
989
990        Ok(vec![Digested::from(Tbox {
991          text: arena::pin(&presentation),
992          tokens: Tokens!(reversion_cs),
993          font,
994          properties: shared_options.to_hash_stored_with_overrides(
995            Some(mode_static),
996            mathstyle_override,
997            scriptpos_override,
998          ),
999          locator: Some(locator),
1000          empty_marker: false,
1001        })])
1002      })),
1003      options,
1004      ..MathPrimitive::default()
1005    },
1006    scope,
1007  );
1008}
1009
1010/// Uses of DefMath without arguments, but with constructor-like options, are realized via a
1011/// `Constructor` definition
1012pub fn def_math_constructor(
1013  cs: Token,
1014  paramlist: Option<Parameters>,
1015  presentation: String,
1016  mut options: MathPrimitiveOptions,
1017) -> Result<()> {
1018  // TODO: do we need to do anything about digesting the presentation?
1019  let nargs = paramlist
1020    .as_ref()
1021    .map(|pl| pl.get_parameters().len())
1022    .unwrap_or(0);
1023  // let csname_alias = if options.alias.is_none() && options.robust {
1024  //   Some(String::from(cs.get_cs_name()))
1025  // } else {
1026  //   None
1027  // };
1028  let defcs = if options.robust {
1029    def_robust_cs(cs, options.locked, options.scope)?
1030  } else {
1031    cs
1032  };
1033  if options.reversion.is_none() && nargs == 0 && options.alias.is_none() {
1034    if options.revert_as.is_none() || options.revert_as == Some(Cow::Borrowed("content")) {
1035      options.reversion = Some(Reversion::Tokens(Tokens!(cs)));
1036    } else if options.revert_as == Some(Cow::Borrowed("context")) {
1037      // Perl decides at reversion time,
1038      //   ($LaTeXML::DUAL_BRANCH || 'content') eq 'content' ? $cs : $presentation
1039      // so that the `tex` attribute of ltx:Math (presentation branch) gets the
1040      // presentation and `content-tex` (content branch) the user's CS.
1041      let content_toks = Tokens!(cs);
1042      let presentation_toks = Tokens::new(Explode!(presentation));
1043      options.reversion = Some(Reversion::Closure(Rc::new(move |_whatsit, _args| {
1044        Ok(if get_dual_branch().unwrap_or("content") == "content" {
1045          content_toks.clone()
1046        } else {
1047          presentation_toks.clone()
1048        })
1049      })));
1050    } else {
1051      // TODO: This differs from the Perl, where `presentation` comes in as Tokens
1052      //       we have it come in as a `String`,
1053      //       so need to tokenize when reusing it as a reversion.
1054      options.reversion = Some(Reversion::Tokens(Tokens::new(Explode!(presentation))));
1055    }
1056  }
1057  let presentation_for_sizer = presentation.clone();
1058  let presentation_for_replacement = presentation.clone();
1059  let compiled_replacement: Option<ReplacementClosure> = Some(if nargs == 0 {
1060    // Perl defmath_cons (Package.pm L1841-1844):
1061    //   $nargs == 0
1062    //     && $presentation !~ /(?:\(|\)|\\)/
1063    //   ? "?#isMath(<ltx:XMTok …$end_tok)($qpresentation)"
1064    //   : "<ltx:XMTok …$end_tok"
1065    //
1066    // The `?#isMath(…)(…)` form is Perl's construction-time conditional —
1067    // in math context emit the XMTok, otherwise emit the bare presentation
1068    // character. The check is gated on presentation NOT containing `(`,
1069    // `)`, or `\`, which would collide with template-specials.
1070    //
1071    // Ported here as a runtime DOM-ancestry walk (same predicate as
1072    // `tbox.rs::be_absorbed`), and the presentation-content guard mirrors
1073    // Perl's regex. `\rightarrowfill` (`\x{2192}`, no specials) gets the
1074    // text fallback; symbols like `\(` / `\)` / anything with a backslash
1075    // keep the unconditional XMTok — matching Perl.
1076    let presentation_is_trivial = !presentation_for_replacement
1077      .chars()
1078      .any(|c| c == '(' || c == ')' || c == '\\');
1079    Rc::new(
1080      move |document: &mut Document, _, props: &SymHashMap<Stored>| {
1081        let font_opt = match props.get("font") {
1082          Some(Stored::Font(f)) => Some(Cow::Borrowed(&**f)),
1083          Some(Stored::FontDirective(FontDirective::Closure(code))) => {
1084            Some(Cow::Owned(code(None)?))
1085          },
1086          Some(Stored::FontDirective(FontDirective::Asset(font))) => Some(Cow::Borrowed(&**font)),
1087          _ => None,
1088        };
1089        // Perl's `?#isMath(…)` conditional compiles to `ToString($prop{'isMath'})`
1090        // (Constructor/Compiler.pm parse_conditional L164-173 + L197: `#prop` →
1091        // `$prop{'prop'}`). That property is set on the Whatsit at digestion
1092        // time from the stomach's math-mode flag (Constructor.pm L108). So the
1093        // check here is on the *Whatsit's* isMath, not document-ancestry — an
1094        // `\hbox{\rightarrowfill}` inside `\mathop{…}` digests the XMTok with
1095        // isMath=false (hbox switched stomach to text mode), even though the
1096        // document insertion point is nested under <ltx:Math>.
1097        let is_math = matches!(props.get("isMath"), Some(Stored::Bool(true)));
1098        if !is_math && presentation_is_trivial {
1099          // Perl `?#isMath(…)(plain)` text branch — just emit the char.
1100          document.absorb_string(&presentation_for_replacement, props)?;
1101          return Ok(());
1102        }
1103        let mut attrs = HashMap::default();
1104        for key in ["role", "scriptpos", "stretchy"] {
1105          if let Some(v) = props.get(key) {
1106            attrs.insert(key.to_owned(), v.to_string());
1107          }
1108        }
1109        for key in MATH_CONSTRUCTOR_ATTRIBUTES {
1110          if let Some(v) = props.get(key) {
1111            attrs.insert(key.to_string(), v.to_string());
1112          }
1113        }
1114        if let Some(font) = font_opt {
1115          document.open_element("ltx:XMTok", Some(attrs), Some(&font))?;
1116        } else {
1117          document.open_element("ltx:XMTok", Some(attrs), None)?;
1118        }
1119        document.absorb_string(&presentation_for_replacement, props)?;
1120        document.close_element("ltx:XMTok")?;
1121        Ok(())
1122      },
1123    )
1124  } else {
1125    // Perl defmath_cons (Package.pm L1847-1851): when `$nargs` > 0 the
1126    // template is always `<ltx:XMApp>…<ltx:XMTok …/></ltx:XMApp>` — there
1127    // is NO text-mode fallback for this arm. The `requireMath` beforeDigest
1128    // (Perl L1689, same as Rust L1606) has already warned the user; math
1129    // context is assumed. Keep parity — emit the XMApp/XMTok structure as
1130    // before.
1131    Rc::new(
1132      move |document: &mut Document, args: &Vec<Option<Digested>>, props: &SymHashMap<Stored>| {
1133        let mut attrs = HashMap::default();
1134        for key in ["role", "scriptpos", "stretchy"] {
1135          if let Some(v) = props.get(key) {
1136            attrs.insert(key.to_owned(), v.to_string());
1137          }
1138        }
1139        let font_opt = match props.get("font") {
1140          Some(Stored::Font(f)) => Some(Cow::Borrowed(&**f)),
1141          Some(Stored::FontDirective(FontDirective::Closure(code))) => {
1142            Some(Cow::Owned(code(None)?))
1143          },
1144          Some(Stored::FontDirective(FontDirective::Asset(font))) => Some(Cow::Borrowed(&**font)),
1145          _ => None,
1146        };
1147        if let Some(ref font) = font_opt {
1148          document.open_element("ltx:XMApp", Some(attrs), Some(font))?;
1149        } else {
1150          document.open_element("ltx:XMApp", Some(attrs), None)?;
1151        }
1152        // operator
1153        let mut op_attrs = HashMap::default();
1154        if let Some(role) = props.get("operator_role") {
1155          op_attrs.insert(String::from("role"), role.to_string());
1156        }
1157        if let Some(stretchy) = props.get("operator_stretchy") {
1158          op_attrs.insert(String::from("stretchy"), stretchy.to_string());
1159        }
1160        if let Some(scriptpos) = props.get("operator_scriptpos") {
1161          op_attrs.insert(String::from("scriptpos"), scriptpos.to_string());
1162        }
1163        for key in MATH_CONSTRUCTOR_ATTRIBUTES {
1164          if let Some(v) = props.get(key) {
1165            op_attrs.insert(key.to_string(), v.to_string());
1166          }
1167        }
1168        if let Some(font) = font_opt {
1169          document.open_element("ltx:XMTok", Some(op_attrs), Some(&font))?;
1170        } else {
1171          document.open_element("ltx:XMTok", Some(op_attrs), None)?;
1172        }
1173        document.absorb_string(&presentation_for_replacement, props)?;
1174        document.close_element("ltx:XMTok")?;
1175        // arguments
1176        for arg in args {
1177          document.open_element("ltx:XMArg", None, None)?;
1178          if let Some(arg_v) = arg {
1179            document.absorb(arg_v, None)?;
1180          }
1181          document.close_element("ltx:XMArg")?;
1182        }
1183
1184        document.close_element("ltx:XMApp")?;
1185        Ok(())
1186      },
1187    )
1188  });
1189  let sizer: Option<SizingClosure> = Some(Rc::new(move |_| {
1190    Ok(Font::math_default().compute_string_size(&presentation_for_sizer, SymHashMap::default()))
1191  }));
1192
1193  // let mut prop_options = options.clone();
1194  let mut constructor = Constructor {
1195    cs: defcs,
1196    paramlist,
1197    replacement: compiled_replacement,
1198    nargs: Some(nargs),
1199    sizer,
1200    // capture_body: options.capture_body,
1201    // outer
1202    // long
1203    ..Constructor::default()
1204  };
1205  let scope = options.scope;
1206  transfer_common_constructor_options(&cs, &presentation, options, &mut constructor);
1207  install_definition(constructor, scope);
1208  Ok(())
1209}
1210
1211fn infer_sizer(
1212  sizer: Option<&SizingClosure>,
1213  _reversion: Option<&Reversion>,
1214) -> Option<SizingClosure> {
1215  // Perl: sizer is only set if explicitly provided. Never infer from reversion.
1216  // Previously this inferred from reversion text, but that's wrong for body-capturing
1217  // constructors (e.g. \lx@begin@inline@math with reversion "$" would measure the "$"
1218  // character instead of the math body content).
1219  sizer.map(Rc::clone)
1220}
1221
1222/// `\cs` as a macro for the primitive `\lx@size@cs` (a size switch, `def_primitive`); returns it.
1223/// Not `\cs␣`: that is the name `\DeclareRobustCommand\cs` writes to, so a document copying the
1224/// size command (`\NewCommandCopy\oldsmall\small`) and redefining it robustly
1225/// (`\DeclareRobustCommand\small{\oldsmall\itshape}`) overwrote the primitive with a call to itself.
1226fn def_switch_alias(cs: Token, locked: bool, scope: Option<Scope>) -> Result<Token> {
1227  let inner = T_CS!(cs.with_str(|name| format!("\\lx@size@{}", name.trim_start_matches('\\'))));
1228  let options = ExpandableOptions {
1229    locked,
1230    ..ExpandableOptions::default()
1231  };
1232  install_definition(
1233    Expandable::new(cs, None, Tokens!(inner).into(), Some(options))?,
1234    scope,
1235  );
1236  Ok(inner)
1237}
1238
1239fn def_robust_cs(cs: Token, locked: bool, scope: Option<Scope>) -> Result<Token> {
1240  let cs_str = cs.with_str(|cstr| format!("{cstr} "));
1241  let defcs = T_CS!(cs_str);
1242  let return_cs = defcs;
1243  let expansion = Tokens!(T_CS!("\\protect"), defcs);
1244  let options = ExpandableOptions {
1245    locked,
1246    robust: true,
1247    ..ExpandableOptions::default()
1248  };
1249  // scope should be \x@protect?
1250  install_definition(
1251    Expandable::new(cs, None, expansion.into(), Some(options))?,
1252    scope,
1253  );
1254  Ok(return_cs)
1255}
1256
1257/// Binding definition connecting a TeX command sequence with a structured XML output.
1258///
1259/// The Constructor is where LaTeXML really starts getting interesting;
1260/// invoking the control sequence will generate an arbitrary XML
1261/// fragment in the document tree.  More specifically: during digestion, the arguments
1262/// will be read and digested, creating a `Whatsit` to represent the object. During
1263/// absorption by the `Document`, the `Whatsit` will generate the XML fragment according
1264/// to the `compiled_replacement`.
1265pub fn def_constructor(
1266  cs: Token,
1267  paramlist: Option<Parameters>,
1268  compiled_replacement: Option<ReplacementClosure>,
1269  mut options: ConstructorOptions,
1270) {
1271  if provide_only_declines(&cs) {
1272    return;
1273  }
1274  // TODO: This won't work, as we can only invoke method calls on paramlist in runtime
1275  //*latexml_codegen::constructable::NARGS = $paramlist.get_num_args();
1276  let scope = options.scope;
1277  let cs = if options.robust {
1278    // Perl Package.pm L1480-1481:
1279    //   alias => (defined $options{alias} ? coerceCS($options{alias})
1280    //             : ($options{robust} ? $cs : undef)),
1281    // A `robust` definition is installed under the MUNGED cs — LaTeX2e's
1282    // `\DeclareRobustCommand` idiom, where `\ref` becomes `\protect\ref␣` and
1283    // the real definition lives at `\ref␣`, with a literal trailing space in the
1284    // name. The reversion must still print the original `\ref`, so absent an
1285    // explicit alias the pre-munge cs becomes one (`Whatsit::revert` prefers the
1286    // alias over `get_cs`).
1287    //
1288    // Without this, every robust constructor reverted with its munged name and
1289    // the trailing space rode into user-visible output: `\ref{sec:one}` became
1290    // `tex="\ref {sec:one}"` on `ltx:Math`, and through that the MathML
1291    // `alttext` — the screen-reader / no-MathML fallback.
1292    //
1293    // This changes the REVERSION only. The definition is still installed under
1294    // the munged cs, so `get_cs_name()` still reports `\ref ` and code that
1295    // identifies a whatsit by its cs must keep accepting both spellings (see
1296    // `lxrdfa_sty.rs`'s `cs == "\\ref" || cs == "\\ref "`, or use
1297    // `get_cs_or_alias`). Only the alias is clean.
1298    //
1299    // Note this fallback is DefConstructor-only in Perl: `DefPrimitiveI`
1300    // (L1318) deliberately passes `undef` when no alias is given, and the
1301    // DefMath family has its own rule (`defmath_common_constructor_options`
1302    // L1703 sets `alias => $cs` unconditionally).
1303    if options.alias.is_none() {
1304      options.alias = Some(cs.with_cs_name(ToString::to_string));
1305    }
1306    def_robust_cs(cs, options.locked, scope).expect("def_robust_cs for constructor failed")
1307  } else {
1308    cs
1309  };
1310  let cs_name = cs.with_cs_name(ToString::to_string);
1311  let locked_key_opt = if options.locked {
1312    Some(s!("{cs_name}:locked"))
1313  } else {
1314    None
1315  };
1316
1317  let mut before_digest_closures: Vec<BeforeDigestClosure> = Vec::new();
1318
1319  let (mode, declared_mode) = command_declared_mode(
1320    options.mode,
1321    options.enter_horizontal,
1322    options.leave_horizontal,
1323    options.bounded,
1324    options.require_math,
1325    options.forbid_math,
1326  );
1327
1328  if declared_mode.require_math {
1329    // (named as the command it reverts as, its `alias`, where it stands in for one: the Springer classes' `\vec` is
1330    // `\lx@sv@vec@boldmath`, and pdflatex's "Missing $ inserted" is the author's `\vec`'s; probe rev79b/ltext)
1331    let cs_name_cloned = options
1332      .alias
1333      .clone()
1334      .filter(|alias| alias.starts_with('\\') && alias.len() > 1)
1335      .unwrap_or_else(|| cs_name.clone());
1336    let require_math_closure = before_digest_simple!({ requireMath!(cs_name_cloned) });
1337    before_digest_closures.push(require_math_closure);
1338  }
1339  if declared_mode.forbid_math {
1340    let cs_name_cloned = cs_name;
1341    let forbid_math_closure = before_digest_simple!({ forbidMath!(cs_name_cloned) });
1342    before_digest_closures.push(forbid_math_closure);
1343  }
1344  if declared_mode.enter_horizontal {
1345    before_digest_closures.push(before_digest_simple!({
1346      enter_horizontal();
1347    }));
1348  }
1349  if declared_mode.leave_horizontal {
1350    before_digest_closures.push(before_digest_simple!({
1351      leave_horizontal()?;
1352    }));
1353  }
1354  if let Some(ref mode) = mode {
1355    let mode_clone = mode.clone();
1356    let begin_mode_closure = before_digest_simple!({
1357      begin_mode(&mode_clone)?;
1358    });
1359    before_digest_closures.push(begin_mode_closure);
1360  } else if declared_mode.bounded {
1361    let bgroup_closure = before_digest_simple!({
1362      bgroup();
1363    });
1364    before_digest_closures.push(bgroup_closure);
1365  }
1366  // DG: The situations with Fonts in Constructors appears rather complex?
1367  //  LaTeXML seems to currently rely on both the top-level "font" option but *also*
1368  //  has code checking for a second-tier "properties => { font => VALUE}" option
1369  //  Can we consolidate into a single, top-level, font handler?
1370  let declared_font = options.font.clone();
1371  match options.font {
1372    Some(FontDirective::Asset(chosen_font)) => {
1373      let merge_font_closure = before_digest_simple!({
1374        merge_font((*chosen_font).clone());
1375      });
1376      before_digest_closures.push(merge_font_closure);
1377    },
1378    Some(FontDirective::Closure(font_closure)) => {
1379      let execute_font_closure = before_digest_simple!({
1380        merge_font(font_closure(None)?);
1381      });
1382      before_digest_closures.push(execute_font_closure);
1383    },
1384    None => {},
1385  };
1386  before_digest_closures.extend(options.before_digest);
1387
1388  let mut after_digest_closures: Vec<DigestionClosure> = options.after_digest;
1389  if let Some(ref mode_str) = mode {
1390    let mode_clone = mode_str.clone();
1391    let end_mode_closure: DigestionClosure = after_digest_simple!(_whatsit, {
1392      end_mode(&mode_clone)?;
1393    });
1394    after_digest_closures.push(end_mode_closure);
1395  } else if declared_mode.bounded {
1396    let egroup_closure: DigestionClosure = after_digest_simple!(_whatsit, {
1397      egroup()?;
1398    });
1399    after_digest_closures.push(egroup_closure);
1400  }
1401
1402  let constructor = Constructor {
1403    cs,
1404    paramlist,
1405    replacement: compiled_replacement,
1406    before_digest: before_digest_closures,
1407    after_digest: after_digest_closures,
1408    before_construct: options.before_construct,
1409    after_construct: options.after_construct,
1410    nargs: options.nargs,
1411    alias: options.alias,
1412    sizer: infer_sizer(options.sizer.as_ref(), options.reversion.as_ref()),
1413    reversion: options.reversion,
1414    capture_body: options.capture_body,
1415    properties: options.properties,
1416    declared_mode: Some(declared_mode),
1417    font: declared_font,
1418    halign_primitive: options.halign_primitive,
1419    template: options.template,
1420    salvage_close: options.salvage_close,
1421    // outer
1422    // long
1423    ..Constructor::default()
1424  };
1425  install_definition(constructor, scope);
1426
1427  if let Some(locked_key) = locked_key_opt {
1428    assign_value(&locked_key, true, Some(Scope::Global));
1429  }
1430}
1431
1432/// `\UseHook{env/<name>/<point>}` as tokens, or `None` when `\UseHook` is not
1433/// defined (plain format): the LaTeX kernel fires these around every
1434/// environment (latex.ltx:15347/15362/15388/15391), from the lthooks store.
1435fn env_hook_invocation(name: &str, point: &str) -> Option<Tokens> {
1436  let use_hook = T_CS!("\\UseHook");
1437  lookup_meaning(&use_hook)?;
1438  let mut toks = vec![use_hook, T_BEGIN!()];
1439  toks.extend(ExplodeText!(format!("env/{name}/{point}")));
1440  toks.push(T_END!());
1441  Some(Tokens::new(toks))
1442}
1443
1444/// Marks the frame of an environment whose `\end` hooks ran before its end constructor
1445/// (stomach.rs `end_command_form_before_enclosing_end`).
1446pub const END_HOOKS_RAN: &str = "lx@env@end@hooks@ran";
1447
1448/// `\end{name}`'s hooks: the pre-`\AddToHook` `\AtEndEnvironment` store (`@environment@name@atend`, filled by
1449/// bindings: deluxetable's table end), then `\UseHook{env/name/end}` (latex.ltx:15386-15388) when it has code.
1450/// `end_hook` is that invocation if the caller built it already.
1451pub fn environment_end_hooks(name: &str, end_hook: Option<&Tokens>) -> Vec<Tokens> {
1452  let mut hooks = Vec::new();
1453  if let Some(code) = lookup_tokens(&s!("@environment@{name}@atend")) {
1454    hooks.push(code);
1455  }
1456  if env_hook_has_code(name, "end")
1457    && let Some(hook) = end_hook
1458      .cloned()
1459      .or_else(|| env_hook_invocation(name, "end"))
1460  {
1461    hooks.push(hook);
1462  }
1463  hooks
1464}
1465
1466/// `\begin`'s TeX record of the environment it opens, in its group: latex.ltx:15349-15351 `\def\@currenvir{#1}`
1467/// `\edef\@currenvline{\on@line}`. Perl (Package.pm:1927, latex_constructs.pool.ltxml:186-188) leaves `\@currenvline`
1468/// `\@empty`, so `\@badend` and a hook read no line (OXIDIZED_DESIGN_DIVERGENCES #1242).
1469pub fn set_currenvir(body: Tokens) -> Result<()> {
1470  thread_local! {
1471    /// latex.ltx `\on@line`'s text before the number: " on input line ", letters and spaces.
1472    static ON_LINE_PREFIX: Vec<Token> = " on input line "
1473      .chars()
1474      .map(|c| match c {
1475        ' ' => T_SPACE!(),
1476        _ => Token::new(c.encode_utf8(&mut [0; 4]), Catcode::LETTER),
1477      })
1478      .collect();
1479  }
1480  def_macro(
1481    T_CS!("\\@currenvir"),
1482    None,
1483    Some(ExpansionBody::Tokens(body)),
1484    None,
1485  )?;
1486  let on_line = T_CS!("\\on@line");
1487  // The kernel's `\on@line` (sect13.rs) is built here, as its `\edef` gives it (an `Expand` per `\begin`
1488  // cost +0.6 % on 1,200 environments).
1489  let line = if x_equals(&on_line, &T_CS!("\\lx@kernel@on@line")) {
1490    let from_line = gullet::get_input_locator().from_line;
1491    let mut line = ON_LINE_PREFIX.with(Vec::clone);
1492    for digit in from_line.to_string().chars() {
1493      line.push(Token::new(digit.encode_utf8(&mut [0; 4]), Catcode::OTHER));
1494    }
1495    Some(Tokens::new(line))
1496  } else if lookup_meaning(&on_line).is_some() {
1497    Some(gullet::do_expand(Tokens::new(vec![on_line]))?)
1498  } else {
1499    None
1500  };
1501  if let Some(line) = line {
1502    def_macro(
1503      T_CS!("\\@currenvline"),
1504      None,
1505      Some(ExpansionBody::Tokens(line)),
1506      None,
1507    )?;
1508  }
1509  Ok(())
1510}
1511
1512/// latex.ltx:15386 fires `env/#1/end` only `\IfHookEmptyTF`-guarded (an empty
1513/// hook must contribute nothing inside an alignment's last cell): the kernel's
1514/// own predicate, [`hook_has_code`].
1515pub fn env_hook_has_code(name: &str, point: &str) -> bool {
1516  hook_has_code(&format!("env/{name}/{point}"))
1517}
1518
1519/// The three lthooks macro names for `hook`: labelled prop, toplevel, next-use.
1520fn hook_slot_names(hook: &str) -> (String, String, String) {
1521  (
1522    format!("\\g__hook_{hook}_code_prop"),
1523    format!("\\__hook_toplevel {hook}"),
1524    format!("\\__hook_next {hook}"),
1525  )
1526}
1527
1528/// `\prop_if_empty:N` (expl3-code.tex:10450): a flat prop is empty when its
1529/// meaning is `\c_empty_prop`'s.
1530fn hook_prop_has_code(prop: &Token) -> bool {
1531  with_macro_body(prop, |body| match body {
1532    Some(body) => {
1533      with_macro_body(&T_CS!("\\c_empty_prop"), |empty| empty != Some(body)).unwrap_or(true)
1534    },
1535    None => true,
1536  })
1537  .unwrap_or(false)
1538}
1539
1540/// Whether the kernel hook `hook` holds code: [`HookStore::has_code`].
1541/// Checks `l3_hooks_loaded()` first and probes with non-interning [`Token::try_cs`]
1542/// so checking an empty/undeclared hook never permanently interns 3 `SymStr`s.
1543pub fn hook_has_code(hook: &str) -> bool {
1544  if !l3_hooks_loaded() {
1545    return false;
1546  }
1547  let (prop, toplevel, next) = hook_slot_names(hook);
1548  Token::try_cs(prop).is_some_and(|tok| hook_prop_has_code(&tok))
1549    || Token::try_cs(toplevel).is_some_and(|tok| hook_slot_has_code(&tok))
1550    || Token::try_cs(next).is_some_and(|tok| hook_slot_has_code(&tok))
1551}
1552
1553/// The slots lthooks keeps a hook's code in, named once (a hook read at every `\selectfont` keeps its own).
1554pub struct HookStore {
1555  prop:     Token,
1556  toplevel: Token,
1557  next:     Token,
1558}
1559
1560impl HookStore {
1561  pub fn new(hook: &str) -> Self {
1562    let (prop, toplevel, next) = hook_slot_names(hook);
1563    HookStore {
1564      prop:     T_CS!(prop),
1565      toplevel: T_CS!(toplevel),
1566      next:     T_CS!(next),
1567    }
1568  }
1569
1570  /// Build from already-pinned literal tokens (e.g. `T_CS!("...")`), safe
1571  /// across `arena::reset()` because `pin!` re-interns automatically.
1572  pub fn from_tokens(prop: Token, toplevel: Token, next: Token) -> Self {
1573    HookStore { prop, toplevel, next }
1574  }
1575
1576  /// lthooks' `\hook_if_empty:nTF` (latex.ltx:6436-6448) read from its storage, no expansion: the labelled code
1577  /// (`\g__hook_<hook>_code_prop` not `\c_empty_prop`), the document's (`\__hook_toplevel <hook>`) and the next-use
1578  /// code (`\__hook_next <hook>`) — a slot holds code when it is a macro with a non-empty body
1579  /// (`\__hook_cs_if_empty:c`, :5688).
1580  pub fn has_code(&self) -> bool {
1581    if !l3_hooks_loaded() {
1582      return false;
1583    }
1584    hook_prop_has_code(&self.prop)
1585      || hook_slot_has_code(&self.toplevel)
1586      || hook_slot_has_code(&self.next)
1587  }
1588}
1589
1590/// Whether `hook` holds a chunk labelled `label`: lthooks keeps labelled code in a flat prop (`\prop_if_in:cnTF`,
1591/// latex.ltx:5544), each entry `\__prop_pair:wn <label> \s__prop {<code>}` (expl3-code.tex:9873).
1592pub fn hook_has_labelled_code(hook: &str, label: &str) -> bool {
1593  if !l3_hooks_loaded() {
1594    return false;
1595  }
1596  let (pair, sep) = (T_CS!("\\__prop_pair:wn"), T_CS!("\\s__prop"));
1597  with_macro_body(&T_CS!(s!("\\g__hook_{hook}_code_prop")), |prop| {
1598    let Some(prop) = prop else {
1599      return false;
1600    };
1601    let mut entries = prop.split(|t| *t == pair).skip(1);
1602    entries.any(|entry| {
1603      let key = entry
1604        .iter()
1605        .take_while(|t| **t != sep)
1606        .map(|t| t.to_string())
1607        .collect::<String>();
1608      key == label
1609    })
1610  })
1611  .unwrap_or(false)
1612}
1613
1614/// No L3 hook system (the plain/no-op format): no hook code anywhere.
1615fn l3_hooks_loaded() -> bool {
1616  with_meaning(&T_CS!("\\hook_if_empty:nTF"), |meaning| meaning.is_some())
1617}
1618
1619/// lthooks' `\__hook_cs_if_empty:cF` (latex.ltx:5688-5699): `cs` is a macro with a non-empty body.
1620pub fn hook_slot_has_code(cs: &Token) -> bool {
1621  // (a macro whose body is Rust: code, by the safe answer)
1622  with_macro_body(cs, |body| body.is_none_or(|body| !body.is_empty())).unwrap_or(false)
1623}
1624
1625/// `f` of a macro's body, borrowed (`None` when the body is a closure); `None` for anything else.
1626fn with_macro_body<R>(cs: &Token, f: impl FnOnce(Option<&[Token]>) -> R) -> Option<R> {
1627  with_meaning(cs, |meaning| match meaning {
1628    Some(Stored::Expandable(code)) => Some(match code.get_expansion() {
1629      Some(ExpansionBody::Tokens(body)) => f(Some(body.unlist_ref())),
1630      Some(ExpansionBody::Closure(_)) => f(None),
1631      None => f(Some(&[])),
1632    }),
1633    _ => None,
1634  })
1635}
1636
1637/// The tokens running the kernel hook `hook` as `\UseHook` (or, `once`, `\UseOneTimeHook`) does, or none when it has
1638/// no code: an empty `\UseHook` does nothing; an empty one-time hook only marks itself used (`\__hook_use_once_set:n`,
1639/// latex.ltx:6399-6411, so later code runs at once), which an already used one needs not. Not kept: the clear code
1640/// `\__hook_use_once:nn` leaves in an undeclared hook's next slot, which only `\IfHookEmptyTF` on it would see.
1641pub fn hook_use_tokens(hook: &str, once: bool) -> Vec<Token> {
1642  if !l3_hooks_loaded() {
1643    return Vec::new();
1644  }
1645  let has_code = hook_has_code(hook);
1646  // `\__hook_parse_label_default:nN` (:5174) rewrites a name with `./` or surrounding spaces: such a name takes
1647  // lthooks' own path
1648  let plain_name = !hook.contains("./") && hook != "." && hook.trim() == hook;
1649  if !has_code && plain_name {
1650    if !once || hook_used_once(hook) {
1651      return Vec::new();
1652    }
1653    let mut toks = vec![T_CS!("\\__hook_use_once_set:n"), T_BEGIN!()];
1654    toks.extend(ExplodeText!(hook));
1655    toks.push(T_END!());
1656    return toks;
1657  }
1658  let mut toks = vec![
1659    T_CS!(if once {
1660      "\\UseOneTimeHook"
1661    } else {
1662      "\\UseHook"
1663    }),
1664    T_BEGIN!(),
1665  ];
1666  toks.extend(ExplodeText!(hook));
1667  toks.push(T_END!());
1668  toks
1669}
1670
1671/// `\__hook_if_execute_immediately:nTF` (latex.ltx:6421-6435): a one-time hook already used runs later code at once.
1672fn hook_used_once(hook: &str) -> bool {
1673  // (`\if:w I`: the slot's first token is the character `I`)
1674  let used = [T_LETTER!("I"), T_OTHER!("I")];
1675  with_macro_body(&T_CS!(s!("\\g__hook_{hook}_reversed_tl")), |body| {
1676    body.is_some_and(|body| body.first().is_some_and(|t| used.contains(t)))
1677  })
1678  .unwrap_or(false)
1679}
1680
1681/// The TeX group an environment's begin code leaves open: its definition's
1682/// `tex_group`, unless a binding set `\begin{X}:tex_group` (a
1683/// [`TexGroup::as_str`] name) for the begin code a class or package gives it.
1684fn environment_tex_group(key: &str, declared: TexGroup) -> TexGroup {
1685  if lookup_value(key).is_none() {
1686    return declared;
1687  }
1688  TexGroup::from_name(&lookup_string(key)).unwrap_or(declared)
1689}
1690
1691/// Defines an Environment that generates a specific XML fragment.
1692///
1693/// `compiled_replacement` is of the same form as for DefConstructor, but will generally include
1694/// reference to the `#body` property.
1695/// Upon encountering a `\begin{env}`:  the mode is switched, if needed, else a new group is opened;
1696/// then the environment name is noted; the beforeDigest hook is run.
1697/// Then the Whatsit representing the begin command (but ultimately the whole environment) is
1698/// created and the `after_digest_begin` hook is run.
1699/// Next, the body will be digested and collected until the balancing `\end{env}`.
1700/// Then, any `after_digest` hook is run, the environment is ended, finally the mode is ended or the
1701/// group is closed.  The body and `\end{env}` whatsit are added to the `\begin{env}`'s whatsit as
1702/// body and trailer, respectively.
1703pub fn def_environment(
1704  name: String,
1705  paramlist: Option<Parameters>,
1706  compiled_replacement: Option<ReplacementClosure>,
1707  mut options: ConstructorOptions,
1708) {
1709  // One environment, all or none of its names (`\begin{X}`, `\end{X}`, `\X`, `\endX`).
1710  if provide_only_declines(&T_CS!(s!("\\begin{{{name}}}"))) {
1711    return;
1712  }
1713  // This is for the common case where the environment is opened by \begin{env}
1714  let begin_name = s!("\\begin{{{name}}}");
1715  let end_name = s!("\\end{{{name}}}");
1716  let mut before_digest_env: Vec<BeforeDigestClosure> = Vec::new();
1717
1718  // Perl Package.pm:1902: $mode = 'restricted_horizontal' if !$mode || ($mode eq 'text');
1719  // Environments ALWAYS have a mode — defaults to restricted_horizontal.
1720  // This means \end{env} always calls endMode(), never egroup().
1721  let mode = match options.mode.as_deref() {
1722    None | Some("text") => Some("restricted_horizontal".to_string()),
1723    _ => options.mode,
1724  };
1725  let declared_mode = DeclaredMode {
1726    mode:             mode.as_deref().map(arena::pin),
1727    enter_horizontal: options.enter_horizontal,
1728    leave_horizontal: options.leave_horizontal,
1729    bounded:          false,
1730    require_math:     options.require_math,
1731    forbid_math:      options.forbid_math,
1732    // an environment is a box by its begin code's group (`TexGroup::Box`, below), not by its mode
1733    restricted_box:   false,
1734  };
1735
1736  if declared_mode.require_math {
1737    let require_name = begin_name.clone();
1738    let require_math_closure = before_digest_simple!({ requireMath!(require_name) });
1739    before_digest_env.push(require_math_closure);
1740  }
1741  if declared_mode.forbid_math {
1742    let forbid_name = begin_name.clone();
1743    let forbid_math_closure = before_digest_simple!({ forbidMath!(forbid_name) });
1744    before_digest_env.push(forbid_math_closure);
1745  }
1746  let begin_frame_end = T_CS!(end_name.as_str());
1747  let tex_group = options.tex_group;
1748  // A binding whose class or package redefines the environment's begin code
1749  // overrides the kind at run time (REVTeX 3's `figure` without `floats`).
1750  let tex_group_key = s!("\\begin{{{name}}}:tex_group");
1751  let begin_tex_group_key = tex_group_key.clone();
1752  let bgroup_closure = before_digest_simple!({
1753    bgroup();
1754    // This frame stands for the `\begingroup` of LaTeX's `\begin`
1755    // (latex.ltx:15355); a plain `\endgroup` meeting it ends the environment
1756    // by its `\end{X}` (stomach.rs `close_environment_frame`). Marked here,
1757    // before an `@atbegin` hook can open a group of its own above it: marked
1758    // after the hook, 2001.02707's `\AtBeginEnvironment{defn}{\begin{samepage}}`
1759    // put the marker on samepage's group and its errors rose 27 -> 77.
1760    assign_frame_value_sym(crate::pin!("lx@env@begin@end"), begin_frame_end);
1761    let kind = environment_tex_group(&begin_tex_group_key, tex_group);
1762    if kind != TexGroup::None {
1763      assign_frame_value_sym(crate::pin!("lx@env@tex@group"), kind.as_str());
1764    }
1765  });
1766  before_digest_env.push(bgroup_closure);
1767  // latex.ltx:15349-15351 `\begin` defines `\@currenvir` and `\@currenvline` in its group BEFORE
1768  // `\UseHook{env/#1/begin}`, so a begin hook (etoolbox's `\AtBeginEnvironment` too) reads its own environment's
1769  // name; Perl Package.pm:1919-1927 digests `@atbegin` first (KNOWN_PERL_ERRORS #1405). LaTeXML's
1770  // `current_environment` stays with the mode, below: it names the frame the mode is begun in, which may be a group
1771  // a hook left open (2001.02707's `\AtBeginEnvironment{thm}{\begin{samepage}}`).
1772  let env_name = name.clone();
1773  let currenvir_closure = before_digest_simple!({
1774    // Perl Package.pm:1927 `DefMacroI('\@currenvir', undef, $name)` — the
1775    // string body is TokenizeInternal'd into CHARACTER tokens (= latex.ltx:15350
1776    // `\def\@currenvir{#1}`), so `\ifx\reserved@a\@currenvir` comparisons
1777    // (`\@checkend` latex.ltx:15394, collectbox:208, storebox:36, nag:258,
1778    // powerdot:529 …) see the same token list as a `\def\reserved@a{center}`.
1779    // A single multi-char T_LETTER stringified right but never `\ifx`-matched.
1780    set_currenvir(mouth::tokenize_internal(TeXString::assembled(
1781      env_name.clone(),
1782    )))?;
1783  });
1784  before_digest_env.push(currenvir_closure);
1785  let atbegin_key = s!("@environment@{name}@atbegin");
1786  // latex.ltx:15362 `\UseHook{env/#1/begin}` inside the group (the
1787  // kernel's lthooks store); the `@environment@…` PushValue store is
1788  // etoolbox's. `\UseHook` exists only under the LaTeX format.
1789  let begin_hook_tokens = env_hook_invocation(&name, "begin");
1790  let begin_hook_name = name.clone();
1791  let atbegin_hook_closure = before_digest_simple!({
1792    let mut boxes = Vec::new();
1793    if let Some(b) = lookup_tokens(&atbegin_key) {
1794      boxes.push(digest_hook_code(b.unlist())?);
1795    }
1796    if let Some(hook) = begin_hook_tokens.clone()
1797      && env_hook_has_code(&begin_hook_name, "begin")
1798    {
1799      boxes.push(digest_hook_code(hook.unlist())?);
1800    }
1801    boxes
1802  });
1803
1804  before_digest_env.push(atbegin_hook_closure);
1805  if declared_mode.enter_horizontal {
1806    before_digest_env.push(before_digest_simple!({
1807      enter_horizontal();
1808    }));
1809  }
1810  if declared_mode.leave_horizontal {
1811    before_digest_env.push(before_digest_simple!({
1812      leave_horizontal()?;
1813    }));
1814  }
1815  // Perl Package.pm line 1908: beginMode($mode, 1) — noframe=1 since bgroup already pushed. A begin hook that leaves
1816  // a group open (2001.02707's `\AtBeginEnvironment{thm}{\begin{samepage}}`, closed by `\AtEndEnvironment`) is on
1817  // top by now: the mode goes to the environment's own frame, below it, as `\endX`'s place after `env/X/end`
1818  // (latex.ltx:15386-15390) needs; Perl binds it in the hook's group (KNOWN_PERL_ERRORS #1409, OD #1248). A math
1819  // mode stays on top: its TeX math group opens inside the hook's.
1820  if let Some(ref mode) = mode {
1821    let bmode = mode.clone();
1822    let mode_end = T_CS!(end_name.as_str());
1823    let mode_closure = before_digest_simple!({
1824      if environment_frame_under_hook_groups(&mode_end, &bmode).is_some() {
1825        begin_mode_under_hook_groups(&bmode, &mode_end)?;
1826      } else {
1827        begin_mode_opt(&bmode, true)?;
1828      }
1829    });
1830    before_digest_env.push(mode_closure);
1831  }
1832  let env_name = name.clone();
1833  let env_end = T_CS!(end_name.as_str());
1834  let env_mode = mode.clone().unwrap_or_default();
1835  before_digest_env.push(before_digest_simple!({
1836    // With the mode, in the environment's own frame: `\end{X}` checks it after the end hook closed the hook's group.
1837    match environment_frame_under_hook_groups(&env_end, &env_mode) {
1838      Some(frame) if is_value_bound("BOUND_MODE", Some(frame)) => bind_value_in_frame(
1839        "current_environment",
1840        frame,
1841        Stored::String(arena::pin(&env_name)),
1842      ),
1843      _ => assign_value_sym(crate::pin!("current_environment"), env_name.clone(), None),
1844    }
1845  }));
1846
1847  match options.font {
1848    Some(FontDirective::Asset(chosen_font)) => {
1849      // Perf: capture Rc<Font> directly; closure borrows through it.
1850      // Previously: `(*chosen_font).clone()` cloned the Font per invocation.
1851      let merge_font_closure = before_digest_simple!({
1852        merge_font_ref(&chosen_font);
1853      });
1854      before_digest_env.push(merge_font_closure);
1855    },
1856    Some(FontDirective::Closure(font_closure)) => {
1857      let execute_font_closure = before_digest_simple!({
1858        merge_font(font_closure(None)?);
1859      });
1860      before_digest_env.push(execute_font_closure);
1861    },
1862    None => {},
1863  }
1864  // Clone before_digest so the bare `\name` form can run the same
1865  // user-supplied hooks. Perl Package.pm L1949-1969 states that the bare
1866  // form (entered e.g. via `\csname env\endcsname` or by another macro
1867  // expanding to `\env[…]`) "gets the same hook pipeline as \begin{FOO}" —
1868  // including the user's `beforeDigest`. sidecap's `\SCfigure[…]` → `\figure[…]`
1869  // is the canonical trigger: without this, `beforeFloat('figure')` never
1870  // fires, `\@captype` stays undefined, and nested `\caption` cascades as
1871  // "outside any known float".
1872  let bare_before_digest = options.before_digest.clone();
1873  before_digest_env.extend(options.before_digest);
1874
1875  // Clone fields needed for the bare \name constructor (Perl Package.pm lines 1949-1969)
1876  // before they are moved into the \begin{name} constructor below.
1877  let bare_after_digest_begin = options.after_digest_begin.clone();
1878  // An environment whose begin code opens a box group (`\setbox\@tempboxa\vbox\bgroup`, a minipage) is a TeX box: the
1879  // first element its constructor opens is marked for a frontmatter field's print (`document::FIELD_BOX_PROPERTY`,
1880  // OXIDIZED_DESIGN #715), unless the binding's run-time kind says otherwise. The field-ink gate first: the kind is a
1881  // State lookup, for every such body (review r5 finding 3).
1882  if tex_group == TexGroup::Box {
1883    let box_key = tex_group_key.clone();
1884    options.after_digest_body.insert(
1885      0,
1886      after_digest_simple!(whatsit, {
1887        if crate::document::field_box_marks_live()
1888          && environment_tex_group(&box_key, TexGroup::Box) == TexGroup::Box
1889        {
1890          crate::document::field_box_whatsit(whatsit);
1891        }
1892      }),
1893    );
1894  }
1895  let bare_after_digest_body = options.after_digest_body.clone();
1896  let bare_before_construct = options.before_construct.clone();
1897  let bare_after_construct = options.after_construct.clone();
1898  let bare_sizer = options.sizer.clone();
1899  let bare_reversion = options.reversion.clone();
1900  let bare_alias = options.alias.clone();
1901
1902  let push_frame_closure = Rc::new(|_document: &mut Document, _whatsit: &Whatsit| {
1903    push_frame();
1904    Ok(())
1905  });
1906  let mut before_construct_with_frame: Vec<ConstructionClosure> = vec![push_frame_closure];
1907  before_construct_with_frame.extend(options.before_construct);
1908
1909  let mut after_construct_with_frame: Vec<ConstructionClosure> = options.after_construct;
1910
1911  let pop_frame_closure = Rc::new(|_document: &mut Document, _whatsit: &Whatsit| {
1912    pop_frame()?;
1913    Ok(())
1914  });
1915  after_construct_with_frame.push(pop_frame_closure);
1916
1917  // Perl Package.pm L1908-1912: "in pure LaTeX would usually have expanded to \env
1918  // and would have skipped spaces before parsing args, if any."
1919  // Prepend SkipSpaces parameter when the environment has arguments.
1920  let paramlist_skips = match paramlist {
1921    Some(ref pl) if pl.get_num_args() > 0 => {
1922      let skip_spaces_param = Parameter {
1923        novalue: true,
1924        name: pin!("SkipSpaces"),
1925        spec: pin!("SkipSpaces"),
1926        reader: Rc::new(|_inner, _extra| {
1927          gullet::skip_spaces()?;
1928          Ok(ArgWrap::None)
1929        }),
1930        ..Parameter::default()
1931      };
1932      let mut params = vec![skip_spaces_param];
1933      params.extend(pl.get_parameters().iter().cloned());
1934      Some(Parameters::new(params))
1935    },
1936    _ => paramlist.clone(),
1937  };
1938
1939  let begin_name_constructor = Rc::new(Constructor {
1940    origin:            crate::definition::origin::current_origin(),
1941    cs:                T_CS!(begin_name),
1942    paramlist:         paramlist_skips,
1943    replacement:       compiled_replacement.clone(),
1944    nargs:             options.nargs,
1945    before_digest:     before_digest_env,
1946    after_digest:      options.after_digest_begin,
1947    after_digest_body: options.after_digest_body,
1948    before_construct:  before_construct_with_frame,
1949    // Curiously, it's the \begin whose afterConstruct gets called.
1950    after_construct:   after_construct_with_frame,
1951    capture_body:      true,
1952    properties:        options.properties.clone(),
1953    // (defined $options{reversion} ? (reversion => $options{reversion}) : ()),
1954    // (defined $sizer ? (sizer => $sizer) : ()),
1955    // ), $options{scope});
1956    sizer:             infer_sizer(options.sizer.as_ref(), options.reversion.as_ref()),
1957    reversion:         options.reversion,
1958    alias:             options.alias,
1959    declared_mode:     Some(declared_mode),
1960    font:              None,
1961    halign_primitive:  false,
1962    template:          None,
1963    salvage_end:       Some((T_CS!(end_name.as_str()), options.after_digest.clone())),
1964    salvage_close:     options.salvage_close.clone(),
1965  });
1966  install_definition(begin_name_constructor, options.scope);
1967
1968  let mut after_digest_env = options.after_digest.clone();
1969  let name_clone = name.clone();
1970  let end_name_clone = end_name.clone();
1971  let unexpected_end_closure = after_digest_simple!(_whatsit, {
1972    let env = lookup_string_from_sym(crate::pin!("current_environment"));
1973    if env.is_empty() || name_clone != env {
1974      // Perl Package.pm:1946-1947: message has a trailing `;`, and the
1975      // open-environment list is introduced by "Current are:" (with colon).
1976      let message1 = s!("Can't close environment {};", name_clone);
1977      let message2 = s!(
1978        "Current are: {}",
1979        with_stacked_values_sym(crate::pin!("current_environment"), |vals| vals
1980          .iter()
1981          .map(|x| s!("{:?}", x))
1982          .collect::<Vec<String>>()
1983          .join(", "))
1984      );
1985      Error!("unexpected", end_name_clone, message1, message2);
1986    }
1987    Ok(Vec::new())
1988  });
1989  after_digest_env.push(unexpected_end_closure);
1990
1991  match mode {
1992    Some(ref emode) => {
1993      let emode = emode.clone();
1994      let own_end = T_CS!(end_name.as_str());
1995      let own_name = name.clone();
1996      let emode_closure = Rc::new(move |_whatsit: &mut Whatsit| {
1997        // `\end{X}` over a `\begingroup` the class opened inside X (raa.cls:322-349): it closes that group and X,
1998        // and X's group stays for the class's `\endgroup` (stomach.rs `end_environment_over_plain_groups`).
1999        if end_environment_over_plain_groups(&own_name, own_end)? {
2000          return Ok(Vec::new());
2001        }
2002        // Perl Package.pm L1961-1962:
2003        //   # Switch mode (w/stack frame pop), OR egroup
2004        //   ($mode ? (sub { $_[0]->endMode($mode) }) : sub { $_[0]->egroup; }),
2005        // endMode(mode) with no second arg defaults to noframe=0 — it DOES
2006        // pop a frame. This pairs with L1902's `bgroup` + L1908's
2007        // `beginMode($mode, 1)` (noframe=1, no push) on the begin side:
2008        // bgroup pushes exactly one frame, beginMode writes MODE/BOUND_MODE
2009        // Local into that frame, endMode pops the frame and reverts.
2010        end_mode(&emode)?;
2011        Ok(Vec::new())
2012      });
2013      after_digest_env.push(emode_closure);
2014    },
2015    None => {
2016      let egroup_closure = Rc::new(|_whatsit: &mut Whatsit| {
2017        egroup()?;
2018        Ok(Vec::new())
2019      });
2020      after_digest_env.push(egroup_closure);
2021    },
2022  };
2023
2024  let (mut before_digest_for_endenv, before_digest_end_clone) = {
2025    let cloned = options.before_digest_end.clone();
2026    (options.before_digest_end, cloned)
2027  };
2028  // latex.ltx:15386-15388 `\UseHook{env/#1/end}` inside the group before
2029  // `\end#1`.
2030  let end_hook_tokens = env_hook_invocation(&name, "end");
2031  let end_hook_name = name.clone();
2032  let atend_hook_closure = before_digest_simple!({
2033    // `\end`'s hooks (latex.ltx:15386-15393) never run when a plain
2034    // `\endgroup` closed `\begin`'s group (stomach.rs `close_environment_frame`),
2035    // and ran already when a command-form environment left open in it was ended first.
2036    if environment_ended_by_group() || environment_end_hooks_ran() {
2037      Vec::new()
2038    } else {
2039      // Read as input: an `\egroup` closing the begin hook's `\bgroup` ends no digestion (`stomach::digest_hook_code`).
2040      environment_end_hooks(&end_hook_name, end_hook_tokens.as_ref())
2041        .into_iter()
2042        .map(|hook| digest_hook_code(hook.unlist()))
2043        .collect::<Result<Vec<_>>>()?
2044    }
2045  });
2046  before_digest_for_endenv.push(atend_hook_closure);
2047
2048  let end_envname_constructor = Rc::new(Constructor {
2049    cs: T_CS!(end_name),
2050    replacement: None,
2051    paramlist: None,
2052    before_digest: before_digest_for_endenv,
2053    after_digest: after_digest_env,
2054    ..Constructor::default() // TODO ? fill in missing ones
2055  });
2056  install_definition(end_envname_constructor, options.scope);
2057
2058  // For the uncommon case opened by \csname env\endcsname
2059  // Perl Package.pm lines 1949-1969: \FOO gets the same hook pipeline as \begin{FOO}
2060  let mut before_digest_bare: Vec<BeforeDigestClosure> = Vec::new();
2061  // The bare `\X` opens no TeX group (latex.ltx:15346-15355: only `\begin`
2062  // does), so this frame is LaTeXML's alone; a `}` or `\endgroup` of an
2063  // enclosing group meeting it ends the environment by its `\endX` first
2064  // (stomach.rs `close_environment_frame`): the binding's own, under a private name, since a document's `\endX`
2065  // (`\def\endremark{\vspace{1ex}}` beside a wrapped `\remark`, 1907.13475) closes nothing.
2066  let bare_frame_end = T_CS!(s!("\\lx@env@bare@end@{}", &name));
2067  let bare_end_alias = bare_frame_end;
2068  let bare_frame_shown_end = T_CS!(s!("\\end{}", &name));
2069  // (and any bare start as the document knows it, `\X`, whatever name the start was reached by)
2070  let bare_frame_shown = T_CS!(s!("\\{}", &name));
2071  before_digest_bare.push(before_digest_simple!({
2072    bgroup();
2073    assign_frame_value_sym(crate::pin!("lx@env@bare@end"), bare_frame_end);
2074    assign_frame_value_sym(crate::pin!("lx@env@bare@end@shown"), bare_frame_shown_end);
2075    assign_frame_value_sym(crate::pin!("lx@env@bare@shown"), bare_frame_shown);
2076    let kind = environment_tex_group(&tex_group_key, tex_group);
2077    if kind != TexGroup::None {
2078      assign_frame_value_sym(crate::pin!("lx@env@tex@group"), kind.as_str());
2079    }
2080  }));
2081  if declared_mode.enter_horizontal {
2082    before_digest_bare.push(before_digest_simple!({
2083      enter_horizontal();
2084    }));
2085  }
2086  if declared_mode.leave_horizontal {
2087    before_digest_bare.push(before_digest_simple!({
2088      leave_horizontal()?;
2089    }));
2090  }
2091  if let Some(ref bmode) = mode {
2092    let bmode = bmode.clone();
2093    before_digest_bare.push(before_digest_simple!({
2094      begin_mode_opt(&bmode, true)?;
2095    }));
2096  }
2097  // Perl Package.pm L1949-1969: bare `\name` runs the same user beforeDigest
2098  // hooks as `\begin{name}` (e.g. beforeFloat for `{figure}`). Order matters:
2099  // bgroup + mode have already been pushed; the user hooks come last, mirroring
2100  // the `\begin{name}` pipeline.
2101  before_digest_bare.extend(bare_before_digest);
2102  let push_frame_bare = Rc::new(|_document: &mut Document, _whatsit: &Whatsit| {
2103    push_frame();
2104    Ok(())
2105  });
2106  let pop_frame_bare = Rc::new(|_document: &mut Document, _whatsit: &Whatsit| {
2107    pop_frame()?;
2108    Ok(())
2109  });
2110  // Perl: \name gets the same afterDigest, afterDigestBody, beforeConstruct, afterConstruct,
2111  // sizer, reversion, alias as \begin{name}
2112  let mut before_construct_bare: Vec<ConstructionClosure> = vec![push_frame_bare];
2113  before_construct_bare.extend(bare_before_construct);
2114  let mut after_construct_bare: Vec<ConstructionClosure> = bare_after_construct;
2115  after_construct_bare.push(pop_frame_bare);
2116  let name_constructor = Rc::new(Constructor {
2117    origin: crate::definition::origin::current_origin(),
2118    cs: T_CS!(s!("\\{}", &name)),
2119    paramlist,
2120    replacement: compiled_replacement,
2121    nargs: options.nargs,
2122    capture_body: true,
2123    properties: options.properties.clone(),
2124    before_digest: before_digest_bare,
2125    after_digest: bare_after_digest_begin,
2126    after_digest_body: bare_after_digest_body,
2127    before_construct: before_construct_bare,
2128    after_construct: after_construct_bare,
2129    sizer: infer_sizer(bare_sizer.as_ref(), bare_reversion.as_ref()),
2130    reversion: bare_reversion,
2131    alias: bare_alias,
2132    declared_mode: Some(declared_mode),
2133    font: None,
2134    halign_primitive: false,
2135    template: None,
2136    salvage_end: Some((T_CS!(s!("\\end{}", &name)), options.after_digest.clone())),
2137    salvage_close: options.salvage_close.clone(),
2138  });
2139  install_definition(name_constructor, options.scope);
2140  let end_name = s!("\\end{}", &name);
2141  let mut after_digest_end = options.after_digest;
2142  // Perl Package.pm lines 1970-1975: \endFOO calls endMode if mode was specified
2143  match mode {
2144    Some(ref emode) => {
2145      let emode = emode.clone();
2146      // The frames a bare `\endFOO` may end are environments' frames: a bare `\X`'s (marked `lx@env@bare@end`), a
2147      // `\begin{X}`'s (`lx@env@begin@end`), or one a group's end handed back (`lx@env@ended@by@group`, stomach.rs
2148      // `close_environment_frame`) — any environment's, not only FOO's: amsmath ends a `\equation*` display with
2149      // `\endequation` (tcolorbox's `ams equation*`, tcbtheorems.code.tex:301; 2211.17024), and `end_mode` still checks the
2150      // mode. A frame no environment opened is left alone, with one Warning: LaTeX's `\endquotation` is
2151      // `\endlist`/`\endtrivlist` (latex.ltx), no group work, so an IEEE Open Journal `\IEEEkeywords` box's
2152      // `\vbox\bgroup … \par\endquotation\egroup` (ieeetmlcn.cls:3711-3715) must not lose the box's frame — ending the
2153      // mode there made the box reader read the whole body into the box (2301.00752, 2602.19492; 54 papers). Perl ends
2154      // the mode there too (an Error, content kept; KNOWN_PERL_ERRORS #674, OD #584). Guard:
2155      // `perfect_kernel_batch66t::bare_end_without_its_begin_keeps_the_box`.
2156      let own_end = end_name.clone();
2157      after_digest_end.push(Rc::new(move |_whatsit: &mut Whatsit| {
2158        let owns_top_frame = [
2159          "lx@env@ended@by@group",
2160          "lx@env@bare@end",
2161          "lx@env@begin@end",
2162        ]
2163        .iter()
2164        .any(|key| is_value_bound(key, Some(0)));
2165        if owns_top_frame {
2166          end_mode(&emode)?;
2167        } else {
2168          Warn!(
2169            "unexpected",
2170            T_CS!(own_end.as_str()),
2171            s!("{own_end} without an environment open: no environment frame to end")
2172          );
2173        }
2174        Ok(Vec::new())
2175      }));
2176    },
2177    None => {
2178      // No mode specified — no egroup needed for this simplified closer.
2179      // (The \end{FOO} constructor already handles egroup.)
2180    },
2181  };
2182
2183  // Perl Package.pm lines 1970-1975: \endFOO has beforeDigestEnd + afterDigest + endMode
2184  let end_cs = T_CS!(end_name);
2185  let end_name_constructor = Constructor {
2186    cs: end_cs,
2187    paramlist: None,
2188    replacement: None,
2189    before_digest: before_digest_end_clone,
2190    after_digest: after_digest_end,
2191    ..Constructor::default()
2192  };
2193  install_definition(Rc::new(end_name_constructor), options.scope);
2194  let_i(&bare_end_alias, &end_cs, options.scope);
2195
2196  if options.locked {
2197    assign_value(
2198      &s!("\\begin{{{}}}:locked", &name),
2199      true,
2200      Some(Scope::Global),
2201    );
2202    assign_value(&s!("\\end{{{}}}:locked", &name), true, Some(Scope::Global));
2203    assign_value(&s!("\\{}:locked", &name), true, Some(Scope::Global));
2204    assign_value(&s!("\\end{}:locked", &name), true, Some(Scope::Global));
2205  }
2206}
2207
2208//======================================================================
2209// Support for XMDual
2210
2211// Perhaps it would be better to use a label(-like) indirection here,
2212// so all ID's can stay in the desired format?
2213pub fn get_xmarg_id() -> Result<Tokens> {
2214  // `@lx@xmarg` is an internal-only counter (no user-visible
2215  // counters nest inside it), so `noreset: true` skips the
2216  // `\cl@@lx@xmarg` nested-reset probe — the same observation as
2217  // in xmath_helpers::get_xm_arg_id.
2218  step_counter("@lx@xmarg", true)?;
2219  def_macro(
2220    T_CS!("\\@@lx@xmarg@ID"),
2221    None,
2222    Tokens!(Explode!(
2223      lookup_register("\\c@@lx@xmarg", Vec::new())?
2224        .unwrap()
2225        .value_of()
2226    )),
2227    Some(ExpandableOptions {
2228      scope: Some(Scope::Global),
2229      ..ExpandableOptions::default()
2230    }),
2231  )?;
2232  gullet::do_expand(T_CS!("\\the@lx@xmarg@ID"))
2233}
2234
2235type ArgsUnpacked = Vec<Option<Tokens>>;
2236/// Flesh out two dual (mathematical) forms of a given list of arguments.
2237///
2238/// Given a list of Tokens (to be expanded into mathematical objects)
2239/// return two lists
2240///   (1) The Tokens' wrapped in an XMAarg, with an ID added
2241///   (2) a corresponding list of Tokens creating XMRef's to those IDs
2242///
2243/// Ah, but there are complications!!!
2244/// On the one hand, arguments may be hidden, never appearing on the presentation side
2245/// (all will be passed to the content side); This argues for putting the XMArg's on the content
2246/// side. OTOH, they ought to be on the presentation side, so that they can be expanded & digested
2247/// in the proper context they will be presented, and pick up all the styling (font size,
2248/// displaystyle..) I don't know how to work around the latter, so we'll put args on the
2249/// presentation side, UNLESS they are hidden, in which case they'll be on the content side.
2250/// So, how do we know if they're hidden? We'll scan the presentation for #\d, that's how!
2251pub fn dualize_arglist(
2252  presentation: &str,
2253  args: Vec<Option<Tokens>>,
2254) -> Result<(ArgsUnpacked, ArgsUnpacked)> {
2255  let mut used = HashMap::default();
2256  for cap in ARG_HOLE.captures_iter(presentation) {
2257    // Get the args that were actually used!
2258    let argi = cap.get(1).unwrap().as_str();
2259    let entry = used.entry(argi.parse::<usize>().expect(argi)).or_insert(0);
2260    *entry += 1;
2261  }
2262  let mut cargs = Vec::new();
2263  let mut pargs = Vec::new();
2264  for (index, arg_opt) in args.into_iter().enumerate() {
2265    match arg_opt {
2266      None => {
2267        pargs.push(None);
2268        cargs.push(None);
2269      },
2270      Some(arg) if arg.unlist_ref().is_empty() => {
2271        pargs.push(Some(arg.clone()));
2272        cargs.push(Some(arg));
2273      },
2274      Some(arg_toks) => {
2275        if used.get(&(1 + index)).unwrap_or(&0) > &0 {
2276          // used in presentation?
2277          let id = get_xmarg_id()?;
2278          pargs.push(Some(Tokens!(
2279            T_CS!("\\lx@xmarg"),
2280            T_BEGIN!(),
2281            id.clone().unlist(),
2282            T_END!(),
2283            T_BEGIN!(),
2284            arg_toks.unlist(),
2285            T_END!()
2286          ))); // put XMArg in presentation
2287          cargs.push(Some(Tokens!(
2288            T_CS!("\\lx@xmref"),
2289            T_BEGIN!(),
2290            id.unlist(),
2291            T_END!()
2292          )));
2293        } else {
2294          // Hidden arg, put XMArg in content.
2295          let id = get_xmarg_id()?;
2296          cargs.push(Some(Tokens!(
2297            T_CS!("\\lx@xmarg"),
2298            T_BEGIN!(),
2299            id.clone().unlist(),
2300            T_END!(),
2301            T_BEGIN!(),
2302            arg_toks.unlist(),
2303            T_END!()
2304          )));
2305          pargs.push(Some(Tokens!(
2306            T_CS!("\\lx@xmref"),
2307            T_BEGIN!(),
2308            id.unlist(),
2309            T_END!()
2310          )));
2311        }
2312      },
2313    }
2314  }
2315  Ok((cargs, pargs))
2316}
2317
2318/// A DefMath presentation, Perl `DefMathI`'s `$presentation`: TeX source text, tokenized at
2319/// definition, or the tokens a binding built (amsopn's `Invocation(T_CS('\operatorname'), $star,
2320/// $text)`), which keep their catcodes and are dispatched on them (Package.pm:1650-1661).
2321pub enum MathPresentation {
2322  Text(String),
2323  Tokens(Tokens),
2324}
2325impl From<String> for MathPresentation {
2326  fn from(text: String) -> Self { MathPresentation::Text(text) }
2327}
2328impl From<&str> for MathPresentation {
2329  fn from(text: &str) -> Self { MathPresentation::Text(text.to_string()) }
2330}
2331impl From<Tokens> for MathPresentation {
2332  fn from(tokens: Tokens) -> Self { MathPresentation::Tokens(tokens) }
2333}
2334
2335/// Define a Mathematical symbol or function.
2336///
2337/// There are two sets of cases:
2338///  (1) If the presentation appears to be TeX code, we create an XMDual,
2339/// since the presentation may end up with structure, etc.
2340///  (2) But if the presentation is a simple string, or unicode,
2341/// it is just the content of the symbol; even if the function takes arguments.
2342// ALSO
2343//  arrange that the operator token gets cs="$cs"
2344// ALSO
2345//  Possibly some trick with SUMOP/INTOP affecting limits ?
2346//  Well, not exactly, but....
2347// HMM.... Still fishy.
2348// When to make a dual ?
2349// If the $presentation seems to be TeX (ie. it involves #1... but not ONLY!)
2350pub fn def_math(
2351  cs: Token,
2352  paramlist: Option<Parameters>,
2353  presentation: impl Into<MathPresentation>,
2354  mut options: MathPrimitiveOptions,
2355) -> Result<()> {
2356  if provide_only_declines(&cs) {
2357    return Ok(());
2358  }
2359  let presentation_in = presentation.into();
2360  // Perl compares the name with the presentation as a string (`$name eq $presentation`, a Tokens
2361  // presentation stringified).
2362  let presentation = match &presentation_in {
2363    MathPresentation::Text(text) => text.clone(),
2364    MathPresentation::Tokens(tokens) => tokens.to_string(),
2365  };
2366  // Can't defer parsing parameters since we need to know number of args!
2367  // $paramlist = parseParameters($paramlist, $cs) if defined $paramlist && !ref $paramlist;
2368
2369  let nargs = match paramlist {
2370    Some(ref plist) => plist.get_num_args(),
2371    None => 0,
2372  };
2373  let csname = cs.with_str(ToString::to_string);
2374  let name_opt = {
2375    let name = match options.name {
2376      Some(ref name) => Cow::Owned(name.to_owned()),
2377      None => {
2378        let mut inferred_name = match options.alias {
2379          Some(ref alias) => Cow::Owned(alias.to_owned()),
2380          None => Cow::Borrowed(&csname),
2381        };
2382        if inferred_name.starts_with('\\') {
2383          inferred_name = Cow::Owned(inferred_name.replacen('\\', "", 1))
2384        }
2385        inferred_name
2386      },
2387    };
2388    let meaning_check = options
2389      .meaning
2390      .as_ref()
2391      .map_or_else(|| Cow::Owned(String::new()), Cow::Borrowed);
2392    // Perl `$name eq $presentation`: a Tokens presentation stringifies to its object address,
2393    // so only a text presentation can equal the name (Package.pm:1628-1632).
2394    let same_as_presentation =
2395      matches!(&presentation_in, MathPresentation::Text(text) if *text == *name);
2396    if same_as_presentation || (name.is_empty()) || *name == *meaning_check {
2397      None
2398    } else {
2399      Some(name.into_owned())
2400    }
2401  };
2402  options.name = name_opt;
2403  if nargs == 0 && options.role.is_none() {
2404    options.role = Some(String::from("UNKNOWN"))
2405  }
2406  if nargs > 0 && options.operator_role.is_none() {
2407    options.operator_role = Some(String::from("UNKNOWN"))
2408  }
2409  if options.hide_content_reversion {
2410    options.revert_as = Some(Cow::Borrowed("context"));
2411  }
2412
2413  let locked = options.locked;
2414  // Store some data for introspection
2415  // defmath_introspective(cs, paramlist, presentation, options);
2416
2417  // If single character, handle with a rewrite rule
2418  if csname.len() == 1 {
2419    let mut math_attr_hash: HashMap<String, String> = HashMap::default();
2420    transfer_opt_default!(name, options, math_attr_hash);
2421    transfer_opt_default!(meaning, options, math_attr_hash);
2422    transfer_opt_default!(omcd, options, math_attr_hash);
2423    transfer_opt_default!(decl_id, options, math_attr_hash);
2424    transfer_opt_default!(role, options, math_attr_hash);
2425    transfer_opt_default!(replace, options, math_attr_hash);
2426    transfer_opt_default!(mathstyle, options, math_attr_hash);
2427    transfer_opt_default!(stretchy, options, math_attr_hash);
2428    assign_value(
2429      &s!("math_token_attributes_{}", csname),
2430      math_attr_hash,
2431      Some(Scope::Global),
2432    );
2433  }
2434  // If the macro involves arguments,
2435  // we will create an XMDual to separate simple content application
2436  // from the (likely) convoluted presentation. Perl Package.pm:1650-1653: a string presentation
2437  // naming an argument or a control sequence, or tokens holding an argument or `#`.
2438  else if match &presentation_in {
2439    MathPresentation::Text(text) => HAS_ARG_OR_CS.is_match(text),
2440    MathPresentation::Tokens(tokens) => tokens
2441      .unlist_ref()
2442      .iter()
2443      .any(|t| matches!(t.get_catcode(), Catcode::ARG | Catcode::PARAM)),
2444  } {
2445    let presentation = match presentation_in {
2446      MathPresentation::Tokens(tokens) => tokens.untex(),
2447      MathPresentation::Text(text) => text,
2448    };
2449    def_math_dual(cs, paramlist, presentation, options)?;
2450  }
2451  // Perl Package.pm:1656-1660: no arguments, but tokens naming control sequences (presumably with
2452  // internal structure) — the presentation is wrapped to carry the semantic attributes.
2453  else if let MathPresentation::Tokens(tokens) = &presentation_in
2454    && tokens.unlist_ref().iter().any(Token::is_executable)
2455  {
2456    def_math_wrapped(cs, tokens.clone(), options)?;
2457  }
2458  // EXPERIMENT: Introduce an intermediate case for simple symbols
2459  // Define a primitive that will create a Box with the appropriate set of XMTok attributes.
2460  else if nargs == 0 && !options.has_complex_option() {
2461    def_math_primitive(cs, paramlist, presentation, options);
2462  } else {
2463    def_math_constructor(cs, paramlist, presentation, options)?;
2464  }
2465  if locked {
2466    assign_value(&format!("{csname}:locked"), true, Some(Scope::Global));
2467  }
2468  Ok(())
2469}
2470
2471/// Transfers the common MathPrimitive options to a (ideally freshly instantiated) Constructor.
2472fn transfer_common_constructor_options(
2473  cs: &Token,
2474  presentation: &str,
2475  options: MathPrimitiveOptions,
2476  cons: &mut Constructor,
2477) {
2478  let cs_str = cs.with_str(ToString::to_string);
2479  let mut properties = options.to_hash_stored();
2480  // (an accent's glyph, `accent`, which its token prints over or under its base: Rust only, for the readers of what a
2481  // digested mark prints — `\bar{\dag}` is no `\dag`, the frontmatter label keys, latexml_engine
2482  // `util_text::accent_combining_form`)
2483  if matches!(
2484    options.operator_role.as_deref(),
2485    Some("OVERACCENT" | "UNDERACCENT")
2486  ) {
2487    properties.insert("accent", Stored::from(presentation.to_string()));
2488  }
2489  cons.alias = Some(options.alias.unwrap_or_else(|| cs_str.clone()));
2490  if let Some(sizer) = infer_sizer(options.sizer.as_ref(), options.reversion.as_ref()) {
2491    cons.sizer = Some(sizer);
2492  }
2493  if let Some(reversion) = options.reversion {
2494    cons.reversion = Some(reversion);
2495  }
2496  //
2497  // before_digest
2498  //
2499  // Perl's DefMath constructors all begin with `requireMath($cs)` (Package.pm:1706), which warns
2500  // `unexpected:<cs>` outside math (Package.pm:1069-1073). The symbols safe in text are boxes, not
2501  // constructors (Package.pm:1665; `MathPrimitiveOptions::has_complex_option`): a gate on
2502  // `require_math` here hid every DefMath warning, while the over-emission it was added for
2503  // (witness 0802.3360, `\hbox to 40pt{\rightarrowfill}`) came from `\rightarrowfill`, which has
2504  // `stretchy`, wrongly being a constructor.
2505  let declared_mode = DeclaredMode {
2506    bounded: !options.nogroup,
2507    require_math: true,
2508    ..DeclaredMode::default()
2509  };
2510  cons.declared_mode = Some(declared_mode);
2511  let mut before_digest_closures: Vec<BeforeDigestClosure> = vec![before_digest_simple!({
2512    requireMath!(cs_str);
2513  })];
2514  if declared_mode.bounded {
2515    before_digest_closures.push(before_digest_simple!({
2516      bgroup();
2517    }));
2518  }
2519  // A Warning raised where the box is printed (`absorb_warning`, an undecodable glyph's): its position is the
2520  // gullet's here, as the arguments are about to be read (the one a simple symbol's Tbox carries as its locator),
2521  // recorded in the constructor's group and moved onto the whatsit after digestion, for the document to raise it at
2522  // (core `document::ABSORB_WARNING_LOCATOR_PROPERTY`). Not the whatsit's own locator: that is `--source-map`'s.
2523  // Witness 1902.03183 (newtxsf's `\bar`, `\dot`).
2524  let records_absorb_locator = options.absorb_warning.is_some();
2525  if records_absorb_locator {
2526    before_digest_closures.push(before_digest_simple!({
2527      assign_value(
2528        crate::document::ABSORB_WARNING_LOCATOR_PROPERTY,
2529        Stored::from(gullet::get_locator()),
2530        Some(Scope::Local),
2531      );
2532    }));
2533  }
2534  // Perl Package.pm:1708: `MergeFont(%{ $options{font} })` inside the group just opened.
2535  if let Some(font) = options.font {
2536    before_digest_closures.push(before_digest_simple!({
2537      merge_font((*font.get_font(None)?).clone());
2538    }));
2539  }
2540  before_digest_closures.extend(options.before_digest);
2541  cons.before_digest = before_digest_closures;
2542  //
2543  // after_digest
2544  //
2545  let mut after_digest_closures = options.after_digest;
2546  // Perl: mathstyle => \&doVariablesizeOp — compute mathstyle at digest time
2547  if options.variablesize_op {
2548    after_digest_closures.push(after_digest_simple!(_args, {
2549      let state_font = lookup_font().unwrap();
2550      let is_display = state_font
2551        .get_mathstyle()
2552        .is_some_and(|s| s.as_ref() == "display");
2553      let mathstyle = if is_display { "display" } else { "text" };
2554      _args.set_property("mathstyle", Stored::from(mathstyle.to_string()));
2555    }));
2556  }
2557  if records_absorb_locator {
2558    after_digest_closures.push(after_digest_simple!(_args, {
2559      if let Some(locator) = lookup_value(crate::document::ABSORB_WARNING_LOCATOR_PROPERTY) {
2560        _args.set_property(crate::document::ABSORB_WARNING_LOCATOR_PROPERTY, locator);
2561      }
2562    }));
2563  }
2564  if declared_mode.bounded {
2565    after_digest_closures.push(after_digest_simple!(_args, {
2566      egroup()?;
2567    }));
2568  }
2569  cons.after_digest = after_digest_closures;
2570  cons.before_construct = options.before_construct;
2571  cons.after_construct = options.after_construct;
2572  // Perl Package.pm:1726-1728: the `font` property is code, run as the whatsit's properties are
2573  // computed (Constructor.pm:97-104) — at digestion, inside the constructor's group, after its own
2574  // font merged — so the token takes the font in force there (`\boldsymbol`'s bold, the
2575  // operator's upright), not the state at construction. Golden
2576  // tests/parse/math_lexemes.tex#defmath_accent_takes_the_digestion_font.
2577  let presentation_for_font = presentation.to_owned();
2578  let mathstyle_for_font = options.mathstyle;
2579  let letters_class = options.letters_class;
2580  // Perl `scriptpos => \&doScriptpos` (TeX_Math.pool.ltxml:350): `mid` in display, else `post`,
2581  // read with the other code properties — a starred `\DeclareMathOperator` puts its limits
2582  // below in display (amsopn.sty.ltxml:26).
2583  let dynamic_scriptpos = options.dynamic_scriptpos;
2584  cons.properties = Rc::new(move |_args| {
2585    let mut font = lookup_font().unwrap();
2586    let mut properties = properties.clone();
2587    if dynamic_scriptpos {
2588      let display = font
2589        .get_mathstyle()
2590        .is_some_and(|s| s.as_ref() == "display");
2591      let scriptpos = if display { "mid" } else { "post" };
2592      properties.insert("scriptpos", Stored::from(scriptpos.to_string()));
2593    }
2594    if let Some(ref mathstyle) = mathstyle_for_font {
2595      font = Rc::new(font.merge(Font {
2596        mathstyle: Some(Cow::Owned(mathstyle.clone())),
2597        ..Font::default()
2598      }));
2599    }
2600    let font = match letters_class {
2601      Some(class) => font.specialize_letters(&presentation_for_font, class),
2602      None => font.specialize(&presentation_for_font),
2603    };
2604    properties.insert("font", Stored::Font(Rc::new(font)));
2605    Ok(properties)
2606  });
2607}
2608
2609//======================================================================
2610// Allocated registers.
2611// We ASSUME the same set of \count positions used by TeX & LaTeX
2612// for recording the next available position in \count,\dimen,\skip,\muskip.
2613
2614pub fn allocate_register(rtype: &str, cs: &str) -> Result<Option<String>> {
2615  let addr = match rtype {
2616    "\\count" => "\\count10",
2617    "\\dimen" => "\\count11",
2618    "\\skip" => "\\count12",
2619    "\\muskip" => "\\count13",
2620    "\\box" => "\\count14",
2621    "\\toks" => "\\count15",
2622    _ => "",
2623  };
2624  if !addr.is_empty() {
2625    // addr is a Register but MUST be stored as \count<#>
2626    if let Some(n) = lookup_number(addr) {
2627      // Perl Package.pm L617-622: the allocation counter picks the NEXT
2628      // unbound slot. If `\<type>N+1` is already an explicit DefRegister
2629      // (e.g. a system-allocated `\count10`, `\toks0`), advance past it
2630      // so the new register doesn't collide. Matches Perl's
2631      //   while ($STATE->isValueBound($loc)) { $next++; $loc = $type . $next; }
2632      let mut next = n.value_of() + 1;
2633      let mut loc = format!("{rtype}{next}");
2634      while is_value_bound(&loc, None) {
2635        next += 1;
2636        loc = format!("{rtype}{next}");
2637      }
2638      assign_value(addr, Number::new(next), Some(Scope::Global));
2639      Ok(Some(loc))
2640    } else {
2641      Ok(None)
2642    }
2643  } else {
2644    // Perl Package.pm L626-627: the error names the CS being allocated
2645    // (`Type $type is not an allocated register type, for ToString($cs)`).
2646    Error!(
2647      "misdefined",
2648      rtype,
2649      format!("Type {rtype} is not an allocated register type, for {cs}")
2650    );
2651    Ok(None)
2652  }
2653}
2654
2655/// The leading size10.clo gives each of its sizes (`\@setfontsize\small\@ixpt{11}` …), which the
2656/// class bindings' size switches use (`font => {size => …}`); 1.2 × the size otherwise.
2657fn size10_leading(size: f64) -> f64 {
2658  const LEADING: [(f64, f64); 11] = [
2659    (5.0, 6.0),
2660    (7.0, 8.0),
2661    (8.0, 9.5),
2662    (9.0, 11.0),
2663    (10.0, 12.0),
2664    (12.0, 14.0),
2665    (14.4, 18.0),
2666    (17.28, 22.0),
2667    (20.74, 25.0),
2668    (24.88, 30.0),
2669    (29.8, 30.0), // the article/report/book bindings' `\Huge` (Perl's 29.8; size10.clo's 24.88)
2670  ];
2671  LEADING
2672    .iter()
2673    .find(|(at, _)| (at - size).abs() < 0.01)
2674    .map_or(size * 1.2, |(_, leading)| *leading)
2675}