Expand description
The Gullet is responsible for reading Tokens and other data from the Mouth
Structs§
- File
Hooks End - A content file read with latex.ltx’s file hooks (
content::input_content_with_file_hooks): its request, and whether its load pushed ltfilehook’s file-name stack, which its end pops (content::input_file_ended). - Gullet
- Input
Mark - A place in the input (
input_mark): how many mouths enclose it, the current mouth’s read position, its pushback’s length then, the mark’s serial on the mouth’s watch (PushbackWatch), and the pushback’s lastMARK_HELDtokens, the next to read last.Copy: a mark holds nothing on the heap, so the marks a ledger keeps (an author block’s each) cost what their number does, whatever the pushback holds (revRC1: a copy of the pushback per mark made 3,000 macro-held authors take 3.7 GB). - Mouth
Runtime - Number
Scan - RAII marker for a number/dimension/glue scan (see
NUMBER_SCAN_DEPTH). Every?-return and every unwind past a reader runs the drop, so the depth is back to what it was the moment the scan ends. The eTeX expression evaluator (etex.rs) takes one too, for its own inter-operand reads (etex.chscan_exprtreats a tab/row end the same). - Number
Scan Suspended - The guard
NumberScan::suspendreturns: restores the suspended depth. - Operand
Read - RAII marker for the read of a quantity’s operand head (
READING_OPERAND):scan_optional_signs’s, and the eTeX expression’s factor (etex.chscan_expr). - Read
Budget - What
read_budgetbegan; the budget is off once this is ended or dropped. - Read
Budget End - What
ReadBudget::endtells. - Scanner
Status Guard - Restores the enclosing
ScannerStatus(andwarning_index) when it drops, on every exit path of the scan that set it,?included. The runaway argument (argument_runaway) is scoped the same way: a scan starts without one, and the enclosing scan’s comes back when it ends. - Speculative
Digestion - A speculative digestion runs while this lives (
speculative_digestion).
Enums§
- Balanced
Boundary - What a balanced read (
read_balanced) does when it exhausts a mouth before the braces balance. - Expansion
Level - A directive describing to what degree a gullet reader should perform TeX’s expansion
- File
EndRecovery - What
recover_at_file_enddid. - Runaway
- Why a macro call’s arguments are abandoned (
argument_runaway). - Scanner
Status - What the scanner is reading, for the recovery TeX makes when a file ends in
the middle of it: tex.web §305
scanner_status(withwarning_index, the command it names). A scan that owns a status sets it for its duration withset_scanner_statusand restores the enclosing one after, as tex.web saves and restores it (§389macro_call, §473scan_toks); every nested read that sets none inherits it.recover_at_file_endconsults it.
Constants§
- CYCLE_
GUARD_ ACTIVATE_ GRAPHICS - Cycle-guard activation floor for graphics-heavy bindings (pgf/tikz/xy).
These packages legitimately expand 100M+ tokens; this floor sits above the
heaviest measured healthy graphics doc (1805.03265 tikz-cd ~155M) so they
stay out of the per-token fingerprint regime, while remaining far below the
1G
token_limitbackstop. Raised — never lowered — perraise_cycle_guard_activate. - DEFAULT_
TOKEN_ LIMIT - The runaway-token BACKSTOP’s baseline: real runaways are cut far earlier
by the cycle guards / pushback limit / byte budget, so erring high costs
no detection latency. The heaviest measured legit arXiv paper is
math0402448 (amsart + xy-pic, 80.2M end-of-run progress under the
2026-06-10 all-three-reader-loop accounting; the old “80M” figure
predated that multi-counting) and the former 400M ceiling was 5× that —
but the TeX Live doc corpus goes higher with NO loop: tikzlings-doc
(scrartcl, ~250 raw-pgf animal pictures through tcolorbox listings,
each box typeset twice) completes at a measured 444.5M
(
Debug:gullet:progress, 2026-09-01, 30 KB main source so the per-byte scaling never engaged), and finite O(n²) macro work goes further still: circularglyphs-sample (xstring\StrSubstitute×34 over 600-char phrases, ~2.5G) and source2e (l3doc crossrefs over 46k codelines, ~2G) both COMPLETE underLATEXML_TOKEN_LIMIT=0within the 300 s budget where Perl times out, yet died at the former 1G with a false “infinite loop?”. 4G; raised, never lowered (a genuine loop is still bounded — by this ceiling, by the--timeoutwall clock, by the cycle guards, and by the RSS cap).LATEXML_TOKEN_LIMIToverrides (0 disables). Book-scale sources raise it proportionally per conversion — seescale_token_limit_to_source. 20e9 = the 300 s sweep wall at the measured 65 M tok/s ceiling: at 4e9 the backstop fired at 61 s on lie-hasse’s legitimate E8 poset figure (completes at ~8e9 in 124 s with a 304 KB picture; pdflatex 83 s) and mislabelled it “infinite loop” with a 39-byte XML. True loops are still bounded by the wall clock, the cycle guards and the RSS cap. - MAX_
IN_ OPEN - TeX’s limit on simultaneously open input files (
\inputfiles and\scantokenspseudo-files):max_in_open, texmf.cnf:868 (TL 2025; tex.web §328begin_file_readingchecksin_open = max_in_openbefore opening another).
Statics§
- CSNAME_
TRACE - Cached
LATEXML_CSNAME_TRACEflag + the shared lookahead dump used by both csname-assembly error sites: reads up to 40 tokens, prints them, and puts them back (a counted-read/retracting-unread round trip — align ledger symmetric). - TRACE_
GROUP_ END - Cached snapshot of
LXML_TRACE_GROUP_ENDenv var, sampled exactly once per process. Inliningstd::env::var(...)on the hotread_x_tokenpath was triggering SIGSEGVs in__GI_getenvunder concurrent test-thread execution: glibc’sgetenvwalks the process-globalenvironarray unprotected, and the volume of concurrent calls (millions/sec across N threads) made the unsafe concurrent walks visible. The fix is to read the env var ONCE at static-init time; subsequent checks are a free atomic load.
Functions§
- abandon_
argument_ at_ par - Abandon the call at the
\parjust read into its argument (is_par_ending_argument): the readers stop, andabandon_runaway_callreports it and puts the\parback (tex.web §396). - abandon_
runaway_ call - Abandon the call of
cswhose argument ran off the end of a file, given therunawaytokens it had read (ScannerStatusGuard::end_taking_runaway_argument). - argument_
ran_ off_ a_ file recover_at_file_endfor a reader of macro arguments only (a single token, a delimited argument; tex.web §392): whether the call is abandoned. At any other status such a reader keeps its own end-of-input behaviour.- argument_
runaway - Whether a macro argument has run off the end of a file and the call is to
be abandoned (see
FileEndRecovery::Abandoned); readers stop at once. - at_
end_ of_ all_ input - Return a (balanced) sequence tokens until a match against one of the Tokens in @delims.
- braced_
length_ evaluator - The braced-length evaluator, when the current document loaded calc.
- calc_
expressions_ active - Whether the current document loaded calc, whose seams
(
set_internal_dimension_fn,set_braced_length_fn) are then in force. - close_
mouth - consume_
pushback_ to - Consume the pushback down to its first
lentokens, as a native reader’s answer does (with_pushback); braces among them must balance, since the brace ledger counts none of them, read or not. - count_
reads - Count
readstokens as read, where a run’s reading is known without making it (the frontmatter’s rehearsal of a text it rehearsed before):progressstands where the run would leave it, its limits read again. - do_
expand - Fully expand
tokensand return the result, without digesting them. - do_
expand_ partially - As
do_expand, but stopping at the first unexpandable token of each branch (ExpansionLevel::Partial) instead of expanding to the bitter end. - expand_
as_ csname_ text - Fully expand
tokensas the name inside a\csname…\endcsname(\ifincsnametrue), the way LaTeX reads a file name:\set@curr@file(latex.ltx) expands\input’s argument within\csname, so an active character guarded by\ifincsnamekeeps its literal form there (underscore-ltx.sty’s_, utf8.def’s octets). - expand_
as_ file_ name - A file name as latex.ltx reads one (
\set@curr@file,\@kernel@make@file@csname, latex.ltx:9654, :19745-19747):\@firstofone#1strips the braces of a leading group (\include{{./x}}reads./x.tex; 2406.05605), then the name is expanded within\csname(expand_as_csname_text). - expand_
depth_ left - How many more levels of expansion recursion the guard of
read_x_tokenallows,usize::MAXif it is off. - expand_
once_ partial - Expand
token, just read, ONE level ifread_x_token(Some(false), ..)would expand it, pushing the expansion back onto the input, and report whether it did. A reader that must look at every token an expansion yields before expanding it further (the case changer’s l3text checks) steps with this; a token it leaves alone is still the caller’s to handle (unread it forread_x_tokento return, stub or resolve). - field_
cover_ of - What the invocation of a token with field provenance
prov(Token::prov) consumed of its field’s stored value, now that it read what it reads: its own position up to the next token of that value still to be read, if the pushback holds one (a primitive’s or a macro’s arguments:\hspace{1em},\\[2pt],$x$), else its own position alone. The pushback only: a field’s stored tokens are read from it (an expansion, a digested argument), never from a mouth, so nothing is read or tokenized. OXIDIZED_DESIGN #715. - fix_
token_ limit - The front end’s explicit token limit (
--token-limit): kept as given, asLATEXML_TOKEN_LIMITis, wherescale_token_limit_to_sourcewould raise a limit below the source’s scaled one. - flush
- Obscure, but the only way I can think of to End!! (see \bye or \end{document}) Flush all sources (close all pending mouth’s)
- flush_
mouth - This flushes a mouth so that it will be automatically closed, next time it’s read Corresponds to TeX’s \endinput
- get_
input_ locator \inputlineno‘s locator: the innermost TeX input level, past the token mouths anExpandopens (Perl’s are sourceless, Gullet.pm:150-156).\scantokens’ pseudo-file is a level that counts its own lines (eTeX’spseudo_startsetsline:=0, pdftex.web:38551), so it stops the walk though it reads no named source.- get_
location - Comment-oriented location string, based on
get_locator - get_
location_ opt - A message’s location (
Error/Warn,error::location_line): the innermost mouth reading a named source, past the token lists a binding digests (digest()’s “Anonymous String”), as Perl’sgetLocatorwalks past a sourceless mouth (Gullet.pm:150-162;\lx@empheq@box); elseget_locator_opt’s;Nonewhere it finds no mouth (a--preloaded binding, the dump load), where Perl’s message has noatline (Error.pm:623) instead ofLocator::default’s Rust file. A box’s locator staysget_locator_opt’s, which--source-mapreads. - get_
locator - Get the current location of input getting read
- get_
locator_ from_ start get_locator’s accurate-start sibling (§1, docs/performance/SOURCE_PROVENANCE.md): same mouthstack walk, but reads the mouth’sget_locator_from_start(from= the last token’s captured start) instead of the heuristicfrom. Used for the construct-START snapshot at constructor digest under--source-map.- get_
locator_ opt - After Perl’s
getLocator(Gullet.pm:150-162): the innermost mouth with a source, else the first mouth of the stack;Nonewhen there is neither (before the first mouth opens, or a sourceless one alone). Perl keeps the last mouth its walk examined, so a sourceless mouth alone reports its ownString; line …and an all-sourceless stack ends on the outermost mouth; here the first case has noatline (the binding machinery’s mouth, not the document’s, is the only one open) and the second takes the innermost (front()), as before. Porting Perl’s walk exactly is a logged follow-up (row R RHAILOCWALK); only the message text differs. - get_
pending_ comment - get_
source_ location - The location of the innermost mouth that reads a source (not a token string,
Anonymous String): where in the document a construct digested from a token list stands —\footnote{…}’s or\section{…}’s line, rather than nowhere. - gullet_
root - has_
more_ input - Check if there is more input to be read from the current mouth
- if_next
- in_
csname - True while a
\csname…\endcsnamename is being scanned. - in_
speculative_ digestion - Is a speculative digestion running (
speculative_digestion)? - initialize_
gullet - Initialize (or reset, if reentrant) a Gullet to its default empty state.
- input_
mark - Mark the input as it stands: everything still to be read now (
input_unread_since). What is pushed back after the mark (a macro’s expansion, unread on top of the pushback) is read before anything the mark holds. - input_
unread_ since - Whether none of the input
markheld has been read since it was taken (input_mark): its mouth is still open, has read no further, and its pushback still holds every token it held then (only what was pushed after the mark was read, or what a mouth opened since holds). Read-only, for an observer telling apart what a call’s expansion did from what the input after the call did (the frontmatter observer’s ledger, the title-page check’s document calls). The mouth’s watch tells how short its pushback has been since the mark (PushbackWatch): no shorter than the mark’s length, nothing it held was read; shorter by at mostMARK_HELDtokens, those read were put back if the slots hold the very tokens they held (same_token: a peek leaves the input unread); shorter still, it was read. Tokens read below the mark and others pushed in their place read as read, though the token now at the mark’s last slot equals the one it held — IEEEtran’s\IEEEauthorblockN{…}⏎\IEEEauthorblockA{…}, whose line-end space was read with\IEEEauthorblockAand its argument and whose expansion, longer, put another space there: its affiliation calls read as the author block’s own and were lost by the frontmatter emitter (2401.11731, 1801.03314). No token is copied but the held ones: a mark costs at most one run of the watch, a test a binary search of its runs. - insert_
par_ at_ extra_ brace - A macro’s argument scan met a
}(is_extra_brace_in_argument): “Argument of \x has an extra }”, the}put back, and the\parTeX inserts returned as the reader’s next token, the rest of the call read as a non-\longmacro’s (tex.web §395long_state:=call): a\pardelimiter takes it, any other reader ends the call (§396). - is_
column_ end - Is
tokenan alignment column end — a tab or a row end — and which one: theCOLUMN_ENDSentry (the token to act on, its keyword, whether it is hidden), or(token, "align", false)for a tab. - is_
extra_ brace_ in_ argument - Whether
token, read into a macro argument, is a}that ends the call (tex.web §392cur_tok<right_brace_limit, §395): a right brace met while a macro’s arguments are read, delimited or not. - is_
left_ brace - tex.web’s
cur_cmd=left_brace: a character of catcode 1, or a control sequence or active character\letto one (\bgroup). - is_
par_ ending_ argument - Whether
token, read into a macro argument, ends the call: tex.web §392/§399cur_tok=par_token— the control sequence namedpar, whatever it means (a\noexpanded one too) — while a non-\longmacro’s arguments are read. - is_
right_ brace - tex.web’s
cur_cmd=right_brace(§1068handle_right_brace): a character of catcode 2, or a control sequence or active character\letto one (\egroup). The closer that matchesis_left_brace’s opener: under\catcode<=1 \catcode\>=2,\hbox<…>is a box (2606.11726’s plain-TeX macros), where Perl’sdefined_as(T_END)knew only}. - is_
space_ or_ implicit_ space - Check if a token is a space token (catcode SPACE) or an “implicit space”
(a CS or ACTIVE token
\letto a space token). See TeXbook p269:<one optional space>absorbs both explicit and implicit spaces. (tex.web’scur_cmd=spacer.) - isolated_
input_ ends_ here - Whether the token just read ends an isolated reading context (
reading_from_mouth: a token list digested on its own, such as a constructor’s argument{$x}, which may come wrapped in a further brace pair): only}s left in its pushback and its mouth exhausted. A}read here is the argument’s own closing brace, which TeX strips with the argument — one end of a construct digested as a unit (stomach.rsformula_ends_with_its_unit, OXIDIZED_DESIGN #553).falsewhenever a mouth of its own is still open in the context. - mark_
everyeof_ mouth - Mark the CURRENT mouth as an eTeX file level whose end inserts the
\everyeoftoken list (seeMouthRuntime::insert_everyeof). Every\inputfile mouth is marked (content.rs::load_tex_content), and so is the\scantokenspseudo-file (etex.rs). - mark_
file_ hooks_ mouth - Mark the CURRENT mouth, a content file just opened, as one whose end runs
\InputIfFileExists’ code after\@@input(latex.ltx:19670-19673), decided when the file ends as TeX reads it then (content::input_file_ended). - mouth_
depth - The mouths open: the one in reading (
Gullet::runtime) and those under it.open_mouthpushes nothing on the stack when none is in reading, so the stack alone doesn’t count them. Apushback_lencompares only at one depth: a constructor digests its argument in a mouth of its own (a rehearsal’s notes,token::FieldNotesHook). - mouth_
is_ open - note_
missing_ argument - A required argument of
specwhose reader ran out: at the true end of all input Perl’s “Missing argument” Error (Parameter.pm:93-97), the call then running on the reader’s empty value; an isolated mouth’s end stays quiet. - note_
runaway_ tokens - A reader stopping at a runaway argument puts in front of the runaway
tokens the ones it had read itself, so that
abandon_runaway_callsees the argument as it was read: a delimited reader’s text before a brace group that ran off, then the group’s own. - open_
mouth - open_
mouth_ with open_mouth, choosing how a balanced read treats the new mouth’s end.- operand_
lookahead - The guards of a read ahead of a quantity’s operand that expands as the operand’s does: an assignment’s optional
=(tex.web §405scan_optional_equals), thebyof\advance,\multiplyand\divide(§1236scan_keyword), whose first non-matching token is the operand’s. Only whileOPERAND_VALUESholds values (the deposit). - peek_
nonspace_ remove - ltcmd’s
\__cmd_peek_nonspace_remove:NTF(latex.ltx:4475-4482): whether the next token past spaces meanstarget, peeked unexpanded; if so it goes with the spaces, else one explicit space per space taken goes back. - peek_
token - Perl: peekToken — peek at the next token without triggering alignment Sets ALIGN_STATE to 1000000 to suppress alignment template handling (Perl line 331-337)
- peek_
upcoming_ tokens - The tokens the current input holds next, without reading them: the pushback, next-read first, then the current
mouth’s next
max_linessource lines (at mostmax_charscharacters of them,Mouth::peek_text) tokenized by a scratch mouth under the current catcodes as the iterator is drawn on,max_tokensin all. Nothing is read, expanded or moved, so a catcode change the look-ahead runs past still applies to the text when it is really read. Only the current mouth: the input levels outside it are not reached. The cost is bounded by the limits, not by the length of the line or of the pending expansion. A look-ahead for a decision about what follows (stomach.rsformula_continues_past_par, OXIDIZED_DESIGN #553). - pushback_
holds_ nonspace - Read the next raw line (string); primarily to read from the Mouth, but keep any unread input! Whether the gullet’s unread (pushed-back) tokens include a non-space token.
- pushback_
is_ empty - Whether the input’s pushback is empty: no token of a field’s stored value is left to read (
field_cover_of). - pushback_
len - How many tokens the input’s pushback holds (
with_pushback): a macro’s expansion is being read while it holds more than it did before the expansion (a rehearsal’s notes,token::FieldNotesHook). - pushback_
text - The pending pushback as text, next-to-read first, left in place: what a raw
line reader would take before the mouth’s line (see
read_raw_line). - queue_
sizes - Queue sizes
(mouthstack, pending_comments)— pass-1 streaming telemetry. - raise_
cycle_ guard_ activate - Raise the cycle-guard activation floor for the current (thread-local) gullet,
only ever upward. Called from graphics package bindings (pgf/tikz/xy) whose
healthy expansion runs to 100M+ tokens — see
CYCLE_GUARD_ACTIVATE_GRAPHICS. Idempotent and order-independent: loading several graphics packages just re-asserts the same floor. The per-conversion reset (initialize_gullet) restores the default so the raise does not leak across documents. - read_
arg - Read and return a “normal” TeX argument
- read_
arg_ or_ none read_arg, orNonewhen the input ran out before the argument (PerlreadArg’s undef, Gullet.pm:735).- read_
balanced - Approximates TeX’s scan_toks (but doesn’t parse \def parameter lists) and only optionally requires the openning “{”.
- read_
balanced_ text - A balanced text: tex.web §473
scan_toks(false, xpand)(eTeXscan_general_text), read atabsorbingstatus for the command being executed (\write,\uppercase,\detokenize,\toks=, the pdfTeX texts …). A file that ends inside it ends the text there (§339). - read_
balanced_ with_ close read_balancedthat also hands back the CLOSE token that ended the group (Nonewhen the read ran out or found no opening brace). A delimited reader stores a matched group verbatim (tex.web §392-398macro_call’sstore_new_token(cur_tok)— the argument keeps the braces it was scanned with; the single-group outer-brace strip is §399-400, by catcode). Diverges from Perl’s canonicalT_END(Gullet.pm:661/674), OXIDIZED_DESIGN_DIVERGENCES #224. chemfig scans(…)submols with(/)given catcodes 1/2 (chemfig.tex:1315-1324) and a canonical}in their place re-tokenized as a real end-brace in the next\scantokens, unbalancing it (chemexec/chemnum, sweep 74).- read_
budget - A run of digestion’s limit on the tokens it reads, until
ReadBudget::end: the read past it fails, and so does each one after, with anErrorCategory::ReadBudgeterror that is logged nowhere and latches nothing, so whoever made the run ends it and the document goes on. The title-page check’s runs (latexml_engine sect05.rsspeculative_run_read): a run’s cost is bounded whatever the document’s text does. The count is the oneprogresskeeps; the token limit, the deadline and the cycle guard read theirs as before. - read_
cs_ name - read_
cs_ name_ quiet - Quiet version of read_cs_name — used by \ifcsname. In TeX, \ifcsname silently skips non-expandable CS tokens and returns the constructed name without emitting errors (unlike \csname which DOES emit errors).
- read_
definition_ body - A definition body: tex.web §473
scan_toks(true, xpand), read atdefiningstatus with its#parameters packed (\def,\edef, via theDefPlain/DefExpandedparameter types). A file that ends inside it ends the definition there (§339). TeX names the macro being defined; the body reader does not know it, so the report says “definition” alone. - read_
delimited_ balanced - The rest of an xparse
o/O{}/r[]/D<>argument whoseopenwas just read: up to the matchingclose, nested pairs and braced groups kept whole, as ltcmd’s delimited grab nests them (LaTeX’s\@ifnextchar[stops at the first). - read_
dimension - read_
factor - Return a number (Rust f64 number)
- read_
float - ====================================================================== Float, a floating point number. Similar to factor, but does NOT accept comma! This is NOT part of TeX, but is convenient.
- read_
glue - read_
keyword - Match the input against a set of keywords; Similar to readMatch, but the keywords are strings, and Case and catcodes are ignored; additionally, leading spaces are skipped. AND, macros are expanded.
- read_
ltcmd_ optional - ltcmd’s
oargument (\__cmd_grab_D_aux:NNnNN, latex.ltx:3594-3651) of the commandcs:[…]past spaces, to the matching explicit](read_delimited_balanced), one brace pair around the whole of it stripped;Some(None)when absent. Read as the non-\longdelimited macro ltcmd grabs it with (\cs_set_protected_nopar:Npn): a\par, a}or a file’s end in it ends the call,None, with TeX’s Error namingcs(tex.web §395-396, §338). - read_
ltcmd_ star - ltcmd’s
sargument (\__cmd_grab_t:w, latex.ltx:3816): a*past spaces. - read_
match - Match the input against one of the Token or Tokens in @choices; return the matching one or undef.
- read_
mu_ dimension - read_
mu_ glue - read_
mu_ unit - read_
next_ conditional - reads and discards tokens, until it encounters a conditional, if any.
Perl: skipConditionalBody inner loop (Conditional.pm L127-133) reads tokens directly
from pushback/mouth (NOT through readToken) and manually tracks
$LaTeXML::ALIGN_STATEfor{and}. This loop does not callread_tokeneither: its expansion and comment handling belong to digestion, and calling it from here once let pmatrix’s&get treated as the OUTER alignment’s column-end during\ifx.#1.\else…\fiskip when#1contains\begin{pmatrix}…&…\end{pmatrix}. (REG-2 / math-ph0501074: the 9-line\nonumber+\lefteqn+\pmatrixrepro.) It does take a column end at a zero count for the cell’s end, as tex.web’spass_textdoes throughget_next(§342) and Perl does not (KNOWN_PERL_ERRORS #1183). - read_
non_ blank_ non_ call - tex.web §406 “Get the next non-blank non-call token”:
get_x_token, so a\protectedmacro expands too, past spaces and implicit spaces (cur_cmd=spacer); an undefined control sequence is reported byexpandand discarded (§370), as inread_non_blank_non_relax. §577scan_font_identreads a font identifier with it. - read_
non_ blank_ non_ relax - tex.web §404 “Get the next non-blank non-relax non-call token”: expanded (a
\protectedmacro too, asget_x_tokenexpands it), past spaces and implicit spaces,\relaxand\noexpanded tokens (relax, §358); an undefined control sequence is reported byexpandand discarded (§370), as the csname reader does — the scan goes on, so\hbox\undefined{…}is still the box of{…}. - read_
non_ space - Read a single non-space token
- read_
normal_ integer - read_
number - read_
optional - Read and return a LaTeX optional argument
- read_
optional_ angled - The angle-bracket twin of
read_optional. - read_
optional_ signs - read_
primitive_ token - Read a token as a primitive reads one: tex.web §365
get_tokenunder the currentScannerStatus(\let,\futurelet,\afterassignment,\aftergroup,\expandafter, aTokenparameter). An input level that ends here closes (§362end_file_reading) and §336check_outer_validitylooks at the status: - read_
raw_ current_ line_ from_ start - The current mouth line as raw text from column 0, DROPPING the pushback:
for a reader that knows the pushback holds tokens probed off this very
line (
pushback_holds_nonspace), so the line comes back whole — with its indentation and any catcode-9 characters the probe’s tokenization lost. - read_
raw_ line - read_
raw_ line_ decoded read_raw_linefrom the current mouth with its input bytes decoded through the declared input encoding (Mouth::read_raw_line_decoded); the.bibreader’s and{verbatim}’s line source. Pending pushback is taken asread_raw_linetakes it, and decoded with the rest of the line: a pushed-back active byte prints as its Latin-1 character (a{verbatim}wrapper whose optional-argument check peeked the body’s first character left a cp1251 first line as mojibake).- read_
redefinable_ token - The control sequence a definition names: tex.web §1215
get_r_token,repeat get_token until cur_tok<>space_token(\def,\let,\futurelet,\chardef,\countdef…). Each read isread_primitive_token, so a bare\letor\defas a file’s last token takes its name from the input after the file, skipping the spaces there. - read_
register_ value - read_
register_ value_ coerce - Read a register value, optionally coercing from a compatible larger type. Perl: readRegisterValue($self, $type, $sign, $coerce) Coercion rules (from Perl %RegisterCoercionTypes): Number <- Dimension, Glue (extract raw i64) Dimension <- Glue (extract skip as Dimension) MuDimension <- MuGlue (extract skip as MuDimension)
- read_
required_ arg read_argfor a required parameter of typespec: input that ran out isnote_missing_argument’s, and the call runs on the empty argument (Perl’s put-back, Parameter.pm:93-97; OD #304).- read_
rubber - read_
token - Gullet.pm
readToken(L300-324); its loop is inread_token_after. - read_
token_ across_ input_ ends - Read a token as tex.web §367
\noexpanddoes:get_tokenunderscanner_status := normal, so an input level that ends here closes without a runaway (§362end_file_reading, §336 passes) and the read goes on in the enclosing level. Crosses exactly whatread_x_tokendrains: autoclose mouths with a parent (\inputfiles,\scantokenspseudo-files, line remainders), never areading_from_mouthcontext. A definition, text, preamble or macro argument that runs off a file’s end is still a §338 runaway:read_tokenstops there, and the scan recovers by itsScannerStatus(recover_at_file_end). This is what\everyeof{\noexpand}relies on (catchfile.sty:251-261, morewrites.sty:465, l3build regression-test.tex:101). Guards:noexpand_input_ends::*. - read_
token_ required - Read a token that the calling macro/primitive REQUIRES, holding the “argument expected but input ended” diagnostic in one place.
- read_
tokens_ value - The right-hand side of a token-list assignment,
\toks<n>=…,\everypar=…(tex.web §1226-1227), after its optional=: the next non-blank non-\relaxtoken, expanding (§404,get_x_token, which at a file’s end goes on in the enclosing input). A left brace, explicit or implicit (\toks0=\bgroup abc}), opens the balanced text, read atabsorbingstatus (scan_toks(false, false),read_balanced_text); a token-list register or parameter gives its value. Any other token is the value itself, as in Perl (Gullet.pm:824-842readTokensValue), after TeX’s error, “Missing { inserted” (§403scan_left_brace; TeX then absorbs up to the next}). Perl reads the token unexpanded and recurses on an expandable one, so a\relax, an implicit brace or a file end before the text lost it: Paul Taylor’s diagrams.sty:15\toks0=\bgroup}stored\bgroup, and its}closed a group (arXiv 2605.02221, 2605.25087). Guards:token_kernel_gaps::*. - read_
unit - Read a unit, returning the exact TeX
(num, den)conversion fraction (seeconvert_unit_ratio/numeric_ops::fixpoint_unit). Internal/coerced units (\wd0,\dimen, glue) yield(value_sp, 65536)— thefloor(fix·v/65536)path of tex.web §8983, exact in integer arithmetic. - read_
until - read_
until_ brace - reads until it encounters a Catcode::BEGIN token
Note: Perl uses
$$token[1] == CC_BEGIN(catcode check, not defined_as) - read_
until_ token - read_
value - read_
x_ non_ space - Read a single expanded, non-space, token
- read_
x_ token - Read the next non-expandable token, expanding until one appears. Hot path —
read_tokenis folded in.toplevel(default true): on mouth exhaustion, step to the containing mouth.fully_expand(default = toplevel): expand even protected defns (“for execution”). Unlikeread_balanced, does NOT defer\the& friends;\noexpand’d tokens act like\relax. For\if/\ifxarguments passfor_conditional=true(handles\noexpandand CS\letto tokens specially). - read_
x_ token_ cell_ head - The alignment’s cell-head peek, tex.web §785
align_peekand §791 (e-TeXget_x_or_protected): expand until the first token that is not expandable — or protected, asread_x_token(Some(true), false, Some(false))stops — and stop as well at a macro whose optional argument is a\newcommandone (Parameter::testopt): LaTeX’s\newcommand\dg[3][]is\@protected@testopt\dg\\dg{}, whose expansion reaches the unexpandable\letof\kernel@ifnextcharbefore it reads an argument (latex.ltx:1249-1261), so TeX starts the cell there and the arguments are read inside it. Our macro reads its arguments as it expands; expanded in the peek it read the cell’s&before the cell existed (diagbox.sty:212\newcommand\diagbox[3][], 2406.11917). The token is returned unexpanded: the cell’s own reader expands it. The binding closures that peek by\futurelet(Definition::peeks_by_futurelet, the kernel’s\@ifnextcharfamily) still expand here: several stand for a TeX macro whose head is not the peek (booktabs’\cmidruleis\noalign{…\@ifnextchar[…}, booktabs.sty:166). - read_
x_ token_ cell_ head_ stopping_ at read_x_token_cell_head, also stopping, unexpanded, at a tokenstopaccepts (empheq’sleft, which looks for a\multicolumnbefore it expands).- read_
x_ until - Convenience method wrapping around
read_until— EOF degrades to empty (callers that need to distinguish useread_untildirectly). Expanding delimited scan: read tokens with full expansion up to (and consuming)until, copying brace groups unexpanded once opened. TheXUntil:parameter type’s reader (PerlParameters.pmXUntil, after PR #2767 “should only expand, not digest”: a bare token push is all that remains). A\noexpand’d token collected here reverts to its plain shadowed identity, as inread_balanced: TeX’s no_expand_flag is transient (tex.web §1149-1153), so a\protect\cspair produced under\@unexpandable@protectis stored as the plain pair, not relax markers. - read_
x_ until_ any read_x_untilup to the first ofuntils, returned with the text (Nonewhen the input ran out).- reading_
context - The reading context tokens are read in now, as
(serial, depth): the serialreading_from_mouthgives each isolated context (a constructor’s argument digested on its own; 0 for the document’s own input,\inputfiles included), and how many such contexts are open. A\leftrecords it (stomach.rsrecord_left_group_input), so that only the end of the input it was read in closes its group (OXIDIZED_DESIGN #530). - reading_
document_ text - Is the next token read straight from the document’s own text — nothing pushed back, the mouth a content file’s
(
Mouth::is_document_text)? A macro called now reads its arguments from what the document wrote (state::note_document_call). - reading_
from_ mouth - Do something, while reading tokens from a specific Mouth.
- recover_
at_ file_ end - A file has just ended under the current read: tex.web §362 closes it and
calls §336
check_outer_validity, which, when theScannerStatusis not normal, reports the runaway (§338 “File ended while scanning definition / use / preamble / text of \cs”) and inserts the tokens that should lead to recovery (§339). - reset_
mouth_ closed_ errors - Forgets the mouth-closed errors counted: a predecessor that spent the budget (0906.1883) silenced the next paper’s first ten and made its first a Fatal.
- restore_
raw_ line_ rest - Give back the rest of the line a raw reader just read, as the current line of the input it came from, so the next
token or raw line is read from it and then from the lines after — one TeX input line (
\end{lstlisting} x \begin{lstlisting}: the second listing’s raw reader reads its body from the following lines, 2408.11865). False when tokens wait in front of it, which the line would then follow. - restore_
token_ limit - Restore the token limit and progress from a previous set_token_limit call.
- retract_
scanned_ brace back_input-style ledger retraction WITHOUT pushing anything: apply to tokens that were READ through a counting reader and are about to be RE-EMITTED as part of an expansion result (so they will be counted again when rescanned). tex.web §368:\expandaftersaves its first token andback_inputs it (§325 retracts a scanned brace) around the one-step expansion, which enters as an unadjusted token list. A closure-style expandable that returns previously-read tokens inside its expansion must call this on that re-emitted portion, or every{/}passed through it is double-counted (l3’s\exp_after:wN {idiom drove the alignment ledger positive and&went stray — seeunread_expansion).- retract_
scanned_ braces - scale_
token_ limit_ to_ source - Scale the runaway-token backstop to the SOURCE size — cumulatively, over
every file the conversion opens. The
DEFAULT_TOKEN_LIMITbaseline is sized for arXiv-scale inputs; a book-scale source legitimately expands past it (witness: a 131 MB flat-index compilation died at the then-400M ceiling mid-digestion with no loop in sight, at a measured ~3+ tokens/byte and paper-class documents measured up to ~160 tokens/byte; l3doc’s crossref pass over source2e’s.dtxs ~1000/byte). ×1000/byte keeps the ceiling finite — a true infinite loop still trips, and opens no new files while it spins — while never LOWERING the baseline for small documents. The bytes are summed over the main source AND everything it\inputs/\DocIncludes (everyMouth::open_file): source2e.tex is a 15 KB driver over ~40.dtxfiles (~2 MB), so the driver-only sizing never engaged. An explicitLATEXML_TOKEN_LIMITor--token-limit(fix_token_limit) wins unchanged (including 0 = disabled). - scan_
left_ brace - tex.web §403
scan_left_brace: the next non-blank non-relax token (read_non_blank_non_relax) is a{(is_left_brace); any other is put back with “Missing { inserted”, and the group is taken as begun. - scan_
stops_ at_ futurelet_ peek - TeX’s number scan stops at the unexpandable head of a peeking macro.
latex.ltx’s
\@ifnextchar(1756-1760), and with it\@ifstar,\@testoptand every\newcommandoptional argument, opens with\letand peeks by\futurelet; the digits of a number scan end at the first unexpandable token (tex.web §445), so the peek happens only where the macro is executed. Our peeking macros are closures that peek as they expand: in a scan they stay unexpanded, the scan ends at them, and the next reader outside the scan (the main loop, an alignment’s cell-head peek) expands them. Expanding them in the scan read the chosen branch into the number (\count@=1\@ifstar{7}{5}*assigned 17), or its conditionals into a false branch’s skip: egpeirce.sty:184-189\ifodd \the\value{cutdepth}%+\psset→\XKV@ifstarexposed\let\ifXKV@st\iffalseand the skip ran off the end of the document (egpeirce-doc, 51 errors; Perl shares the bug). Guards:cluster_package_guards::ifnextchar_scans. - scanner_
status - The current
ScannerStatus. - set_
braced_ length_ fn - Install the braced-length evaluator and switch the calc seams on for the current document (calc.sty at load time).
- set_
internal_ dimension_ fn - Install the internal-dimension resolver (calc.sty at load time).
- set_
operand_ values - Give the control sequences
OPERAND_VALUESholds, returning the ones given before. - set_
pushback_ limit - Set the pushback limit (maximum pushback stack size before fatal error).
- set_
scanner_ status - Enter a scan at
status, namingwarning_index(the command TeX’s runaway message names: the macro whose arguments are read, the primitive whose text is absorbed). tex.web saves and restores the status around such a scan; the returned guard does the restoring. - set_
scanner_ status_ checking_ par set_scanner_statusfor a macro call’s arguments, withchecks_parits macro’scrate::definition::expandable::Expandable::checks_par(tex.web §389long_state).- set_
token_ limit - Set the token limit and reset progress. Returns previous (limit, progress) for restoration.
- show_
unexpected - Perl: showUnexpected — returns a debug message about the next available token
- skip_
filler <filler> = <optional spaces> | <filler>\relax<optional spaces>- skip_
one_ space - Skip one optional space.
If
expandedis true, acts like<one optional space>and expands tokens (readXToken). Perl: skip1Space($self, $expanded) - skip_
spaces - Discard any run of spaces at the head of the input — Perl
Package.pm:SkipSpaces. - speculative_
digestion - A run of digestion whose output and assignments are all discarded starts (latexml_engine sect05.rs
speculative_run_read, the observer’s rehearsal,queue_digest::speculative_label_ink), until the guard drops: the document does not end in it. A\end{document},\enddocument,\@@endor\byeit reads does nothing (flush, the kernel’s document end), whatever text brought it there: a stored argument,\closing{\end{document}}, ended the real document with the run otherwise, and took the whole body with it. - take_
rest_ of_ mouth - Take everything still unread in the CURRENT mouth — its pushback, then the
rest of its source — as raw tokens, leaving it exhausted. The enclosing
input is untouched. This is how a braced argument hands back what followed
the quantity scanned from it (
crate::parameter::Parameters::reparse_argument): TeX leaves that tail in the input (\setlength#1#2{#1 #2\relax}, latex.ltx:10253). The tokens count as READ for the alignment brace ledger (asread_tokencounts them), so a caller that puts them back usesunread_vec, which retracts them again. - token_
or_ relax - A token argument, or
\relaxwhen the input ran out (afternote_missing_argument): the no-op stand-in a primitive’s coercion accepts. - token_
progress - How many tokens the gullet has read so far: at the end of a run, the
telemetry basis for
token_limit/CYCLE_GUARD_ACTIVATE; during one, the input a stretch of digestion consumed, for the stomach’s box-cycle guard (stomach.rscycle_guard_record). - unread
- Push the
tokensback into the input stream to be re-read. - unread_
after_ current_ file - Push
tokensto be read where the innermost\inputfile (mark_everyeof_mouth) ends, in its enclosing level, after the file’s own end code (content::input_file_ended); false when no such file is open. - unread_
expansion - Push EXPANSION OUTPUT (macro bodies, conditional-branch replays,
\theresults) to the start of the token stream WITHOUT touching the alignment brace ledger. - unread_
one - Unreads a single
Tokento the start of the token stream. Perl: unread() always adjusts $ALIGN_STATE when unreading { or } tokens. - unread_
substituted unread_expansionof a macro body with its parameters substituted (Tokens::substitute_parameters), without building the list first: tex.webmacro_call(§390) puts the body on the input as stored and the arguments where itsout_params are. The pieces go onto the pushback stack last first, each reversed;args[n - 1]is parameter#n’s argument. The brace ledger is not touched, as for any expansion output.- unread_
substituted_ args unread_substitutedof arguments all read as tokens, each found where it is.- unread_
vec - Unreads a
Vec<Token>to the start of the token stream Perl: also adjusts ALIGN_STATE by retracting scanned braces (Gullet.pm lines 343-358). Correct ONLY for tokens that were previously READ (and hence counted) — for expansion output useunread_expansion(tex.webbegin_token_listflavor, which adjusts nothing). - with_
mouth_ mut - Execute a function with a mutable reference to the current mouth
- with_
pushback - A look at the input’s pushback as it stands, the next token to read last; nothing is read, so nothing is tokenized
or counted. For a native reader of what a macro’s own expansion put there (
crate::definition::expandable::NativeCall).
Type Aliases§
- Braced
Length Fn - A package-installed evaluator for a braced LENGTH argument — calc.sty’s
expression scanner. latex.ltx hands every user length to
\setlength(\@hspace,\@imakebox,\@rule,\@iiiparbox,\@iiiminipage, array’s\@startpbox: latex.ltx:9425, 16099-16102, 16360-16366, 16249, 16305), and calc redefines\setlengthto evaluate its whole argument as an expression (calc.sty:86,\calc@assign@skip→\calc@open(#4!, :51-53). A binding’s{Dimension}/{Glue}argument is that\setlengthoperand, so with calc loadedcrate::parameter::Parameters::reparse_argumentevaluates it here:\makebox[\widthof{ab}+\widthof{cd}]gets the sum, not the first term. The evaluator reads from the argument’s own mouth, leaving unread whatever calc could not parse (after reporting it, as calc.sty:281-284 does). - Internal
Dimension Fn - A package-installed resolver for control sequences that yield an internal
dimension by reading their own argument — e.g. calc.sty’s
\widthof{box}. Given the already-read CS token, it either consumes that CS’s argument(s) from the gullet and returns the measured value (Ok(Some(_))), or leaves the stream untouched and declines (Ok(None)), in which case the caller un-reads the token. Keeps core calc-agnostic: the base dimension reader consults this seam before giving up with “Missing number”, so\makebox[\widthof{X}]/\rule{\widthof{X}}{…}resolve like real LaTeX without\widthofhaving to be a register (which would change its bare digestion). Seecalc_sty.rs/ OXIDIZED_DESIGN #115.