Skip to main content

latexml_core/binding/counter/
dialect.rs

1//! # Counters
2//!
3//! This is modelled on LaTeX's counter mechanisms, but since it also
4//! provides support for ID's, even where there is no visible reference number,
5//! it is defined in general.
6//! These id's should be both unique, and parallel the visible reference numbers
7//! (as much as possible).  Also, for consistency, we add id's to unnumbered
8//! document elements (eg from \section*); this requires an additional counter
9//! (eg. UNsection) and  mechanisms to track it.
10
11use std::{collections::VecDeque, rc::Rc};
12
13use crate::{
14  BoxOps, Digested, DigestedData, RegisterValue,
15  binding::{
16    content::{build_invocation, digest_literal, digest_text},
17    def::dialect::{RegisterOptions, def_macro, def_register, is_defined},
18  },
19  common::{
20    arena::{self, SymHashMap as HashMap, SymStr},
21    cleaners::{clean_id, clean_label, roman_aux},
22    error::*,
23    glue::Glue,
24    number::Number,
25    numeric_ops::NumericOps,
26  },
27  definition::{Definition, ExpansionBody, expandable::ExpandableOptions},
28  list::List,
29  mouth,
30  state::*,
31  stomach,
32  token::*,
33  tokens::{TeXString, Tokens},
34  whatsit::Whatsit,
35};
36
37/// configuration for new_counter
38#[derive(Default)]
39pub struct NewCounterOptions<'ct> {
40  /// specifies a prefix to be used in formatting ID's for document structure elements
41  /// counted by this counter.  Ie. subsection 3 in section 2 might get: id="S2.SS3"
42  pub idprefix: &'ct str,
43  /// specifies that the ID is composed from $idwithin's ID,, even though
44  /// the counter isn't numbered within it.  (mainly to avoid duplicated ids)
45  pub idwithin: &'ct str,
46  /// a list of counters that correspond to scopes which are "inside" this one.
47  /// Whenever any definitions scoped to this counter are deactivated,
48  /// the inner counter's scopes are also deactivated.
49  // NOTE: I'm not sure this is even a sensible implementation,
50  // or why inner should be different than the counters reset by incrementing this counter.
51  pub nested: Vec<&'ct str>,
52}
53
54/// Perl `addtoCounterReset` (latex_constructs.pool.ltxml:3005-3012): put `\<ctr>` and `\UN<ctr>`
55/// at the front of `\cl@<within>`, globally, as latex.ltx:10156's `\@cons` `\xdef`s — a reset
56/// registered inside a group outlives it — and re-derive the list's macro.
57/// Repro macro-state/counter_reset_lists_are_global.
58pub fn add_to_counter_reset(ctr: &str, within: &str) -> Result<()> {
59  if copy_provides_keeps_counter(ctr) {
60    return Ok(());
61  }
62  let reg = s!("\\cl@{within}");
63  let mut toks = vec![T_CS!(ctr), T_CS!(s!("UN{ctr}"))];
64  if let Some(prev) = lookup_tokens(&reg) {
65    toks.extend(prev.unlist());
66  }
67  assign_value(&reg, Stored::Tokens(Tokens::new(toks)), Some(Scope::Global));
68  sync_reset_list_macro(within)?;
69  define_hyper_counter_name(ctr, within)
70}
71
72/// The `\theH<ctr>` hyperref builds a counter's anchor from (`\hyper@makecurrent`), as the
73/// kernel makes it since 2024-11-01: latex.ltx:10145 `\@definecounter` xdefs it as
74/// `\the\value{<ctr>}`, and :10157 `\@addtoreset` as `\theH<within>.\the\value{<ctr>}`, so
75/// hyperref.sty:6607 skips its own `\providecommand` list. Perl's counters have none. A package
76/// building on them needs them: pgfplots' `\theHpgfplotslink{\theHsection.…}`
77/// (pgfplots.code.tex:6138, through `\hyper@makecurrent{pgfplotslink}` at :6123). LaTeXML's
78/// pseudo-counter `document` is no parent: no `\theHdocument` prefix.
79/// Guard: `perfect_kernel_batch64::kernel_counters_have_hyperref_names`.
80fn define_hyper_counter_name(ctr: &str, within: &str) -> Result<()> {
81  let mut body: Vec<Token> = Vec::new();
82  if !within.is_empty() && within != "document" {
83    body.push(T_CS!(s!("\\theH{within}")));
84    body.push(T_OTHER!("."));
85  }
86  body.push(T_CS!("\\the"));
87  body.push(T_CS!("\\value"));
88  body.push(T_BEGIN!());
89  body.extend(ExplodeText!(ctr));
90  body.push(T_END!());
91  def_macro(
92    T_CS!(s!("\\theH{ctr}")),
93    None,
94    ExpansionBody::from(Tokens::new(body)),
95    Some(ExpandableOptions {
96      scope: Some(Scope::Global),
97      ..ExpandableOptions::default()
98    }),
99  )
100}
101
102/// Perl `remfromCounterReset` (latex_constructs.pool.ltxml:3014-3022): drop `\<ctr>` and
103/// `\UN<ctr>` from `\cl@<within>`, globally (latex.ltx:10170 `\xdef`), when there is a list.
104pub fn remove_from_counter_reset(ctr: &str, within: &str) -> Result<()> {
105  let reg = s!("\\cl@{within}");
106  if let Some(prev) = lookup_tokens(&reg) {
107    let (t, unt) = (T_CS!(ctr), T_CS!(s!("UN{ctr}")));
108    let kept: Vec<Token> = prev
109      .unlist()
110      .into_iter()
111      .filter(|x| *x != t && *x != unt)
112      .collect();
113    assign_value(&reg, Stored::Tokens(Tokens::new(kept)), Some(Scope::Global));
114    sync_reset_list_macro(within)?;
115  }
116  Ok(())
117}
118
119/// Mirror the reset list into the `\cl@<ctr>` MACRO latex.ltx exposes.
120///
121/// latex.ltx:10140-10142 `\@definecounter` lets `\cl@<ctr>` to `\@empty` and
122/// :10156 `\@addtoreset` `\@cons`es `\@elt{<child>}` onto it, so the reset list
123/// is a macro raw code expands and rewrites: contract.sty:336
124/// `\edef\cl@Clause{\cl@Clause\cl@contractClause}` (contract-example-de/-en,
125/// 44 errors each), afthesis.cls:44-49's `\@removefromreset` re-`\edef` with a
126/// filtering `\@elt` (usethesis: "`\cl@chapter` expands into itself"). LaTeXML
127/// keeps the list as the State VALUE `\cl@<ctr>` (Perl Package.pm:674, entries
128/// `\<child>`/`\UN<child>`), which stays authoritative for stepping; this
129/// re-derives the macro (`\@elt{child}` per non-`UN` entry) after every
130/// mutation so both faces agree. Perl shares the gap (sectioning topic).
131/// Guard: `perfect_kernel_batch54::reset_list_is_an_expandable_cl_macro`.
132pub fn sync_reset_list_macro(ctr: &str) -> Result<()> {
133  let clctr = s!("\\cl@{ctr}");
134  let mut body: Vec<Token> = Vec::new();
135  if let Some(list) = lookup_tokens(&clctr) {
136    for t in list.unlist() {
137      let name = t.with_str(|s| s.to_string());
138      if name.starts_with("UN") {
139        continue;
140      }
141      body.push(T_CS!("\\@elt"));
142      body.push(T_BEGIN!());
143      body.extend(ExplodeText!(name));
144      body.push(T_END!());
145    }
146  }
147  def_macro(
148    T_CS!(&clctr),
149    None,
150    ExpansionBody::from(Tokens::new(body)),
151    Some(ExpandableOptions {
152      scope: Some(Scope::Global),
153      ..ExpandableOptions::default()
154    }),
155  )
156}
157
158/// Defines a new counter named $ctr.
159/// If `within` is defined, `ctr` will be reset whenever `within` is incremented.
160pub fn new_counter(ctr: &str, within: &str, options_opt: Option<NewCounterOptions>) -> Result<()> {
161  // (a stand-in's copy keeps a counter the binding owns as the binding numbers it: `state::copy_provides_keeps_counter`)
162  if copy_provides_keeps_counter(ctr) {
163    return Ok(());
164  }
165  // (any other counter a stand-in's copy declares is declared for real — its `\c@`, `\cl@`, `\the`, `\p@` names outlive
166  // the copy's overlay, as the real class's do: `state::copy_provides_keeps_counter`)
167  let _declared = (crate::definition::origin::copy_provides() != 0)
168    .then(|| crate::definition::origin::CopyProvidesGuard::new(0));
169  let unctr = s!("UN{ctr}"); // UNctr is counter for generating ID's for UN-numbered items.
170  if !within.is_empty()
171    && within != "document"
172    && lookup_definition(&T_CS!(s!("\\c@{within}")))?.is_none()
173  {
174    new_counter(within, "", None)?;
175  }
176  let cctr = s!("\\c@{ctr}");
177  let clctr = s!("\\cl@{ctr}");
178  let cunctr = s!("\\c@{unctr}");
179  let clunctr = s!("\\cl@{unctr}");
180  // Perl Package.pm L660-672: Check if counter already defined. Skip register if already a
181  // Register. Warn if previously defined as something other than \relax.
182  let cs_cctr = T_CS!(&cctr);
183  let prev_defn = lookup_definition(&cs_cctr)?;
184  if let Some(ref defn) = prev_defn {
185    if defn.is_register() {
186      // Counter already exists as a register — fine, just continue (may change within/nesting)
187    } else {
188      // Warn unless the previous definition was \relax
189      let relax_meaning = lookup_meaning(&T_RELAX!());
190      let prev_meaning = lookup_meaning(&cs_cctr);
191      if prev_meaning != relax_meaning {
192        Warn!(
193          "unexpected",
194          &cctr,
195          s!("Counter {} was already defined; redefining", cctr)
196        );
197      }
198      def_register(
199        cs_cctr,
200        None,
201        Number::new(0),
202        Some(RegisterOptions {
203          allocate: Some(String::from("\\count")),
204          ..RegisterOptions::default()
205        }),
206      )?;
207    }
208  } else {
209    def_register(
210      cs_cctr,
211      None,
212      Number::new(0),
213      Some(RegisterOptions {
214        allocate: Some(String::from("\\count")),
215        ..RegisterOptions::default()
216      }),
217    )?;
218  }
219  // An alias counter (`register_counter_alias`) given a register of its own (`\let\c@case\relax\newcounter{case}`
220  // after llncs's `\@spothm{case}[theorem]`: 2303.08726) is an alias no more: `\refstepcounter{case}` steps the new
221  // register, as in LaTeX, where the alias was only the `\let` of `\c@case`. A counter whose `\c@` is still the alias's
222  // register keeps it (LaTeX refuses that `\newcounter`, "Command \c@case already defined").
223  if !prev_defn.as_ref().is_some_and(|defn| defn.is_register()) && is_counter_alias(ctr) {
224    assign_mapping::<Stored>("counter_for_type", ctr, None);
225    assign_mapping::<Stored>("counter_alias", ctr, None);
226  }
227  after_assignment()?;
228  if !has_value(&clctr) {
229    assign_value(&clctr, Tokens!(), Some(Scope::Global));
230  }
231  sync_reset_list_macro(ctr)?;
232  def_register(T_CS!(&cunctr), None, Number::new(0), None)?;
233  if !has_value(&clunctr) {
234    assign_value(&clunctr, Tokens!(), Some(Scope::Global));
235  }
236
237  if !within.is_empty() {
238    let clwithin = s!("\\cl@{within}");
239    let clunwithin = s!("\\cl@UN{within}");
240    let x = if let Some(cl) = lookup_tokens(&clwithin) {
241      cl.unlist()
242    } else {
243      Vec::new()
244    };
245    let mut clwithin_tokens = vec![T_CS!(ctr), T_CS!(&unctr)];
246    clwithin_tokens.extend(x);
247    assign_value(
248      &clwithin,
249      Stored::Tokens(Tokens::new(clwithin_tokens)),
250      Some(Scope::Global),
251    );
252
253    let mut unx = if let Some(clun) = lookup_tokens(&clunwithin) {
254      clun.unlist()
255    } else {
256      Vec::new()
257    };
258    let mut clunwithin_tokens = vec![T_CS!(unctr)];
259    clunwithin_tokens.append(&mut unx);
260
261    assign_value(
262      &clunwithin,
263      Stored::Tokens(Tokens::new(clunwithin_tokens)),
264      Some(Scope::Global),
265    );
266    sync_reset_list_macro(within)?;
267  }
268  define_hyper_counter_name(ctr, within)?;
269
270  // default is equivalent to \arabic{ctr}, but w/o using the LaTeX macro:
271  // Perl Package.pm:686 `\the<ctr>` = `\lx@counter@arabic{<ctr>}`, a Token
272  // body the format dump can carry (a closure is opaque to it).
273  let ctr_string = ctr.to_string();
274  def_macro(
275    T_CS!(s!("\\the{}", ctr)),
276    None,
277    Some(ExpansionBody::Tokens(mouth::tokenize_internal(
278      TeXString::assembled(s!("\\lx@counter@arabic{{{ctr_string}}}")),
279    ))),
280    Some(ExpandableOptions {
281      scope: Some(Scope::Global),
282      ..ExpandableOptions::default()
283    }),
284  )?;
285  let p_ctr_cs = T_CS!(&s!("\\p@{}", ctr));
286  if lookup_definition(&p_ctr_cs)?.is_none() {
287    def_macro(
288      p_ctr_cs,
289      None,
290      Tokens::default(),
291      Some(ExpandableOptions {
292        scope: Some(Scope::Global),
293        ..ExpandableOptions::default()
294      }),
295    )?;
296  }
297
298  // (a standard-class derivative re-declaring a counter its standard class's binding declared — article.cls's
299  // `\newcounter{figure}` in a full copy — keeps the binding's ids, LaTeXML's markup: `S1.F1`, not `F1`; the register,
300  // its reset list and `\the<ctr>` are the copy's, as TeX makes them. OXIDIZED_DESIGN_DIVERGENCES #731 rule 13;
301  // 2402.12725's article_saj.cls; guard `perfect_kernel_batch77w::standard_class_derivative_patches_stand`)
302  let ids = T_CS!(s!("\\the{ctr}@ID"));
303  if crate::binding::content::standard_class_binding_assigned(meaning_key(&ids)) {
304    return Ok(());
305  }
306  define_counter_ids(ctr, within, options_opt.as_ref())
307}
308
309/// The id half of [`new_counter`] (Perl Package.pm:689-705, `NewCounter`'s `idprefix`/`idwithin`/`nested`): records
310/// `@ID@prefix@<ctr>` and `nested_counters_<ctr>`, and defines `\the<ctr>@ID` and `\@<ctr>@ID`. A binding calls it
311/// alone for a counter a raw class declared, to give it the ids its standard-class binding gives (the KOMA classes,
312/// `koma_script.rs`: `S1.SS1`, not `section1.subsection1`); the register and its reset list stay the class's.
313pub fn define_counter_ids(
314  ctr: &str,
315  within: &str,
316  options_opt: Option<&NewCounterOptions>,
317) -> Result<()> {
318  if let Some(options) = options_opt
319    && !options.nested.is_empty()
320  {
321    assign_value(
322      &s!("nested_counters_{}", ctr),
323      options.nested.clone(),
324      Some(Scope::Global),
325    )
326  }
327
328  let mut prefix = match options_opt {
329    None => String::new(),
330    Some(opt) => opt.idprefix.to_string(),
331  };
332  if !prefix.is_empty() {
333    assign_value(
334      &s!("@ID@prefix@{}", ctr),
335      prefix.clone(),
336      Some(Scope::Global),
337    );
338  } else {
339    prefix = lookup_string(&s!("@ID@prefix@{}", ctr));
340    if prefix.is_empty() {
341      prefix = ctr.to_string();
342    }
343  }
344  prefix = clean_id(&prefix);
345
346  if !prefix.is_empty() {
347    let idwithin = match options_opt {
348      Some(opts) => {
349        if opts.idwithin.is_empty() {
350          within
351        } else {
352          opts.idwithin
353        }
354      },
355      None => within,
356    }
357    .to_string();
358    // A counter within itself (`\newcounter{subsubsection}[subsubsection]`, AEA.cls:800, witness 2308.05200) resets
359    // itself (`reset_counter_in_cascade`); its id cannot be built within its own id, which expanded without end.
360    let idwithin = if idwithin == ctr {
361      String::new()
362    } else {
363      idwithin
364    };
365
366    let ctr_string = ctr.to_string();
367    let thectrid = s!("\\the{}@ID", ctr);
368    // Token bodies, as Perl's `DefMacroI` string bodies (Package.pm:695-703):
369    // a closure here is opaque to the format dump (recorded as an unresolvable
370    // self-alias), so every kernel counter's `\the<ctr>@ID` was lost on the
371    // dump path and a class with no binding (ptptex) generated ids from an
372    // undefined formatter — `subequations` children `.1`/`X.1`, colliding.
373    if !idwithin.is_empty() {
374      def_macro(
375        T_CS!(thectrid),
376        None,
377        Some(ExpansionBody::Tokens({
378          // Perl Package.pm L696 probes `\lx@empty`, NOT `\@empty` — and
379          // deliberately so: `\@empty` is LaTeX-pool-only (latex_base.rs
380          // aliases it to `\lx@empty`), while `\lx@empty` is engine-level
381          // (base_schema.rs) and exists in PLAIN TeX documents too. With
382          // `\@empty` here, a plain-TeX document's `\the<ctr>@ID` probe
383          // compared `\thedocument@ID` (an alias of `\lx@empty`) against an
384          // UNDEFINED `\@empty` → unequal → the \else branch re-expands the
385          // parent's @ID formatter, spinning the gullet into a 4-token
386          // expansion cycle (caught by the cycle guard as a phantom
387          // `Fatal:Timeout:Recursion`, swallowed inside math-parser
388          // semantics — `create_xmrefs`/`get_xmarg_id`). Witness
389          // math0402448 (plain TeX + 3464 formulae): "Conversion failed:
390          // 1 fatal error" with no Fatal: line in the log.
391          // The names are spliced in as characters (`id_name_chars`, as `define_hyper_counter_name` does), never
392          // re-read from a string: a counter named `claim_nb` or `c_n` (2606.16543, 1912.04210) made the `_` a
393          // subscript, digested for the id ("Script _ can only appear in math mode"; Perl Package.pm:695-702 alike,
394          // KNOWN_PERL_ERRORS #621). Guard `perfect_kernel_batch65m::counter_name_with_underscore_is_its_id`.
395          let mut body = vec![T_CS!("\\expandafter"), T_CS!("\\ifx"), T_CS!("\\csname")];
396          body.extend(id_name_chars(&s!("the{idwithin}@ID")));
397          body.extend([
398            T_CS!("\\endcsname"),
399            T_CS!("\\lx@empty"),
400            T_CS!("\\else"),
401            T_CS!("\\csname"),
402          ]);
403          body.extend(id_name_chars(&s!("the{idwithin}@ID")));
404          body.extend([T_CS!("\\endcsname"), T_OTHER!("."), T_CS!("\\fi")]);
405          body.extend(id_name_chars(&prefix));
406          body.extend(counter_id_number(&ctr_string));
407          Tokens::new(body)
408        })),
409        Some(ExpandableOptions {
410          scope: Some(Scope::Global),
411          ..ExpandableOptions::default()
412        }),
413      )?;
414    } else {
415      def_macro(
416        T_CS!(thectrid),
417        None,
418        Some(ExpansionBody::Tokens({
419          let mut body = id_name_chars(&prefix);
420          body.extend(counter_id_number(&ctr_string));
421          Tokens::new(body)
422        })),
423        Some(ExpandableOptions {
424          scope: Some(Scope::Global),
425          ..ExpandableOptions::default()
426        }),
427      )?;
428    }
429    def_macro(
430      T_CS!(s!("\\@{}@ID", ctr)),
431      None,
432      Some(ExpansionBody::Tokens(Tokens!(T_OTHER!("0")))),
433      Some(ExpandableOptions {
434        scope: Some(Scope::Global),
435        ..ExpandableOptions::default()
436      }),
437    )?;
438  }
439
440  Ok(())
441}
442/// A name in a `\the<ctr>@ID` body as characters: letters and `@` letters, the rest other, as `tokenize_internal`
443/// reads a name made of them (the format dump keeps those bodies), but a `_`, `^` or `&` in the name is a character too.
444fn id_name_chars(name: &str) -> Vec<Token> {
445  name
446    .chars()
447    .map(|c| {
448      let mut buf = [0u8; 4];
449      let c_str: &str = c.encode_utf8(&mut buf);
450      if c == ' ' {
451        T_SPACE!()
452      } else if c == '@' || c.is_alphabetic() {
453        T_LETTER!(c_str)
454      } else {
455        T_OTHER!(c_str)
456      }
457    })
458    .collect()
459}
460/// `\csname @<ctr>@ID\endcsname`, the counter's number in an id, the name spliced in as characters.
461fn counter_id_number(ctr: &str) -> Vec<Token> {
462  let mut toks = vec![T_CS!("\\csname")];
463  toks.extend(id_name_chars(&s!("@{ctr}@ID")));
464  toks.push(T_CS!("\\endcsname"));
465  toks
466}
467/// Fetches the value associated with the counter C<$ctr>.
468pub fn counter_value(ctr: &str) -> Result<Number> {
469  match lookup_register(&s!("\\c@{ctr}"), Vec::new())? {
470    None => {
471      // Perl Package.pm L712 quotes the counter name: `Counter '$ctr' ...`.
472      let message = s!("Counter '{}' was not defined; assuming 0", ctr);
473      Warn!("undefined", ctr, message);
474      Ok(Number::new(0))
475    },
476    Some(value) => Ok(Number::new(value.value_of())),
477  }
478}
479/// Perl `SetCounter` (Package.pm:722): assign `\\c@<ctr>` globally, run any `\\afterassignment`, re-derive
480/// `\\@<ctr>@ID`.
481pub fn set_counter(ctr: &str, value: Number) -> Result<()> {
482  assign_register(
483    &s!("\\c@{ctr}"),
484    value.into(),
485    Some(Scope::Global),
486    Vec::new(),
487  )?;
488  after_assignment()?;
489  def_macro(
490    T_CS!(s!("\\@{ctr}@ID")),
491    None,
492    Tokens::new(Explode!(value.value_of())),
493    Some(ExpandableOptions {
494      scope: Some(Scope::Global),
495      ..ExpandableOptions::default()
496    }),
497  )
498}
499/// increments a named counter by a `Number`
500pub fn add_to_counter(ctr: &str, value: Number) -> Result<()> {
501  let v = counter_value(ctr)?.add(value);
502  assign_register(&s!("\\c@{ctr}"), v.into(), Some(Scope::Global), Vec::new())?;
503  after_assignment()?;
504  let id_cs = T_CS!(s!("\\@{ctr}@ID"));
505  def_macro(
506    id_cs,
507    None,
508    Tokens::new(Explode!(v.value_of())),
509    Some(ExpandableOptions {
510      scope: Some(Scope::Global),
511      ..ExpandableOptions::default()
512    }),
513  )
514}
515
516/// Analog of `\stepcounter`, steps the counter and returns the expansion of
517/// `\the$ctr`  Usually you should use `ref_step_counter(ctr)` instead.
518pub fn step_counter(ctr: &str, noreset: bool) -> Result<()> {
519  let value = counter_value(ctr)?;
520  let newvalue = value.add(Number::new(1));
521  let c_ctr = s!("\\c@{ctr}");
522  assign_register(&c_ctr, newvalue.into(), Some(Scope::Global), Vec::new())?;
523  after_assignment()?;
524  let token_value = Tokens::new(Explode!(newvalue.value_of()));
525  def_macro(
526    T_CS!(s!("\\@{ctr}@ID")),
527    None,
528    token_value,
529    Some(ExpandableOptions {
530      scope: Some(Scope::Global),
531      ..ExpandableOptions::default()
532    }),
533  )?;
534
535  // and reset any within counters!
536  if !noreset && let Some(nested) = lookup_tokens(&s!("\\cl@{ctr}")) {
537    // An id's `UN` counter (`ref_step_id`, a unit beyond secnumdepth) is LaTeXML's alone; TeX steps the others.
538    let tex_step = !ctr.starts_with("UN");
539    let mut path = vec![ctr.to_string()];
540    for c in nested.unlist() {
541      reset_counter_in_cascade(&c, &mut path, tex_step)?;
542    }
543  }
544  Ok(())
545}
546
547/// Analog of `\refstepcounter`, steps the counter and returns a hash
548/// containing the keys `refnum` and `id`.
549///
550/// This makes it
551/// suitable for use in a `properties` option to constructors.
552/// The `id` is generated in parallel with the reference number
553/// to assist debugging.
554// TODO: Maybe these should be specialized types in Rust, rather than hashmaps?
555pub fn ref_step_counter(ctype: &str, noreset: bool) -> Result<HashMap<Stored>> {
556  let ctype = strip_counter_type_sentinel(ctype);
557  let ctr = counter_for_type(ctype);
558  step_counter(&ctr, noreset)?;
559  label_stepped_counter(ctype, &ctr)
560}
561
562thread_local! {
563  /// Per counter, the type whose tags the step in progress makes (`ref_step_counter_planned`),
564  /// taken by the kernel's `\lx@refstepcounter`: theorem types share a counter (`counter_for_type`)
565  /// and LaTeX's `\refstepcounter` is passed the counter.
566  static PENDING_STEPS: std::cell::RefCell<rustc_hash::FxHashMap<String, String>> =
567    std::cell::RefCell::new(rustc_hash::FxHashMap::default());
568  /// Per counter, the props the kernel's label computed for a planned step.
569  static REFSTEP_PROPS: std::cell::RefCell<rustc_hash::FxHashMap<String, HashMap<Stored>>> =
570    std::cell::RefCell::new(rustc_hash::FxHashMap::default());
571}
572
573/// Forgets pending steps and recorded props (per document: they hold its symbols).
574pub fn reset_refstep_state() {
575  PENDING_STEPS.with(|steps| steps.borrow_mut().clear());
576  REFSTEP_PROPS.with(|slot| slot.borrow_mut().clear());
577}
578
579/// The type whose tags the step in progress on `counter` makes, if a binding planned one (the
580/// kernel's `\lx@refstepcounter`).
581pub fn take_pending_step(counter: &str) -> Option<String> {
582  PENDING_STEPS.with(|steps| steps.borrow_mut().remove(counter))
583}
584
585/// Records the props the kernel's `\refstepcounter` label computed for a planned step on `counter`.
586pub fn record_refstep_props(counter: &str, props: &HashMap<Stored>) {
587  REFSTEP_PROPS.with(|slot| slot.borrow_mut().insert(counter.to_string(), props.clone()));
588}
589
590/// The tags of the step a raw `\refstepcounter` made (`note_raw_refstep`): one no constructor took, so no element
591/// carries its number.
592const RAW_REFSTEP_TAGS: &str = "raw_refstep_tags";
593/// The counter of that step.
594const RAW_REFSTEP_COUNTER: &str = "raw_refstep_counter";
595/// Which step it is (a serial, one per raw step), told apart from another step's on the object one numbered
596/// (`Document::take_raw_refstep_number`).
597const RAW_REFSTEP_SERIAL: &str = "raw_refstep_serial";
598/// The step [`forget_raw_refstep`] forgot (a listing's start), for [`renote_forgotten_raw_refstep`].
599const RAW_REFSTEP_FORGOTTEN: &str = "raw_refstep_forgotten";
600/// The step an amsmath display's labels name ([`hold_raw_refstep_for_display`]): `Some` inside one.
601const RAW_REFSTEP_DISPLAY: &str = "raw_refstep_display";
602
603thread_local! {
604  static RAW_REFSTEP_SERIALS: std::cell::Cell<i64> = const { std::cell::Cell::new(0) };
605}
606
607/// A raw counter step a `\label` names ([`current_raw_refstep`]): the `tags` LaTeXML makes for every step and the
608/// step's serial.
609#[derive(Clone, Debug)]
610pub struct RawRefstep {
611  /// The step's `tags` (`label_stepped_counter`), whose `refnum` is what `\ref` prints.
612  pub tags:   Digested,
613  /// Which step it is: two steps that print the same number are still two.
614  pub serial: i64,
615}
616
617/// Records the step a raw `\refstepcounter` made on `counter` (its `props` from [`label_stepped_counter`]), whose
618/// number LaTeX's `\label` takes from `\@currentlabel` (latex.ltx:14963-14967), for the labels made after it
619/// ([`current_raw_refstep`]). Local, as LaTeX's `\@currentlabel` is (`\protected@edef`): a box's step stays in
620/// the box. Any other step forgets it ([`label_stepped_counter`]). Witnesses: 2506.01072 (`\newtcbtheorem`),
621/// 2505.20088 (`\newtcolorbox[auto counter]`), 2402.06608 (`[blend into=figures]`), 2609.20563 (`\newtcblisting`).
622pub fn note_raw_refstep(counter: &str, props: &HashMap<Stored>) {
623  if let Some(tags @ Stored::Digested(_)) = props.get("tags") {
624    let serial = RAW_REFSTEP_SERIALS.with(|c| {
625      c.set(c.get() + 1);
626      c.get()
627    });
628    assign_value(RAW_REFSTEP_TAGS, tags.clone(), Some(Scope::Local));
629    assign_value(RAW_REFSTEP_COUNTER, counter.to_string(), Some(Scope::Local));
630    assign_value(RAW_REFSTEP_SERIAL, Stored::Int(serial), Some(Scope::Local));
631  }
632}
633
634/// The raw step recorded now ([`note_raw_refstep`]) stays recorded after the group it was made in: a package that
635/// makes `\@currentlabel` global after its `\refstepcounter` (algorithm2e.sty:1663 `\gdef\@currentlabel{\theAlgoLine}`,
636/// :1659 with hyperref), so that a `\label` after the group (`\While{c}{\label{x} …}`, the line's number made in the
637/// header's group) still names the step (`\lx@refstep@global`, algorithm2e_sty.rs). Witness 1602.05866
638/// (`algline:mainloop`, PDF 8).
639pub fn globalize_raw_refstep() {
640  if let Some((tags, counter, serial)) = recorded_raw_refstep() {
641    assign_value(
642      RAW_REFSTEP_TAGS,
643      Stored::Digested(tags),
644      Some(Scope::Global),
645    );
646    assign_value(RAW_REFSTEP_COUNTER, counter, Some(Scope::Global));
647    assign_value(RAW_REFSTEP_SERIAL, Stored::Int(serial), Some(Scope::Global));
648  }
649}
650
651/// The raw step current now, as recorded ([`note_raw_refstep`]).
652fn recorded_raw_refstep() -> Option<(Digested, String, i64)> {
653  let Some(Stored::Digested(tags)) = lookup_value(RAW_REFSTEP_TAGS) else {
654    return None;
655  };
656  let serial = match lookup_value(RAW_REFSTEP_SERIAL) {
657    Some(Stored::Int(serial)) => serial,
658    _ => 0,
659  };
660  Some((tags, lookup_string(RAW_REFSTEP_COUNTER), serial))
661}
662
663/// Forgets the raw step locally, keeping it for [`renote_forgotten_raw_refstep`]: a listing starts, where listings
664/// makes `\@currentlabel` its line number's (lstmisc.sty:1228 `\lst@Init`, and `\refstepcounter{lstnumber}` per line,
665/// :1225), so a `\label` in an unnumbered listing does not name a step made before it (a `\refstepcounter{problem}`
666/// then an `lstlisting` with `(*\label{ln1}*)`: pdflatex the line's 2; repro
667/// `cross-references/listing_label_names_no_step_before_it.tex`).
668pub fn forget_raw_refstep() {
669  let forgotten = recorded_raw_refstep();
670  assign_value(
671    RAW_REFSTEP_FORGOTTEN,
672    forgotten.is_some(),
673    Some(Scope::Local),
674  );
675  if let Some((tags, counter, serial)) = forgotten {
676    assign_value(
677      &s!("{RAW_REFSTEP_FORGOTTEN}_tags"),
678      Stored::Digested(tags),
679      Some(Scope::Local),
680    );
681    assign_value(
682      &s!("{RAW_REFSTEP_FORGOTTEN}_counter"),
683      counter,
684      Some(Scope::Local),
685    );
686    assign_value(
687      &s!("{RAW_REFSTEP_FORGOTTEN}_serial"),
688      Stored::Int(serial),
689      Some(Scope::Local),
690    );
691    assign_value(RAW_REFSTEP_TAGS, Stored::None, Some(Scope::Local));
692  }
693}
694
695/// Notes again, locally, the step [`forget_raw_refstep`] forgot where the listing started: the box a tcolorbox
696/// listing box is, whose phantom code (its `label`) runs before the listing in the box (tcolorbox.sty:1154-1161,
697/// :1925) while this port runs it in the listing's first line (`listings_sty::with_tcb_phantom`): its label names
698/// the box's step (`\newtcblisting` with `auto counter`, 2609.20563).
699pub fn renote_forgotten_raw_refstep() {
700  if !matches!(
701    lookup_value(RAW_REFSTEP_FORGOTTEN),
702    Some(Stored::Bool(true))
703  ) {
704    return;
705  }
706  if let Some(tags @ Stored::Digested(_)) = lookup_value(&s!("{RAW_REFSTEP_FORGOTTEN}_tags")) {
707    assign_value(RAW_REFSTEP_TAGS, tags, Some(Scope::Local));
708    let counter = lookup_string(&s!("{RAW_REFSTEP_FORGOTTEN}_counter"));
709    assign_value(RAW_REFSTEP_COUNTER, counter, Some(Scope::Local));
710    if let Some(serial) = lookup_value(&s!("{RAW_REFSTEP_FORGOTTEN}_serial")) {
711      assign_value(RAW_REFSTEP_SERIAL, serial, Some(Scope::Local));
712    }
713  }
714}
715
716/// A label the display's own `\label` makes ([`mark_display_label`]) is pending until the kernel's `\label` takes it.
717const RAW_REFSTEP_DISPLAY_LABEL: &str = "raw_refstep_display_label";
718
719/// An amsmath display starts (`{gather}`, `{align}`, `{multline}`, `{aligned}` … and their starred forms): the labels
720/// its own `\label` makes ([`mark_display_label`]) name the step held here, not one made in a row. amsmath's `\label`
721/// there is `\label@in@display` (amsmath.sty:1230-1236), which only stores the key; `\make@display@tag` makes the label
722/// in the row's tag cell (:1240-1252, :1621-1627 `{gather}`, every row), after the cell group a `\refstepcounter` was
723/// made in restored `\@currentlabel` — `\begin{gather*} u=v \refstepcounter{foo}\label{e6} \end{gather*}` is the
724/// section's 7 in pdflatex. `names_the_step`: the display's labels may name the step current here (`{gather}`, and an
725/// `{aligned}`/`{split}` in an `{equation*}`: pdflatex 44, 45). Not for the align family (`{align}`, `{flalign}`,
726/// `{alignat}`) and `{multline}`, starred or not: `\math@cr@@@align` makes the display tag only under `\iftag@`
727/// (:1833-1843), so an untagged row's label is the next tagged row's (`\df@label` carried) or none (pdflatex `??`),
728/// never a step held at the start (repro `cross-references/amsmath_row_label_names_the_display_step.tex`, review probe
729/// rev78g2 al2.tex: `\begin{align} a&=b \label{n2}\notag \\ c&=d \end{align}` in a `\refstepcounter` environment is
730/// equation 1). The kernel's `\label` a document saved before (`\let\originallabel\label` at `\begin{document}`, the
731/// `\labelrel` idiom of 2310.19138) labels at once, after the cell's step ("a"). Local to the display; an inner one
732/// (`{aligned}` in `{gather*}`) keeps the outer's. The outermost start forgets a display label announced and never made
733/// ([`mark_display_label`]).
734pub fn hold_raw_refstep_for_display(names_the_step: bool) {
735  if matches!(lookup_value(RAW_REFSTEP_DISPLAY), Some(Stored::Bool(true))) {
736    return;
737  }
738  end_display_label();
739  if let Some(step) = current_raw_refstep_now().filter(|_| names_the_step) {
740    assign_value(
741      &s!("{RAW_REFSTEP_DISPLAY}_tags"),
742      Stored::Digested(step.tags),
743      Some(Scope::Local),
744    );
745    assign_value(
746      &s!("{RAW_REFSTEP_DISPLAY}_serial"),
747      Stored::Int(step.serial),
748      Some(Scope::Local),
749    );
750  } else {
751    assign_value(
752      &s!("{RAW_REFSTEP_DISPLAY}_tags"),
753      Stored::None,
754      Some(Scope::Local),
755    );
756  }
757  assign_value(RAW_REFSTEP_DISPLAY, Stored::Bool(true), Some(Scope::Local));
758}
759
760/// A paragraph box (`{minipage}`, `\parbox`, the kernel's `\@arrayparboxrestore`) starts: amsmath's
761/// `\@arrayparboxrestore` restores `\label` to the kernel's (amsmath.sty:1237-1238 `\let\label\ltx@label`), so a label
762/// in the box is made at once and names the step current in it, not the display's held step (review probe rev78g2
763/// nest.tex z5, `\begin{gather*} a=b \refstepcounter{foo}\text{\begin{minipage}{2cm}\label{z5}x\end{minipage}}
764/// \end{gather*}`: pdflatex 42; repro `cross-references/amsmath_row_label_names_the_display_step.tex`). Local to the
765/// box. Outside an amsmath display nothing.
766pub fn leave_display_for_parbox() {
767  if !matches!(lookup_value(RAW_REFSTEP_DISPLAY), Some(Stored::Bool(true))) {
768    return;
769  }
770  assign_value(RAW_REFSTEP_DISPLAY, Stored::Bool(false), Some(Scope::Local));
771  let display_label = matches!(
772    (lookup_meaning(&T_CS!("\\label")), lookup_meaning(&T_CS!("\\lx@ams@display@label"))),
773    (Some(Stored::Expandable(a)), Some(Stored::Expandable(b))) if Rc::ptr_eq(&a, &b)
774  );
775  if display_label && lookup_meaning(&T_CS!("\\ltx@label")).is_some() {
776    let_i(&T_CS!("\\label"), &T_CS!("\\ltx@label"), None);
777  }
778}
779
780/// The display's own `\label` is making a label (amsmath's `\label@in@display`, expanded): the kernel's `\label` it
781/// reaches (directly, through cleveref's, or after a row's `\noalign` deferral) names the step current where the
782/// display started ([`hold_raw_refstep_for_display`]), until [`end_display_label`].
783pub fn mark_display_label() { assign_value(RAW_REFSTEP_DISPLAY_LABEL, true, Some(Scope::Global)); }
784
785/// The kernel's `\label` made the label [`mark_display_label`] announced.
786pub fn end_display_label() {
787  if lookup_bool(RAW_REFSTEP_DISPLAY_LABEL) {
788    assign_value(RAW_REFSTEP_DISPLAY_LABEL, false, Some(Scope::Global));
789  }
790}
791
792/// The raw step ([`note_raw_refstep`]) a `\label` made now names: `\@currentlabel` is still the step's
793/// `\the<counter>`, not text a package defined since (`\protected@edef\@currentlabel{…}`); for an amsmath display's
794/// own `\label` ([`mark_display_label`]) the step current where the display started ([`hold_raw_refstep_for_display`]).
795/// Witnesses: 2506.01072 (`\newtcbtheorem`), 2505.20088 (`\newtcolorbox[auto counter]`), 2402.06608 (`[blend into=
796/// figures]`), 2609.20563 (`\newtcblisting`), 2310.19138 (`\labelrel` in `{align*}`).
797pub fn current_raw_refstep() -> Option<RawRefstep> {
798  if !(matches!(lookup_value(RAW_REFSTEP_DISPLAY), Some(Stored::Bool(true)))
799    && lookup_bool(RAW_REFSTEP_DISPLAY_LABEL))
800  {
801    return current_raw_refstep_now();
802  }
803  let Some(Stored::Digested(tags)) = lookup_value(&s!("{RAW_REFSTEP_DISPLAY}_tags")) else {
804    return None;
805  };
806  let serial = match lookup_value(&s!("{RAW_REFSTEP_DISPLAY}_serial")) {
807    Some(Stored::Int(serial)) => serial,
808    _ => 0,
809  };
810  Some(RawRefstep { tags, serial })
811}
812
813/// The raw step a `\label`'s whatsit recorded ([`current_raw_refstep`], its `raw_refstep_tags` and
814/// `raw_refstep_serial` properties).
815pub fn raw_refstep_of(props: &HashMap<Stored>) -> Option<RawRefstep> {
816  let Some(Stored::Digested(tags)) = props.get("raw_refstep_tags") else {
817    return None;
818  };
819  let serial = match props.get("raw_refstep_serial") {
820    Some(Stored::Int(serial)) => *serial,
821    _ => 0,
822  };
823  Some(RawRefstep { tags: tags.clone(), serial })
824}
825
826/// [`current_raw_refstep`] outside an amsmath display.
827fn current_raw_refstep_now() -> Option<RawRefstep> {
828  let (tags, counter, serial) = recorded_raw_refstep()?;
829  let the_counter = Tokens!(T_CS!(s!("\\the{}", counter)));
830  let names_the_step = match lookup_meaning(&T_CS!("\\@currentlabel")) {
831    Some(Stored::Expandable(label)) => {
832      matches!(label.get_expansion(), Some(ExpansionBody::Tokens(body)) if *body == the_counter)
833    },
834    _ => false,
835  };
836  names_the_step.then_some(RawRefstep { tags, serial })
837}
838
839/// `\refstepcounter{<ctype>}` through what `\refstepcounter` means now
840/// (`ref_step_counter_planned`).
841pub fn ref_step_counter_by_meaning(ctype: &str) -> Result<HashMap<Stored>> {
842  ref_step_counter_planned(ctype, Vec::new(), false)
843}
844
845/// A counter step as LaTeX's caption, equation, item and section steps are: `\refstepcounter`
846/// with its current meaning (latex.ltx:17391-17399 `\refstepcounter\@captype`, :15737-15738), so a
847/// rebinding applies — floatrow measures each floatbox under `\FR@loc@`, whose `\refstepcounter`
848/// is a local `\advance` undone with the box (floatrow.sty:543-556); cleveref's (and hyperref's, on a
849/// format before 2024-11-01) wrap the kernel's; crossreference.sty and old varioref copy it. As caption does
850/// (caption.sty:551-570): `before` (its prepare hook) is digested first, and a continued float's
851/// step suppresses the counter's own `\stepcounter` for the length of the `\refstepcounter`
852/// (`\caption@@refcounter`), so the number repeats without resets. With the kernel meaning this is
853/// direct; otherwise `\refstepcounter{<counter>}` is digested — the counter's name in letters, as LaTeX
854/// passes it (cleveref's `\cref@isinresetlist` compares it with `\ifx`, cleveref.sty:658-685; fncylab's
855/// `\stepcounter{#1}` reads it) — with `ctype`
856/// left for the kernel's label to make the tags of (a shared-counter theorem's own type); the props
857/// are the ones it recorded, else (a rebinding that never reaches the kernel) the label of the
858/// counter's value as it now stands. Perl steps the counter directly (`RefStepCounter`; KPE #412).
859/// Witness kaytannollista-latexia (floatrow), 2605.17685 (continued floats).
860/// Guards `perfect_kernel_batch58::{caption_steps_through_refstepcounter,
861/// floatrow_floatbox_steps_its_counter_once, floatbox_steps_its_equation_once,
862/// steps_keep_their_type_and_continuation_through_a_wrapper}`.
863pub fn ref_step_counter_planned(
864  ctype: &str,
865  before: Vec<Token>,
866  continued: bool,
867) -> Result<HashMap<Stored>> {
868  let ctype = strip_counter_type_sentinel(ctype);
869  let ctr = counter_for_type(ctype);
870  if !before.is_empty() {
871    stomach::digest(Tokens::new(before))?;
872  }
873  let refstep = T_CS!("\\refstepcounter");
874  if x_equals(&refstep, &T_CS!("\\lx@kernel@refstepcounter")) {
875    if continued {
876      // The suppressed `\stepcounter`: the value stays, no counter within is reset, and the
877      // continuation is used up (caption's next step clears its flags, caption.sty:590-599).
878      assign_value("lx@float@continued", String::new(), Some(Scope::Global));
879      add_to_counter(&ctr, Number::new(-1))?;
880      return ref_step_counter(ctype, true);
881    }
882    return ref_step_counter(ctype, false);
883  }
884  PENDING_STEPS.with(|steps| steps.borrow_mut().insert(ctr.clone(), ctype.to_string()));
885  REFSTEP_PROPS.with(|slot| slot.borrow_mut().remove(&ctr));
886  let mut tokens = Vec::new();
887  if continued {
888    // caption.sty:557-568 `\caption@@refcounter`.
889    tokens.extend([
890      T_CS!("\\let"),
891      T_CS!("\\lx@caption@stepcounter@ORI"),
892      T_CS!("\\stepcounter"),
893      T_CS!("\\def"),
894      T_CS!("\\stepcounter"),
895      T_PARAM!(),
896      T_OTHER!("1"),
897      T_BEGIN!(),
898      T_CS!("\\lx@caption@stepcounter@unless"),
899      T_BEGIN!(),
900    ]);
901    tokens.extend(ExplodeText!(&ctr));
902    tokens.extend([
903      T_END!(),
904      T_BEGIN!(),
905      T_PARAM!(),
906      T_OTHER!("1"),
907      T_END!(),
908      T_END!(),
909    ]);
910  }
911  tokens.extend([refstep, T_BEGIN!()]);
912  tokens.extend(ExplodeText!(&ctr));
913  tokens.push(T_END!());
914  if continued {
915    tokens.extend([
916      T_CS!("\\let"),
917      T_CS!("\\stepcounter"),
918      T_CS!("\\lx@caption@stepcounter@ORI"),
919    ]);
920  }
921  let digested = stomach::digest(Tokens::new(tokens));
922  take_pending_step(&ctr);
923  digested?;
924  match REFSTEP_PROPS.with(|slot| slot.borrow_mut().remove(&ctr)) {
925    Some(props) => Ok(props),
926    None => label_stepped_counter(ctype, &ctr),
927  }
928}
929
930/// Does the `\the<start>@ID` formatter chain reach `\the<target>@ID`?
931/// `begin_itemize` defines each list's `\the<usecounter>@ID` through its
932/// own `\the<listcounter>@ID`, which is defined through the enclosing
933/// list's `\the<outerusecounter>@ID` — so the open lists form a chain of
934/// `\the…@ID` macros. Walking the bodies (never expanding) is bounded by
935/// the nesting depth.
936pub fn list_id_chain_reaches(start: &str, target: &str) -> Result<bool> {
937  let target_cs = T_CS!(s!("\\the{target}@ID"));
938  let mut frontier = vec![T_CS!(s!("\\the{start}@ID"))];
939  let mut seen: Vec<Token> = Vec::new();
940  while let Some(cs) = frontier.pop() {
941    if cs == target_cs {
942      return Ok(true);
943    }
944    if seen.contains(&cs) || seen.len() > 64 {
945      continue;
946    }
947    seen.push(cs);
948    if let Some(defn) = lookup_definition(&cs)?
949      && defn.is_expandable()
950      && let Some(ExpansionBody::Tokens(body)) = defn.get_expansion()
951    {
952      for t in body.unlist_ref() {
953        if t.get_catcode() == Catcode::CS
954          && t.with_cs_name(|n| n.starts_with("\\the") && n.ends_with("@ID"))
955        {
956          frontier.push(*t);
957        }
958      }
959    }
960  }
961  Ok(false)
962}
963
964/// The counter that `\refstepcounter{<ctype>}` steps: the `counter_for_type` mapping (theorem
965/// types sharing a counter), else `<ctype>` itself.
966///
967/// The mapping holds the counter a theorem was declared with, the one LaTeX's `\refstepcounter` is passed and hyperref
968/// names the target by; that may be a type sharing a counter in turn (thmtools' `sibling=` of a `sibling=`, a
969/// `\newtheorem` over an aliascnt alias), whose `\c@` LaTeX aliases to the end of the chain (aliasctr.sty:54-79
970/// `\@counteralias`, aliascnt's `\newaliascnt`). So the chain is followed. Perl takes one link (Package.pm:758),
971/// stepping an undefined `\c@definition`: witnesses 2009.11843, 1809.01129 (KNOWN_PERL_ERRORS #1349, OXIDIZED_DESIGN
972/// #1174).
973pub fn counter_for_type(ctype: &str) -> String {
974  let mut ctr = ctype.to_string();
975  // (bounded: a cycle of mappings ends where it started)
976  for _ in 0..16 {
977    let next = with_mapping("counter_for_type", &ctr, |meaning| match meaning {
978      Some(Stored::String(next)) => Some(arena::to_string(*next)),
979      _ => None,
980    });
981    match next {
982      Some(next) if next != ctr && next != ctype => ctr = next,
983      _ => break,
984    }
985  }
986  ctr
987}
988
989/// Records `alias` as an alias counter of `base`, as aliascnt.sty's `\newaliascnt{alias}{base}` makes it
990/// (aliascnt_sty.rs; llncs.cls v2.16+'s `\@spothm`, llncs_cls.rs): `\refstepcounter{alias}` steps `base`'s root
991/// counter (`counter_for_type`, following a chain of aliases), so the alias shares its number and its ids, while the
992/// type stays `alias` — the counter LaTeX's `\refstepcounter` is passed, whose name hyperref gives the target
993/// (`\<alias>autorefname`, `\<alias>name`; [`is_counter_alias`]). Witnesses 2605.20695 (aliascnt lemmas), 2202.10090
994/// (llncs, envcountsame).
995pub fn register_counter_alias(alias: &str, base: &str) {
996  let root = counter_for_type(base);
997  assign_mapping("counter_for_type", alias, Some(root.clone()));
998  assign_mapping("counter_alias", alias, Some(root));
999}
1000
1001/// Is `ctype` an alias counter ([`register_counter_alias`])?
1002pub fn is_counter_alias(ctype: &str) -> bool {
1003  with_mapping("counter_alias", ctype, |meaning| meaning.is_some())
1004}
1005
1006/// `<ctype>` without a trailing sentinel control sequence the parameter reader may have pulled in.
1007pub fn strip_counter_type_sentinel(ctype: &str) -> &str {
1008  // Defensive: under some upstream conditions the {} parameter reader pulls a
1009  // trailing `\par` (or similar trailing CS) into a counter-type identifier
1010  // before it reaches us (Cluster A: math0010095, hep-ph0204075). Strip it
1011  // here so the downstream `\csname @<ctype>...@ID\endcsname` and similar
1012  // constructions stay well-formed. We strip the same well-known sentinels
1013  // as latex_constructs::strip_trailing_cs.
1014  for tail in ["\\par", "\\@startsection@hook", "\\relax"] {
1015    if let Some(stripped) = ctype.strip_suffix(tail) {
1016      return stripped;
1017    }
1018  }
1019  ctype
1020}
1021
1022/// The serial of the counter step in scope ([`label_stepped_counter`]; local).
1023const CURRENT_REFSTEP_SERIAL: &str = "current_refstep_serial";
1024/// The serial of the latest counter step made ([`label_stepped_counter`]; global).
1025const LATEST_REFSTEP_SERIAL: &str = "latest_refstep_serial";
1026
1027/// Whether a `\label` made now follows a counter step a group has since undone: LaTeX's `\label` names
1028/// `\@currentlabel` (latex.ltx:14963-14967), which reverts when the group of the step that set it closes, so a label
1029/// after `\end{equation}` inside a theorem names the theorem, not the equation (math0107195, "Theorem 5.3"). Such a
1030/// label never names the object that closed step numbered, however near it is (`Document::float_to_label_scoped`).
1031pub fn label_follows_an_undone_step() -> bool {
1032  match (
1033    lookup_value(CURRENT_REFSTEP_SERIAL),
1034    lookup_value(LATEST_REFSTEP_SERIAL),
1035  ) {
1036    (Some(Stored::Int(current)), Some(Stored::Int(latest))) => current != latest,
1037    (None, Some(Stored::Int(_))) => true,
1038    _ => false,
1039  }
1040}
1041
1042/// The serial of the counter step in scope, which a `\label` made now names (`\@currentlabel`, latex.ltx:14963): what
1043/// tells a step made inside a frontmatter item from one made before it (`\lx@set@frontmatter@label`).
1044pub fn refstep_in_scope() -> Option<i64> {
1045  match lookup_value(CURRENT_REFSTEP_SERIAL) {
1046    Some(Stored::Int(serial)) => Some(serial),
1047    _ => None,
1048  }
1049}
1050
1051/// The latest counter step stays the one in scope although the group it was made in has closed: a wrapper group of
1052/// LaTeXML's own (caption's `\captionof` set in a float, caption_sty.rs `\@captionof@`) around a step LaTeX makes in
1053/// the current group (caption.sty:390-391 `\setcaptiontype*` then `\caption`), so a `\label` after it names the step's
1054/// object (2402.05535 `\captionof{figure}{…}\fi\label{…}`).
1055pub fn keep_latest_refstep_in_scope() {
1056  if let Some(latest @ Stored::Int(_)) = lookup_value(LATEST_REFSTEP_SERIAL) {
1057    assign_value(CURRENT_REFSTEP_SERIAL, latest, Some(Scope::Local));
1058  }
1059}
1060
1061/// The labelling half of `\refstepcounter` (latex.ltx:14956-14967, after its `\stepcounter`):
1062/// `\@currentlabel`, `\@currentID`, the tags and the counter's scope, for the counter `ctr` just
1063/// stepped for `ctype`. Returns the `tags` and `id` properties.
1064pub fn label_stepped_counter(ctype: &str, ctr: &str) -> Result<HashMap<Stored>> {
1065  let ctr = ctr.to_string();
1066  // A step is the current label's now (`note_raw_refstep` records it again for a raw one); global, as this port's
1067  // `\@currentlabel` is.
1068  if matches!(lookup_value(RAW_REFSTEP_TAGS), Some(Stored::Digested(_))) {
1069    assign_value(RAW_REFSTEP_TAGS, Stored::None, Some(Scope::Global));
1070  }
1071  maybe_preempt_refnum(&ctr, false);
1072
1073  let the_ctr_id = s!("\\the{ctr}@ID");
1074  let the_ctr = s!("\\the{ctr}");
1075
1076  let has_id: bool = match lookup_definition(&T_CS!(&the_ctr_id))? {
1077    Some(iddef) => {
1078      if let Some(params) = iddef.get_parameters() {
1079        params.get_num_args() == 0
1080      } else {
1081        true
1082      }
1083    },
1084    _ => false,
1085  };
1086
1087  let the_ctr_cs = T_CS!(&the_ctr);
1088  let the_ctr_id_cs = T_CS!(&the_ctr_id);
1089  def_macro(
1090    T_CS!("\\@currentlabel"),
1091    None,
1092    the_ctr_cs,
1093    Some(ExpandableOptions {
1094      scope: Some(Scope::Global),
1095      ..ExpandableOptions::default()
1096    }),
1097  )?;
1098  if has_id {
1099    def_macro(
1100      T_CS!("\\@currentID"),
1101      None,
1102      the_ctr_id_cs,
1103      Some(ExpandableOptions {
1104        scope: Some(Scope::Global),
1105        ..ExpandableOptions::default()
1106      }),
1107    )?;
1108  }
1109
1110  let id = if has_id {
1111    digest_literal(Tokens!(T_CS!(&the_ctr_id)))?.to_string()
1112  } else {
1113    String::new()
1114  };
1115
1116  let digest_label = || -> Result<(Digested, Digested)> {
1117    let refnum = digest_text(Tokens!(T_CS!(&the_ctr)))?;
1118    // (a step inside the text of its own type's tags makes none: [`making_tags`])
1119    let invocation = if tags_in_progress(ctype) {
1120      Tokens!()
1121    } else {
1122      build_invocation(T_CS!("\\lx@make@tags"), vec![Some(Tokens!(T_OTHER!(
1123        ctype
1124      )))])?
1125    };
1126    Ok((refnum, stomach::digest(invocation)?))
1127  };
1128  // TeX keeps the label unexpanded (`\@currentlabel`, latex.ltx:14963-14967) and typesets it only where `\ref`
1129  // prints it; Perl digests it as text here (Package.pm:770 `DigestText`). A step made in math whose label text
1130  // cannot set (`\renewcommand{\theconsta}{{\kappa_{\arabic{consta}}}}`, `$\refstepcounter{consta}…$`: three "Script _
1131  // can only appear in math mode" per step, 1609.03070, 1904.00290) is the author's math: its digest is discarded and
1132  // the label set as `\ensuremath{\the<ctr>}`, local to the label (OXIDIZED_DESIGN #748; guard
1133  // `perfect_kernel_batch73b::refstepcounter_in_math_sets_a_math_label`). A label text sets keeps Perl's digest.
1134  let (refnum, tags) = if lookup_bool("IN_MATH") {
1135    let hold = crate::util::logger::DiagnosticsHold::begin();
1136    match digest_label() {
1137      Ok(label) if hold.errors_raised() == 0 => {
1138        hold.commit();
1139        label
1140      },
1141      Err(err) => {
1142        hold.commit();
1143        return Err(err);
1144      },
1145      Ok(_) => {
1146        hold.discard();
1147        push_frame();
1148        let saved = T_CS!(s!("\\lx@the@in@math@{ctr}"));
1149        let math_label = Tokens::new(vec![T_CS!("\\ensuremath"), T_BEGIN!(), saved, T_END!()]);
1150        // (a label whose digest left a group open — a `\p@equation` taking nine arguments ate the closing braces,
1151        // 1902.09345 — keeps the frame this pushed, and with it the math label: saved again, the label would call
1152        // itself, `\@ensuremath` for ever)
1153        let label = if matches!(lookup_meaning(&the_ctr_cs), Some(Stored::Expandable(ref d))
1154          if matches!(d.get_expansion(), Some(ExpansionBody::Tokens(body)) if *body == math_label))
1155        {
1156          digest_label()
1157        } else {
1158          let_i(&saved, &the_ctr_cs, Some(Scope::Local));
1159          def_macro(
1160            the_ctr_cs,
1161            None,
1162            math_label,
1163            Some(ExpandableOptions {
1164              scope: Some(Scope::Local),
1165              ..ExpandableOptions::default()
1166            }),
1167          )
1168          .and_then(|()| digest_label())
1169        };
1170        pop_frame()?;
1171        label?
1172      },
1173    }
1174  } else {
1175    digest_label()?
1176  };
1177
1178  // Any scopes activated for previous value of this counter (& any nested counters) must be
1179  // removed. This may also include scopes activated for \label
1180  deactivate_counter_scope(arena::pin(&ctr));
1181
1182  // And install the scope (if any) for this reference number.
1183  assign_value("current_counter", ctr.clone(), Some(Scope::Local));
1184  // latex.ltx:14958-14962 `\let\@currentcounter\reserved@a` (local; not for `*`, the current counter's alias): a
1185  // `label` hook reads it (unbtex.cls:485-493 `\cref@updatelabeldata{\@currentcounter}`, unbtex-example).
1186  if ctr != "*" {
1187    def_macro(
1188      T_CS!("\\@currentcounter"),
1189      None,
1190      Tokens::new(ExplodeText!(&ctr)),
1191      Some(ExpandableOptions {
1192        scope: Some(Scope::Local),
1193        ..ExpandableOptions::default()
1194      }),
1195    )?;
1196  }
1197  // The step's serial: in scope (local, as LaTeX's `\@currentlabel` is, latex.ltx:14963) and the latest one made
1198  // (global). A `\label` whose scope's step is not the latest comes after a step a group has since undone
1199  // ([`label_follows_an_undone_step`]).
1200  let serial = match lookup_value(LATEST_REFSTEP_SERIAL) {
1201    Some(Stored::Int(serial)) => serial + 1,
1202    _ => 1,
1203  };
1204  assign_value(
1205    CURRENT_REFSTEP_SERIAL,
1206    Stored::Int(serial),
1207    Some(Scope::Local),
1208  );
1209  assign_value(
1210    LATEST_REFSTEP_SERIAL,
1211    Stored::Int(serial),
1212    Some(Scope::Global),
1213  );
1214
1215  let scope = arena::pin(format!("{ctr}:{refnum}"));
1216  let mut receiver = VecDeque::new();
1217  receiver.push_front(Stored::String(scope));
1218  assign_value(
1219    &s!("scopes_for_counter:{ctr}"),
1220    receiver,
1221    Some(Scope::Local),
1222  );
1223  activate_scope(scope);
1224
1225  Ok(stored_map!(
1226    "tags" => Stored::Digested(tags),
1227    "id" => Stored::String(arena::pin(id))
1228  ))
1229}
1230
1231/// Internal: Use a label-derived reference number and/or ID
1232/// instead of the traditional counter based ones.
1233/// Since the \label{} determins the reference number and ID,
1234/// we MUST sniff out the label BEFORE we call RefStepCounter/RefStepID !!!!!
1235/// (see MaybePeekLabel below; and also MaybeNoteLabel for use within
1236/// captions & certain equation environments)
1237/// Assign a sub to LABEL_MAPPING_HOOK: &sub($label,$counter,$norefnum)
1238/// to return the desired refnum and id for a given object.
1239fn maybe_preempt_refnum(ctr: &str, norefnum: bool) {
1240  if let Some(mapper) = get_label_mapping_hook() {
1241    let hj_refnum = T_CS!(s!("\\_PREEMPTED_REFNUM_{ctr}"));
1242    let hj_id = T_CS!(s!("\\_PREEMPTED_ID_{ctr}"));
1243    // First, restore the \the<ctr> and \the<ctr>@ID macros to defaults
1244    if !norefnum && has_meaning(&hj_refnum) {
1245      let_i(&T_CS!(s!("\\the{ctr}")), &hj_refnum, Some(Scope::Global));
1246    }
1247    if has_meaning(&hj_id) {
1248      let_i(&T_CS!(s!("\\the{ctr}@ID")), &hj_id, Some(Scope::Global));
1249    }
1250    let label = lookup_string("PEEKED_LABEL");
1251    let (fixedrefnum, fixedid) = mapper(&label, ctr, norefnum);
1252    if let Some(refnum) = fixedrefnum
1253      && !norefnum
1254    {
1255      if !has_meaning(&hj_refnum) {
1256        // Save for later
1257        let_i(&hj_refnum, &T_CS!(s!("\\the{ctr}")), Some(Scope::Global));
1258      }
1259      let _ = def_macro(
1260        T_CS!(s!("\\the{ctr}")),
1261        None,
1262        ExpansionBody::Tokens(Tokens::new(Explode!(&refnum))),
1263        Some(ExpandableOptions {
1264          scope: Some(Scope::Global),
1265          ..Default::default()
1266        }),
1267      );
1268    }
1269    if let Some(id) = fixedid {
1270      if !has_meaning(&hj_id) {
1271        // Save for later
1272        let_i(&hj_id, &T_CS!(s!("\\the{ctr}@ID")), Some(Scope::Global));
1273      }
1274      let _ = def_macro(
1275        T_CS!(s!("\\the{ctr}@ID")),
1276        None,
1277        ExpansionBody::Tokens(Tokens::new(Explode!(&id))),
1278        Some(ExpandableOptions {
1279          scope: Some(Scope::Global),
1280          ..Default::default()
1281        }),
1282      );
1283    }
1284    remove_value("PEEKED_LABEL"); // CONSUME the label
1285    assign_value(
1286      "PROCESSED_LABEL",
1287      Stored::String(arena::pin(label)),
1288      Some(Scope::Global),
1289    );
1290  }
1291}
1292
1293/// Use to peek for FOLLOWING \label{...} to support label-derived reference numbers
1294/// (Perl: MaybePeekLabel)
1295pub fn maybe_peek_label() -> Result<()> {
1296  if get_label_mapping_hook().is_some() {
1297    let peek = crate::gullet::read_non_space()?;
1298    if let Some(ref token) = peek {
1299      if x_equals(token, &T_CS!("\\label")) {
1300        begin_semiverbatim(None);
1301        let arg = crate::gullet::read_arg(crate::gullet::ExpansionLevel::Off)?;
1302        end_semiverbatim()?;
1303        let arg_str = arg.to_string();
1304        let label = clean_label(&arg_str, Some("")).into_owned();
1305        assign_value(
1306          "PEEKED_LABEL",
1307          Stored::String(arena::pin(&label)),
1308          Some(Scope::Global),
1309        );
1310        // Put back the arg wrapped in braces so \label can re-read it
1311        crate::gullet::unread(Tokens!(T_BEGIN!(), arg, T_END!()));
1312      } else {
1313        remove_value("PROCESSED_LABEL");
1314        remove_value("PEEKED_LABEL");
1315      }
1316    }
1317    if let Some(token) = peek {
1318      crate::gullet::unread_one(token);
1319    }
1320  }
1321  Ok(())
1322}
1323
1324/// Use to note a discovered label to support label-derived refererence numbers
1325/// Can by used by \label, among others. Note we only record the label
1326/// if it hasn't already been peeked, and consumed.
1327pub fn maybe_note_label(label: &str) {
1328  if get_label_mapping_hook().is_some() {
1329    let label = clean_label(label, Some(""));
1330    let processed = lookup_string("PROCESSED_LABEL");
1331    if processed.is_empty() || processed != label {
1332      // Only if not already processed
1333      remove_value("PROCESSED_LABEL");
1334      assign_value(
1335        "PEEKED_LABEL",
1336        Stored::String(arena::pin(label)),
1337        Some(Scope::Global),
1338      );
1339    }
1340  }
1341}
1342
1343fn deactivate_counter_scope(ctr: SymStr) {
1344  let (scopes_for_counter, nested_counters) = arena::with(ctr, |cstr| {
1345    (
1346      s!("scopes_for_counter:{cstr}"),
1347      s!("nested_counters_{cstr}"),
1348    )
1349  });
1350  // with_value avoids the outer Stored::clone by reading through a
1351  // borrow; we still collect the scope SymStrs (Copy) or panic-pointers
1352  // into owned Vecs to outlive the borrow.
1353  let scope_syms: Vec<SymStr> = with_value(&scopes_for_counter, |v| match v {
1354    Some(Stored::VecDequeStored(stored_scopes)) => stored_scopes
1355      .iter()
1356      .map(|s| match s {
1357        Stored::String(scope) => *scope,
1358        _ => panic!("assignment scopes should be stored as strings, got: {s:?}"),
1359      })
1360      .collect(),
1361    _ => Vec::new(),
1362  });
1363  for scope in scope_syms {
1364    deactivate_scope(scope);
1365  }
1366
1367  // TODO: if we ever want to unshift from the nested_counters, we'll need to also use
1368  // Stored::VecDequeStored for them.
1369  let inner_ctrs: Vec<SymStr> = with_value(&nested_counters, |v| match v {
1370    Some(Stored::Strings(stored_counters)) => stored_counters.iter().copied().collect(),
1371    _ => Vec::new(),
1372  });
1373  for inner_ctr in inner_ctrs {
1374    deactivate_counter_scope(inner_ctr);
1375  }
1376}
1377
1378/// For UN-numbered units.
1379/// Like `RefStepCounter`, but only steps the "uncounter",
1380/// and returns only the id;  This is useful for unnumbered cases
1381/// of objects that normally get both a refnum and id.
1382pub fn ref_step_id(ctype: &str) -> Result<HashMap<Stored>> {
1383  let ctr = with_mapping("counter_for_type", ctype, |mapping| match mapping {
1384    Some(map) => map.to_string(),
1385    None => ctype.to_string(),
1386  });
1387  let unctr = s!("UN{ctr}");
1388  // Perl Package.pm L863-864 ("Avoid fatals..."): if `\c@UN<ctr>` isn't
1389  // defined as a register, `NewCounter(ctr)` creates both `\c@<ctr>` and
1390  // `\c@UN<ctr>` and the associated `\the<ctr>@ID` expansion. Without it,
1391  // unnumbered-section callers like `\specialsection*{}` (which amsart
1392  // Let's to `\chapter*{}` even though amsart has no chapter counter) hit
1393  // Error:undefined:\thechapter@ID because the counter was never created.
1394  let unctr_cmd = s!("\\c@{unctr}");
1395  let unctr_defined = lookup_register(&unctr_cmd, Vec::new())
1396    .ok()
1397    .flatten()
1398    .is_some();
1399  if !unctr_defined {
1400    let _ = new_counter(&ctr, "document", None);
1401  }
1402  step_counter(&unctr, false)?;
1403  maybe_preempt_refnum(&ctr, true);
1404  let cunctr_val = lookup_number(&s!("\\c@{unctr}"))
1405    .unwrap_or_default()
1406    .value_of();
1407  def_macro(
1408    T_CS!(s!("\\@{ctr}@ID")),
1409    None,
1410    Tokens!(T_OTHER!("x"), Explode!(cunctr_val)),
1411    Some(ExpandableOptions {
1412      scope: Some(Scope::Global),
1413      ..ExpandableOptions::default()
1414    }),
1415  )?;
1416
1417  let the_ctr_id = s!("\\the{ctr}@ID");
1418  def_macro(T_CS!("\\@currentID"), None, T_CS!(&the_ctr_id), None)?;
1419  Ok(stored_map!("id" =>
1420    clean_id(&digest_literal(T_CS!(the_ctr_id))?.to_string())))
1421}
1422
1423/// Recycle the last ID without incrementing (Perl: RefCurrentID)
1424/// Useful if the last ID-ed box got pruned.
1425pub fn ref_current_id(ctype: &str) -> Result<HashMap<Stored>> {
1426  let ctr = with_mapping("counter_for_type", ctype, |mapping| match mapping {
1427    Some(map) => map.to_string(),
1428    None => ctype.to_string(),
1429  });
1430  let the_ctr_id = s!("\\the{ctr}@ID");
1431  let id = clean_id(&digest_literal(T_CS!(the_ctr_id))?.to_string());
1432  Ok(stored_map!("id" => id))
1433}
1434
1435/// Whether resetting `from` resets `target`: `target` is in `from`'s reset list (`\cl@<from>`), or in the list of a
1436/// counter there, and so on.
1437pub fn reset_list_reaches(from: &str, target: &str) -> bool {
1438  list_reaches(from, target, latexml_reset_list)
1439}
1440
1441/// Whether TeX's lists, the `\cl@<ctr>` macros of `\@elt{<child>}` (latex.ltx `\@addtoreset`), lead from `from` to
1442/// `target`: a document's `\def\cl@subsection{}` (the stand-in for a class's own sectioning counters, AEA.cls:797-802,
1443/// 2308.05200) empties TeX's list, not LaTeXML's.
1444fn tex_reset_list_reaches(from: &str, target: &str) -> bool {
1445  list_reaches(from, target, tex_reset_list)
1446}
1447
1448fn list_reaches(from: &str, target: &str, list: fn(&str) -> Vec<String>) -> bool {
1449  let mut seen: Vec<String> = Vec::new();
1450  let mut pending = vec![from.to_string()];
1451  while let Some(ctr) = pending.pop() {
1452    for name in list(&ctr) {
1453      if name == target {
1454        return true;
1455      }
1456      if !seen.contains(&name) {
1457        seen.push(name.clone());
1458        pending.push(name);
1459      }
1460    }
1461  }
1462  false
1463}
1464
1465fn latexml_reset_list(ctr: &str) -> Vec<String> {
1466  lookup_tokens(&s!("\\cl@{ctr}")).map_or_else(Vec::new, |list| {
1467    list
1468      .unlist()
1469      .iter()
1470      .map(|t| t.with_str(str::to_string))
1471      .collect()
1472  })
1473}
1474
1475/// The `<child>` of each `\@elt{<child>}` in the macro `\cl@<ctr>`: the list's groups, read by their catcodes, as
1476/// the `\@elt` before each is whatever the reader `\let` it to.
1477fn tex_reset_list(ctr: &str) -> Vec<String> {
1478  let Ok(Some(defn)) = lookup_definition(&T_CS!(s!("\\cl@{ctr}"))) else {
1479    return Vec::new();
1480  };
1481  let Some(ExpansionBody::Tokens(body)) = defn.get_expansion() else {
1482    return Vec::new();
1483  };
1484  let mut children = Vec::new();
1485  let mut tokens = body.unlist_ref().iter();
1486  while let Some(t) = tokens.next() {
1487    if t.get_catcode() == Catcode::BEGIN {
1488      let child: String = tokens
1489        .by_ref()
1490        .take_while(|t| t.get_catcode() != Catcode::END)
1491        .map(|t| t.with_str(str::to_string))
1492        .collect();
1493      children.push(child);
1494    }
1495  }
1496  children
1497}
1498
1499/// Resets the counter `ctr` to zero.
1500pub fn reset_counter(ctr: &Token) -> Result<()> {
1501  reset_counter_in_cascade(ctr, &mut Vec::new(), false)
1502}
1503
1504/// [`reset_counter`] within one cascade: `path` holds the counters stepped or reset on the way to `ctr`, from
1505/// `path[0]`, which `tex_step` says TeX steps too (`\stepcounter`), not LaTeXML alone (an id's `UN` counter, a reset).
1506/// A cycle of reset lists (`\newcounter{subsubsection}[subsubsection]`, AEA.cls:800, witness 2308.05200; any
1507/// `\@addtoreset`/`\numberwithin` chain back to its start) loops in TeX's `\@stpelt` (latex.ltx:10138) and in
1508/// Perl's `ResetCounter` (Package.pm:892, deep recursion) once stepped. A counter already on the path is reset, so
1509/// it is skipped: an Error where TeX's own lists loop from that step ("TeX capacity exceeded"), else a Warning naming
1510/// it (each once; its `UN` companion, whose list mirrors its own, is not named).
1511pub fn reset_counter_in_cascade(ctr: &Token, path: &mut Vec<String>, tex_step: bool) -> Result<()> {
1512  let name = ctr.with_str(str::to_string);
1513  if path.contains(&name) {
1514    if !name.starts_with("UN") {
1515      let tex_loops = tex_step
1516        && path
1517          .first()
1518          .is_some_and(|root| *root == name || tex_reset_list_reaches(root, &name))
1519        && tex_reset_list_reaches(&name, &name);
1520      // One Error, else one Warning, per counter: a Warning after the Error would report the same cycle again.
1521      let (erred, warned) = (
1522        s!("lx@counter@reset@cycle@error@{name}"),
1523        s!("lx@counter@reset@cycle@{name}"),
1524      );
1525      let flag = if tex_loops {
1526        erred.as_str()
1527      } else {
1528        warned.as_str()
1529      };
1530      if lookup_value(&erred).is_none() && lookup_value(flag).is_none() {
1531        assign_value(flag, Stored::Bool(true), Some(Scope::Global));
1532        let message = s!("Counter '{name}' is in a cycle of reset lists; not reset again");
1533        if tex_loops {
1534          Error!("unexpected", &name, message);
1535        } else {
1536          Warn!("unexpected", &name, message);
1537        }
1538      }
1539    }
1540    return Ok(());
1541  }
1542  let (c_ctr, c_un_ctr, ctr_id) =
1543    ctr.with_str(|ctr| (s!("\\c@{ctr}"), s!("\\c@UN{ctr}"), s!("\\@{ctr}@ID")));
1544  let exists = |cs: &str| lookup_register(cs, Vec::new()).ok().flatten().is_some();
1545  // A reset list names each child and its `UN` companion (Package.pm:674); a
1546  // companion never allocated (below) has nothing to reset.
1547  if ctr.with_str(|cstr| cstr.starts_with("UN")) && !exists(&c_ctr) {
1548    return Ok(());
1549  }
1550  path.push(name);
1551  assign_register(
1552    &c_ctr,
1553    Number::new(0).into(),
1554    Some(Scope::Global),
1555    Vec::new(),
1556  )?;
1557  // but not UN — and only a companion that exists: `\c@UN<ctr>` is LaTeXML's
1558  // (`new_counter`), so a raw `\newcount\c@CodelineNo` (doc.sty:870) in a reset
1559  // list (l3doc.cls:463 `\@addtoreset{CodelineNo}{part}`) has none, and
1560  // assigning it warned "not a register" at every `\part` (ltx-talk-code, 20).
1561  // Perl `ResetCounter` (Package.pm:886) assigns unconditionally and warns
1562  // too; the same existence test guards `ref_step_id` above (Package.pm:863).
1563  // OXIDIZED_DESIGN #268.
1564  if !ctr.with_str(|cstr| cstr.starts_with("UN")) && exists(&c_un_ctr) {
1565    assign_register(
1566      &c_un_ctr,
1567      Number::new(0).into(),
1568      Some(Scope::Global),
1569      Vec::new(),
1570    )?;
1571  }
1572  def_macro(
1573    T_CS!(ctr_id),
1574    None,
1575    Tokens!(T_OTHER!("0")),
1576    Some(ExpandableOptions {
1577      scope: Some(Scope::Global),
1578      ..ExpandableOptions::default()
1579    }),
1580  )?;
1581  // and reset any within counters!
1582  if let Some(nested) = lookup_tokens(&s!("\\cl@{ctr}")) {
1583    for c in nested.unlist() {
1584      reset_counter_in_cascade(&c, path, tex_step)?;
1585    }
1586  }
1587  path.pop();
1588  Ok(())
1589}
1590
1591/// The counter of the last numbered `\item` in force, whose label an `\item[…]` references ([`ref_step_item_counter`]).
1592const ITEM_LABEL_COUNTER: &str = "lx@item@label@counter";
1593/// The [`ITEM_LABEL_COUNTER`] the list's first numbered `\item` found in force: an enclosing list's counter, empty in
1594/// a top-level list ([`ref_step_item_counter`]).
1595const ITEM_LABEL_ENCLOSING: &str = "lx@item@label@enclosing";
1596
1597/// Whether the macro `cs` expands to something: defined, and not a parameterless empty macro. An empty body is
1598/// stored as no expansion at all (`Expandable::new` "treat empty tokens as None"), so both forms are empty: the
1599/// itemize's `\the@item<n>` (sect06.rs) and enumitem's emptied `\p@enum<n>` (enumitem_sty.rs).
1600fn prints_something(cs: &str) -> Result<bool> {
1601  Ok(match lookup_definition(&T_CS!(cs))? {
1602    Some(defn) => {
1603      !(defn.is_expandable()
1604        && defn.get_conditional_type().is_none()
1605        && defn
1606          .get_parameters()
1607          .is_none_or(|params| params.get_num_args() == 0)
1608        && match defn.get_expansion() {
1609          None => true,
1610          Some(ExpansionBody::Tokens(body)) => body.is_empty(),
1611          Some(ExpansionBody::Closure(_)) => false,
1612        })
1613    },
1614    None => false,
1615  })
1616}
1617
1618/// The `\fnum@<counter>` an item's tag defines as `label` (Perl latex_constructs.pool.ltxml:1391, :1650): when the
1619/// label is the author's own `\fnum@<counter>` (`\list{\fnum@figcaption}{\usecounter{figcaption}}`), whose label TeX
1620/// typesets with `\fnum@` untouched (latex.ltx `\@item`), the author's meaning is kept as `\lx@author@fnum@<counter>`
1621/// and the label calls that, so the new `\fnum@<counter>` no longer expands into itself (Perl: one Error; we looped to
1622/// a Fatal: cond-mat9505034). KNOWN_PERL_ERRORS #1325. The returned tokens make the definition.
1623pub fn define_item_fnum(counter: &str, label: Vec<Token>) -> Vec<Token> {
1624  let fnum = T_CS!(s!("\\fnum@{counter}"));
1625  let mut tokens = Vec::new();
1626  let label = if label_calls_fnum(counter, &label) {
1627    let author = T_CS!(s!("\\lx@author@fnum@{counter}"));
1628    // (an `\item[\fnum@<counter>]` in such a list finds the list's `\fnum@<counter>` calling the kept meaning already)
1629    let calls_author = lookup_definition(&fnum)
1630      .ok()
1631      .flatten()
1632      .is_some_and(|defn| matches!(defn.get_expansion(), Some(ExpansionBody::Tokens(body)) if body.unlist_ref().contains(&author)));
1633    if !calls_author {
1634      tokens.extend([T_CS!("\\let"), author, fnum]);
1635    }
1636    label
1637      .into_iter()
1638      .map(|t| if t == fnum { author } else { t })
1639      .collect()
1640  } else {
1641    label
1642  };
1643  tokens.extend([T_CS!("\\def"), fnum, T_BEGIN!()]);
1644  tokens.extend(label);
1645  tokens.push(T_END!());
1646  tokens
1647}
1648
1649/// Whether an item label calls `\fnum@<counter>` itself ([`define_item_fnum`]).
1650pub fn label_calls_fnum(counter: &str, label: &[Token]) -> bool {
1651  let fnum = T_CS!(s!("\\fnum@{counter}"));
1652  label.contains(&fnum)
1653}
1654
1655/// The counter types whose tags are being digested now, innermost last ([`making_tags`]).
1656const TAGS_IN_PROGRESS: &str = "lx_tags_in_progress";
1657
1658/// Whether the tags of counter type `ctype` are being digested ([`making_tags`]).
1659fn tags_in_progress(ctype: &str) -> bool {
1660  match lookup_value(TAGS_IN_PROGRESS) {
1661    Some(Stored::String(types)) => arena::to_string(types).split(',').any(|t| t == ctype),
1662    _ => false,
1663  }
1664}
1665
1666/// Digest an `\item[…]`'s tags of `ctype` with `digest`. A step of the same type inside its label, which TeX typesets
1667/// once and LaTeXML formats again in each tag, makes no tags of its own: an `\item[\refstepcounter{\@listctr}…]` read
1668/// itself in `\fnum@enumi` without end (witness 1704.06431; Perl's deep recursion, KNOWN_PERL_ERRORS #1338).
1669fn making_tags<T>(ctype: &str, digest: impl FnOnce() -> Result<T>) -> Result<T> {
1670  let before = lookup_string(TAGS_IN_PROGRESS);
1671  let now = if before.is_empty() {
1672    ctype.to_string()
1673  } else {
1674    s!("{before},{ctype}")
1675  };
1676  assign_value(TAGS_IN_PROGRESS, now, Some(Scope::Global));
1677  let digested = digest();
1678  assign_value(TAGS_IN_PROGRESS, before, Some(Scope::Global));
1679  digested
1680}
1681
1682/// Create id, and tags for an itemize type \item
1683/// Whether a label the document wrote can act when its reference forms re-read it: it holds a control sequence or an
1684/// active character (a `\footnote`, `\label`, `\index`, a `\stepcounter`). A label of characters only (`\item[(b)]`) has
1685/// nothing for them to neutralize (`tag_forms`, OD #1233) nor to undo (OD #1250) and pays nothing.
1686pub fn label_can_act(label: &[Token]) -> bool { label.iter().any(Token::is_active_or_cs) }
1687
1688/// The tags of a label the document wrote: `\lx@make@reread@tags` if it can act ([`label_can_act`]), else `\lx@make@tags`.
1689pub fn make_tags_for(label: &[Token]) -> Token {
1690  if label_can_act(label) {
1691    T_CS!("\\lx@make@reread@tags")
1692  } else {
1693    T_CS!("\\lx@make@tags")
1694  }
1695}
1696
1697pub fn ref_step_item_counter(tag_opt: Option<&Tokens>) -> Result<HashMap<Stored>> {
1698  let counter = lookup_string("itemcounter");
1699  let n = lookup_int("itemization_items");
1700  assign_value("itemization_items", n + 1, None);
1701  let mut attr: HashMap<Stored> = HashMap::default();
1702  if n > 0
1703    && let Some(sep) = lookup_dimension("\\itemsep")
1704  {
1705    let default_opt = lookup_dimension("\\lx@default@itemsep");
1706    if default_opt.is_none() || sep.value_of() != default_opt.unwrap().value_of() {
1707      attr.insert("itemsep", sep.into());
1708    }
1709  }
1710
1711  let mut result = if let Some(tag) = tag_opt {
1712    let mut props = ref_step_id(&counter)?;
1713    if tag.is_empty() {
1714      return Ok(props);
1715    }
1716    let description = counter.starts_with("@desc");
1717    let formatter = if description {
1718      T_CS!("\\descriptionlabel")
1719    } else {
1720      T_CS!("\\makelabel")
1721    };
1722    let counter_name = s!("\\{counter}name");
1723    let typename = if is_defined(&counter_name) {
1724      T_CS!(counter_name)
1725    } else {
1726      T_CS!("\\itemtyperefname")
1727    };
1728
1729    let mut tag_tokens = vec![T_BEGIN!()];
1730    // An `\item[…]` does not `\refstepcounter` (latex.ltx `\@item`: only `\if@noitemarg`), so a `\label` on it takes
1731    // `\@currentlabel` as the last numbered item in force left it. Perl types `\p@<counter>` instead
1732    // (latex_constructs.pool.ltxml:1383 `\let\the<counter>\@empty`), the enclosing item's label only while `\p@enumii`
1733    // is the kernel's `\theenumi`: enumitem empties it below the first level (enumitem.sty:551-556), and the reference
1734    // was lost (2603.02347, 7 items; covington's `\item[b.]` in an `{example}`, 2405.01972). So when the last numbered
1735    // item in force is an enclosing list's (`ITEM_LABEL_COUNTER` names another counter), the refnum is that item's
1736    // `\p@<ctr>\the<ctr>`, read before `\the<counter>` is emptied. After a numbered item of the same list LaTeX's
1737    // label is that sibling's. Perl's form keeps the enclosing item's label (`\p@enumii` = `\theenumi`, "1" where
1738    // LaTeX has "1a"), and nothing at all once enumitem has emptied `\p@<ctr>`: there a nested list's refnum is the
1739    // sibling's `\p@<ctr>\the<ctr>`, LaTeX's `\@currentlabel` ("a"). A top-level list keeps Perl's form (no refnum,
1740    // the reference reads the item's own label): its `\p@enumi` is empty too, but its authors replace the sibling's
1741    // label with their own (`\def\@currentlabel{(P2')}\label{…}`, 2502.11630; 2409.02896), and `\@currentlabel` is
1742    // not read here; so is a top-level `\item[…]` with no numbered item in force, where LaTeX's label is the last
1743    // section's or equation's. A nested list's author can override it too, and there the sibling's label wins
1744    // (2609.14520: "ii)" for the author's "ii′)"); reading an author-set `\@currentlabel` is deferred (user ruling
1745    // 2026-10-20, SYNC_STATUS 77u residual). KNOWN_PERL_ERRORS #1003; guards `perfect_kernel_batch77u::{
1746    // item_with_its_own_label_takes_the_enclosing_label, enumitem_item_with_its_own_label_takes_the_enclosing_label}`.
1747    let ctr = counter_for_type(&counter);
1748    let labelled = lookup_string(ITEM_LABEL_COUNTER);
1749    let sibling_label = labelled == ctr
1750      && !lookup_string(ITEM_LABEL_ENCLOSING).is_empty()
1751      && !prints_something(&s!("\\p@{ctr}"))?;
1752    if !labelled.is_empty() && (labelled != ctr || sibling_label) {
1753      for (alias, cs) in [
1754        ("\\lx@item@label@p@", s!("p@{labelled}")),
1755        ("\\lx@item@label@the@", s!("the{labelled}")),
1756      ] {
1757        tag_tokens.extend([
1758          T_CS!("\\expandafter"),
1759          T_CS!("\\let"),
1760          T_CS!("\\expandafter"),
1761          T_CS!(alias),
1762          T_CS!("\\csname"),
1763        ]);
1764        tag_tokens.extend(Explode!(cs));
1765        tag_tokens.push(T_CS!("\\endcsname"));
1766      }
1767      tag_tokens.extend([
1768        T_CS!("\\def"),
1769        T_CS!(s!("\\p@{ctr}")),
1770        T_BEGIN!(),
1771        T_CS!("\\lx@item@label@p@"),
1772        T_CS!("\\lx@item@label@the@"),
1773        T_END!(),
1774      ]);
1775    }
1776    tag_tokens.extend([
1777      T_CS!("\\let"),
1778      T_CS!(s!("\\the{counter}")),
1779      T_CS!("\\@empty"),
1780    ]);
1781    // TODO: Another iffy clone...
1782    let reverted_tag = (*tag).clone().revert();
1783    let mut label = vec![
1784      T_CS!("\\lx@item@labelbox"),
1785      T_BEGIN!(),
1786      formatter,
1787      T_BEGIN!(),
1788    ];
1789    label.extend(reverted_tag.clone());
1790    label.extend([T_END!(), T_END!()]);
1791    tag_tokens.extend(define_item_fnum(&counter, label));
1792    tag_tokens.extend(vec![
1793      T_CS!("\\def"),
1794      T_CS!(s!("\\typerefnum@{counter}")),
1795      T_BEGIN!(),
1796      typename,
1797      T_SPACE!(),
1798      T_CS!("\\lx@item@labelbox"),
1799      T_BEGIN!(),
1800    ]);
1801    // (the label box as the item's, minus the formatter's fonts: a description's opens with its `\hspace\labelsep`)
1802    if description {
1803      tag_tokens.extend([T_CS!("\\hspace"), T_CS!("\\labelsep")]);
1804    }
1805    tag_tokens.extend(reverted_tag);
1806    tag_tokens.extend([T_END!(), T_END!()]);
1807    tag_tokens.extend(
1808      build_invocation(make_tags_for(tag.unlist_ref()), vec![Some(Tokens!(
1809        T_OTHER!(&counter)
1810      ))])?
1811      .unlist(),
1812    );
1813    tag_tokens.push(T_END!());
1814
1815    let tags = making_tags(&counter, || stomach::digest(tag_tokens))?;
1816    if !tags.is_empty()? {
1817      props.insert("tags", tags.into());
1818    }
1819    props
1820  } else {
1821    let props = ref_step_counter_by_meaning(&counter)?;
1822    // The item set `\@currentlabel` (latex.ltx `\refstepcounter` in `\@item`) when its list is numbered — its
1823    // `\the<counter>` prints something; an itemize's `\the@item<n>` and a description's are empty (sect06.rs), as
1824    // LaTeX's `\@nmbrlistfalse` lists never step, so an `\item[…]` after an itemize sibling still takes the enclosing
1825    // enumerate item's label ("1"). Local to the list, as the `\protected@edef` is; the first numbered item records
1826    // the enclosing list's counter it replaces.
1827    let ctr = counter_for_type(&counter);
1828    if prints_something(&s!("\\the{ctr}"))? {
1829      let in_force = lookup_string(ITEM_LABEL_COUNTER);
1830      if in_force != ctr {
1831        assign_value(ITEM_LABEL_ENCLOSING, in_force, None);
1832      }
1833      assign_value(ITEM_LABEL_COUNTER, ctr, None);
1834    }
1835    props
1836  };
1837  for (k, v) in attr.into_iter() {
1838    result.insert_sym(k, v);
1839  }
1840  Ok(result)
1841}
1842
1843/// configuration for begin_itemize
1844#[derive(Debug, Default, Clone)]
1845pub struct BeginItemizeOptions {
1846  /// disable nested id suffix based on stacking level
1847  pub nolevel:       bool,
1848  /// enumitem series
1849  pub series:        Option<Tokens>,
1850  /// start at a custom value
1851  pub start:         Option<Number>,
1852  /// enumitem resume?
1853  pub resume:        Option<String>,
1854  /// enumitem resume* ?
1855  pub resume_star:   Option<String>,
1856  /// a list that opens no `\list` (paralist's `in…` lists), so `\@listdepth` stays;
1857  /// enumitem's inline lists do open one (enumitem.sty:1188-1191)
1858  pub opens_no_list: bool,
1859  /// what the list's `\list` second argument sets after `\@list<depth>` (`begin_list_registers`): enumitem's
1860  /// margin keys
1861  pub setup:         Option<Tokens>,
1862}
1863
1864/// Runs `\lx@trivlist@hook` in the current group: what a package adds to latex.ltx's `\@trivlist`, which every list but
1865/// an in-paragraph one runs (:15862; tabu.sty:2390 `\tabu@trivlist`) and which is locked here (sect06.rs).
1866pub fn run_trivlist_hook() -> Result<()> {
1867  let hook = T_CS!("\\lx@trivlist@hook");
1868  match lookup_meaning(&hook) {
1869    None => return Ok(()),
1870    Some(Stored::Expandable(defn)) if matches!(defn.expansion, Some(ExpansionBody::Tokens(ref tks)) if tks.is_empty()) =>
1871    {
1872      return Ok(());
1873    },
1874    _ => {},
1875  }
1876  stomach::digest(Tokens!(hook))?;
1877  Ok(())
1878}
1879
1880/// Prepare for an list (itemize/enumerate/description/etc)
1881/// by determining the right counter (level)
1882/// and binding the right \item ( \$type@item, if $type is defined)
1883pub fn begin_itemize(
1884  itype: &str,
1885  counter: Option<&str>,
1886  options: BeginItemizeOptions,
1887) -> Result<HashMap<Stored>> {
1888  // The list-type and level of the *containing* list (if any!)
1889  let outercounter = lookup_string("itemcounter");
1890  let outerlevel = if !outercounter.is_empty() {
1891    lookup_int(&s!("{outercounter}level"))
1892  } else {
1893    0
1894  };
1895  let counter = counter.unwrap_or("@item");
1896  // latex.ltx's itemize and enumerate (:16061, :16072) make `\makelabel` their own, so an enclosing description's
1897  // `\descriptionlabel` never labels their items (1406.1992: a paralist `{compactenum}` in a `{description}`).
1898  if matches!(itype.trim_start_matches("inline@"), "itemize" | "enumerate")
1899    && is_defined("\\@firstofone")
1900  {
1901    let_i(&T_CS!("\\makelabel"), &T_CS!("\\@firstofone"), None);
1902  }
1903  let listlevel = lookup_int("itemization_level") + 1; // level for this list overall
1904  let level = lookup_int(&s!("{counter}level")) + // level for lists of specific type
1905    (if options.nolevel { 0 } else { 1 });
1906  assign_value("itemization_level", listlevel, None);
1907  assign_value(&s!("{counter}level"), level, None);
1908  // latex.ltx's `\itemize`/`\enumerate` advance `\@itemdepth`/`\@enumdepth` inside their group
1909  // (as do enumitem's and paralist's inline forms; a `\newlist` list has its own
1910  // `\enitdp@<name>`), and every list but an in-paragraph one opens a `\list` that advances
1911  // `\@listdepth` globally until `\endlist` (latex.ltx:15852, :15913; enumitem.sty:1188-1191,
1912  // :1254 for its inline lists). Packages read them (enumitem's `list<depth>` keys,
1913  // enumitem.sty:977-978). The kernel `\list` binding keeps its own `\@listdepth`, and
1914  // `\trivlist` opens no `\list`. Perl's beginItemize (latex_constructs.pool.ltxml:1296) leaves all
1915  // three at 0 (SHARED).
1916  let depth_register = match itype {
1917    "itemize" | "inline@itemize" => Some("\\@itemdepth"),
1918    "enumerate" | "inline@enumerate" => Some("\\@enumdepth"),
1919    _ => None,
1920  };
1921  let register_depth = |cs: &str| match lookup_register_quiet(cs) {
1922    Some(RegisterValue::Number(n)) => n.0,
1923    _ => 0,
1924  };
1925  let mut item_depth = None;
1926  if let Some(cs) = depth_register {
1927    let depth = register_depth(cs) + 1;
1928    assign_register(cs, RegisterValue::Number(Number(depth)), None, vec![])?;
1929    if cs == "\\@itemdepth" && counter == "@item" {
1930      item_depth = Some(depth);
1931    }
1932  }
1933  // The list's `\list` registers (`begin_list_registers`; the kernel `\list` and a raw class's set their own, and
1934  // `\trivlist` clears them, `trivlist_registers`), the item spacing then Perl's default.
1935  let opens_list = !options.opens_no_list && !matches!(itype, "list" | "trivlist");
1936  let sets_margins = opens_list && !itype.starts_with("inline@");
1937  if opens_list {
1938    step_list_depth()?;
1939  }
1940  if sets_margins {
1941    let mut setup = options
1942      .setup
1943      .clone()
1944      .map(|s| s.unlist())
1945      .unwrap_or_default();
1946    // article.cls:360-363 `{description}`: `\list{}{\labelwidth\z@ \itemindent-\leftmargin \let\makelabel…}`, its
1947    // label after `\list`'s reset (latex.ltx:15859).
1948    if itype == "description" {
1949      setup.splice(
1950        0..0,
1951        mouth::tokenize_internal(
1952          r"\labelwidth\z@\itemindent-\leftmargin\let\makelabel\descriptionlabel",
1953        )
1954        .unlist(),
1955      );
1956    }
1957    begin_list_registers(setup)?;
1958  }
1959  AssignRegister!(
1960    "\\itemsep",
1961    lookup_dimension("\\lx@default@itemsep")
1962      .unwrap_or_default()
1963      .into()
1964  );
1965  assign_value("itemization_items", 0, None);
1966  let listpostfix = roman!(listlevel).to_string();
1967  let postfix = roman!(level).to_string();
1968  let mut usecounter = counter.to_string();
1969  if !options.nolevel && !postfix.is_empty() {
1970    usecounter.push_str(&postfix);
1971  }
1972  // The `@item` levels past the six the kernel declares (sect06.rs) are declared as they are reached, in the same
1973  // id chain: lists nest that deep where a source opens trivlists it ends at once (doc.sty's `\@doc@env` opens one
1974  // per documented name; frankenstein, source2e).
1975  if counter == "@item" && level > 6 && lookup_definition(&T_CS!(s!("\\c@{usecounter}")))?.is_none()
1976  {
1977    let within = s!("@item{}", roman!(level - 1));
1978    new_counter(
1979      &usecounter,
1980      "",
1981      Some(NewCounterOptions {
1982        idprefix: "i",
1983        idwithin: &within,
1984        ..Default::default()
1985      }),
1986    )?;
1987    // As the kernel's six: an unnumbered item, named as an item (Perl pool:1514-1519, :1622).
1988    let global = || {
1989      Some(ExpandableOptions {
1990        scope: Some(Scope::Global),
1991        ..Default::default()
1992      })
1993    };
1994    def_macro(
1995      T_CS!(s!("\\the{usecounter}")),
1996      None,
1997      Tokens::new(Vec::new()),
1998      global(),
1999    )?;
2000    def_macro(
2001      T_CS!(s!("\\{usecounter}name")),
2002      None,
2003      Tokens!(T_CS!("\\itemtyperefname")),
2004      global(),
2005    )?;
2006  }
2007  if !itype.starts_with("inline@") {
2008    run_trivlist_hook()?;
2009  }
2010  if !itype.is_empty() {
2011    let itype_cs = T_CS!(s!("\\{itype}@item"));
2012    let_i(&T_CS!("\\item"), &itype_cs, None);
2013  }
2014  // In case within odd environment.
2015  let_i(&T_CS!("\\par"), &T_CS!("\\lx@normal@par"), None);
2016  def_macro(
2017    T_CS!("\\@listctr"),
2018    None,
2019    Tokens!(Explode!(usecounter)),
2020    None,
2021  )?;
2022  // latex.ltx:16068-16075 `\itemize` labels by `\labelitem\romannumeral\the\@itemdepth`, which only
2023  // itemizes advance; the `@item` level (the counter the item ids hang on) also counts kernel
2024  // `\list`s and `\trivlist`s (Perl pool:1639 `beginItemize('list')`), so an itemize inside a
2025  // `\list` took `\labelitemii` where pdflatex prints `\labelitemi`. The label follows the depth; the
2026  // counter, and so every id, stays Perl's. PERL-ORIGIN, pdflatex the oracle. A caller's own label
2027  // (enumitem's `label=`, paralist's `[<label>]` through `set_itemization_style`) is defined after
2028  // this. Repros: list-structure/{itemize_in_a_list_takes_the_first_label,
2029  // itemize_label_follows_the_itemize_depth}.
2030  if let Some(depth) = item_depth
2031    && depth != level
2032    && (1..=4).contains(&depth)
2033  {
2034    def_macro(
2035      T_CS!(s!("\\label{usecounter}")),
2036      None,
2037      Tokens!(T_CS!(s!("\\labelitem{}", roman!(depth)))),
2038      None,
2039    )?;
2040  }
2041  // latex.ltx:16057 `\enumerate` also does
2042  // `\edef\@enumctr{enum\romannumeral\the\@enumdepth}`; packages that reuse
2043  // the kernel enumerate read it back (bullenum.sty:58/61
2044  // `\csname the\@enumctr\endcsname`). `usecounter` is already
2045  // `enum` + roman(level), so this is the same value; enumerate-only, as in
2046  // the kernel. Perl's beginItemize (pool:1314) omits it (SHARED).
2047  // Witness: bullcntr/bullcntr-man (100-error cascade).
2048  if itype == "enumerate" {
2049    def_macro(
2050      T_CS!("\\@enumctr"),
2051      None,
2052      Tokens!(Explode!(usecounter)),
2053      None,
2054    )?;
2055  }
2056  // Now arrange that this list's id's are relative to the current (outer) item (if any)
2057  // And that the items within this list's id's are relative to this (new) list.
2058  assign_value("itemcounter", Stored::String(arena::pin(&usecounter)), None);
2059  // …and the environment this itemization is (natbib's `\bibitem` keeps its place only among this list's own `\item`s)
2060  assign_value(
2061    "itemization_environment",
2062    Stored::String(arena::pin(lookup_string("current_environment"))),
2063    None,
2064  );
2065  let listcounter = s!("@itemize{listpostfix}");
2066  if lookup_definition(&T_CS!(s!("\\c@{listcounter}")))?.is_none() {
2067    //Create new list counters as needed
2068    new_counter(&listcounter, "", None)?;
2069  }
2070  let mut shared = false;
2071  if !outercounter.is_empty() {
2072    // Make this list's ID relative to outer list's ID
2073    let outerusecounter = s!("{outercounter}{}", roman!(outerlevel).to_string());
2074    let thectr = s!("\\the{listcounter}@ID");
2075    // Explicit tokens, as `useexp` below: a counter name with a digit (`steps2i`) must stay one
2076    // control sequence (KPE #414).
2077    let mut expansion = vec![
2078      T_CS!(s!("\\the{outerusecounter}@ID")),
2079      T_OTHER!(".I"),
2080      T_CS!("\\arabic"),
2081      T_BEGIN!(),
2082    ];
2083    expansion.extend(Explode!(&listcounter));
2084    expansion.push(T_END!());
2085    // A list numbered by a counter an enclosing list's id hangs on — `\list{}{\usecounter{enumi}}`
2086    // around an `enumerate`, directly or through lists in between — redefines that counter's id
2087    // below through this list's, so the formatters would expand one another
2088    // (Fatal:Timeout:PushbackLimit; Perl loops too, latex_constructs.pool.ltxml:1323-1335). Then
2089    // the list hangs on the enclosing item, its id expanded once (the item's `\@<counter>@ID` is put
2090    // back when a list on the shared counter closes, below), and the shared counter's steps (this
2091    // list's own items) no longer reset the open lists' counters. Only inputs that looped meet the
2092    // condition. Guards `perfect_kernel_batch58::{
2093    // numbered_list_with_a_nested_enumerate_converts, list_numbered_by_an_enclosing_counter}`.
2094    shared = list_id_chain_reaches(&outerusecounter, &usecounter)?;
2095    if shared {
2096      let outer_id = crate::gullet::do_expand(Tokens!(expansion[0]))?;
2097      let mut frozen = outer_id.unlist();
2098      frozen.extend(expansion.drain(1..));
2099      expansion = frozen;
2100    }
2101    def_macro(T_CS!(thectr), None, Tokens::new(expansion), None)?;
2102    if shared {
2103      let open: Vec<Token> = (1..=listlevel)
2104        .map(|k| T_CS!(s!("@itemize{}", roman!(k))))
2105        .collect();
2106      let cl_use = s!("\\cl@{usecounter}");
2107      let kept = with_value(&cl_use, |v| match v {
2108        Some(Stored::Tokens(tks)) => Some(
2109          tks
2110            .clone()
2111            .unlist()
2112            .into_iter()
2113            .filter(|t| !open.contains(t))
2114            .collect::<Vec<_>>(),
2115        ),
2116        _ => None,
2117      });
2118      if let Some(kept) = kept {
2119        assign_value(
2120          &cl_use,
2121          Stored::Tokens(Tokens::new(kept)),
2122          Some(Scope::Global),
2123        );
2124      }
2125    }
2126
2127    // AND reset this list's counter when the outer item is stepped
2128    let mut cl_toks = if shared && outerusecounter == usecounter {
2129      Vec::new()
2130    } else {
2131      vec![T_CS!(&listcounter)]
2132    };
2133    let cl_name = s!("\\cl@{outerusecounter}");
2134    let existing = with_value(&cl_name, |v| match v {
2135      Some(Stored::Tokens(tks)) => tks.clone().unlist(),
2136      _ => Vec::new(),
2137    });
2138    cl_toks.extend(existing);
2139    assign_value(
2140      &cl_name,
2141      Stored::Tokens(Tokens::new(cl_toks)),
2142      Some(Scope::Global),
2143    );
2144  }
2145  // format the id of \item's relative to the id of this list.
2146  // Perl: Tokens(T_CS('\the' . $listcounter . '@ID'), T_OTHER('.i'),
2147  //              T_CS('\@' . $usecounter . '@ID'))
2148  // — build the Tokens array directly from 3 explicit tokens rather than
2149  // round-tripping through a string tokenizer. This matters when `usecounter`
2150  // contains digits (e.g. "count1" from \usecounter{count1}): `tokenize_internal`
2151  // on a literal string "\@count1@ID" would split into \@count + "1" + "@" + "ID"
2152  // because TeX's CS reader stops at digits (digits are catcode OTHER even in
2153  // the style table). Perl uses T_CS($name) to build a single CS token directly
2154  // by name, bypassing tokenization.
2155  let useexp = Tokens::new(vec![
2156    T_CS!(s!("\\the{listcounter}@ID")),
2157    T_OTHER!(".i"),
2158    T_CS!(s!("\\@{usecounter}@ID")),
2159  ]);
2160  def_macro(T_CS!(s!("\\the{usecounter}@ID")), None, useexp, None)?;
2161
2162  let mut series = if let Some(s) = options.series {
2163    s.to_string()
2164  } else {
2165    String::new()
2166  };
2167  // The shared counter's `\@<counter>@ID` is the enclosing item's id while this list is open
2168  // (`shared`, above): this list resets and steps it, so its value as the enclosing item had it is
2169  // put back, globally as the step set it, when the list closes — a later sibling list, or the
2170  // enclosing list's next items, hang on that item again.
2171  if shared {
2172    let at_id = T_CS!(s!("\\@{usecounter}@ID"));
2173    if let Some(defn) = lookup_definition(&at_id)?
2174      && let Some(ExpansionBody::Tokens(body)) = defn.get_expansion()
2175    {
2176      let mut restore = vec![T_CS!("\\gdef"), at_id, T_BEGIN!()];
2177      restore.extend(body.clone().unlist());
2178      restore.push(T_END!());
2179      push_value("afterGroup", Stored::Tokens(Tokens::new(restore)))?;
2180    }
2181  }
2182  if let Some(start) = options.start {
2183    SetCounter!(usecounter, start);
2184    add_to_counter(&usecounter, Number(-1))?;
2185  } else if let Some(s) = match options.resume {
2186    Some(s) => Some(s),
2187    None => options.resume_star,
2188  } {
2189    if s != "noseries" {
2190      series = s.clone();
2191      let last_val = lookup_int(&s!("enumitem_series_{s}_last"));
2192      if last_val != 0 {
2193        SetCounter!(usecounter, Number(last_val));
2194      }
2195    }
2196  } else {
2197    reset_counter(&T_OTHER!(&usecounter))?;
2198  }
2199
2200  let mut rsc = ref_step_counter(&s!("@itemize{listpostfix}"), false)?;
2201  rsc.insert("counter", usecounter.into());
2202  rsc.insert("series", series.into());
2203  // Perl latex_constructs.pool L1354-1356: the list carries its TeX vertical
2204  // padding (\topsep + \parskip + \partopsep) as padtop/padbottom sizing
2205  // properties; Box::computeSizeStore adds them to the computed height/depth
2206  // (compute_size_and_cache here). Omitting them under-measured every list,
2207  // clipping tcolorbox frames drawn from the estimate (2605.02240).
2208  let pad = lookup_dimension_cs("\\topsep", false)
2209    .unwrap_or_default()
2210    .add(lookup_dimension_cs("\\parskip", false).unwrap_or_default())
2211    .add(lookup_dimension_cs("\\partopsep", false).unwrap_or_default());
2212  rsc.insert("padtop", Stored::Dimension(pad));
2213  rsc.insert("padbottom", Stored::Dimension(pad));
2214  if sets_margins {
2215    end_list_registers()?;
2216  } else if itype == "trivlist" {
2217    trivlist_registers()?;
2218  }
2219  Ok(rsc)
2220}
2221
2222/// latex.ltx:16028-16039 `\@item` sets the label's box after `\hskip-\labelsep`, so the glue a label opens with
2223/// (`\hskip\labelsep`, :17206 `\@begintheorem`, article.cls:364 `\descriptionlabel`) nets against it: of the label's
2224/// leading run of skips and kerns, an `\unhbox`ed box's too, `max(0, sum - \labelsep)` stays (`\lx@item@labelbox`).
2225/// Witnesses 1508.03599 (acmlarge.cls:628 `\hskip10pt\hskip\labelsep`: 10pt), 2605.07451 (syntax.sty:244: none).
2226pub fn net_label_labelsep(items: Vec<Digested>) -> Result<Vec<Digested>> {
2227  let mut widths = Vec::new();
2228  let (items, _) = rewrite_leading_glue(items, &mut |item, width| {
2229    widths.push(width);
2230    Ok(item.clone())
2231  })?;
2232  if widths.is_empty() {
2233    return Ok(items);
2234  }
2235  let labelsep = lookup_dimension("\\labelsep").map_or(0, |d| d.value_of());
2236  // A skip of `\labelsep` in the run (the class's `\hspace\labelsep`) is the one cancelled, the others stay as written
2237  // (a `~`, a `\quad`, their font); else the net is on the first, the rest emptied, each an `\hskip` in its own font.
2238  let cancelled = widths.iter().position(|&width| width == labelsep);
2239  let mut left = (widths.iter().sum::<i64>() - labelsep).max(0);
2240  let mut index = 0;
2241  let (items, _) = rewrite_leading_glue(items, &mut |item, _| {
2242    index += 1;
2243    let width = match cancelled {
2244      Some(at) if at + 1 != index => return Ok(item.clone()),
2245      Some(_) => 0,
2246      None => std::mem::take(&mut left),
2247    };
2248    let mut skip = vec![T_CS!("\\hskip")];
2249    skip.extend(Explode!(&s!("{width}sp")));
2250    skip.push(T_CS!("\\relax"));
2251    let glue = stomach::digest(Tokens::new(skip))?.unlist();
2252    if let Some(font) = item.get_font()? {
2253      for item in &glue {
2254        item.try_set_property("font", Stored::Font(font.clone()));
2255      }
2256    }
2257    Ok(one_or_list(glue))
2258  })?;
2259  Ok(items)
2260}
2261
2262/// The items with each of their leading finite skips and kerns replaced by `replace(item, width)`, and whether the run
2263/// ended at another item. A leading list or horizontal box is entered and rebuilt (a `\usebox`ed register keeps its
2264/// own); a fill ends the run.
2265fn rewrite_leading_glue(
2266  items: Vec<Digested>,
2267  replace: &mut dyn FnMut(&Digested, i64) -> Result<Digested>,
2268) -> Result<(Vec<Digested>, bool)> {
2269  let mut out = Vec::with_capacity(items.len());
2270  let mut items = items.into_iter();
2271  let mut ended = false;
2272  for item in items.by_ref() {
2273    if let Some(width) = finite_glue_width(&item) {
2274      out.push(replace(&item, width)?);
2275      continue;
2276    }
2277    let (item, at_content) = match item.data() {
2278      // (a group's `{`/`}` marker boxes, `isEmpty`, print nothing)
2279      DigestedData::Comment(_) => (item.clone(), false),
2280      _ if item.get_property_bool("isEmpty") => (item.clone(), false),
2281      DigestedData::List(list) => match list.try_borrow() {
2282        Ok(list) => {
2283          let mut list = list.clone();
2284          let (boxes, at_content) = rewrite_leading_glue(std::mem::take(&mut list.boxes), replace)?;
2285          list.boxes = boxes;
2286          (Digested::from(list), at_content)
2287        },
2288        Err(_) => (item.clone(), true),
2289      },
2290      DigestedData::Whatsit(w) => match w.try_borrow() {
2291        Ok(w) if is_hbox(&w) && w.get_arg(2).is_some() => {
2292          let contents = w.get_arg(2).cloned().into_iter().collect();
2293          let (contents, at_content) = rewrite_leading_glue(contents, replace)?;
2294          let mut whatsit = w.clone();
2295          let mut args = whatsit.get_args().clone();
2296          args[1] = Some(one_or_list(contents));
2297          whatsit.set_args(args);
2298          (Digested::from(whatsit), at_content)
2299        },
2300        _ => (item.clone(), true),
2301      },
2302      _ => (item.clone(), true),
2303    };
2304    out.push(item);
2305    if at_content {
2306      ended = true;
2307      break;
2308    }
2309  }
2310  out.extend(items);
2311  Ok((out, ended))
2312}
2313
2314/// Whether `whatsit` is a `\hbox` (by its definition, the meaning `\hbox` has).
2315fn is_hbox(whatsit: &Whatsit) -> bool {
2316  lookup_definition(&T_CS!("\\hbox"))
2317    .ok()
2318    .flatten()
2319    .is_some_and(|hbox| Rc::ptr_eq(&hbox, &whatsit.get_definition()))
2320}
2321
2322fn one_or_list(items: Vec<Digested>) -> Digested {
2323  match <[Digested; 1]>::try_from(items) {
2324    Ok([item]) => item,
2325    Err(items) => Digested::from(List::new(items)),
2326  }
2327}
2328
2329/// The natural width of a finite horizontal skip or kern (`\hskip`, `\hspace`, `\quad`, `\kern`), `None` for a fill
2330/// (its net stays infinite) and for anything else.
2331fn finite_glue_width(item: &Digested) -> Option<i64> {
2332  if !(item.get_property_bool("isSkip") || item.get_property_bool("isKern"))
2333    || item.get_property_bool("isFill")
2334    || item.get_property_bool("isVerticalSpace")
2335  {
2336    return None;
2337  }
2338  let fill = |glue: &Glue| glue.pfill.is_some();
2339  if let Some(glue) = item.get_property("glue")
2340    && let Stored::Glue(glue) = &*glue
2341    && fill(glue)
2342  {
2343    return None;
2344  }
2345  if let DigestedData::Whatsit(w) = item.data()
2346    && let Ok(w) = w.try_borrow()
2347    && let Some(arg) = w.get_arg(1)
2348    && let DigestedData::RegisterValue(RegisterValue::Glue(glue)) = arg.data()
2349    && fill(glue)
2350  {
2351    return None;
2352  }
2353  match item.get_property("width").as_deref() {
2354    Some(Stored::Dimension(width)) => Some(width.value_of()),
2355    _ => None,
2356  }
2357}
2358
2359/// latex.ltx:15852 `\list`'s `\global\advance\@listdepth\@ne` (`set_list_depth`).
2360pub fn step_list_depth() -> Result<()> { set_list_depth(list_depth() + 1) }
2361
2362/// The current `\@listdepth`.
2363pub fn list_depth() -> i64 {
2364  match lookup_register_quiet("\\@listdepth") {
2365    Some(RegisterValue::Number(n)) => n.0,
2366    _ => 0,
2367  }
2368}
2369
2370/// `\@listdepth` set globally to `depth`, its value put back where the current group ends by `\lx@listdepth@restore`
2371/// (the `\endlist` half, latex.ltx:15913; a minipage's `\@mplistdepth`, :16325).
2372pub fn set_list_depth(depth: i64) -> Result<()> {
2373  let restore_to = list_depth();
2374  assign_register(
2375    "\\@listdepth",
2376    RegisterValue::Number(Number(depth)),
2377    Some(Scope::Global),
2378    vec![],
2379  )?;
2380  let mut restore = vec![T_CS!("\\lx@listdepth@restore")];
2381  restore.extend(Explode!(&restore_to.to_string()));
2382  restore.push(T_CS!("\\relax"));
2383  push_value("afterGroup", Stored::Tokens(Tokens::new(restore)))
2384}
2385
2386/// latex.ltx:15854-15861 `\list`'s parameters, in the current group: `\rightmargin`, `\listparindent` and
2387/// `\itemindent` cleared, `\@list<depth>` run (the class's `\leftmargin` and spacing), `\makelabel` reset (:15859),
2388/// then `setup`, the list's own second argument (its `\makelabel`). `end_list_registers` then narrows the line.
2389pub fn begin_list_registers(setup: Vec<Token>) -> Result<()> {
2390  let mut tokens = vec![T_CS!("\\lx@list@params")];
2391  tokens.extend(setup);
2392  tokens.push(T_CS!("\\relax"));
2393  stomach::digest(Tokens::new(tokens))?;
2394  Ok(())
2395}
2396
2397/// latex.ltx:15863-15867, after `\@trivlist`: `\parskip\parsep`, and `\linewidth` and `\@totalleftmargin` moved in by
2398/// the list's margins (`\lx@list@margins`; `\parindent` stays, sect06.rs).
2399pub fn end_list_registers() -> Result<()> {
2400  stomach::digest(Tokens!(T_CS!("\\lx@list@margins")))?;
2401  Ok(())
2402}
2403
2404/// latex.ltx:15903-15910 `\trivlist`: `\parsep\parskip`, and no label or left margin (`\lx@trivlist@margins`), the
2405/// line as wide as around it. For the environments that are a `\trivlist` in LaTeX (center, theorem, proof).
2406pub fn trivlist_registers() -> Result<()> {
2407  stomach::digest(Tokens!(T_CS!("\\lx@trivlist@margins")))?;
2408  Ok(())
2409}
2410
2411/// Set the itemization style for a given level.
2412/// Perl: setItemizationStyle($stuff, $level)
2413/// If $level is not given, uses the current itemize depth: paralist.sty:281-282 names the label
2414/// `labelitem\romannumeral\the\@itemdepth`, the register `begin_itemize` labels an itemize by. Perl
2415/// reads `@itemlevel`, which also counts kernel `\list`s (PERL-ORIGIN; repro
2416/// list-structure/itemize_label_follows_the_itemize_depth).
2417/// Defines \labelitem$level to $stuff.
2418pub fn set_itemization_style(stuff: Option<&Tokens>, level: Option<i32>) -> Result<()> {
2419  if let Some(stuff) = stuff {
2420    if stuff.is_empty() {
2421      return Ok(());
2422    }
2423    let level = level.unwrap_or_else(|| match lookup_register_quiet("\\@itemdepth") {
2424      Some(RegisterValue::Number(n)) => n.0.max(0) as i32,
2425      _ => 0,
2426    });
2427    let level_str = roman_aux(level);
2428    let cs_name = s!("\\labelitem{level_str}");
2429    def_macro(T_CS!(&cs_name), None, stuff.clone(), None)?;
2430  }
2431  Ok(())
2432}
2433
2434/// Set the enumeration style for a given level.
2435/// Perl: setEnumerationStyle($stuff, $level)
2436/// Parses the style tokens to detect A/a/I/i/1 patterns
2437/// and defines \theenum$level and \labelenum$level accordingly.
2438pub fn set_enumeration_style(stuff: Option<&Tokens>, level: Option<i32>) -> Result<()> {
2439  if let Some(stuff) = stuff {
2440    if stuff.is_empty() {
2441      return Ok(());
2442    }
2443    let level = level.unwrap_or_else(|| lookup_int("enumlevel").max(0) as i32);
2444    let level_str = roman_aux(level);
2445    // Iterate the borrowed token slice — no clone needed, only reads.
2446    let tokens = stuff.unlist_ref();
2447    let mut out: Vec<Token> = Vec::with_capacity(tokens.len());
2448    let ctr = T_OTHER!(s!("enum{level_str}"));
2449    let mut i = 0;
2450    while i < tokens.len() {
2451      let t = tokens[i];
2452      if t.get_catcode() == Catcode::BEGIN {
2453        // Copy braced groups verbatim
2454        out.push(t);
2455        let mut brlevel = 1i32;
2456        i += 1;
2457        while brlevel > 0 && i < tokens.len() {
2458          let tt = tokens[i];
2459          if tt.get_catcode() == Catcode::BEGIN {
2460            brlevel += 1;
2461          } else if tt.get_catcode() == Catcode::END {
2462            brlevel -= 1;
2463          }
2464          out.push(tt);
2465          i += 1;
2466        }
2467      } else {
2468        let ch = char::from_u32(t.get_charcode()).unwrap_or('\0');
2469        let cat = t.get_catcode();
2470        match (ch, cat) {
2471          ('A', Catcode::LETTER) => {
2472            // \Alph{enum$level}
2473            def_macro(
2474              T_CS!(s!("\\theenum{level_str}")),
2475              None,
2476              Tokens::new(vec![T_CS!("\\Alph"), T_BEGIN!(), ctr, T_END!()]),
2477              None,
2478            )?;
2479            out.push(T_CS!(s!("\\theenum{level_str}")));
2480          },
2481          ('a', Catcode::LETTER) => {
2482            // \alph{enum$level}
2483            def_macro(
2484              T_CS!(s!("\\theenum{level_str}")),
2485              None,
2486              Tokens::new(vec![T_CS!("\\alph"), T_BEGIN!(), ctr, T_END!()]),
2487              None,
2488            )?;
2489            out.push(T_CS!(s!("\\theenum{level_str}")));
2490          },
2491          ('I', Catcode::LETTER) => {
2492            // \Roman{enum$level}
2493            def_macro(
2494              T_CS!(s!("\\theenum{level_str}")),
2495              None,
2496              Tokens::new(vec![T_CS!("\\Roman"), T_BEGIN!(), ctr, T_END!()]),
2497              None,
2498            )?;
2499            out.push(T_CS!(s!("\\theenum{level_str}")));
2500          },
2501          ('i', Catcode::LETTER) => {
2502            // \roman{enum$level}
2503            def_macro(
2504              T_CS!(s!("\\theenum{level_str}")),
2505              None,
2506              Tokens::new(vec![T_CS!("\\roman"), T_BEGIN!(), ctr, T_END!()]),
2507              None,
2508            )?;
2509            out.push(T_CS!(s!("\\theenum{level_str}")));
2510          },
2511          ('1', Catcode::OTHER) => {
2512            // \arabic{enum$level}
2513            def_macro(
2514              T_CS!(s!("\\theenum{level_str}")),
2515              None,
2516              Tokens::new(vec![T_CS!("\\arabic"), T_BEGIN!(), ctr, T_END!()]),
2517              None,
2518            )?;
2519            out.push(T_CS!(s!("\\theenum{level_str}")));
2520          },
2521          _ => {
2522            out.push(t);
2523          },
2524        }
2525        i += 1;
2526      }
2527    }
2528    // Define \labelenum$level = { out }
2529    let mut label_tokens = vec![T_BEGIN!()];
2530    label_tokens.extend(out);
2531    label_tokens.push(T_END!());
2532    def_macro(
2533      T_CS!(s!("\\labelenum{level_str}")),
2534      None,
2535      Tokens::new(label_tokens),
2536      None,
2537    )?;
2538  }
2539  Ok(())
2540}
2541
2542/// Copies the current id, tags, and inlist counter values into whatsit properties
2543/// Perl: RescueCaptionCounters (latex_constructs.pool.ltxml L3203-3214)
2544pub fn rescue_caption_counters(captype: &str, whatsit: &mut Whatsit) {
2545  let tagskey = &s!("{captype}_tags");
2546  if let Some(tags) = remove_value(tagskey) {
2547    whatsit.set_property("tags", tags);
2548  }
2549  let idkey = s!("{captype}_id");
2550  if let Some(id) = remove_value(&idkey) {
2551    whatsit.set_property("id", id);
2552  }
2553  let inlistkey = s!("{captype}_inlist");
2554  if let Some(inlist) = remove_value(&inlistkey) {
2555    whatsit.set_property("inlist", inlist);
2556  }
2557}
2558
2559#[cfg(test)]
2560mod tests {
2561  /// A step planned on a counter that a panic unwound past (`take_pending_step` never ran, `ref_step_counter_planned`)
2562  /// is gone when the next conversion starts, with its recorded props: its first `\lx@refstepcounter` on that counter
2563  /// takes no stale type (`reset_conversion_state` at `initialize_report`, revST3; cortex_worker catches a paper's
2564  /// panic and goes on).
2565  #[test]
2566  fn a_step_a_panic_left_pending_is_not_the_next_conversions() {
2567    super::PENDING_STEPS.with(|steps| steps.borrow_mut().insert("theorem".into(), "lemma".into()));
2568    super::record_refstep_props("theorem", &Default::default());
2569    crate::common::error::initialize_report();
2570    assert_eq!(super::take_pending_step("theorem"), None);
2571    assert!(super::REFSTEP_PROPS.with(|slot| slot.borrow().is_empty()));
2572  }
2573}