1use std::{borrow::Cow, rc::Rc, sync::LazyLock};
2
3use regex::Regex;
4use rustc_hash::FxHashMap as HashMap;
5
6use crate::binding::content::{merge_font, merge_font_ref};
8use crate::{
9 BoxOps, Digested,
10 binding::{counter::dialect::step_counter, def::traits::IntoDigestedResult},
11 common::{
12 arena, arena::SymHashMap, def_parser::parse_parameters, error::*, font::Font, number::Number,
13 numeric_ops::NumericOps, object::Object,
14 },
15 definition::{
16 BeforeDigestClosure, ConditionalClosure, ConstructionClosure, DeclaredMode, Definition,
17 DigestionClosure, ExpansionBody, FontDirective, PrimitiveBody, ReplacementClosure, Reversion,
18 SizingClosure,
19 argument::ArgWrap,
20 conditional::{Conditional, ConditionalOptions, ConditionalType},
21 constructor::{Constructor, ConstructorOptions, TexGroup},
22 expandable::{Expandable, ExpandableOptions},
23 math_primitive::{MathPrimitive, MathPrimitiveOptions},
24 primitive::{Primitive, PrimitiveOptions},
25 register::{
26 Register, RegisterGetterClosure, RegisterSetterClosure, RegisterType, RegisterValue,
27 },
28 },
29 document::Document,
30 gullet, mouth,
31 parameter::{Parameter, Parameters},
32 pin,
33 state::*,
34 stomach::*,
35 tbox::Tbox,
36 token::*,
37 tokens::{TeXString, Tokens},
38 whatsit::Whatsit,
39};
40
41const MATH_CONSTRUCTOR_ATTRIBUTES: &[&str] = &[
42 "name",
43 "meaning",
44 "omcd",
45 "decl_id",
46 "mathstyle",
47 "lpadding",
48 "rpadding",
49];
50
51pub static CONDITIONAL_CS_RE: LazyLock<Regex> =
53 LazyLock::new(|| Regex::new(r"^\\(?:if(.*)|unless)$").unwrap());
54pub static LEADING_PROTOCOL_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\w+:").unwrap());
56pub static TRAILING_SLASH_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"/$").unwrap());
58pub static SPACES_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\s+").unwrap());
60pub static DIRTY_ID_IDIOM_RE: LazyLock<Regex> =
62 LazyLock::new(|| Regex::new(r"\$\{\}\^\{(?P<label>[^\}]*)\}\$").unwrap());
63pub static NON_ID_CHARSET_RE: LazyLock<Regex> =
65 LazyLock::new(|| Regex::new(r"[^\w_\-.]+").unwrap());
66pub static TILDE_NOISE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\\~\{\}").unwrap());
68pub static HAS_ARG_OR_CS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"#\d|\\.").unwrap());
70pub static ARG_HOLE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"#(\d)").unwrap());
72
73pub fn is_defined(name: &str) -> bool {
75 let cs = T_CS!(name);
76 is_defined_token(&cs)
77}
78
79pub fn is_defined_token(cs: &Token) -> bool {
81 match lookup_meaning(cs) {
82 Some(store) => match store {
83 Stored::Token(_) => true,
84 Stored::Expandable(ref m) => m.get_cs_name() != "\\relax",
85 Stored::Primitive(ref m) => m.get_cs_name() != "\\relax",
86 Stored::Constructor(ref m) => m.get_cs_name() != "\\relax",
87 Stored::Register(ref m) => m.get_cs_name() != "\\relax",
88 Stored::Conditional(ref m) => m.get_cs_name() != "\\relax",
89 Stored::MathPrimitive(ref m) => m.get_cs_name() != "\\relax",
90 _ => true, },
92 _ => false,
93 }
94}
95
96pub fn is_definable(token: &Token) -> bool {
98 if !token.get_catcode().is_active_or_cs() {
108 return true;
109 }
110 let meaning = lookup_meaning(token);
111 token.with_str(|name| name != "\\relax" && !name.starts_with("\\end"))
112 && (meaning.is_none()
113 || (meaning == lookup_meaning(&TOKEN_RELAX))
114 || lookup_bool("2.09_COMPATIBILITY"))
115}
116
117pub fn def_conditional(
132 cs: Token,
133 paramlist: Option<Parameters>,
134 test: Option<ConditionalClosure>,
135 options: ConditionalOptions,
136) -> Result<()> {
137 if provide_only_declines(&cs) {
138 return Ok(());
139 }
140 let locked_key_opt = if let Some(true) = options.locked {
141 Some(arena::with(cs.get_sym(), |cs_name| s!("{cs_name}:locked")))
142 } else {
143 None
144 };
145 if cs.with_str(|cs_name| matches!(cs_name, "\\fi" | "\\else" | "\\or" | "\\unless")) {
146 install_definition(
147 Conditional {
148 origin: crate::definition::origin::current_origin(),
149 cs,
150 paramlist,
151 test,
152 conditional_type: cs.with_str(|cs_name| ConditionalType::from(cs_name)),
153 skipper: options.skipper,
154 },
155 options.scope,
156 )
157 } else {
158 let (name_opt, warn_misnamed) = cs.with_str(|custom| {
165 if let Some(captures) = CONDITIONAL_CS_RE.captures(custom) {
167 let name = captures.get(1).map_or("", |m| m.as_str()).to_string();
168 return (Some(name), false);
169 }
170 let bytes = custom.as_bytes();
173 if bytes.len() > 3 && bytes[0] == b'\\' {
174 let rest = std::str::from_utf8(&bytes[3..]).ok().map(str::to_string);
175 (rest, true)
176 } else {
177 (None, false)
178 }
179 });
180 if warn_misnamed {
181 let message = s!(
182 "The conditional {} is being defined but doesn't start with \\if",
183 cs
184 );
185 Warn!("misdefined", cs, message);
186 }
187 if let Some(name) = name_opt {
188 if name != "case" && test.is_none() {
197 def_macro(
205 T_CS!(s!("\\{}true", name)),
206 None,
207 Tokens!(T_CS!("\\let"), cs, T_CS!("\\iftrue")),
208 None,
209 )?;
210 def_macro(
211 T_CS!(s!("\\{}false", name)),
212 None,
213 Tokens!(T_CS!("\\let"), cs, T_CS!("\\iffalse")),
214 None,
215 )?;
216 let_i(&cs, &T_CS!("\\iffalse"), None);
217 } else {
218 install_definition(
220 Conditional {
221 origin: crate::definition::origin::current_origin(),
222 cs,
223 paramlist,
224 test,
225 conditional_type: ConditionalType::If,
226 skipper: options.skipper,
227 },
228 options.scope,
229 );
230 }
231 } else {
232 let message = s!(
233 "The conditional {} is being defined but doesn't start with \\if",
234 cs
235 );
236 Error!("misdefined", cs, message);
237 }
238 }
239
240 if let Some(locked_key) = locked_key_opt {
241 assign_value(&locked_key, true, Some(Scope::Global));
242 }
243 Ok(())
244}
245
246pub fn def_macro<T: Into<Option<ExpansionBody>>>(
252 cs: Token,
253 paramlist: Option<Parameters>,
254 expansion: T,
255 options_opt: Option<ExpandableOptions>,
256) -> Result<()> {
257 let mut options = options_opt.unwrap_or_default();
258 if !options.extends && provide_only_declines(&cs) {
259 return Ok(());
260 }
261 let expansion_opt: Option<ExpansionBody> = expansion.into();
262 let scope = options.scope.take();
265 if options.mathactive && cs.with_str(|s| s.len()) == 1 {
266 assign_mathcode(
267 cs.with_str(|cstr| cstr.chars().next().unwrap()),
268 0x8000u16,
269 scope,
270 );
271 }
272 let locked_key_opt = if options.locked {
273 Some(format!("{cs}:locked"))
274 } else {
275 None
276 };
277 let (robust, locked) = (options.robust, options.locked);
284 let defcs = if robust {
285 T_CS!(cs.with_str(|cstr| format!("{cstr} ")))
286 } else {
287 cs
288 };
289 install_definition(
290 Expandable::new(defcs, paramlist, expansion_opt, Some(options))?,
291 scope,
292 );
293 if robust {
294 def_robust_cs(cs, locked, scope)?;
295 }
296 if let Some(locked_key) = locked_key_opt {
297 assign_value(&locked_key, true, Some(Scope::Global));
298 if robust {
305 assign_value(&format!("{defcs}:locked@files"), true, Some(Scope::Global));
306 }
307 }
308 Ok(())
309}
310
311#[derive(Default)]
313pub struct RegisterOptions {
314 pub getter: Option<RegisterGetterClosure>,
316 pub setter: Option<RegisterSetterClosure>,
318 pub readonly: bool,
320 pub address: Option<String>,
322 pub allocate: Option<String>,
324 pub local: bool,
327}
328
329pub fn def_register<T: Into<RegisterValue>>(
337 cs: Token,
338 parameters: Option<Parameters>,
339 value: T,
340 options: Option<RegisterOptions>,
341) -> Result<()> {
342 if provide_only_declines(&cs) {
343 return Ok(());
344 }
345 let mut options: RegisterOptions = options.unwrap_or_default();
346 let value: RegisterValue = value.into();
347 let has_address_option = options.address.is_some();
348 let mut address = match options.address.take() {
349 Some(v) => v,
350 None => match options.allocate {
351 Some(v) => allocate_register(&v, &cs.to_string())?.unwrap_or_default(),
352 None => String::new(),
353 },
354 };
355 if address.is_empty()
363 && let Some(existing) = lookup_register_definition(&cs)
364 && is_allocated_register_address(&existing.address)
365 {
366 address = existing.address.to_string();
367 }
368 if address.is_empty() {
370 address = cs.to_string();
371 }
372 if !has_address_option || !has_value(&address) {
374 assign_value(&address, value.clone(), Some(Scope::Global));
375 }
376
377 let register_type: RegisterType = (&value).into();
378 install_definition(
379 Register {
380 cs,
381 address,
382 parameters,
383 register_type,
384 readonly: options.readonly,
385 getter: options.getter,
386 setter: options.setter,
387 default: Some(value),
388 value: None,
389 locator: gullet::get_locator(),
390 ..Register::default()
391 },
392 if options.local {
393 None
394 } else {
395 Some(Scope::Global)
396 },
397 );
398 Ok(())
399}
400
401fn command_declared_mode(
407 mode: Option<String>,
408 enter_horizontal: bool,
409 leave_horizontal: bool,
410 bounded: bool,
411 require_math: bool,
412 forbid_math: bool,
413) -> (Option<String>, DeclaredMode) {
414 let text = mode.as_deref() == Some("text");
415 let restricted_box = mode.as_deref() == Some("restricted_horizontal");
416 let mode = if text {
417 Some("restricted_horizontal".to_string())
418 } else {
419 mode
420 };
421 let declared_mode = DeclaredMode {
422 mode: mode.as_deref().map(arena::pin),
423 enter_horizontal: enter_horizontal || text,
424 leave_horizontal,
425 bounded: mode.is_none() && bounded,
426 require_math,
427 forbid_math,
428 restricted_box,
429 };
430 (mode, declared_mode)
431}
432
433pub fn def_primitive(
442 cs: Token,
443 paramlist: Option<Parameters>,
444 compiled_replacement: Option<PrimitiveBody>,
445 options: PrimitiveOptions,
446) -> Result<()> {
447 if provide_only_declines(&cs) {
448 return Ok(());
449 }
450 let options_locked = options.locked;
451 let scope = options.scope;
452 let mut before_digest_env: Vec<BeforeDigestClosure> = Vec::new();
453 let cs_name = cs.with_cs_name(ToString::to_string);
454
455 let string_body = matches!(compiled_replacement, Some(PrimitiveBody::String(_)));
460 let enters_horizontal = options.enter_horizontal || (string_body && options.mode.is_none());
461 let (mode, declared_mode) = command_declared_mode(
462 options.mode,
463 enters_horizontal,
464 options.leave_horizontal,
465 options.bounded,
466 options.require_math,
467 options.forbid_math,
468 );
469
470 if declared_mode.require_math {
471 let cs_name_cloned = cs_name.clone();
472 let require_math_closure = before_digest_simple!({ requireMath!(cs_name_cloned) });
473 before_digest_env.push(require_math_closure);
474 }
475
476 if declared_mode.forbid_math {
477 let cs_name_cloned = cs_name.clone();
478 let forbid_math_closure = before_digest_simple!({ forbidMath!(cs_name_cloned) });
479 before_digest_env.push(forbid_math_closure);
480 }
481 if declared_mode.enter_horizontal {
482 before_digest_env.push(before_digest_simple!({
483 enter_horizontal();
484 }));
485 }
486 if declared_mode.leave_horizontal {
487 before_digest_env.push(before_digest_simple!({
488 leave_horizontal()?;
489 }));
490 }
491 if let Some(ref mode) = mode {
492 let mode_clone = mode.clone();
493 let begin_mode_closure = before_digest_simple!({
494 begin_mode(&mode_clone)?;
495 });
496 before_digest_env.push(begin_mode_closure);
497 } else if declared_mode.bounded {
498 let bgroup_closure = before_digest_simple!({
499 bgroup();
500 assign_frame_value("lx@group@code", Stored::Token(cs));
505 });
506 before_digest_env.push(bgroup_closure);
507 }
508 let size_switch = paramlist.is_none()
517 && matches!(&options.font, Some(FontDirective::Asset(font))
518 if font.size.is_some() && font.family.is_none() && font.series.is_none() && font.shape.is_none());
519 let declared_font = options.font.clone();
520 match options.font {
521 Some(FontDirective::Asset(chosen_font)) => {
522 let is_size_switch = chosen_font.size.is_some()
532 && chosen_font.family.is_none()
533 && chosen_font.series.is_none()
534 && chosen_font.shape.is_none();
535 let ends_in_selectfont = is_size_switch && paramlist.is_none();
554 let merge_font_closure = before_digest_simple!({
555 merge_font_ref(&chosen_font);
556 if is_size_switch {
557 let_i(&T_CS!("\\@currsize"), &cs, None);
558 }
559 if ends_in_selectfont && !lookup_bool_sym(pin!("IN_MATH")) {
560 let selectfont = T_CS!("\\selectfont");
561 if lookup_definition(&selectfont)?.is_some() {
562 gullet::unread_one(selectfont);
563 let fontsize = T_CS!("\\fontsize");
570 if let Some(size) = chosen_font.size
571 && lookup_definition(&fontsize)?.is_some()
572 {
573 let leading = size10_leading(size);
574 let mut tokens = vec![fontsize, T_BEGIN!()];
575 tokens.extend(Explode!(s!("{size}")));
576 tokens.extend([T_END!(), T_BEGIN!()]);
577 tokens.extend(Explode!(s!("{leading}")));
578 tokens.push(T_END!());
579 gullet::unread(Tokens::new(tokens));
580 }
581 }
582 }
583 });
584 before_digest_env.push(merge_font_closure);
585 },
586 Some(FontDirective::Closure(font_closure)) => {
587 let execute_font_closure = before_digest_simple!({
588 merge_font(font_closure(None)?);
589 });
590 before_digest_env.push(execute_font_closure);
591 },
592 None => {},
593 }
594 before_digest_env.extend(options.before_digest);
595
596 let mut after_digest_env: Vec<DigestionClosure> = options.after_digest;
597 if let Some(ref mode_str) = mode {
598 let mode_clone = mode_str.clone();
599 let end_mode_closure: DigestionClosure = after_digest_simple!(_whatsit, {
600 end_mode(&mode_clone)?;
601 });
602 after_digest_env.push(end_mode_closure);
603 } else if declared_mode.bounded {
604 let egroup_closure: DigestionClosure = after_digest_simple!(_whatsit, {
605 let mine = is_value_bound("lx@group@code", Some(0))
615 && lookup_token("lx@group@code").is_some_and(|t| t == cs);
616 if mine {
617 egroup()?;
618 }
619 });
620 after_digest_env.push(egroup_closure);
621 }
622 let mut alias = options.alias;
624 let defcs = if options.robust {
625 def_robust_cs(cs, options.locked, scope)?
626 } else if size_switch {
627 if alias.is_none() {
628 alias = Some(cs_name.clone());
629 }
630 def_switch_alias(cs, options.locked, scope)?
631 } else {
632 cs
633 };
634
635 install_definition(
636 Primitive {
637 origin: crate::definition::origin::current_origin(),
638 cs: defcs,
639 paramlist,
640 replacement: compiled_replacement,
641 before_digest: before_digest_env,
642 after_digest: after_digest_env,
643 alias,
644 nargs: options.nargs,
645 is_prefix: options.is_prefix,
646 reversion: options.reversion,
647 font_id: options.font_id,
648 declared_mode: Some(declared_mode),
649 font: declared_font,
650 },
651 scope,
652 );
653 if options_locked {
654 assign_value(&s!("{}:locked", cs_name), true, Some(Scope::Global));
655 }
656 Ok(())
657}
658
659pub fn def_math_dual(
661 cs: Token,
662 paramlist: Option<Parameters>,
663 presentation: String,
664 options: MathPrimitiveOptions,
665) -> Result<()> {
666 let (cont_cs_str, pres_cs_str) =
667 cs.with_str(|csname| (s!("{csname}@content"), s!("{csname}@presentation")));
668 let cont_cs = T_CS!(cont_cs_str);
669 let pres_cs = T_CS!(pres_cs_str);
670 let defcs = if options.robust {
671 def_robust_cs(cs, options.locked, options.scope)?
672 } else {
673 cs
674 };
675 let presentation_toks = mouth::tokenize_internal(TeXString::assembled(presentation.clone()));
676
677 let captured_role = options.role.clone();
679 let captured_revert_as = options.revert_as.clone();
680 let captured_cont_cs = cont_cs;
681 let captured_pres_cs = pres_cs;
682 let captured_pres = presentation.clone();
683 install_definition(
684 Expandable::new(
685 defcs,
686 paramlist.clone(),
687 Some(ExpansionBody::Closure(Rc::new(move |args| {
688 let args_opt_tks = args
689 .into_iter()
690 .map(|arg| arg.into())
691 .collect::<Vec<Option<Tokens>>>();
692 let (cargs, pargs) = dualize_arglist(&captured_pres, args_opt_tks)?;
693
694 let mut dtks = vec![T_CS!("\\lx@dual")];
695 if captured_role.is_some() || captured_revert_as.is_some() {
697 dtks.push(T_OTHER!("["));
698 if let Some(ref role) = captured_role {
699 dtks.extend(vec![T_OTHER!("role"), T_OTHER!("="), T_OTHER!(role)]);
700 if let Some(ref _revert_as) = captured_revert_as {
701 dtks.push(T_OTHER!(","));
702 }
703 }
704 if let Some(ref revert_as) = captured_revert_as {
705 dtks.extend(vec![
706 T_OTHER!("revert_as"),
707 T_OTHER!("="),
708 T_OTHER!(revert_as),
709 ]);
710 }
711 dtks.push(T_OTHER!("]"));
712 }
713 dtks.push(T_BEGIN!());
717 dtks.push(captured_cont_cs);
718 for carg in cargs.into_iter().flatten() {
719 dtks.push(T_BEGIN!());
720 dtks.extend(carg.unlist());
721 dtks.push(T_END!());
722 }
723 dtks.push(T_END!());
724 dtks.push(T_BEGIN!());
725 dtks.push(captured_pres_cs);
726 for parg in pargs.into_iter().flatten() {
727 dtks.push(T_BEGIN!());
728 dtks.extend(parg.unlist());
729 dtks.push(T_END!());
730 }
731 dtks.push(T_END!());
732
733 Ok(Tokens::new(dtks))
734 }))),
735 Some(ExpandableOptions {
736 protected: options.protected,
737 ..ExpandableOptions::default()
738 }),
739 )?,
740 options.scope,
741 );
742
743 install_definition(
745 Expandable::new(
746 pres_cs,
747 paramlist.clone(),
748 Some(ExpansionBody::Tokens(presentation_toks)),
749 Some(ExpandableOptions {
750 protected: options.protected,
751 ..ExpandableOptions::default()
752 }),
753 )?,
754 options.scope,
755 );
756
757 let nargs = paramlist
760 .as_ref()
761 .map(|pl| pl.get_parameters().len())
762 .unwrap_or(0);
763 let content_closure: ReplacementClosure = if nargs == 0 {
764 Rc::new(|document, _args, props| {
765 let mut attrs = HashMap::default();
766 for key in ["role", "scriptpos", "stretchy"] {
767 if let Some(v) = props.get(key) {
768 attrs.insert(key.to_owned(), v.to_string());
769 }
770 }
771 for key in MATH_CONSTRUCTOR_ATTRIBUTES {
772 if let Some(v) = props.get(key) {
773 attrs.insert(key.to_string(), v.to_string());
774 }
775 }
776 document.insert_element("ltx:XMTok", Vec::new(), Some(attrs))?;
777 Ok(())
778 })
779 } else {
780 Rc::new(|document, args, props| {
781 let mut app_attrs = HashMap::default();
782 for key in ["role", "scriptpos"] {
783 if let Some(v) = props.get(key) {
784 app_attrs.insert(key.to_owned(), v.to_string());
785 }
786 }
787 document.open_element("ltx:XMApp", Some(app_attrs), None)?;
788 let mut op_attrs = HashMap::default();
789 if let Some(v) = props.get("operator_stretchy") {
790 op_attrs.insert("stretchy".to_owned(), v.to_string());
791 }
792 if let Some(v) = props.get("operator_role") {
793 op_attrs.insert("role".to_owned(), v.to_string());
794 }
795 if let Some(v) = props.get("operator_scriptpos") {
796 op_attrs.insert("scriptpos".to_owned(), v.to_string());
797 }
798 for key in MATH_CONSTRUCTOR_ATTRIBUTES {
799 if let Some(v) = props.get(key) {
800 op_attrs.insert(key.to_string(), v.to_string());
801 }
802 }
803 document.insert_element("ltx:XMTok", Vec::new(), Some(op_attrs))?;
805 for arg in args.iter().flatten() {
808 document.absorb(arg, None)?;
809 }
810 document.close_element("ltx:XMApp")?;
811 Ok(())
812 })
813 };
814 let mut content_constructor = Constructor {
816 cs: cont_cs,
817 paramlist,
818 replacement: Some(content_closure),
819 ..Constructor::default()
820 };
821 let scope = options.scope;
822 transfer_common_constructor_options(&cs, &presentation, options, &mut content_constructor);
823 install_definition(content_constructor, scope);
824 Ok(())
825}
826
827pub fn def_math_wrapped(
834 cs: Token,
835 presentation: Tokens,
836 options: MathPrimitiveOptions,
837) -> Result<()> {
838 let (wrap_cs_str, pres_cs_str) =
839 cs.with_str(|csname| (s!("{csname}@wrapper"), s!("{csname}@presentation")));
840 let wrap_cs = T_CS!(wrap_cs_str);
841 let pres_cs = T_CS!(pres_cs_str);
842 let defcs = if options.robust {
843 def_robust_cs(cs, options.locked, options.scope)?
844 } else {
845 cs
846 };
847 install_definition(
848 Expandable::new(
849 defcs,
850 None,
851 Some(ExpansionBody::Tokens(Tokens::new(vec![
852 wrap_cs,
853 T_BEGIN!(),
854 pres_cs,
855 T_END!(),
856 ]))),
857 Some(ExpandableOptions {
858 protected: options.protected,
859 ..ExpandableOptions::default()
860 }),
861 )?,
862 options.scope,
863 );
864 install_definition(
865 Expandable::new(
866 pres_cs,
867 None,
868 Some(ExpansionBody::Tokens(presentation.clone())),
869 Some(ExpandableOptions {
870 protected: options.protected,
871 ..ExpandableOptions::default()
872 }),
873 )?,
874 options.scope,
875 );
876 let replacement: ReplacementClosure = Rc::new(|document, args, props| {
877 let mut attrs = HashMap::default();
878 for key in ["role", "scriptpos", "stretchy"] {
879 if let Some(v) = props.get(key) {
880 attrs.insert(key.to_owned(), v.to_string());
881 }
882 }
883 for key in MATH_CONSTRUCTOR_ATTRIBUTES {
884 if let Some(v) = props.get(key) {
885 attrs.insert(key.to_string(), v.to_string());
886 }
887 }
888 document.open_element("ltx:XMWrap", Some(attrs), None)?;
889 for arg in args.iter().flatten() {
890 document.absorb(arg, None)?;
891 }
892 document.close_element("ltx:XMWrap")?;
893 Ok(())
894 });
895 let mut wrapper = Constructor {
896 cs: wrap_cs,
897 paramlist: parse_parameters("{}", &wrap_cs, true)?,
898 replacement: Some(replacement),
899 ..Constructor::default()
900 };
901 let scope = options.scope;
902 transfer_common_constructor_options(&cs, &presentation.to_string(), options, &mut wrapper);
903 wrapper.reversion = Some(Reversion::Closure(Rc::new(move |_whatsit, args| {
904 if get_dual_branch() == Some("content") {
905 return Ok(Tokens::new(vec![cs]));
906 }
907 match args.first().and_then(Option::as_ref) {
908 Some(arg) => arg.revert(),
909 None => Ok(Tokens::new(Vec::new())),
910 }
911 })));
912 install_definition(wrapper, scope);
913 Ok(())
914}
915
916pub fn def_math_primitive(
919 cs: Token,
920 _paramlist: Option<Parameters>,
921 presentation: String,
922 options: MathPrimitiveOptions,
923) {
924 let scope = options.scope;
925 let reqfont_opt = options.font.clone();
926 let shared_options = Rc::new(options.clone());
931 let variablesize_op = shared_options.variablesize_op;
932 let dynamic_scriptpos = shared_options.dynamic_scriptpos;
933 let letters_class = shared_options.letters_class;
934 let reversion_cs = options.alias.as_deref().map_or(cs, Token::from);
937
938 install_definition(
939 MathPrimitive {
940 cs,
941 paramlist: None, replacement: Some(Rc::new(move |_args| {
943 let locator = gullet::get_locator();
944 let cur_mode = lookup_string_from_sym(pin!("MODE"));
949 let mode_static: &'static str = match cur_mode.as_str() {
950 "math" => "math",
951 "display_math" => "display_math",
952 "inline_math" => "inline_math",
953 "vertical" => "vertical",
954 "internal_vertical" => "internal_vertical",
955 "horizontal" => "horizontal",
956 "restricted_horizontal" => "restricted_horizontal",
957 _ => "math",
958 };
959 let state_font = lookup_font().unwrap();
960 let mathstyle_override: Option<&'static str> = if variablesize_op {
962 let is_display = state_font
963 .get_mathstyle()
964 .is_some_and(|s| s.as_ref() == "display");
965 Some(if is_display { "display" } else { "text" })
966 } else {
967 None
968 };
969 let scriptpos_override: Option<&'static str> = if dynamic_scriptpos {
971 let is_display = state_font
972 .get_mathstyle()
973 .is_some_and(|s| s.as_ref() == "display");
974 Some(if is_display { "mid" } else { "post" })
975 } else {
976 None
977 };
978 let specialize = |font: &Font| match letters_class {
980 Some(class) => font.specialize_letters(&presentation, class),
981 None => font.specialize(&presentation),
982 };
983 let font = Rc::new(if let Some(ref reqfont) = reqfont_opt {
984 let this_reqfont = reqfont.get_font(None)?;
985 specialize(&state_font.merge_ref(&this_reqfont))
986 } else {
987 specialize(&state_font)
988 });
989
990 Ok(vec![Digested::from(Tbox {
991 text: arena::pin(&presentation),
992 tokens: Tokens!(reversion_cs),
993 font,
994 properties: shared_options.to_hash_stored_with_overrides(
995 Some(mode_static),
996 mathstyle_override,
997 scriptpos_override,
998 ),
999 locator: Some(locator),
1000 empty_marker: false,
1001 })])
1002 })),
1003 options,
1004 ..MathPrimitive::default()
1005 },
1006 scope,
1007 );
1008}
1009
1010pub fn def_math_constructor(
1013 cs: Token,
1014 paramlist: Option<Parameters>,
1015 presentation: String,
1016 mut options: MathPrimitiveOptions,
1017) -> Result<()> {
1018 let nargs = paramlist
1020 .as_ref()
1021 .map(|pl| pl.get_parameters().len())
1022 .unwrap_or(0);
1023 let defcs = if options.robust {
1029 def_robust_cs(cs, options.locked, options.scope)?
1030 } else {
1031 cs
1032 };
1033 if options.reversion.is_none() && nargs == 0 && options.alias.is_none() {
1034 if options.revert_as.is_none() || options.revert_as == Some(Cow::Borrowed("content")) {
1035 options.reversion = Some(Reversion::Tokens(Tokens!(cs)));
1036 } else if options.revert_as == Some(Cow::Borrowed("context")) {
1037 let content_toks = Tokens!(cs);
1042 let presentation_toks = Tokens::new(Explode!(presentation));
1043 options.reversion = Some(Reversion::Closure(Rc::new(move |_whatsit, _args| {
1044 Ok(if get_dual_branch().unwrap_or("content") == "content" {
1045 content_toks.clone()
1046 } else {
1047 presentation_toks.clone()
1048 })
1049 })));
1050 } else {
1051 options.reversion = Some(Reversion::Tokens(Tokens::new(Explode!(presentation))));
1055 }
1056 }
1057 let presentation_for_sizer = presentation.clone();
1058 let presentation_for_replacement = presentation.clone();
1059 let compiled_replacement: Option<ReplacementClosure> = Some(if nargs == 0 {
1060 let presentation_is_trivial = !presentation_for_replacement
1077 .chars()
1078 .any(|c| c == '(' || c == ')' || c == '\\');
1079 Rc::new(
1080 move |document: &mut Document, _, props: &SymHashMap<Stored>| {
1081 let font_opt = match props.get("font") {
1082 Some(Stored::Font(f)) => Some(Cow::Borrowed(&**f)),
1083 Some(Stored::FontDirective(FontDirective::Closure(code))) => {
1084 Some(Cow::Owned(code(None)?))
1085 },
1086 Some(Stored::FontDirective(FontDirective::Asset(font))) => Some(Cow::Borrowed(&**font)),
1087 _ => None,
1088 };
1089 let is_math = matches!(props.get("isMath"), Some(Stored::Bool(true)));
1098 if !is_math && presentation_is_trivial {
1099 document.absorb_string(&presentation_for_replacement, props)?;
1101 return Ok(());
1102 }
1103 let mut attrs = HashMap::default();
1104 for key in ["role", "scriptpos", "stretchy"] {
1105 if let Some(v) = props.get(key) {
1106 attrs.insert(key.to_owned(), v.to_string());
1107 }
1108 }
1109 for key in MATH_CONSTRUCTOR_ATTRIBUTES {
1110 if let Some(v) = props.get(key) {
1111 attrs.insert(key.to_string(), v.to_string());
1112 }
1113 }
1114 if let Some(font) = font_opt {
1115 document.open_element("ltx:XMTok", Some(attrs), Some(&font))?;
1116 } else {
1117 document.open_element("ltx:XMTok", Some(attrs), None)?;
1118 }
1119 document.absorb_string(&presentation_for_replacement, props)?;
1120 document.close_element("ltx:XMTok")?;
1121 Ok(())
1122 },
1123 )
1124 } else {
1125 Rc::new(
1132 move |document: &mut Document, args: &Vec<Option<Digested>>, props: &SymHashMap<Stored>| {
1133 let mut attrs = HashMap::default();
1134 for key in ["role", "scriptpos", "stretchy"] {
1135 if let Some(v) = props.get(key) {
1136 attrs.insert(key.to_owned(), v.to_string());
1137 }
1138 }
1139 let font_opt = match props.get("font") {
1140 Some(Stored::Font(f)) => Some(Cow::Borrowed(&**f)),
1141 Some(Stored::FontDirective(FontDirective::Closure(code))) => {
1142 Some(Cow::Owned(code(None)?))
1143 },
1144 Some(Stored::FontDirective(FontDirective::Asset(font))) => Some(Cow::Borrowed(&**font)),
1145 _ => None,
1146 };
1147 if let Some(ref font) = font_opt {
1148 document.open_element("ltx:XMApp", Some(attrs), Some(font))?;
1149 } else {
1150 document.open_element("ltx:XMApp", Some(attrs), None)?;
1151 }
1152 let mut op_attrs = HashMap::default();
1154 if let Some(role) = props.get("operator_role") {
1155 op_attrs.insert(String::from("role"), role.to_string());
1156 }
1157 if let Some(stretchy) = props.get("operator_stretchy") {
1158 op_attrs.insert(String::from("stretchy"), stretchy.to_string());
1159 }
1160 if let Some(scriptpos) = props.get("operator_scriptpos") {
1161 op_attrs.insert(String::from("scriptpos"), scriptpos.to_string());
1162 }
1163 for key in MATH_CONSTRUCTOR_ATTRIBUTES {
1164 if let Some(v) = props.get(key) {
1165 op_attrs.insert(key.to_string(), v.to_string());
1166 }
1167 }
1168 if let Some(font) = font_opt {
1169 document.open_element("ltx:XMTok", Some(op_attrs), Some(&font))?;
1170 } else {
1171 document.open_element("ltx:XMTok", Some(op_attrs), None)?;
1172 }
1173 document.absorb_string(&presentation_for_replacement, props)?;
1174 document.close_element("ltx:XMTok")?;
1175 for arg in args {
1177 document.open_element("ltx:XMArg", None, None)?;
1178 if let Some(arg_v) = arg {
1179 document.absorb(arg_v, None)?;
1180 }
1181 document.close_element("ltx:XMArg")?;
1182 }
1183
1184 document.close_element("ltx:XMApp")?;
1185 Ok(())
1186 },
1187 )
1188 });
1189 let sizer: Option<SizingClosure> = Some(Rc::new(move |_| {
1190 Ok(Font::math_default().compute_string_size(&presentation_for_sizer, SymHashMap::default()))
1191 }));
1192
1193 let mut constructor = Constructor {
1195 cs: defcs,
1196 paramlist,
1197 replacement: compiled_replacement,
1198 nargs: Some(nargs),
1199 sizer,
1200 ..Constructor::default()
1204 };
1205 let scope = options.scope;
1206 transfer_common_constructor_options(&cs, &presentation, options, &mut constructor);
1207 install_definition(constructor, scope);
1208 Ok(())
1209}
1210
1211fn infer_sizer(
1212 sizer: Option<&SizingClosure>,
1213 _reversion: Option<&Reversion>,
1214) -> Option<SizingClosure> {
1215 sizer.map(Rc::clone)
1220}
1221
1222fn def_switch_alias(cs: Token, locked: bool, scope: Option<Scope>) -> Result<Token> {
1227 let inner = T_CS!(cs.with_str(|name| format!("\\lx@size@{}", name.trim_start_matches('\\'))));
1228 let options = ExpandableOptions {
1229 locked,
1230 ..ExpandableOptions::default()
1231 };
1232 install_definition(
1233 Expandable::new(cs, None, Tokens!(inner).into(), Some(options))?,
1234 scope,
1235 );
1236 Ok(inner)
1237}
1238
1239fn def_robust_cs(cs: Token, locked: bool, scope: Option<Scope>) -> Result<Token> {
1240 let cs_str = cs.with_str(|cstr| format!("{cstr} "));
1241 let defcs = T_CS!(cs_str);
1242 let return_cs = defcs;
1243 let expansion = Tokens!(T_CS!("\\protect"), defcs);
1244 let options = ExpandableOptions {
1245 locked,
1246 robust: true,
1247 ..ExpandableOptions::default()
1248 };
1249 install_definition(
1251 Expandable::new(cs, None, expansion.into(), Some(options))?,
1252 scope,
1253 );
1254 Ok(return_cs)
1255}
1256
1257pub fn def_constructor(
1266 cs: Token,
1267 paramlist: Option<Parameters>,
1268 compiled_replacement: Option<ReplacementClosure>,
1269 mut options: ConstructorOptions,
1270) {
1271 if provide_only_declines(&cs) {
1272 return;
1273 }
1274 let scope = options.scope;
1277 let cs = if options.robust {
1278 if options.alias.is_none() {
1304 options.alias = Some(cs.with_cs_name(ToString::to_string));
1305 }
1306 def_robust_cs(cs, options.locked, scope).expect("def_robust_cs for constructor failed")
1307 } else {
1308 cs
1309 };
1310 let cs_name = cs.with_cs_name(ToString::to_string);
1311 let locked_key_opt = if options.locked {
1312 Some(s!("{cs_name}:locked"))
1313 } else {
1314 None
1315 };
1316
1317 let mut before_digest_closures: Vec<BeforeDigestClosure> = Vec::new();
1318
1319 let (mode, declared_mode) = command_declared_mode(
1320 options.mode,
1321 options.enter_horizontal,
1322 options.leave_horizontal,
1323 options.bounded,
1324 options.require_math,
1325 options.forbid_math,
1326 );
1327
1328 if declared_mode.require_math {
1329 let cs_name_cloned = options
1332 .alias
1333 .clone()
1334 .filter(|alias| alias.starts_with('\\') && alias.len() > 1)
1335 .unwrap_or_else(|| cs_name.clone());
1336 let require_math_closure = before_digest_simple!({ requireMath!(cs_name_cloned) });
1337 before_digest_closures.push(require_math_closure);
1338 }
1339 if declared_mode.forbid_math {
1340 let cs_name_cloned = cs_name;
1341 let forbid_math_closure = before_digest_simple!({ forbidMath!(cs_name_cloned) });
1342 before_digest_closures.push(forbid_math_closure);
1343 }
1344 if declared_mode.enter_horizontal {
1345 before_digest_closures.push(before_digest_simple!({
1346 enter_horizontal();
1347 }));
1348 }
1349 if declared_mode.leave_horizontal {
1350 before_digest_closures.push(before_digest_simple!({
1351 leave_horizontal()?;
1352 }));
1353 }
1354 if let Some(ref mode) = mode {
1355 let mode_clone = mode.clone();
1356 let begin_mode_closure = before_digest_simple!({
1357 begin_mode(&mode_clone)?;
1358 });
1359 before_digest_closures.push(begin_mode_closure);
1360 } else if declared_mode.bounded {
1361 let bgroup_closure = before_digest_simple!({
1362 bgroup();
1363 });
1364 before_digest_closures.push(bgroup_closure);
1365 }
1366 let declared_font = options.font.clone();
1371 match options.font {
1372 Some(FontDirective::Asset(chosen_font)) => {
1373 let merge_font_closure = before_digest_simple!({
1374 merge_font((*chosen_font).clone());
1375 });
1376 before_digest_closures.push(merge_font_closure);
1377 },
1378 Some(FontDirective::Closure(font_closure)) => {
1379 let execute_font_closure = before_digest_simple!({
1380 merge_font(font_closure(None)?);
1381 });
1382 before_digest_closures.push(execute_font_closure);
1383 },
1384 None => {},
1385 };
1386 before_digest_closures.extend(options.before_digest);
1387
1388 let mut after_digest_closures: Vec<DigestionClosure> = options.after_digest;
1389 if let Some(ref mode_str) = mode {
1390 let mode_clone = mode_str.clone();
1391 let end_mode_closure: DigestionClosure = after_digest_simple!(_whatsit, {
1392 end_mode(&mode_clone)?;
1393 });
1394 after_digest_closures.push(end_mode_closure);
1395 } else if declared_mode.bounded {
1396 let egroup_closure: DigestionClosure = after_digest_simple!(_whatsit, {
1397 egroup()?;
1398 });
1399 after_digest_closures.push(egroup_closure);
1400 }
1401
1402 let constructor = Constructor {
1403 cs,
1404 paramlist,
1405 replacement: compiled_replacement,
1406 before_digest: before_digest_closures,
1407 after_digest: after_digest_closures,
1408 before_construct: options.before_construct,
1409 after_construct: options.after_construct,
1410 nargs: options.nargs,
1411 alias: options.alias,
1412 sizer: infer_sizer(options.sizer.as_ref(), options.reversion.as_ref()),
1413 reversion: options.reversion,
1414 capture_body: options.capture_body,
1415 properties: options.properties,
1416 declared_mode: Some(declared_mode),
1417 font: declared_font,
1418 halign_primitive: options.halign_primitive,
1419 template: options.template,
1420 salvage_close: options.salvage_close,
1421 ..Constructor::default()
1424 };
1425 install_definition(constructor, scope);
1426
1427 if let Some(locked_key) = locked_key_opt {
1428 assign_value(&locked_key, true, Some(Scope::Global));
1429 }
1430}
1431
1432fn env_hook_invocation(name: &str, point: &str) -> Option<Tokens> {
1436 let use_hook = T_CS!("\\UseHook");
1437 lookup_meaning(&use_hook)?;
1438 let mut toks = vec![use_hook, T_BEGIN!()];
1439 toks.extend(ExplodeText!(format!("env/{name}/{point}")));
1440 toks.push(T_END!());
1441 Some(Tokens::new(toks))
1442}
1443
1444pub const END_HOOKS_RAN: &str = "lx@env@end@hooks@ran";
1447
1448pub fn environment_end_hooks(name: &str, end_hook: Option<&Tokens>) -> Vec<Tokens> {
1452 let mut hooks = Vec::new();
1453 if let Some(code) = lookup_tokens(&s!("@environment@{name}@atend")) {
1454 hooks.push(code);
1455 }
1456 if env_hook_has_code(name, "end")
1457 && let Some(hook) = end_hook
1458 .cloned()
1459 .or_else(|| env_hook_invocation(name, "end"))
1460 {
1461 hooks.push(hook);
1462 }
1463 hooks
1464}
1465
1466pub fn set_currenvir(body: Tokens) -> Result<()> {
1470 thread_local! {
1471 static ON_LINE_PREFIX: Vec<Token> = " on input line "
1473 .chars()
1474 .map(|c| match c {
1475 ' ' => T_SPACE!(),
1476 _ => Token::new(c.encode_utf8(&mut [0; 4]), Catcode::LETTER),
1477 })
1478 .collect();
1479 }
1480 def_macro(
1481 T_CS!("\\@currenvir"),
1482 None,
1483 Some(ExpansionBody::Tokens(body)),
1484 None,
1485 )?;
1486 let on_line = T_CS!("\\on@line");
1487 let line = if x_equals(&on_line, &T_CS!("\\lx@kernel@on@line")) {
1490 let from_line = gullet::get_input_locator().from_line;
1491 let mut line = ON_LINE_PREFIX.with(Vec::clone);
1492 for digit in from_line.to_string().chars() {
1493 line.push(Token::new(digit.encode_utf8(&mut [0; 4]), Catcode::OTHER));
1494 }
1495 Some(Tokens::new(line))
1496 } else if lookup_meaning(&on_line).is_some() {
1497 Some(gullet::do_expand(Tokens::new(vec![on_line]))?)
1498 } else {
1499 None
1500 };
1501 if let Some(line) = line {
1502 def_macro(
1503 T_CS!("\\@currenvline"),
1504 None,
1505 Some(ExpansionBody::Tokens(line)),
1506 None,
1507 )?;
1508 }
1509 Ok(())
1510}
1511
1512pub fn env_hook_has_code(name: &str, point: &str) -> bool {
1516 hook_has_code(&format!("env/{name}/{point}"))
1517}
1518
1519fn hook_slot_names(hook: &str) -> (String, String, String) {
1521 (
1522 format!("\\g__hook_{hook}_code_prop"),
1523 format!("\\__hook_toplevel {hook}"),
1524 format!("\\__hook_next {hook}"),
1525 )
1526}
1527
1528fn hook_prop_has_code(prop: &Token) -> bool {
1531 with_macro_body(prop, |body| match body {
1532 Some(body) => {
1533 with_macro_body(&T_CS!("\\c_empty_prop"), |empty| empty != Some(body)).unwrap_or(true)
1534 },
1535 None => true,
1536 })
1537 .unwrap_or(false)
1538}
1539
1540pub fn hook_has_code(hook: &str) -> bool {
1544 if !l3_hooks_loaded() {
1545 return false;
1546 }
1547 let (prop, toplevel, next) = hook_slot_names(hook);
1548 Token::try_cs(prop).is_some_and(|tok| hook_prop_has_code(&tok))
1549 || Token::try_cs(toplevel).is_some_and(|tok| hook_slot_has_code(&tok))
1550 || Token::try_cs(next).is_some_and(|tok| hook_slot_has_code(&tok))
1551}
1552
1553pub struct HookStore {
1555 prop: Token,
1556 toplevel: Token,
1557 next: Token,
1558}
1559
1560impl HookStore {
1561 pub fn new(hook: &str) -> Self {
1562 let (prop, toplevel, next) = hook_slot_names(hook);
1563 HookStore {
1564 prop: T_CS!(prop),
1565 toplevel: T_CS!(toplevel),
1566 next: T_CS!(next),
1567 }
1568 }
1569
1570 pub fn from_tokens(prop: Token, toplevel: Token, next: Token) -> Self {
1573 HookStore { prop, toplevel, next }
1574 }
1575
1576 pub fn has_code(&self) -> bool {
1581 if !l3_hooks_loaded() {
1582 return false;
1583 }
1584 hook_prop_has_code(&self.prop)
1585 || hook_slot_has_code(&self.toplevel)
1586 || hook_slot_has_code(&self.next)
1587 }
1588}
1589
1590pub fn hook_has_labelled_code(hook: &str, label: &str) -> bool {
1593 if !l3_hooks_loaded() {
1594 return false;
1595 }
1596 let (pair, sep) = (T_CS!("\\__prop_pair:wn"), T_CS!("\\s__prop"));
1597 with_macro_body(&T_CS!(s!("\\g__hook_{hook}_code_prop")), |prop| {
1598 let Some(prop) = prop else {
1599 return false;
1600 };
1601 let mut entries = prop.split(|t| *t == pair).skip(1);
1602 entries.any(|entry| {
1603 let key = entry
1604 .iter()
1605 .take_while(|t| **t != sep)
1606 .map(|t| t.to_string())
1607 .collect::<String>();
1608 key == label
1609 })
1610 })
1611 .unwrap_or(false)
1612}
1613
1614fn l3_hooks_loaded() -> bool {
1616 with_meaning(&T_CS!("\\hook_if_empty:nTF"), |meaning| meaning.is_some())
1617}
1618
1619pub fn hook_slot_has_code(cs: &Token) -> bool {
1621 with_macro_body(cs, |body| body.is_none_or(|body| !body.is_empty())).unwrap_or(false)
1623}
1624
1625fn with_macro_body<R>(cs: &Token, f: impl FnOnce(Option<&[Token]>) -> R) -> Option<R> {
1627 with_meaning(cs, |meaning| match meaning {
1628 Some(Stored::Expandable(code)) => Some(match code.get_expansion() {
1629 Some(ExpansionBody::Tokens(body)) => f(Some(body.unlist_ref())),
1630 Some(ExpansionBody::Closure(_)) => f(None),
1631 None => f(Some(&[])),
1632 }),
1633 _ => None,
1634 })
1635}
1636
1637pub fn hook_use_tokens(hook: &str, once: bool) -> Vec<Token> {
1642 if !l3_hooks_loaded() {
1643 return Vec::new();
1644 }
1645 let has_code = hook_has_code(hook);
1646 let plain_name = !hook.contains("./") && hook != "." && hook.trim() == hook;
1649 if !has_code && plain_name {
1650 if !once || hook_used_once(hook) {
1651 return Vec::new();
1652 }
1653 let mut toks = vec![T_CS!("\\__hook_use_once_set:n"), T_BEGIN!()];
1654 toks.extend(ExplodeText!(hook));
1655 toks.push(T_END!());
1656 return toks;
1657 }
1658 let mut toks = vec![
1659 T_CS!(if once {
1660 "\\UseOneTimeHook"
1661 } else {
1662 "\\UseHook"
1663 }),
1664 T_BEGIN!(),
1665 ];
1666 toks.extend(ExplodeText!(hook));
1667 toks.push(T_END!());
1668 toks
1669}
1670
1671fn hook_used_once(hook: &str) -> bool {
1673 let used = [T_LETTER!("I"), T_OTHER!("I")];
1675 with_macro_body(&T_CS!(s!("\\g__hook_{hook}_reversed_tl")), |body| {
1676 body.is_some_and(|body| body.first().is_some_and(|t| used.contains(t)))
1677 })
1678 .unwrap_or(false)
1679}
1680
1681fn environment_tex_group(key: &str, declared: TexGroup) -> TexGroup {
1685 if lookup_value(key).is_none() {
1686 return declared;
1687 }
1688 TexGroup::from_name(&lookup_string(key)).unwrap_or(declared)
1689}
1690
1691pub fn def_environment(
1704 name: String,
1705 paramlist: Option<Parameters>,
1706 compiled_replacement: Option<ReplacementClosure>,
1707 mut options: ConstructorOptions,
1708) {
1709 if provide_only_declines(&T_CS!(s!("\\begin{{{name}}}"))) {
1711 return;
1712 }
1713 let begin_name = s!("\\begin{{{name}}}");
1715 let end_name = s!("\\end{{{name}}}");
1716 let mut before_digest_env: Vec<BeforeDigestClosure> = Vec::new();
1717
1718 let mode = match options.mode.as_deref() {
1722 None | Some("text") => Some("restricted_horizontal".to_string()),
1723 _ => options.mode,
1724 };
1725 let declared_mode = DeclaredMode {
1726 mode: mode.as_deref().map(arena::pin),
1727 enter_horizontal: options.enter_horizontal,
1728 leave_horizontal: options.leave_horizontal,
1729 bounded: false,
1730 require_math: options.require_math,
1731 forbid_math: options.forbid_math,
1732 restricted_box: false,
1734 };
1735
1736 if declared_mode.require_math {
1737 let require_name = begin_name.clone();
1738 let require_math_closure = before_digest_simple!({ requireMath!(require_name) });
1739 before_digest_env.push(require_math_closure);
1740 }
1741 if declared_mode.forbid_math {
1742 let forbid_name = begin_name.clone();
1743 let forbid_math_closure = before_digest_simple!({ forbidMath!(forbid_name) });
1744 before_digest_env.push(forbid_math_closure);
1745 }
1746 let begin_frame_end = T_CS!(end_name.as_str());
1747 let tex_group = options.tex_group;
1748 let tex_group_key = s!("\\begin{{{name}}}:tex_group");
1751 let begin_tex_group_key = tex_group_key.clone();
1752 let bgroup_closure = before_digest_simple!({
1753 bgroup();
1754 assign_frame_value_sym(crate::pin!("lx@env@begin@end"), begin_frame_end);
1761 let kind = environment_tex_group(&begin_tex_group_key, tex_group);
1762 if kind != TexGroup::None {
1763 assign_frame_value_sym(crate::pin!("lx@env@tex@group"), kind.as_str());
1764 }
1765 });
1766 before_digest_env.push(bgroup_closure);
1767 let env_name = name.clone();
1773 let currenvir_closure = before_digest_simple!({
1774 set_currenvir(mouth::tokenize_internal(TeXString::assembled(
1781 env_name.clone(),
1782 )))?;
1783 });
1784 before_digest_env.push(currenvir_closure);
1785 let atbegin_key = s!("@environment@{name}@atbegin");
1786 let begin_hook_tokens = env_hook_invocation(&name, "begin");
1790 let begin_hook_name = name.clone();
1791 let atbegin_hook_closure = before_digest_simple!({
1792 let mut boxes = Vec::new();
1793 if let Some(b) = lookup_tokens(&atbegin_key) {
1794 boxes.push(digest_hook_code(b.unlist())?);
1795 }
1796 if let Some(hook) = begin_hook_tokens.clone()
1797 && env_hook_has_code(&begin_hook_name, "begin")
1798 {
1799 boxes.push(digest_hook_code(hook.unlist())?);
1800 }
1801 boxes
1802 });
1803
1804 before_digest_env.push(atbegin_hook_closure);
1805 if declared_mode.enter_horizontal {
1806 before_digest_env.push(before_digest_simple!({
1807 enter_horizontal();
1808 }));
1809 }
1810 if declared_mode.leave_horizontal {
1811 before_digest_env.push(before_digest_simple!({
1812 leave_horizontal()?;
1813 }));
1814 }
1815 if let Some(ref mode) = mode {
1821 let bmode = mode.clone();
1822 let mode_end = T_CS!(end_name.as_str());
1823 let mode_closure = before_digest_simple!({
1824 if environment_frame_under_hook_groups(&mode_end, &bmode).is_some() {
1825 begin_mode_under_hook_groups(&bmode, &mode_end)?;
1826 } else {
1827 begin_mode_opt(&bmode, true)?;
1828 }
1829 });
1830 before_digest_env.push(mode_closure);
1831 }
1832 let env_name = name.clone();
1833 let env_end = T_CS!(end_name.as_str());
1834 let env_mode = mode.clone().unwrap_or_default();
1835 before_digest_env.push(before_digest_simple!({
1836 match environment_frame_under_hook_groups(&env_end, &env_mode) {
1838 Some(frame) if is_value_bound("BOUND_MODE", Some(frame)) => bind_value_in_frame(
1839 "current_environment",
1840 frame,
1841 Stored::String(arena::pin(&env_name)),
1842 ),
1843 _ => assign_value_sym(crate::pin!("current_environment"), env_name.clone(), None),
1844 }
1845 }));
1846
1847 match options.font {
1848 Some(FontDirective::Asset(chosen_font)) => {
1849 let merge_font_closure = before_digest_simple!({
1852 merge_font_ref(&chosen_font);
1853 });
1854 before_digest_env.push(merge_font_closure);
1855 },
1856 Some(FontDirective::Closure(font_closure)) => {
1857 let execute_font_closure = before_digest_simple!({
1858 merge_font(font_closure(None)?);
1859 });
1860 before_digest_env.push(execute_font_closure);
1861 },
1862 None => {},
1863 }
1864 let bare_before_digest = options.before_digest.clone();
1873 before_digest_env.extend(options.before_digest);
1874
1875 let bare_after_digest_begin = options.after_digest_begin.clone();
1878 if tex_group == TexGroup::Box {
1883 let box_key = tex_group_key.clone();
1884 options.after_digest_body.insert(
1885 0,
1886 after_digest_simple!(whatsit, {
1887 if crate::document::field_box_marks_live()
1888 && environment_tex_group(&box_key, TexGroup::Box) == TexGroup::Box
1889 {
1890 crate::document::field_box_whatsit(whatsit);
1891 }
1892 }),
1893 );
1894 }
1895 let bare_after_digest_body = options.after_digest_body.clone();
1896 let bare_before_construct = options.before_construct.clone();
1897 let bare_after_construct = options.after_construct.clone();
1898 let bare_sizer = options.sizer.clone();
1899 let bare_reversion = options.reversion.clone();
1900 let bare_alias = options.alias.clone();
1901
1902 let push_frame_closure = Rc::new(|_document: &mut Document, _whatsit: &Whatsit| {
1903 push_frame();
1904 Ok(())
1905 });
1906 let mut before_construct_with_frame: Vec<ConstructionClosure> = vec![push_frame_closure];
1907 before_construct_with_frame.extend(options.before_construct);
1908
1909 let mut after_construct_with_frame: Vec<ConstructionClosure> = options.after_construct;
1910
1911 let pop_frame_closure = Rc::new(|_document: &mut Document, _whatsit: &Whatsit| {
1912 pop_frame()?;
1913 Ok(())
1914 });
1915 after_construct_with_frame.push(pop_frame_closure);
1916
1917 let paramlist_skips = match paramlist {
1921 Some(ref pl) if pl.get_num_args() > 0 => {
1922 let skip_spaces_param = Parameter {
1923 novalue: true,
1924 name: pin!("SkipSpaces"),
1925 spec: pin!("SkipSpaces"),
1926 reader: Rc::new(|_inner, _extra| {
1927 gullet::skip_spaces()?;
1928 Ok(ArgWrap::None)
1929 }),
1930 ..Parameter::default()
1931 };
1932 let mut params = vec![skip_spaces_param];
1933 params.extend(pl.get_parameters().iter().cloned());
1934 Some(Parameters::new(params))
1935 },
1936 _ => paramlist.clone(),
1937 };
1938
1939 let begin_name_constructor = Rc::new(Constructor {
1940 origin: crate::definition::origin::current_origin(),
1941 cs: T_CS!(begin_name),
1942 paramlist: paramlist_skips,
1943 replacement: compiled_replacement.clone(),
1944 nargs: options.nargs,
1945 before_digest: before_digest_env,
1946 after_digest: options.after_digest_begin,
1947 after_digest_body: options.after_digest_body,
1948 before_construct: before_construct_with_frame,
1949 after_construct: after_construct_with_frame,
1951 capture_body: true,
1952 properties: options.properties.clone(),
1953 sizer: infer_sizer(options.sizer.as_ref(), options.reversion.as_ref()),
1957 reversion: options.reversion,
1958 alias: options.alias,
1959 declared_mode: Some(declared_mode),
1960 font: None,
1961 halign_primitive: false,
1962 template: None,
1963 salvage_end: Some((T_CS!(end_name.as_str()), options.after_digest.clone())),
1964 salvage_close: options.salvage_close.clone(),
1965 });
1966 install_definition(begin_name_constructor, options.scope);
1967
1968 let mut after_digest_env = options.after_digest.clone();
1969 let name_clone = name.clone();
1970 let end_name_clone = end_name.clone();
1971 let unexpected_end_closure = after_digest_simple!(_whatsit, {
1972 let env = lookup_string_from_sym(crate::pin!("current_environment"));
1973 if env.is_empty() || name_clone != env {
1974 let message1 = s!("Can't close environment {};", name_clone);
1977 let message2 = s!(
1978 "Current are: {}",
1979 with_stacked_values_sym(crate::pin!("current_environment"), |vals| vals
1980 .iter()
1981 .map(|x| s!("{:?}", x))
1982 .collect::<Vec<String>>()
1983 .join(", "))
1984 );
1985 Error!("unexpected", end_name_clone, message1, message2);
1986 }
1987 Ok(Vec::new())
1988 });
1989 after_digest_env.push(unexpected_end_closure);
1990
1991 match mode {
1992 Some(ref emode) => {
1993 let emode = emode.clone();
1994 let own_end = T_CS!(end_name.as_str());
1995 let own_name = name.clone();
1996 let emode_closure = Rc::new(move |_whatsit: &mut Whatsit| {
1997 if end_environment_over_plain_groups(&own_name, own_end)? {
2000 return Ok(Vec::new());
2001 }
2002 end_mode(&emode)?;
2011 Ok(Vec::new())
2012 });
2013 after_digest_env.push(emode_closure);
2014 },
2015 None => {
2016 let egroup_closure = Rc::new(|_whatsit: &mut Whatsit| {
2017 egroup()?;
2018 Ok(Vec::new())
2019 });
2020 after_digest_env.push(egroup_closure);
2021 },
2022 };
2023
2024 let (mut before_digest_for_endenv, before_digest_end_clone) = {
2025 let cloned = options.before_digest_end.clone();
2026 (options.before_digest_end, cloned)
2027 };
2028 let end_hook_tokens = env_hook_invocation(&name, "end");
2031 let end_hook_name = name.clone();
2032 let atend_hook_closure = before_digest_simple!({
2033 if environment_ended_by_group() || environment_end_hooks_ran() {
2037 Vec::new()
2038 } else {
2039 environment_end_hooks(&end_hook_name, end_hook_tokens.as_ref())
2041 .into_iter()
2042 .map(|hook| digest_hook_code(hook.unlist()))
2043 .collect::<Result<Vec<_>>>()?
2044 }
2045 });
2046 before_digest_for_endenv.push(atend_hook_closure);
2047
2048 let end_envname_constructor = Rc::new(Constructor {
2049 cs: T_CS!(end_name),
2050 replacement: None,
2051 paramlist: None,
2052 before_digest: before_digest_for_endenv,
2053 after_digest: after_digest_env,
2054 ..Constructor::default() });
2056 install_definition(end_envname_constructor, options.scope);
2057
2058 let mut before_digest_bare: Vec<BeforeDigestClosure> = Vec::new();
2061 let bare_frame_end = T_CS!(s!("\\lx@env@bare@end@{}", &name));
2067 let bare_end_alias = bare_frame_end;
2068 let bare_frame_shown_end = T_CS!(s!("\\end{}", &name));
2069 let bare_frame_shown = T_CS!(s!("\\{}", &name));
2071 before_digest_bare.push(before_digest_simple!({
2072 bgroup();
2073 assign_frame_value_sym(crate::pin!("lx@env@bare@end"), bare_frame_end);
2074 assign_frame_value_sym(crate::pin!("lx@env@bare@end@shown"), bare_frame_shown_end);
2075 assign_frame_value_sym(crate::pin!("lx@env@bare@shown"), bare_frame_shown);
2076 let kind = environment_tex_group(&tex_group_key, tex_group);
2077 if kind != TexGroup::None {
2078 assign_frame_value_sym(crate::pin!("lx@env@tex@group"), kind.as_str());
2079 }
2080 }));
2081 if declared_mode.enter_horizontal {
2082 before_digest_bare.push(before_digest_simple!({
2083 enter_horizontal();
2084 }));
2085 }
2086 if declared_mode.leave_horizontal {
2087 before_digest_bare.push(before_digest_simple!({
2088 leave_horizontal()?;
2089 }));
2090 }
2091 if let Some(ref bmode) = mode {
2092 let bmode = bmode.clone();
2093 before_digest_bare.push(before_digest_simple!({
2094 begin_mode_opt(&bmode, true)?;
2095 }));
2096 }
2097 before_digest_bare.extend(bare_before_digest);
2102 let push_frame_bare = Rc::new(|_document: &mut Document, _whatsit: &Whatsit| {
2103 push_frame();
2104 Ok(())
2105 });
2106 let pop_frame_bare = Rc::new(|_document: &mut Document, _whatsit: &Whatsit| {
2107 pop_frame()?;
2108 Ok(())
2109 });
2110 let mut before_construct_bare: Vec<ConstructionClosure> = vec![push_frame_bare];
2113 before_construct_bare.extend(bare_before_construct);
2114 let mut after_construct_bare: Vec<ConstructionClosure> = bare_after_construct;
2115 after_construct_bare.push(pop_frame_bare);
2116 let name_constructor = Rc::new(Constructor {
2117 origin: crate::definition::origin::current_origin(),
2118 cs: T_CS!(s!("\\{}", &name)),
2119 paramlist,
2120 replacement: compiled_replacement,
2121 nargs: options.nargs,
2122 capture_body: true,
2123 properties: options.properties.clone(),
2124 before_digest: before_digest_bare,
2125 after_digest: bare_after_digest_begin,
2126 after_digest_body: bare_after_digest_body,
2127 before_construct: before_construct_bare,
2128 after_construct: after_construct_bare,
2129 sizer: infer_sizer(bare_sizer.as_ref(), bare_reversion.as_ref()),
2130 reversion: bare_reversion,
2131 alias: bare_alias,
2132 declared_mode: Some(declared_mode),
2133 font: None,
2134 halign_primitive: false,
2135 template: None,
2136 salvage_end: Some((T_CS!(s!("\\end{}", &name)), options.after_digest.clone())),
2137 salvage_close: options.salvage_close.clone(),
2138 });
2139 install_definition(name_constructor, options.scope);
2140 let end_name = s!("\\end{}", &name);
2141 let mut after_digest_end = options.after_digest;
2142 match mode {
2144 Some(ref emode) => {
2145 let emode = emode.clone();
2146 let own_end = end_name.clone();
2157 after_digest_end.push(Rc::new(move |_whatsit: &mut Whatsit| {
2158 let owns_top_frame = [
2159 "lx@env@ended@by@group",
2160 "lx@env@bare@end",
2161 "lx@env@begin@end",
2162 ]
2163 .iter()
2164 .any(|key| is_value_bound(key, Some(0)));
2165 if owns_top_frame {
2166 end_mode(&emode)?;
2167 } else {
2168 Warn!(
2169 "unexpected",
2170 T_CS!(own_end.as_str()),
2171 s!("{own_end} without an environment open: no environment frame to end")
2172 );
2173 }
2174 Ok(Vec::new())
2175 }));
2176 },
2177 None => {
2178 },
2181 };
2182
2183 let end_cs = T_CS!(end_name);
2185 let end_name_constructor = Constructor {
2186 cs: end_cs,
2187 paramlist: None,
2188 replacement: None,
2189 before_digest: before_digest_end_clone,
2190 after_digest: after_digest_end,
2191 ..Constructor::default()
2192 };
2193 install_definition(Rc::new(end_name_constructor), options.scope);
2194 let_i(&bare_end_alias, &end_cs, options.scope);
2195
2196 if options.locked {
2197 assign_value(
2198 &s!("\\begin{{{}}}:locked", &name),
2199 true,
2200 Some(Scope::Global),
2201 );
2202 assign_value(&s!("\\end{{{}}}:locked", &name), true, Some(Scope::Global));
2203 assign_value(&s!("\\{}:locked", &name), true, Some(Scope::Global));
2204 assign_value(&s!("\\end{}:locked", &name), true, Some(Scope::Global));
2205 }
2206}
2207
2208pub fn get_xmarg_id() -> Result<Tokens> {
2214 step_counter("@lx@xmarg", true)?;
2219 def_macro(
2220 T_CS!("\\@@lx@xmarg@ID"),
2221 None,
2222 Tokens!(Explode!(
2223 lookup_register("\\c@@lx@xmarg", Vec::new())?
2224 .unwrap()
2225 .value_of()
2226 )),
2227 Some(ExpandableOptions {
2228 scope: Some(Scope::Global),
2229 ..ExpandableOptions::default()
2230 }),
2231 )?;
2232 gullet::do_expand(T_CS!("\\the@lx@xmarg@ID"))
2233}
2234
2235type ArgsUnpacked = Vec<Option<Tokens>>;
2236pub fn dualize_arglist(
2252 presentation: &str,
2253 args: Vec<Option<Tokens>>,
2254) -> Result<(ArgsUnpacked, ArgsUnpacked)> {
2255 let mut used = HashMap::default();
2256 for cap in ARG_HOLE.captures_iter(presentation) {
2257 let argi = cap.get(1).unwrap().as_str();
2259 let entry = used.entry(argi.parse::<usize>().expect(argi)).or_insert(0);
2260 *entry += 1;
2261 }
2262 let mut cargs = Vec::new();
2263 let mut pargs = Vec::new();
2264 for (index, arg_opt) in args.into_iter().enumerate() {
2265 match arg_opt {
2266 None => {
2267 pargs.push(None);
2268 cargs.push(None);
2269 },
2270 Some(arg) if arg.unlist_ref().is_empty() => {
2271 pargs.push(Some(arg.clone()));
2272 cargs.push(Some(arg));
2273 },
2274 Some(arg_toks) => {
2275 if used.get(&(1 + index)).unwrap_or(&0) > &0 {
2276 let id = get_xmarg_id()?;
2278 pargs.push(Some(Tokens!(
2279 T_CS!("\\lx@xmarg"),
2280 T_BEGIN!(),
2281 id.clone().unlist(),
2282 T_END!(),
2283 T_BEGIN!(),
2284 arg_toks.unlist(),
2285 T_END!()
2286 ))); cargs.push(Some(Tokens!(
2288 T_CS!("\\lx@xmref"),
2289 T_BEGIN!(),
2290 id.unlist(),
2291 T_END!()
2292 )));
2293 } else {
2294 let id = get_xmarg_id()?;
2296 cargs.push(Some(Tokens!(
2297 T_CS!("\\lx@xmarg"),
2298 T_BEGIN!(),
2299 id.clone().unlist(),
2300 T_END!(),
2301 T_BEGIN!(),
2302 arg_toks.unlist(),
2303 T_END!()
2304 )));
2305 pargs.push(Some(Tokens!(
2306 T_CS!("\\lx@xmref"),
2307 T_BEGIN!(),
2308 id.unlist(),
2309 T_END!()
2310 )));
2311 }
2312 },
2313 }
2314 }
2315 Ok((cargs, pargs))
2316}
2317
2318pub enum MathPresentation {
2322 Text(String),
2323 Tokens(Tokens),
2324}
2325impl From<String> for MathPresentation {
2326 fn from(text: String) -> Self { MathPresentation::Text(text) }
2327}
2328impl From<&str> for MathPresentation {
2329 fn from(text: &str) -> Self { MathPresentation::Text(text.to_string()) }
2330}
2331impl From<Tokens> for MathPresentation {
2332 fn from(tokens: Tokens) -> Self { MathPresentation::Tokens(tokens) }
2333}
2334
2335pub fn def_math(
2351 cs: Token,
2352 paramlist: Option<Parameters>,
2353 presentation: impl Into<MathPresentation>,
2354 mut options: MathPrimitiveOptions,
2355) -> Result<()> {
2356 if provide_only_declines(&cs) {
2357 return Ok(());
2358 }
2359 let presentation_in = presentation.into();
2360 let presentation = match &presentation_in {
2363 MathPresentation::Text(text) => text.clone(),
2364 MathPresentation::Tokens(tokens) => tokens.to_string(),
2365 };
2366 let nargs = match paramlist {
2370 Some(ref plist) => plist.get_num_args(),
2371 None => 0,
2372 };
2373 let csname = cs.with_str(ToString::to_string);
2374 let name_opt = {
2375 let name = match options.name {
2376 Some(ref name) => Cow::Owned(name.to_owned()),
2377 None => {
2378 let mut inferred_name = match options.alias {
2379 Some(ref alias) => Cow::Owned(alias.to_owned()),
2380 None => Cow::Borrowed(&csname),
2381 };
2382 if inferred_name.starts_with('\\') {
2383 inferred_name = Cow::Owned(inferred_name.replacen('\\', "", 1))
2384 }
2385 inferred_name
2386 },
2387 };
2388 let meaning_check = options
2389 .meaning
2390 .as_ref()
2391 .map_or_else(|| Cow::Owned(String::new()), Cow::Borrowed);
2392 let same_as_presentation =
2395 matches!(&presentation_in, MathPresentation::Text(text) if *text == *name);
2396 if same_as_presentation || (name.is_empty()) || *name == *meaning_check {
2397 None
2398 } else {
2399 Some(name.into_owned())
2400 }
2401 };
2402 options.name = name_opt;
2403 if nargs == 0 && options.role.is_none() {
2404 options.role = Some(String::from("UNKNOWN"))
2405 }
2406 if nargs > 0 && options.operator_role.is_none() {
2407 options.operator_role = Some(String::from("UNKNOWN"))
2408 }
2409 if options.hide_content_reversion {
2410 options.revert_as = Some(Cow::Borrowed("context"));
2411 }
2412
2413 let locked = options.locked;
2414 if csname.len() == 1 {
2419 let mut math_attr_hash: HashMap<String, String> = HashMap::default();
2420 transfer_opt_default!(name, options, math_attr_hash);
2421 transfer_opt_default!(meaning, options, math_attr_hash);
2422 transfer_opt_default!(omcd, options, math_attr_hash);
2423 transfer_opt_default!(decl_id, options, math_attr_hash);
2424 transfer_opt_default!(role, options, math_attr_hash);
2425 transfer_opt_default!(replace, options, math_attr_hash);
2426 transfer_opt_default!(mathstyle, options, math_attr_hash);
2427 transfer_opt_default!(stretchy, options, math_attr_hash);
2428 assign_value(
2429 &s!("math_token_attributes_{}", csname),
2430 math_attr_hash,
2431 Some(Scope::Global),
2432 );
2433 }
2434 else if match &presentation_in {
2439 MathPresentation::Text(text) => HAS_ARG_OR_CS.is_match(text),
2440 MathPresentation::Tokens(tokens) => tokens
2441 .unlist_ref()
2442 .iter()
2443 .any(|t| matches!(t.get_catcode(), Catcode::ARG | Catcode::PARAM)),
2444 } {
2445 let presentation = match presentation_in {
2446 MathPresentation::Tokens(tokens) => tokens.untex(),
2447 MathPresentation::Text(text) => text,
2448 };
2449 def_math_dual(cs, paramlist, presentation, options)?;
2450 }
2451 else if let MathPresentation::Tokens(tokens) = &presentation_in
2454 && tokens.unlist_ref().iter().any(Token::is_executable)
2455 {
2456 def_math_wrapped(cs, tokens.clone(), options)?;
2457 }
2458 else if nargs == 0 && !options.has_complex_option() {
2461 def_math_primitive(cs, paramlist, presentation, options);
2462 } else {
2463 def_math_constructor(cs, paramlist, presentation, options)?;
2464 }
2465 if locked {
2466 assign_value(&format!("{csname}:locked"), true, Some(Scope::Global));
2467 }
2468 Ok(())
2469}
2470
2471fn transfer_common_constructor_options(
2473 cs: &Token,
2474 presentation: &str,
2475 options: MathPrimitiveOptions,
2476 cons: &mut Constructor,
2477) {
2478 let cs_str = cs.with_str(ToString::to_string);
2479 let mut properties = options.to_hash_stored();
2480 if matches!(
2484 options.operator_role.as_deref(),
2485 Some("OVERACCENT" | "UNDERACCENT")
2486 ) {
2487 properties.insert("accent", Stored::from(presentation.to_string()));
2488 }
2489 cons.alias = Some(options.alias.unwrap_or_else(|| cs_str.clone()));
2490 if let Some(sizer) = infer_sizer(options.sizer.as_ref(), options.reversion.as_ref()) {
2491 cons.sizer = Some(sizer);
2492 }
2493 if let Some(reversion) = options.reversion {
2494 cons.reversion = Some(reversion);
2495 }
2496 let declared_mode = DeclaredMode {
2506 bounded: !options.nogroup,
2507 require_math: true,
2508 ..DeclaredMode::default()
2509 };
2510 cons.declared_mode = Some(declared_mode);
2511 let mut before_digest_closures: Vec<BeforeDigestClosure> = vec![before_digest_simple!({
2512 requireMath!(cs_str);
2513 })];
2514 if declared_mode.bounded {
2515 before_digest_closures.push(before_digest_simple!({
2516 bgroup();
2517 }));
2518 }
2519 let records_absorb_locator = options.absorb_warning.is_some();
2525 if records_absorb_locator {
2526 before_digest_closures.push(before_digest_simple!({
2527 assign_value(
2528 crate::document::ABSORB_WARNING_LOCATOR_PROPERTY,
2529 Stored::from(gullet::get_locator()),
2530 Some(Scope::Local),
2531 );
2532 }));
2533 }
2534 if let Some(font) = options.font {
2536 before_digest_closures.push(before_digest_simple!({
2537 merge_font((*font.get_font(None)?).clone());
2538 }));
2539 }
2540 before_digest_closures.extend(options.before_digest);
2541 cons.before_digest = before_digest_closures;
2542 let mut after_digest_closures = options.after_digest;
2546 if options.variablesize_op {
2548 after_digest_closures.push(after_digest_simple!(_args, {
2549 let state_font = lookup_font().unwrap();
2550 let is_display = state_font
2551 .get_mathstyle()
2552 .is_some_and(|s| s.as_ref() == "display");
2553 let mathstyle = if is_display { "display" } else { "text" };
2554 _args.set_property("mathstyle", Stored::from(mathstyle.to_string()));
2555 }));
2556 }
2557 if records_absorb_locator {
2558 after_digest_closures.push(after_digest_simple!(_args, {
2559 if let Some(locator) = lookup_value(crate::document::ABSORB_WARNING_LOCATOR_PROPERTY) {
2560 _args.set_property(crate::document::ABSORB_WARNING_LOCATOR_PROPERTY, locator);
2561 }
2562 }));
2563 }
2564 if declared_mode.bounded {
2565 after_digest_closures.push(after_digest_simple!(_args, {
2566 egroup()?;
2567 }));
2568 }
2569 cons.after_digest = after_digest_closures;
2570 cons.before_construct = options.before_construct;
2571 cons.after_construct = options.after_construct;
2572 let presentation_for_font = presentation.to_owned();
2578 let mathstyle_for_font = options.mathstyle;
2579 let letters_class = options.letters_class;
2580 let dynamic_scriptpos = options.dynamic_scriptpos;
2584 cons.properties = Rc::new(move |_args| {
2585 let mut font = lookup_font().unwrap();
2586 let mut properties = properties.clone();
2587 if dynamic_scriptpos {
2588 let display = font
2589 .get_mathstyle()
2590 .is_some_and(|s| s.as_ref() == "display");
2591 let scriptpos = if display { "mid" } else { "post" };
2592 properties.insert("scriptpos", Stored::from(scriptpos.to_string()));
2593 }
2594 if let Some(ref mathstyle) = mathstyle_for_font {
2595 font = Rc::new(font.merge(Font {
2596 mathstyle: Some(Cow::Owned(mathstyle.clone())),
2597 ..Font::default()
2598 }));
2599 }
2600 let font = match letters_class {
2601 Some(class) => font.specialize_letters(&presentation_for_font, class),
2602 None => font.specialize(&presentation_for_font),
2603 };
2604 properties.insert("font", Stored::Font(Rc::new(font)));
2605 Ok(properties)
2606 });
2607}
2608
2609pub fn allocate_register(rtype: &str, cs: &str) -> Result<Option<String>> {
2615 let addr = match rtype {
2616 "\\count" => "\\count10",
2617 "\\dimen" => "\\count11",
2618 "\\skip" => "\\count12",
2619 "\\muskip" => "\\count13",
2620 "\\box" => "\\count14",
2621 "\\toks" => "\\count15",
2622 _ => "",
2623 };
2624 if !addr.is_empty() {
2625 if let Some(n) = lookup_number(addr) {
2627 let mut next = n.value_of() + 1;
2633 let mut loc = format!("{rtype}{next}");
2634 while is_value_bound(&loc, None) {
2635 next += 1;
2636 loc = format!("{rtype}{next}");
2637 }
2638 assign_value(addr, Number::new(next), Some(Scope::Global));
2639 Ok(Some(loc))
2640 } else {
2641 Ok(None)
2642 }
2643 } else {
2644 Error!(
2647 "misdefined",
2648 rtype,
2649 format!("Type {rtype} is not an allocated register type, for {cs}")
2650 );
2651 Ok(None)
2652 }
2653}
2654
2655fn size10_leading(size: f64) -> f64 {
2658 const LEADING: [(f64, f64); 11] = [
2659 (5.0, 6.0),
2660 (7.0, 8.0),
2661 (8.0, 9.5),
2662 (9.0, 11.0),
2663 (10.0, 12.0),
2664 (12.0, 14.0),
2665 (14.4, 18.0),
2666 (17.28, 22.0),
2667 (20.74, 25.0),
2668 (24.88, 30.0),
2669 (29.8, 30.0), ];
2671 LEADING
2672 .iter()
2673 .find(|(at, _)| (at - size).abs() < 0.01)
2674 .map_or(size * 1.2, |(_, leading)| *leading)
2675}