Skip to main content

latexml_core/binding/
preamble_commands.rs

1//! latex.ltx:9521-9522 `\gdef\do#1{\global\let#1\@notprerr}\@preamblecmds`: after `\begin{document}` each listed
2//! command IS `\@notprerr`, which raw code tests with `\ifx` (ltnews23.tex:42-43). LaTeXML also reads a package, class
3//! or sub-file preamble in the body (Perl's recovery for a body `\usepackage`, a binding's load, standalone and
4//! subfiles), which pdflatex never does: there the walk's commands are reopened, and disabled again after it. The walk
5//! keeps each meaning under `\lx@onlypreamble@<name>`; the State holds the list (OXIDIZED_DESIGN_DIVERGENCES #226).
6//! A binding's lock goes aside with its meaning: `\@notprerr` is no binding's, and the body's `\renewcommand` of it
7//! stands as in TeX (imsart.sty:1223 `\@onlypreamble\doi` over OmniBus's locked `\doi`, 2606.22730).
8use crate::{
9  common::{arena, store::Stored},
10  gullet::unread_after_current_file,
11  state::{
12    Scope, assign_meaning, assign_value, lookup_bool, lookup_bool_sym, lookup_meaning,
13    lookup_tokens, x_equals,
14  },
15  token::Token,
16  tokens::Tokens,
17};
18
19/// The commands the walk let to `\@notprerr`, in the walk's order.
20const DISABLED: &str = "lx@preamble@disabled";
21/// Set while the disabled commands are reopened (a body load or a sub-file preamble), so a nested one leaves them.
22const REOPENED: &str = "lx@preamble@reopened";
23/// Set while a sub-file's preamble holds the reopening ([`reopen_for_subfile_preamble`]).
24const SUBFILE: &str = "lx@preamble@subfile";
25
26fn saved_cs(cs: &Token) -> Token {
27  let name = cs.to_string();
28  T_CS!(s!("\\lx@onlypreamble@{}", name.trim_start_matches('\\')))
29}
30
31/// `\global\let<to><from>`, the engine's own write: no file's lock applies to the kernel's walk.
32fn global_let(to: &Token, from: &Token) {
33  assign_meaning(
34    to,
35    lookup_meaning(from).unwrap_or(Stored::None),
36    Some(Scope::Global),
37  );
38}
39
40/// The locks a binding sets on a name (`state::is_name_locked`); the ones qualifying them read nothing without these.
41const LOCKS: [&str; 2] = [":locked", ":locked@files"];
42
43/// Moves the locks `from` carries to `to`, as the walk moves its meaning (probe-only: a name never locked interns
44/// nothing).
45fn move_locks(from: &Token, to: &Token) {
46  let (from, to) = (from.to_string(), to.to_string());
47  for suffix in LOCKS {
48    if let Some(key) = arena::get_suffixed(&from, suffix)
49      && lookup_bool_sym(key)
50    {
51      assign_value(&s!("{from}{suffix}"), false, Some(Scope::Global));
52      assign_value(&s!("{to}{suffix}"), true, Some(Scope::Global));
53    }
54  }
55}
56
57fn let_notprerr(cs: &Token) {
58  let saved = saved_cs(cs);
59  global_let(&saved, cs);
60  move_locks(cs, &saved);
61  global_let(cs, &T_CS!("\\@notprerr"));
62}
63
64/// Whether the walk still holds `cs`: the body has not redefined it since (a document's `\renewcommand{\doi}`).
65fn held(cs: &Token) -> bool { x_equals(cs, &T_CS!("\\@notprerr")) }
66
67/// The walk's `\global\let<cs>\@notprerr`, its meaning kept for a later [`reopen_preamble_commands`].
68pub fn disable_preamble_command(cs: &Token) {
69  // (once: a second `\begin{document}` walks again, sect02.rs)
70  if held(cs) {
71    return;
72  }
73  let_notprerr(cs);
74  let mut list = lookup_tokens(DISABLED)
75    .map(Tokens::unlist)
76    .unwrap_or_default();
77  list.push(*cs);
78  assign_value(DISABLED, Tokens::new(list), Some(Scope::Global));
79}
80
81/// Give the disabled commands back their meanings and locks (a body load, a sub-file's preamble); false when there is
82/// nothing to reopen (still in the preamble, or reopened by an enclosing load). One the body has redefined since is
83/// the body's: the walk no longer holds it, and neither this nor the next walk touches it.
84pub fn reopen_preamble_commands() -> bool {
85  if lookup_bool(REOPENED) {
86    return false;
87  }
88  let Some(list) = lookup_tokens(DISABLED) else {
89    return false;
90  };
91  let list: Vec<Token> = list.unlist().into_iter().filter(held).collect();
92  for cs in &list {
93    let saved = saved_cs(cs);
94    global_let(cs, &saved);
95    move_locks(&saved, cs);
96  }
97  assign_value(DISABLED, Tokens::new(list), Some(Scope::Global));
98  assign_value(REOPENED, true, Some(Scope::Global));
99  true
100}
101
102/// The walk again over the reopened commands: what the load (re)defined is kept for the next reopening.
103pub fn close_preamble_commands() {
104  if !lookup_bool(REOPENED) {
105    return;
106  }
107  if let Some(list) = lookup_tokens(DISABLED) {
108    for cs in list.unlist_ref() {
109      let_notprerr(cs);
110    }
111  }
112  assign_value(REOPENED, false, Some(Scope::Global));
113}
114
115/// [`reopen_preamble_commands`] for a sub-file's preamble (standalone, subfiles): closed at its `\begin{document}` or,
116/// without one, where the sub-file ends (`\lx@subfile@preamble@end`, [`close_subfile_preamble`]).
117pub fn reopen_for_subfile_preamble() {
118  if reopen_preamble_commands() {
119    assign_value(SUBFILE, true, Some(Scope::Global));
120    unread_after_current_file(Tokens::new(vec![T_CS!("\\lx@subfile@preamble@end")]));
121  }
122}
123
124/// The close of the reopening a sub-file's preamble holds; false when it holds none (closed at its `\begin{document}`).
125pub fn close_subfile_preamble() -> bool {
126  if !lookup_bool(SUBFILE) {
127    return false;
128  }
129  assign_value(SUBFILE, false, Some(Scope::Global));
130  close_preamble_commands();
131  true
132}
133
134/// `\lx@subfile@preamble@end`: a sub-file that ends with no `\begin{document}` ends its preamble there (pdflatex:
135/// "File ended while scanning use of \sa@gobble").
136pub fn end_subfile_preamble() {
137  if close_subfile_preamble() {
138    assign_value("inPreamble", false, None);
139    assign_value("lx@subpreamble@begindocument", false, None);
140  }
141}
142
143/// [`reopen_preamble_commands`] for the extent of a load, closed when dropped (also on an Error's early return).
144pub struct ReopenedForLoad(bool);
145
146impl ReopenedForLoad {
147  pub fn new() -> Self { ReopenedForLoad(reopen_preamble_commands()) }
148}
149
150impl Default for ReopenedForLoad {
151  fn default() -> Self { Self::new() }
152}
153
154impl Drop for ReopenedForLoad {
155  fn drop(&mut self) {
156    if self.0 {
157      close_preamble_commands();
158    }
159  }
160}