1use 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#[derive(Default)]
39pub struct NewCounterOptions<'ct> {
40 pub idprefix: &'ct str,
43 pub idwithin: &'ct str,
46 pub nested: Vec<&'ct str>,
52}
53
54pub 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(®) {
65 toks.extend(prev.unlist());
66 }
67 assign_value(®, Stored::Tokens(Tokens::new(toks)), Some(Scope::Global));
68 sync_reset_list_macro(within)?;
69 define_hyper_counter_name(ctr, within)
70}
71
72fn 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
102pub fn remove_from_counter_reset(ctr: &str, within: &str) -> Result<()> {
105 let reg = s!("\\cl@{within}");
106 if let Some(prev) = lookup_tokens(®) {
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(®, Stored::Tokens(Tokens::new(kept)), Some(Scope::Global));
114 sync_reset_list_macro(within)?;
115 }
116 Ok(())
117}
118
119pub 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
158pub fn new_counter(ctr: &str, within: &str, options_opt: Option<NewCounterOptions>) -> Result<()> {
161 if copy_provides_keeps_counter(ctr) {
163 return Ok(());
164 }
165 let _declared = (crate::definition::origin::copy_provides() != 0)
168 .then(|| crate::definition::origin::CopyProvidesGuard::new(0));
169 let unctr = s!("UN{ctr}"); 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 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 } else {
188 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 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 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 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
309pub 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 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 if !idwithin.is_empty() {
374 def_macro(
375 T_CS!(thectrid),
376 None,
377 Some(ExpansionBody::Tokens({
378 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}
442fn 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}
460fn 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}
467pub fn counter_value(ctr: &str) -> Result<Number> {
469 match lookup_register(&s!("\\c@{ctr}"), Vec::new())? {
470 None => {
471 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}
479pub 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}
499pub 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
516pub 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 if !noreset && let Some(nested) = lookup_tokens(&s!("\\cl@{ctr}")) {
537 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
547pub 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 static PENDING_STEPS: std::cell::RefCell<rustc_hash::FxHashMap<String, String>> =
567 std::cell::RefCell::new(rustc_hash::FxHashMap::default());
568 static REFSTEP_PROPS: std::cell::RefCell<rustc_hash::FxHashMap<String, HashMap<Stored>>> =
570 std::cell::RefCell::new(rustc_hash::FxHashMap::default());
571}
572
573pub fn reset_refstep_state() {
575 PENDING_STEPS.with(|steps| steps.borrow_mut().clear());
576 REFSTEP_PROPS.with(|slot| slot.borrow_mut().clear());
577}
578
579pub fn take_pending_step(counter: &str) -> Option<String> {
582 PENDING_STEPS.with(|steps| steps.borrow_mut().remove(counter))
583}
584
585pub 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
590const RAW_REFSTEP_TAGS: &str = "raw_refstep_tags";
593const RAW_REFSTEP_COUNTER: &str = "raw_refstep_counter";
595const RAW_REFSTEP_SERIAL: &str = "raw_refstep_serial";
598const RAW_REFSTEP_FORGOTTEN: &str = "raw_refstep_forgotten";
600const 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#[derive(Clone, Debug)]
610pub struct RawRefstep {
611 pub tags: Digested,
613 pub serial: i64,
615}
616
617pub 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
634pub 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
651fn 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
663pub 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
695pub 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
716const RAW_REFSTEP_DISPLAY_LABEL: &str = "raw_refstep_display_label";
718
719pub 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
760pub 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
780pub fn mark_display_label() { assign_value(RAW_REFSTEP_DISPLAY_LABEL, true, Some(Scope::Global)); }
784
785pub 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
792pub 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
813pub 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
826fn 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
839pub fn ref_step_counter_by_meaning(ctype: &str) -> Result<HashMap<Stored>> {
842 ref_step_counter_planned(ctype, Vec::new(), false)
843}
844
845pub 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 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 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
930pub 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
964pub fn counter_for_type(ctype: &str) -> String {
974 let mut ctr = ctype.to_string();
975 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
989pub 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
1001pub fn is_counter_alias(ctype: &str) -> bool {
1003 with_mapping("counter_alias", ctype, |meaning| meaning.is_some())
1004}
1005
1006pub fn strip_counter_type_sentinel(ctype: &str) -> &str {
1008 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
1022const CURRENT_REFSTEP_SERIAL: &str = "current_refstep_serial";
1024const LATEST_REFSTEP_SERIAL: &str = "latest_refstep_serial";
1026
1027pub 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
1042pub 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
1051pub 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
1061pub fn label_stepped_counter(ctype: &str, ctr: &str) -> Result<HashMap<Stored>> {
1065 let ctr = ctr.to_string();
1066 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 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 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 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 deactivate_counter_scope(arena::pin(&ctr));
1181
1182 assign_value("current_counter", ctr.clone(), Some(Scope::Local));
1184 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 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
1231fn 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 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 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 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"); assign_value(
1286 "PROCESSED_LABEL",
1287 Stored::String(arena::pin(label)),
1288 Some(Scope::Global),
1289 );
1290 }
1291}
1292
1293pub 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 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
1324pub 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 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 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 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
1378pub 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 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
1423pub 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
1435pub fn reset_list_reaches(from: &str, target: &str) -> bool {
1438 list_reaches(from, target, latexml_reset_list)
1439}
1440
1441fn 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
1475fn 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
1499pub fn reset_counter(ctr: &Token) -> Result<()> {
1501 reset_counter_in_cascade(ctr, &mut Vec::new(), false)
1502}
1503
1504pub 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 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 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 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 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
1591const ITEM_LABEL_COUNTER: &str = "lx@item@label@counter";
1593const ITEM_LABEL_ENCLOSING: &str = "lx@item@label@enclosing";
1596
1597fn 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
1618pub 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 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
1649pub fn label_calls_fnum(counter: &str, label: &[Token]) -> bool {
1651 let fnum = T_CS!(s!("\\fnum@{counter}"));
1652 label.contains(&fnum)
1653}
1654
1655const TAGS_IN_PROGRESS: &str = "lx_tags_in_progress";
1657
1658fn 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
1666fn 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
1682pub fn label_can_act(label: &[Token]) -> bool { label.iter().any(Token::is_active_or_cs) }
1687
1688pub 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 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 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 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 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#[derive(Debug, Default, Clone)]
1845pub struct BeginItemizeOptions {
1846 pub nolevel: bool,
1848 pub series: Option<Tokens>,
1850 pub start: Option<Number>,
1852 pub resume: Option<String>,
1854 pub resume_star: Option<String>,
1856 pub opens_no_list: bool,
1859 pub setup: Option<Tokens>,
1862}
1863
1864pub 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
1880pub fn begin_itemize(
1884 itype: &str,
1885 counter: Option<&str>,
1886 options: BeginItemizeOptions,
1887) -> Result<HashMap<Stored>> {
1888 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 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; let level = lookup_int(&s!("{counter}level")) + (if options.nolevel { 0 } else { 1 });
1906 assign_value("itemization_level", listlevel, None);
1907 assign_value(&s!("{counter}level"), level, None);
1908 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 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 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 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 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 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 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 if itype == "enumerate" {
2049 def_macro(
2050 T_CS!("\\@enumctr"),
2051 None,
2052 Tokens!(Explode!(usecounter)),
2053 None,
2054 )?;
2055 }
2056 assign_value("itemcounter", Stored::String(arena::pin(&usecounter)), None);
2059 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 new_counter(&listcounter, "", None)?;
2069 }
2070 let mut shared = false;
2071 if !outercounter.is_empty() {
2072 let outerusecounter = s!("{outercounter}{}", roman!(outerlevel).to_string());
2074 let thectr = s!("\\the{listcounter}@ID");
2075 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 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 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 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 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 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
2222pub 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 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
2262fn 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 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
2314fn 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
2329fn 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
2359pub fn step_list_depth() -> Result<()> { set_list_depth(list_depth() + 1) }
2361
2362pub fn list_depth() -> i64 {
2364 match lookup_register_quiet("\\@listdepth") {
2365 Some(RegisterValue::Number(n)) => n.0,
2366 _ => 0,
2367 }
2368}
2369
2370pub 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
2386pub 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
2397pub fn end_list_registers() -> Result<()> {
2400 stomach::digest(Tokens!(T_CS!("\\lx@list@margins")))?;
2401 Ok(())
2402}
2403
2404pub fn trivlist_registers() -> Result<()> {
2407 stomach::digest(Tokens!(T_CS!("\\lx@trivlist@margins")))?;
2408 Ok(())
2409}
2410
2411pub 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
2434pub 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 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 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 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 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 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 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 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 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
2542pub 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 #[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}