Debian Codegraph @

texk/web2c/texprofdir/texprof.w

raw
1 % TeXprof is copyright (C) 2024 by Martin Ruckert
2 % Hochschule Muenchen, Lothstrasse 64, 80336 Muenchen
3 % and put under the MIT/X11 license.
4 %
5 % Prote is copyright (C) 2021 by Thierry Laronde and put under
6 % the MIT/X11 license.
7 %
8 % As TeX and e-TeX are reserved names for the unchanged (except for the
9 % necessary implementation of system dependencies) instances of, resp.,
10 % Donald E. Knuth's program and the NTS team's e-TeX implementation, the
11 % name Prote is reserved for this kerTeX implementation.
12 %
13 % Hence, this is neither TeX (even if it is compatible at start) nor
14 % e-TeX (even if is compatible when entering the first set of
15 % extensions).
16
17 % Version 0 was released in September 1982 after it passed a variety of tests.
18 % Version 1 was released in November 1983 after thorough testing.
19 % Version 1.1 fixed ``disappearing font identifiers'' et alia (July 1984).
20 % Version 1.2 allowed `0' in response to an error, et alia (October 1984).
21 % Version 1.3 made memory allocation more flexible and local (November 1984).
22 % Version 1.4 fixed accents right after line breaks, et alia (April 1985).
23 % Version 1.5 fixed \the\toks after other expansion in \edefs (August 1985).
24 % Version 2.0 (almost identical to 1.5) corresponds to "Volume B" (April 1986).
25 % Version 2.1 corrected anomalies in discretionary breaks (January 1987).
26 % Version 2.2 corrected "(Please type...)" with null \endlinechar (April 1987).
27 % Version 2.3 avoided incomplete page in premature termination (August 1987).
28 % Version 2.4 fixed \noaligned rules in indented displays (August 1987).
29 % Version 2.5 saved cur_order when expanding tokens (September 1987).
30 % Version 2.6 added 10sp slop when shipping leaders (November 1987).
31 % Version 2.7 improved rounding of negative-width characters (November 1987).
32 % Version 2.8 fixed weird bug if no \patterns are used (December 1987).
33 % Version 2.9 made \csname\endcsname's "relax" local (December 1987).
34 % Version 2.91 fixed \outer\def\a0{}\a\a bug (April 1988).
35 % Version 2.92 fixed \patterns, also file names with complex macros (May 1988).
36 % Version 2.93 fixed negative halving in allocator when mem_min<0 (June 1988).
37 % Version 2.94 kept open_log_file from calling fatal_error (November 1988).
38 % Version 2.95 solved that problem a better way (December 1988).
39 % Version 2.96 corrected bug in "Infinite shrinkage" recovery (January 1989).
40 % Version 2.97 corrected blunder in creating 2.95 (February 1989).
41 % Version 2.98 omitted save_for_after at outer level (March 1989).
42 % Version 2.99 caught $$\begingroup\halign..$$ (June 1989).
43 % Version 2.991 caught .5\ifdim.6... (June 1989).
44 % Version 2.992 introduced major changes for 8-bit extensions (September 1989).
45 % Version 2.993 fixed a save_stack synchronization bug et alia (December 1989).
46 % Version 3.0 fixed unusual displays; was more \output robust (March 1990).
47 % Version 3.1 fixed nullfont, disabled \write{\the\prevgraf} (September 1990).
48 % Version 3.14 fixed unprintable font names and corrected typos (March 1991).
49 % Version 3.141 more of same; reconstituted ligatures better (March 1992).
50 % Version 3.1415 preserved nonexplicit kerns, tidied up (February 1993).
51 % Version 3.14159 allowed fontmemsize to change; bulletproofing (March 1995).
52 % Version 3.141592 fixed \xleaders, glueset, weird alignments (December 2002).
53 % Version 3.1415926 was a general cleanup with minor fixes (February 2008).
54 % Version 3.14159265 was similar (January 2014).
55 % Version 3.141592653 was similar but more extensive (January 2021).
56
57 % A reward of $327.68 will be paid to the first finder of any remaining bug.
58
59 % This is the 1.1 version of Prote, developed during August 2021,
60 % and corrected during september/october 2021 and amended in august 2023
61 % for file primitives behavior matching input behavior.
62 %
63 % 1.0: adds primitives needed by LaTeX as listed in ltnews31.
64 % - 2022-07-21: tiddying formal fix: a spurious line was a left over
65 % of a removed paragraph (pointed by Martin Ruckert). Suppressed.
66 %
67 % 1.1: 2023-08-01: the new file primitives are used in LaTeX expecting
68 % the input behavior that ".tex" be appended if no extension. So
69 % modified to provide this.
70 %
71 % History towards 1.0 release:
72 % 0.99.4:
73 % - typos and style corrections provided by Martin Ruckert for
74 % clean translation in Pascal (forward declarations and underscores
75 % omitted);
76 % - adjustements against e-TeX 2.6 instead of 2.1 (T. Laronde).
77 % 0.99.7:
78 % - \expanded was using an e-TeX procedure not doing def handling
79 % => using scan_toks() now. Reported by Martin Ruckert and
80 % test code narrowed down by Phelype Oleinik.
81 % 0.99.8:
82 % - \expanded again: scan_toks() sets def_ref. But back_list()
83 % has to take not the refernce count, but the first token.
84 % Passing def_ref, a next invocation of scan_toks() was inserting
85 % a missing left brace and then reading pass the end of the token
86 % list to find a matching right one. def_ref => link(def_ref).
87 % Test code narrowed down by Phelype Oleinik (a great help!).
88 % - The API for file related primitives has been changed: no error
89 % is reported on failure to find/open and nothing is returned
90 % (matches current other implementations).
91 % 0.99.9:
92 % - Fix typos in Pascal replacement text; xchg_buffer_length=0 =>
93 % xchg_buffer_length:=0 (caught by Martin Ruckert).
94 % 0.99.10:
95 % - KerTeX Public License -> X11/MIT license.
96 % 1.0:
97 % - Just naming the official release. No change.
98 %
99 % This work was done by Thierry Laronde and is under the MIT/X11
100 % license.
101 %
102 %
103
104 % Here is TeX material that gets inserted after \input webmac
105 \def\hang{\hangindent 3em\noindent\ignorespaces}
106 \def\hangg#1 {\hang\hbox{#1 }}
107 \def\textindent#1{\hangindent2.5em\noindent\hbox to2.5em{\hss#1 }\ignorespaces}
108 \font\ninerm=cmr9
109 \let\mc=\ninerm % medium caps for names like SAIL
110 \def\Prote{{\tenrm P\kern-0.1em R\kern-0.15em\raise.11ex\hbox{o}%
111 \kern-0.22em T\kern-0.05em E}}
112 \def\texprof{{\TeX}prof}
113 \ifpdftex
114 \sanitizecommand{\texprof}{TeXprof}
115 \sanitizecommand{\eTeX}{eTeX}
116 \sanitizecommand{\Prote}{PRoTE}
117 \fi
118 \font\tenlogo=logo10
119 \def\MP{{\tenlogo META}\-{\tenlogo POST}}
120 \def\eTeX{$\varepsilon$-\TeX}
121 \font\revrm=xbmc10 % for right-to-left text
122 % to generate xbmc10 (i.e., reflected cmbx10) use a file
123 % xbmc10.mf containing:
124 %+++++++++++++++++++++++++++++++++++++++++++++++++
125 % if unknown cmbase: input cmbase fi
126 % extra_endchar := extra_endchar &
127 % "currentpicture:=currentpicture " &
128 % "reflectedabout((.5[l,r],0),(.5[l,r],1));";
129 % input cmbx10
130 %+++++++++++++++++++++++++++++++++++++++++++++++++
131 \ifx\beginL\undefined % this is TeX
132 \def\XeT{X\kern-.125em\lower.5ex\hbox{E}\kern-.1667emT}
133 \def\TeXeT{\TeX-\hbox{\revrm \XeT}} % for TeX-XeT
134 \def\TeXXeT{\TeX-\hbox{\revrm -\XeT}} % for TeX--XeT
135 \else
136 \ifx\eTeXversion\undefined % this is \TeXeT
137 \def\TeXeT{\TeX-{\revrm\beginR\TeX\endR}} % for TeX-XeT
138 \def\TeXXeT{\TeX-{\revrm\beginR\TeX-\endR}} % for TeX--XeT
139 \else % this is \eTeX
140 \def\TeXeT{\TeX-{\TeXXeTstate=1\revrm\beginR\TeX\endR}} % for TeX-XeT
141 \def\TeXXeT{\TeX-{\TeXXeTstate=1\revrm\beginR\TeX-\endR}} % for TeX--XeT
142 \fi
143 \fi
144 \def\PASCAL{Pascal}
145 \def\pdfTeX{pdf\TeX}
146 \def\ph{\hbox{Pascal-H}}
147 \def\pct!{{\char`\%}} % percent sign in ordinary text
148 \def\grp{\.{\char'173...\char'175}}
149 \font\logo=logo10 % font used for the METAFONT logo
150 \def\MF{{\logo META}\-{\logo FONT}}
151 \def\<#1>{$\langle#1\rangle$}
152 \def\section{\mathhexbox278}
153
154 \def\(#1){} % this is used to make section names sort themselves better
155 \def\9#1{} % this is used for sort keys in the index via @@:sort key}{entry@@>
156
157 \let\@@=\relax % we want to be able to \write a \?
158
159 \def\title{\texprof}
160 \def\LaTeX{L\kern-.36em\raise.3ex\hbox{\sc A}\kern-.15em\TeX}%
161 % system dependent redefinitions of \title should come later
162 % and should use:
163 % \toks0=\expandafter{\title}
164 % \edef\title{...\the\toks0...}
165 %\let\maybe=\iffalse % print only changed modules
166 \def\topofcontents{\hsize 5.5in
167 \vglue 0pt plus 1fil minus 1.5in
168 \def\@@##1]{\hbox to 1in{\hfil##1.\ }}
169 }
170 \def\botofcontents{\vskip 0pt plus 1fil minus 1.5in}
171 \pageno=3
172 \def\glob{13} % this should be the section number of "<Global...>"
173 \def\gglob{20, 26} % this should be the next two sections of "<Global...>"
174
175 \def\.#1{\leavevmode\hbox{\tentex % typewriter type for strings
176 \let\\=\BS % backslash in a string
177 \let\'=\RQ % right quote in a string
178 \let\`=\LQ % left quote in a string
179 \let\{=\LB % left brace in a string
180 \let\}=\RB % right brace in a string
181 \let\~=\TL % tilde in a string
182 \let\ =\SP % space in a string
183 \let\_=\UL % underline in a string
184 \let\&=\AM % ampersand in a string
185 \let\^=\CF % circumflex in a string
186 #1\kern.05em}}
187 \def\&#1{\leavevmode\hbox{\bf\def\_{\UL}%
188 #1\/\kern.05em}} % boldface type for reserved words
189 \def\\#1{\leavevmode\hbox{\it\def\_{\UL}%
190 #1\/\kern.05em}} % italic type for identifiers
191 \def\vb#1{{\rm #1}}
192 %\def\^{\ifmmode\mathchar"222 \else\char`^ \fi} % pointer or hat
193 \def\LQ{{\tt\char'22}} % left quote in a string
194 \def\RQ{{\tt\char'23}} % right quote in a string
195 \def\UL{{\tt\char`\_}} % underline character in a C identifier
196 \def\CF{{\tt\char`^}}
197 \def\dotdot{\mathrel{.\,.}} % double dot, used only in math mode
198 \setbox\MGbox=\hbox{\kern1pt$\rightarrow$\kern1pt} % C pointer to field
199 \def\MG{\copy\MGbox}
200 @s dotdot TeX
201 @s alpha_file int
202 @s byte_file int
203 @s word_file int
204 @s uint8_t int
205 @s int16_t int
206 @s uint16_t int
207 @s int32_t int
208 @s uint32_t int
209 @s halfword int
210 @s nonnegative_integer int
211 @s small_number int
212 @s glue_ratio double
213 @s Xdimen int
214 @s Kern int
215 @s Font int
216 @s Glue int
217 @s Disc int
218 @s Lig int
219 @s Rule int
220 @s List int
221 @s Kind int
222 @s Info int
223 @s kpse_file_format_type int
224 @s Stretch int
225 @s in TeX
226 @s line normal
227 @s to do
228
229 @* Introduction.
230 This is \texprof, an implementation of \TeX\ with an extension providing profiling
231 capabilities. To be useful nowadays, the profiling capability is not the only
232 extension of Donald Knuth's original implementation of \TeX.
233
234 To obtain the present \CEE/ program, Donald Knuth's \PASCAL\ program was
235 modified in a first step using most of the \eTeX\ extensions by
236 Peter Breitenlohner and Phil Taylor.
237 @^Breitenlohner, Peter@>
238 @^Taylor, Phil@>
239 Then further extensions were added using the \Prote\ change file
240 of Thierry Laronde.
241 @^Laronde, Thierry@>
242 Then the constants defining the size of \TeX's data structures,
243 notably the size of the |mem| array, were increased considerable. All these
244 changes to the \PASCAL\ program are necessary to run a current \LaTeX\ on the
245 resulting \TeX\ engine. The next important step was then to translate this
246 literate \PASCAL\ program to a literate \CEE/ program using the
247 {\tt web2w} source code translator. The use of the \CEE/ based \.{cweb} system
248 instead of the \PASCAL\ based \.{WEB} system greatly simplifies the tool chain
249 necessary for producing an executable program and allows true source level
250 debugging of the resulting program. The latter is indispensable to carry out
251 large scale modifications of the \TeX\ program and is of enormous help even
252 for smaller modifications.
253 The first modification of the resulting \CEE/ program was then the addition
254 of \CEE/ routines from the \TeX\ Live project to enable the use of the
255 kpath search library by Karl Berry.
256 @^Berry, Karl@>
257 The last and final step was the addition of profiling capabilities
258 which includes, as the latest addition, the definition of numerous
259 primitives that enable the \TeX\ profiler to pretend to be \pdfTeX.
260 The code used there reuses parts of the \CEE/ version of \pdfTeX\ by
261 H\`an Th\^e\llap{\raise 0.5ex\hbox{\'{}}} Th\`anh.
262 @^Th\`anh, H\`an Th\^e\llap{\raise 0.5ex\hbox{\'{}}}@>
263
264 All these changes left their traces in the text that follows.
265 No attempt was made to streamline the text and rid it from the traces
266 of its exciting history.
267 So with the next paragraph you can start reading Donald Knuth's
268 introduction to his \TeX\ program. Enjoy!
269 \medskip
270
271 This is \TeX, a document compiler intended to produce typesetting of high
272 quality.
273 The \PASCAL\ program that follows is the definition of \TeX82, a standard
274 @:PASCAL}{\PASCAL@>
275 @!@:TeX82}{\TeX82@>
276 version of \TeX\ that is designed to be highly portable so that identical output
277 will be obtainable on a great variety of computers.
278
279 The main purpose of the following program is to explain the algorithms of \TeX\
280 as clearly as possible. As a result, the program will not necessarily be very
281 efficient when a particular \PASCAL\ compiler has translated it into a
282 particular machine language. However, the program has been written so that it
283 can be tuned to run efficiently in a wide variety of operating environments
284 by making comparatively few changes. Such flexibility is possible because
285 the documentation that follows is written in the \.{WEB} language, which is
286 at a higher level than \PASCAL; the preprocessing step that converts \.{WEB}
287 to \PASCAL\ is able to introduce most of the necessary refinements.
288 Semi-automatic translation to other languages is also feasible, because the
289 program below does not make extensive use of features that are peculiar to
290 \PASCAL.
291
292 A large piece of software like \TeX\ has inherent complexity that cannot
293 be reduced below a certain level of difficulty, although each individual
294 part is fairly simple by itself. The \.{WEB} language is intended to make
295 the algorithms as readable as possible, by reflecting the way the
296 individual program pieces fit together and by providing the
297 cross-references that connect different parts. Detailed comments about
298 what is going on, and about why things were done in certain ways, have
299 been liberally sprinkled throughout the program. These comments explain
300 features of the implementation, but they rarely attempt to explain the
301 \TeX\ language itself, since the reader is supposed to be familiar with
302 {\sl The \TeX book}.
303 @.WEB@>
304 @:TeXbook}{\sl The \TeX book@>
305
306 @ The present implementation has a long ancestry, beginning in the summer
307 of~1977, when Michael~F. Plass and Frank~M. Liang designed and coded
308 a prototype
309 @^Plass, Michael Frederick@>
310 @^Liang, Franklin Mark@>
311 @^Knuth, Donald Ervin@>
312 based on some specifications that the author (in the following, unless
313 specified, ``the author'' refers to D.E.~Knuth) had made in May of that year.
314 This original proto\TeX\ included macro definitions and elementary
315 manipulations on boxes and glue, but it did not have line-breaking,
316 page-breaking, mathematical formulas, alignment routines, error recovery,
317 or the present semantic nest; furthermore,
318 it used character lists instead of token lists, so that a control sequence
319 like \.{\\halign} was represented by a list of seven characters. A
320 complete version of \TeX\ was designed and coded by the author in late
321 1977 and early 1978; that program, like its prototype, was written in the
322 {\mc SAIL} language, for which an excellent debugging system was
323 available. Preliminary plans to convert the {\mc SAIL} code into a form
324 somewhat like the present ``web'' were developed by Luis Trabb~Pardo and
325 @^Trabb Pardo, Luis Isidoro@>
326 the author at the beginning of 1979, and a complete implementation was
327 created by Ignacio~A. Zabala in 1979 and 1980. The \TeX82 program, which
328 @^Zabala Salelles, Ignacio Andr\'es@>
329 was written by the author during the latter part of 1981 and the early
330 part of 1982, also incorporates ideas from the 1979 implementation of
331 @^Guibas, Leonidas Ioannis@>
332 @^Sedgewick, Robert@>
333 @^Wyatt, Douglas Kirk@>
334 \TeX\ in {\mc MESA} that was written by Leonidas Guibas, Robert Sedgewick,
335 and Douglas Wyatt at the Xerox Palo Alto Research Center. Several hundred
336 refinements were introduced into \TeX82 based on the experiences gained with
337 the original implementations, so that essentially every part of the system
338 has been substantially improved. After the appearance of ``Version 0'' in
339 September 1982, this program benefited greatly from the comments of
340 many other people, notably David~R. Fuchs and Howard~W. Trickey.
341 A final revision in September 1989 extended the input character set to
342 eight-bit codes and introduced the ability to hyphenate words from
343 different languages, based on some ideas of Michael~J. Ferguson.
344 @^Fuchs, David Raymond@>
345 @^Trickey, Howard Wellington@>
346 @^Ferguson, Michael John@>
347
348 No doubt there still is plenty of room for improvement, but the author
349 is firmly committed to keeping \TeX82 ``frozen'' from now on; stability
350 and reliability are to be its main virtues.
351
352 On the other hand, the \.{WEB} description can be extended without changing
353 the core of \TeX82 itself, and the program has been designed so that such
354 extensions are not extremely difficult to make.
355 The |banner| string defined here should be changed whenever \TeX\
356 undergoes any modifications, so that it will be clear which version of
357 \TeX\ might be the guilty party when a problem arises.
358 @^extensions to \TeX@>
359 @^system dependencies@>
360
361 This program contains code for various features extending \TeX,
362 therefore this program is called `\Prote' and not
363 `\TeX'; the official name `\TeX' by itself is reserved
364 for software systems that are fully compatible with each other.
365 A special test suite called the ``\.{TRIP} test'' is available for
366 helping to determine whether a particular implementation deserves to be
367 known as `\TeX' [cf.~Stanford Computer Science report CS1027,
368 November 1984].
369
370 A similar test suite called the ``\.{SELLETTE} test'' is available for
371 helping to determine whether a particular implementation deserves to be
372 known as `\Prote'.
373
374 @d eTeX_version 2 /* \.{\\eTeXversion} */
375 @d eTeX_revision ".6" /* \.{\\eTeXrevision} */
376 @d eTeX_version_string "2.6" /*current \eTeX\ version*/
377 @#
378 @d TeX_version_string "3.141592653"
379 @d TeX_banner "This is TeX, Version " TeX_version_string /*printed when \TeX\ starts*/
380 @#
381 @#
382 @d TEX ETEX /*change program name into |ETEX|*/
383 @#
384 @d eTeX_states 1 /*number of \eTeX\ state variables in |eqtb|*/
385 @#
386 @d Prote_version_string "1.1.0" /*current \Prote\ version*/
387 @d Prote_version 1 /* \.{\\Proteversion} */
388 @d Prote_revision ".1.0" /* \.{\\Proterevision} */
389 @#
390 @d Prote_banner "This is Prote, Version " Prote_version_string
391 /*printed when \Prote\ starts*/
392 @#
393
394 @d TeXprof_version "1.1"
395 @d TeXprof_banner "This is texprof, Version " TeXprof_version
396 ", using TeX, Version " TeX_version_string
397
398 @d banner TeXprof_banner
399
400 @ Different \PASCAL s have slightly different conventions, and the present
401 @!@:PASCAL H}{\ph@>
402 program expresses \TeX\ in terms of the \PASCAL\ that was
403 available to the author in 1982. Constructions that apply to
404 this particular compiler, which we shall call \ph, should help the
405 reader see how to make an appropriate interface for other systems
406 if necessary. (\ph\ is Charles Hedrick's modification of a compiler
407 @^Hedrick, Charles Locke@>
408 for the DECsystem-10 that was originally developed at the University of
409 Hamburg; cf.\ {\sl Software---Practice and Experience \bf6} (1976),
410 29--42. The \TeX\ program below is intended to be adaptable, without
411 extensive changes, to most other versions of \PASCAL, so it does not fully
412 use the admirable features of \ph. Indeed, a conscious effort has been
413 made here to avoid using several idiosyncratic features of standard
414 \PASCAL\ itself, so that most of the code can be translated mechanically
415 into other high-level languages. For example, the `\&{with}' and `\\{new}'
416 features are not used, nor are pointer types, set types, or enumerated
417 scalar types; there are no `\&{var}' parameters, except in the case of files
418 --- \eTeX, however, does use `\&{var}' parameters for the |reverse| function;
419 there are no tag fields on variant records; there are no assignments
420 |double=int|; no procedures are declared local to other procedures.)
421
422 The portions of this program that involve system-dependent code, where
423 changes might be necessary because of differences between \PASCAL\ compilers
424 and/or differences between
425 operating systems, can be identified by looking at the sections whose
426 numbers are listed under `system dependencies' in the index. Furthermore,
427 the index entries for `dirty \PASCAL' list all places where the restrictions
428 of \PASCAL\ have not been followed perfectly, for one reason or another.
429 @!@^system dependencies@>
430 @!@^dirty \PASCAL@>
431
432 Incidentally, \PASCAL's standard |round| function can be problematical,
433 because it disagrees with the IEEE floating-point standard.
434 Many implementors have
435 therefore chosen to substitute their own home-grown rounding procedure.
436
437 @ The following is an outline of the program, whose
438 components will be filled in later, using the conventions of \.{cweb}.
439 @.WEB@>
440 For example, the portion of the program called `\X\glob:Global
441 variables\X' below will be replaced by a sequence of variable declarations
442 that starts in $\section\glob$ of this documentation. In this way, we are able
443 to define each individual global variable when we are prepared to
444 understand what it means; we do not have to define all of the globals at
445 once. Cross references in $\section\glob$, where it says ``See also
446 sections \gglob, \dots,'' also make it possible to look at the set of
447 all global variables, if desired. Similar remarks apply to the other
448 portions of the program.
449
450 The program starts with inserting header files and occassionaly a function
451 must be placed before declaring \TeX's macros, because the function
452 uses identifiers that \TeX will declare as macros.
453
454 @p @<Header files and function declarations@>@;
455 @h
456 enum {@<Constants in the outer block@>@;
457 @!empty_string=256 /*the empty string follows after 256 characters*/
458 };
459 @<Types in the outer block@>@;
460 @<Forward declarations@>@;
461 @<Global variables@>@;
462 @#
463 static void initialize(void) /*this procedure gets things started properly*/
464 {@+@<Local variables for initialization@>@;
465 @<Initialize whatever \TeX\ might access@>;
466 } @#
467 @<Basic printing procedures@>@;
468 @<Error handling procedures@>@;
469
470 @ The overall \TeX\ program begins with the heading just shown, after which
471 comes a bunch of procedure declarations and function declarations.
472 Finally we will get to the main program, which begins with the
473 comment `|start_here|'. If you want to skip down to the
474 main program now, you can look up `|start_here|' in the index.
475 But the author suggests that the best way to understand this program
476 is to follow pretty much the order of \TeX's components as they appear in the
477 \.{WEB} description you are now reading, since the present ordering is
478 intended to combine the advantages of the ``bottom up'' and ``top down''
479 approaches to the problem of understanding a somewhat complicated system.
480
481 @ There is no need to declare labels in \CEE/.
482
483 @ Some of the code below is intended to be used only when diagnosing the
484 strange behavior that sometimes occurs when \TeX\ is being installed or
485 when system wizards are fooling around with \TeX\ without quite knowing
486 what they are doing. Such code will not normally be compiled; it is
487 delimited by the codewords `$|@t\#\&{ifdef} \.{DEBUG}@>|\ldots|@t\#\&{endif}@>|$', with apologies
488 to people who wish to preserve the purity of English.
489
490 Similarly, there is some conditional code delimited by
491 `$|@t\#\&{ifdef} \.{STAT}@>|\ldots|@t\#\&{endif}@>|$' that is intended for use when statistics are to be
492 kept about \TeX's memory usage. The |@t\#\&{ifdef} \.{STAT}@>| $\ldots$ |@t\#\&{endif}@>| code also
493 implements diagnostic information for \.{\\tracingparagraphs},
494 \.{\\tracingpages}, and \.{\\tracingrestores}.
495 @^debugging@>
496
497 @ This program has two important variations: (1) There is a long and slow
498 version called \.{INITEX}, which does the extra calculations needed to
499 @.INITEX@>
500 initialize \TeX's internal tables; and (2)~there is a shorter and faster
501 production version, which cuts the initialization to a bare minimum.
502 Parts of the program that are needed in (1) but not in (2) are delimited by
503 the codewords `$|@t\#\&{ifdef} \.{INIT}@>|\ldots|@t\#\&{endif}@>|$'.
504
505 \TeX\ Live has established the common practice
506 to select the initialization code at runtime
507 using the |iniversion| variable.
508
509 @<Initialize whatever...@>=
510 @<Set initial values of key variables@>@/
511 #ifdef @!INIT
512 if (iniversion) /* \TeX\ Live*/
513 {@+@<Initialize table entries (done by \.{INITEX} only)@>@;@+}
514 #endif
515
516 @ The declaration of the necessary type definitions are
517 contained in header files.
518
519
520 @<Header files and function declarations@>=
521 #include <stdbool.h>
522 #include <string.h>
523 #include <math.h>
524
525 @ Further it is necessary to define some build in primitives of
526 \PASCAL\ that are otherwise not available in~\CEE/.
527 @:PASCAL H}{\ph@>
528
529 @d odd(X) ((X)&1)
530 @d chr(X) ((unsigned char)(X))
531 @d ord(X) ((unsigned int)(X))
532 @d abs(X) ((X)>-(X)?(X):-(X))
533 @d round(X) ((int)((X)>=0.0?floor((X)+0.5):ceil((X)-0.5)))
534
535 @ The following parameters can be changed at compile time to extend or
536 reduce \TeX's capacity. They may have different values in \.{INITEX} and
537 in production versions of \TeX.
538 @.INITEX@>
539 @^system dependencies@>
540
541 @<Constants...@>=
542 @!mem_max=5000000, /*greatest index in \TeX's internal |mem| array;
543 must be strictly less than |max_halfword|;
544 must be equal to |mem_top| in \.{INITEX}, otherwise | >= mem_top|*/
545 @!mem_min=0, /*smallest index in \TeX's internal |mem| array;
546 must be |min_halfword| or more;
547 must be equal to |mem_bot| in \.{INITEX}, otherwise | <= mem_bot|*/
548 @!buf_size=2000000, /*maximum number of characters simultaneously present in
549 current lines of open files and in control sequences between
550 \.{\\csname} and \.{\\endcsname}; must not exceed |max_halfword|*/
551 @!error_line=79, /*width of context lines on terminal error messages*/
552 @!half_error_line=50, /*width of first lines of contexts in terminal
553 error messages; should be between 30 and |error_line-15|*/
554 @!max_print_line=79, /*width of longest text lines output; should be at least 60*/
555 @!stack_size=5000, /*maximum number of simultaneous input sources*/
556 @!max_in_open=15, /*maximum number of input files and error insertions that
557 can be going on simultaneously*/
558 @!font_max=255, /*maximum internal font number; must not exceed |max_quarterword|
559 and must be at most |font_base+256|*/
560 @!font_mem_size=8000000, /*number of words of |font_info| for all fonts*/
561 @!param_size=10000, /*maximum number of simultaneous macro parameters*/
562 @!nest_size=500, /*maximum number of semantic levels simultaneously active*/
563 @!max_strings=500000, /*maximum number of strings; must not exceed |max_halfword|*/
564 @!string_vacancies=90000, /*the minimum number of characters that should be
565 available for the user's control sequences and font names,
566 after \TeX's own error messages are stored*/
567 @!pool_size=6250000, /*maximum number of characters in strings, including all
568 error messages and help texts, and the names of all fonts and
569 control sequences; must exceed |string_vacancies| by the total
570 length of \TeX's own strings, which is currently about 23000*/
571 @!save_size=100000, /*space for saving values outside of current group; must be
572 at most |max_halfword|*/
573 @!trie_size=1000000, /*space for hyphenation patterns; should be larger for
574 \.{INITEX} than it is in production versions of \TeX*/
575 @!trie_op_size=35111, /*space for ``opcodes'' in the hyphenation patterns*/
576 @!dvi_buf_size=16384, /*size of the output buffer; must be a multiple of 8*/
577 @!file_name_size=1024, /*file names shouldn't be longer than this*/
578 @!xchg_buffer_size=64, /*must be at least 64*/
579 /*size of |eight_bits| buffer for exchange with system routines*/
580
581 @ Like the preceding parameters, the following quantities can be changed
582 at compile time to extend or reduce \TeX's capacity. But if they are changed,
583 it is necessary to rerun the initialization program \.{INITEX}
584 @.INITEX@>
585 to generate new tables for the production \TeX\ program.
586 One can't simply make helter-skelter changes to the following constants,
587 since certain rather complex initialization
588 numbers are computed from them. They are defined here using
589 \.{WEB} macros, instead of being put into the above |enum| list in order to
590 emphasize this distinction.
591
592 @d mem_bot 0 /*smallest index in the |mem| array dumped by \.{INITEX};
593 must not be less than |mem_min|*/
594 @d mem_top 5000000 /*largest index in the |mem| array dumped by \.{INITEX};
595 must be substantially larger than |mem_bot|
596 and not greater than |mem_max|*/
597 @d font_base 0 /*smallest internal font number; must not be less
598 than |min_quarterword|*/
599 @d hash_size 45000 /*maximum number of control sequences; it should be at most
600 about |(mem_max-mem_min)/(double)10|*/
601 @d hash_prime 35999 /*a prime number equal to about 85\pct! of |hash_size|*/
602 @d hyph_size 8191 /*another prime; the number of \.{\\hyphenation} exceptions*/
603 @^system dependencies@>
604
605 @ In case somebody has inadvertently made bad settings of the ``constants,''
606 \TeX\ checks them using a global variable called |bad|.
607
608 This is the first of many sections of \TeX\ where global variables are
609 defined.
610
611 @<Glob...@>=
612 static int @!bad; /*is some ``constant'' wrong?*/
613
614 @ Later on we will say `\ignorespaces|if (mem_max >= max_halfword) bad=14|',
615 or something similar. (We can't do that until |max_halfword| has been defined.)
616
617 @<Check the ``constant'' values for consistency@>=
618 bad=0;
619 if ((half_error_line < 30)||(half_error_line > error_line-15)) bad=1;
620 if (max_print_line < 60) bad=2;
621 if (dvi_buf_size%8!=0) bad=3;
622 if (mem_bot+1100 > mem_top) bad=4;
623 if (hash_prime > hash_size) bad=5;
624 if (max_in_open >= 128) bad=6;
625 if (mem_top < 256+11) bad=7; /*we will want |null_list > 255|*/
626
627 @ Labels are given symbolic names by the following definitions, so that
628 occasional |goto| statements will be meaningful. We insert the label
629 `|end|' just before the `\ignorespaces|} |\unskip' of a procedure in
630 which we have used the `|goto end|' statement defined below; the label
631 `|restart|' is occasionally used at the very beginning of a procedure; and
632 the label `|reswitch|' is occasionally used just prior to a |case|
633 statement in which some cases change the conditions and we wish to branch
634 to the newly applicable case. Loops that are set up with the |loop|
635 construction defined below are commonly exited by going to `|done|' or to
636 `|found|' or to `|not_found|', and they are sometimes repeated by going to
637 `|resume|'. If two or more parts of a subroutine start differently but
638 end up the same, the shared code may be gathered together at
639 `|common_ending|'.
640
641 Incidentally, this program never declares a label that isn't actually used,
642 because some fussy \PASCAL\ compilers will complain about redundant labels.
643
644 @ Here are some macros for common programming idioms.
645
646 @d incr(A) A=A+1 /*increase a variable by unity*/
647 @d decr(A) A=A-1 /*decrease a variable by unity*/
648 @d negate(A) A=-A /*change the sign of a variable*/
649 @d loop @+while (true) @+ /*repeat over and over until a |goto| happens*/
650 @f loop else
651 /*\.{WEB}'s |else| acts like `\ignorespaces|while true do|\unskip'*/
652 @d do_nothing /*empty statement*/
653 @d empty 0 /*symbolic name for a null constant*/
654
655 @* The character set.
656 In order to make \TeX\ readily portable to a wide variety of
657 computers, all of its input text is converted to an internal eight-bit
658 code that includes standard ASCII, the ``American Standard Code for
659 Information Interchange.'' This conversion is done immediately when each
660 character is read in. Conversely, characters are converted from ASCII to
661 the user's external representation just before they are output to a
662 text file.
663
664 Such an internal code is relevant to users of \TeX\ primarily because it
665 governs the positions of characters in the fonts. For example, the
666 character `\.A' has ASCII code $65=0101$, and when \TeX\ typesets
667 this letter it specifies character number 65 in the current font.
668 If that font actually has `\.A' in a different position, \TeX\ doesn't
669 know what the real position is; the program that does the actual printing from
670 \TeX's device-independent files is responsible for converting from ASCII to
671 a particular font encoding.
672 @^ASCII code@>
673
674 \TeX's internal code also defines the value of constants
675 that begin with a reverse apostrophe; and it provides an index to the
676 \.{\\catcode}, \.{\\mathcode}, \.{\\uccode}, \.{\\lccode}, and \.{\\delcode}
677 tables.
678
679 @ Characters of text that have been converted to \TeX's internal form
680 are said to be of type |ASCII_code|, which is a subrange of the integers.
681
682 @<Types...@>=
683 typedef uint8_t ASCII_code; /*eight-bit numbers*/
684
685 @ The original \PASCAL\ compiler was designed in the late 60s, when six-bit
686 character sets were common, so it did not make provision for lowercase
687 letters. Nowadays, of course, we need to deal with both capital and small
688 letters in a convenient way, especially in a program for typesetting;
689 so the present specification of \TeX\ has been written under the assumption
690 that the \PASCAL\ compiler and run-time system permit the use of text files
691 with more than 64 distinguishable characters. More precisely, we assume that
692 the character set contains at least the letters and symbols associated
693 with ASCII codes 040 through 0176; all of these characters are now
694 available on most computer terminals.
695
696 Since we are dealing with more characters than were present in the first
697 \PASCAL\ compilers, we have to decide what to call the associated data
698 type. Some \PASCAL s use the original name |unsigned char| for the
699 characters in text files, even though there now are more than 64 such
700 characters, while other \PASCAL s consider |unsigned char| to be a 64-element
701 subrange of a larger data type that has some other name.
702
703 In order to accommodate this difference, we shall use the name |text_char|
704 to stand for the data type of the characters that are converted to and
705 from |ASCII_code| when they are input and output. We shall also assume
706 that |text_char| consists of the elements |chr(first_text_char)| through
707 |chr(last_text_char)|, inclusive. The following definitions should be
708 adjusted if necessary.
709 @^system dependencies@>
710
711 @s text_char char
712 @d text_char unsigned char /*the data type of characters in text files*/
713 @d first_text_char 0 /*ordinal number of the smallest element of |text_char|*/
714 @d last_text_char 255 /*ordinal number of the largest element of |text_char|*/
715
716 @<Local variables for init...@>=
717 int @!i;
718
719 @ The \TeX\ processor converts between ASCII code and
720 the user's external character set by means of arrays |xord| and |xchr|
721 that are analogous to \PASCAL's |ord| and |chr| functions.
722
723 @<Glob...@>=
724 static ASCII_code @!xord[256];
725 /*specifies conversion of input characters*/
726 static text_char @!xchr[256];
727 /*specifies conversion of output characters*/
728
729 @ Since we are assuming that our \PASCAL\ system is able to read and
730 write the visible characters of standard ASCII (although not
731 necessarily using the ASCII codes to represent them), the following
732 assignment statements initialize the standard part of the |xchr| array
733 properly, without needing any system-dependent changes. On the other
734 hand, it is possible to implement \TeX\ with less complete character
735 sets, and in such cases it will be necessary to change something here.
736 @^system dependencies@>
737
738 @<Set init...@>=
739 xchr[040]=' ';
740 xchr[041]='!';
741 xchr[042]='"';
742 xchr[043]='#';
743 xchr[044]='$';
744 xchr[045]='%';
745 xchr[046]='&';
746 xchr[047]='\'';@/
747 xchr[050]='(';
748 xchr[051]=')';
749 xchr[052]='*';
750 xchr[053]='+';
751 xchr[054]=',';
752 xchr[055]='-';
753 xchr[056]='.';
754 xchr[057]='/';@/
755 xchr[060]='0';
756 xchr[061]='1';
757 xchr[062]='2';
758 xchr[063]='3';
759 xchr[064]='4';
760 xchr[065]='5';
761 xchr[066]='6';
762 xchr[067]='7';@/
763 xchr[070]='8';
764 xchr[071]='9';
765 xchr[072]=':';
766 xchr[073]=';';
767 xchr[074]='<';
768 xchr[075]='=';
769 xchr[076]='>';
770 xchr[077]='?';@/
771 xchr[0100]='@@';
772 xchr[0101]='A';
773 xchr[0102]='B';
774 xchr[0103]='C';
775 xchr[0104]='D';
776 xchr[0105]='E';
777 xchr[0106]='F';
778 xchr[0107]='G';@/
779 xchr[0110]='H';
780 xchr[0111]='I';
781 xchr[0112]='J';
782 xchr[0113]='K';
783 xchr[0114]='L';
784 xchr[0115]='M';
785 xchr[0116]='N';
786 xchr[0117]='O';@/
787 xchr[0120]='P';
788 xchr[0121]='Q';
789 xchr[0122]='R';
790 xchr[0123]='S';
791 xchr[0124]='T';
792 xchr[0125]='U';
793 xchr[0126]='V';
794 xchr[0127]='W';@/
795 xchr[0130]='X';
796 xchr[0131]='Y';
797 xchr[0132]='Z';
798 xchr[0133]='[';
799 xchr[0134]='\\';
800 xchr[0135]=']';
801 xchr[0136]='^';
802 xchr[0137]='_';@/
803 xchr[0140]='`';
804 xchr[0141]='a';
805 xchr[0142]='b';
806 xchr[0143]='c';
807 xchr[0144]='d';
808 xchr[0145]='e';
809 xchr[0146]='f';
810 xchr[0147]='g';@/
811 xchr[0150]='h';
812 xchr[0151]='i';
813 xchr[0152]='j';
814 xchr[0153]='k';
815 xchr[0154]='l';
816 xchr[0155]='m';
817 xchr[0156]='n';
818 xchr[0157]='o';@/
819 xchr[0160]='p';
820 xchr[0161]='q';
821 xchr[0162]='r';
822 xchr[0163]='s';
823 xchr[0164]='t';
824 xchr[0165]='u';
825 xchr[0166]='v';
826 xchr[0167]='w';@/
827 xchr[0170]='x';
828 xchr[0171]='y';
829 xchr[0172]='z';
830 xchr[0173]='{';
831 xchr[0174]='|';
832 xchr[0175]='}';
833 xchr[0176]='~';@/
834
835 @ Some of the ASCII codes without visible characters have been given symbolic
836 names in this program because they are used with a special meaning.
837
838 @d null_code 00 /*ASCII code that might disappear*/
839 @d carriage_return 015 /*ASCII code used at end of line*/
840 @d invalid_code 0177 /*ASCII code that many systems prohibit in text files*/
841
842 @ The ASCII code is ``standard'' only to a certain extent, since many
843 computer installations have found it advantageous to have ready access
844 to more than 94 printing characters. Appendix~C of {\sl The \TeX book\/}
845 gives a complete specification of the intended correspondence between
846 characters and \TeX's internal representation.
847 @:TeXbook}{\sl The \TeX book@>
848
849 If \TeX\ is being used
850 on a garden-variety \PASCAL\ for which only standard ASCII
851 codes will appear in the input and output files, it doesn't really matter
852 what codes are specified in |xchr[0 dotdot 037]|, but the safest policy is to
853 blank everything out by using the code shown below.
854
855 However, other settings of |xchr| will make \TeX\ more friendly on
856 computers that have an extended character set, so that users can type things
857 like `\.^^Z' instead of `\.{\\ne}'. People with extended character sets can
858 assign codes arbitrarily, giving an |xchr| equivalent to whatever
859 characters the users of \TeX\ are allowed to have in their input files.
860 It is best to make the codes correspond to the intended interpretations as
861 shown in Appendix~C whenever possible; but this is not necessary. For
862 example, in countries with an alphabet of more than 26 letters, it is
863 usually best to map the additional letters into codes less than~040.
864 To get the most ``permissive'' character set, change |' '| on the
865 right of these assignment statements to |chr(i)|.
866 @^character set dependencies@>
867 @^system dependencies@>
868
869 @<Set init...@>=
870 for (i=0; i<=037; i++) xchr[i]=chr(i); /* \TeX\ Live*/
871 for (i=0177; i<=0377; i++) xchr[i]=chr(i); /* \TeX\ Live*/
872
873 @ The following system-independent code makes the |xord| array contain a
874 suitable inverse to the information in |xchr|. Note that if |xchr[i]==xchr[j]|
875 where |i < j < 0177|, the value of |xord[xchr[i]]| will turn out to be
876 |j| or more; hence, standard ASCII code numbers will be used instead of
877 codes below 040 in case there is a coincidence.
878
879 @<Set init...@>=
880 for (i=first_text_char; i<=last_text_char; i++) xord[chr(i)]=invalid_code;
881 for (i=0200; i<=0377; i++) xord[xchr[i]]=i;
882 for (i=0; i<=0176; i++) xord[xchr[i]]=i;
883
884 @* Input and output.
885 The bane of portability is the fact that different operating systems treat
886 input and output quite differently, perhaps because computer scientists
887 have not given sufficient attention to this problem. People have felt somehow
888 that input and output are not part of ``real'' programming. Well, it is true
889 that some kinds of programming are more fun than others. With existing
890 input/output conventions being so diverse and so messy, the only sources of
891 joy in such parts of the code are the rare occasions when one can find a
892 way to make the program a little less bad than it might have been. We have
893 two choices, either to attack I/O now and get it over with, or to postpone
894 I/O until near the end. Neither prospect is very attractive, so let's
895 get it over with.
896
897 The basic operations we need to do are (1)~inputting and outputting of
898 text, to or from a file or the user's terminal; (2)~inputting and
899 outputting of eight-bit bytes, to or from a file; (3)~instructing the
900 operating system to initiate (``open'') or to terminate (``close'') input or
901 output from a specified file; (4)~testing whether the end of an input
902 file has been reached.
903
904 \TeX\ needs to deal with two kinds of files.
905 We shall use the term |alpha_file| for a file that contains textual data,
906 and the term |byte_file| for a file that contains eight-bit binary information.
907 These two types turn out to be the same on many computers, but
908 sometimes there is a significant distinction, so we shall be careful to
909 distinguish between them. Standard protocols for transferring
910 such files from computer to computer, via high-speed networks, are
911 now becoming available to more and more communities of users.
912
913 The program actually makes use also of a third kind of file, called a
914 |word_file|, when dumping and reloading base information for its own
915 initialization. We shall define a word file later; but it will be possible
916 for us to specify simple operations on word files before they are defined.
917
918 @<Types...@>=
919 typedef uint8_t eight_bits; /*unsigned one-byte quantity*/
920 typedef struct {@+FILE *f;@+text_char@,d;@+} alpha_file; /*files that contain textual data*/
921 typedef struct {@+FILE *f;@+eight_bits@,d;@+} byte_file; /*files that contain binary data*/
922
923 @ Most of what we need to do with respect to input and output can be handled
924 by the I/O facilities that are standard in \PASCAL, i.e., the routines
925 called |get|, |put|, |eof|, and so on. But
926 standard \PASCAL\ does not allow file variables to be associated with file
927 names that are determined at run time, so it cannot be used to implement
928 \TeX; some sort of extension to \PASCAL's ordinary |reset| and |rewrite|
929 is crucial for our purposes. We shall assume that |name_of_file| is a variable
930 of an appropriate type such that the \PASCAL\ run-time system being used to
931 implement \TeX\ can open a file whose external name is specified by
932 |name_of_file|.
933 @^system dependencies@>
934
935 @<Glob...@>=
936 static unsigned char @!name_of_file0[file_name_size+1]={0},
937 *const @!name_of_file = @!name_of_file0-1;@;@/
938 /*on some systems this may be a \&{record} variable*/
939 static int @!name_length;@/ /*this many characters are actually
940 relevant in |name_of_file| (the rest are blank)*/
941
942 @ To open files, \TeX\ used \PASCAL's |reset| function.
943 We use the {\tt kpathsearch} library to implement new functions
944 in the section on \TeX\ Live Integration.
945 Here we give only the function prototypes.
946
947 \TeX's file-opening functions do not issue their own
948 error messages if something goes wrong. If a file identified by
949 |name_of_file| cannot be found,
950 or if such a file cannot be opened for some other reason
951 (e.g., someone may already be trying to write the same file)
952 \TeX's file-opening functions return |false|.
953 This allows \TeX\ to undertake appropriate corrective action.
954 @^system dependencies@>
955
956 @p
957 static FILE*open_in(char*filename,kpse_file_format_type t,const char*rwb); /* \TeX\ Live*/
958 static bool a_open_in(alpha_file *f); /*open a text file for input*/
959 static bool b_open_in(byte_file *f); /*open a binary file for input*/
960 static bool w_open_in(word_file *f); /*open a word file for input*/
961 static FILE *open_out(const char *file_name, const char *file_mode); /* \TeX\ Live*/
962 static bool a_open_out(alpha_file *f); /*open a text file for output*/
963 static bool b_open_out(byte_file *f); /*open a binary file for output*/
964 #ifdef @!INIT
965 static bool w_open_out(word_file *f); /*open a word file for output*/
966 #endif
967
968 @ Files can be closed with the \ph\ routine `|pascal_close(f)|', which
969 @:PASCAL H}{\ph@>
970 @^system dependencies@>
971 should be used when all input or output with respect to |f| has been completed.
972 This makes |f| available to be opened again, if desired; and if |f| was used for
973 output, the |pascal_close| operation makes the corresponding external file appear
974 on the user's area, ready to be read.
975
976 These procedures should not generate error messages if a file is
977 being closed before it has been successfully opened.
978
979 @p static void a_close(alpha_file *f) /*close a text file*/
980 {@+pascal_close((*f));
981 }
982 @#
983 static void b_close(byte_file *f) /*close a binary file*/
984 {@+pascal_close((*f));
985 }
986 @#
987 static void w_close(word_file *f) /*close a word file*/
988 {@+pascal_close((*f));
989 }
990
991 @ Binary input and output are done with \PASCAL's ordinary |get| and |put|
992 procedures, so we don't have to make any other special arrangements for
993 binary~I/O. Text output is also easy to do with standard \PASCAL\ routines.
994 The treatment of text input is more difficult, however, because
995 of the necessary translation to |ASCII_code| values.
996 \TeX's conventions should be efficient, and they should
997 blend nicely with the user's operating environment.
998
999 @ Input from text files is read one line at a time, using a routine called
1000 |input_ln|. This function is defined in terms of global variables called
1001 |buffer|, |first|, and |last| that will be described in detail later; for
1002 now, it suffices for us to know that |buffer| is an array of |ASCII_code|
1003 values, and that |first| and |last| are indices into this array
1004 representing the beginning and ending of a line of text.
1005
1006 @<Glob...@>=
1007 static ASCII_code @!buffer[buf_size+1]; /*lines of characters being read*/
1008 static int @!first; /*the first unused position in |buffer|*/
1009 static int @!last; /*end of the line just input to |buffer|*/
1010 static int @!max_buf_stack; /*largest index used in |buffer|*/
1011
1012 @ The |input_ln| function brings the next line of input from the specified
1013 file into available positions of the buffer array and returns the value
1014 |true|, unless the file has already been entirely read, in which case it
1015 returns |false| and sets |last=first|. In general, the |ASCII_code|
1016 numbers that represent the next line of the file are input into
1017 |buffer[first]|, |buffer[first+1]|, \dots, |buffer[last-1]|; and the
1018 global variable |last| is set equal to |first| plus the length of the
1019 line. Trailing blanks are removed from the line; thus, either |last==first|
1020 (in which case the line was entirely blank) or |buffer[last-1]!=' '|.
1021
1022 An overflow error is given, however, if the normal actions of |input_ln|
1023 would make |last >= buf_size|; this is done so that other parts of \TeX\
1024 can safely look at the contents of |buffer[last+1]| without overstepping
1025 the bounds of the |buffer| array. Upon entry to |input_ln|, the condition
1026 |first < buf_size| will always hold, so that there is always room for an
1027 ``empty'' line.
1028
1029 The variable |max_buf_stack|, which is used to keep track of how large
1030 the |buf_size| parameter must be to accommodate the present job, is
1031 also kept up to date by |input_ln|.
1032
1033 If the |bypass_eoln| parameter is |true|, |input_ln| will do a |get|
1034 before looking at the first character of the line; this skips over
1035 an |eoln| that was in |f.d|. The procedure does not do a |get| when it
1036 reaches the end of the line; therefore it can be used to acquire input
1037 from the user's terminal as well as from ordinary text files.
1038
1039 Standard \PASCAL\ says that a file should have |eoln| immediately
1040 before |eof|, but \TeX\ needs only a weaker restriction: If |eof|
1041 occurs in the middle of a line, the system function |eoln| should return
1042 a |true| result (even though |f.d| will be undefined).
1043
1044 Since the inner loop of |input_ln| is part of \TeX's ``inner loop''---each
1045 character of input comes in at this place---it is wise to reduce system
1046 overhead by making use of special routines that read in an entire array
1047 of characters at once, if such routines are available. The following
1048 code uses standard \PASCAL\ to illustrate what needs to be done, but
1049 finer tuning is often possible at well-developed \PASCAL\ sites.
1050 @^inner loop@>
1051
1052 @p static bool input_ln(alpha_file *f, bool @!bypass_eoln)
1053 /*inputs the next line or returns |false|*/
1054 {@+int last_nonblank; /*|last| with trailing blanks removed*/
1055 if (bypass_eoln) if (!eof((*f))) get((*f));
1056 /*input the first character of the line into |f.d|*/
1057 last=first; /*cf.\ Matthew 19\thinspace:\thinspace30*/
1058 if (eof((*f))) return false;
1059 else{@+last_nonblank=first;
1060 while (!eoln((*f)))
1061 {@+if (last >= max_buf_stack)
1062 {@+max_buf_stack=last+1;
1063 if (max_buf_stack==buf_size)
1064 @<Report overflow of the input buffer, and abort@>;
1065 }
1066 buffer[last]=xord[(*f).d];get((*f));incr(last);
1067 if (buffer[last-1]!=' ') last_nonblank=last;
1068 }
1069 last=last_nonblank;return true;
1070 }
1071 }
1072
1073 @ The user's terminal acts essentially like other files of text, except
1074 that it is used both for input and for output. When the terminal is
1075 considered an input file, the file variable is called |term_in|, and when it
1076 is considered an output file the file variable is |term_out|.
1077 @^system dependencies@>
1078
1079 @<Glob...@>=
1080 static alpha_file @!term_in; /*the terminal as an input file*/
1081 static alpha_file @!term_out; /*the terminal as an output file*/
1082
1083 @ Here is how to open the terminal files
1084 in \ph. The `\.{/I}' switch suppresses the first |get|.
1085 @:PASCAL H}{\ph@>
1086 @^system dependencies@>
1087
1088 @d t_open_in term_in.f=stdin /*open the terminal for text input*/
1089 @d t_open_out term_out.f=stdout /*open the terminal for text output*/
1090
1091 @ Sometimes it is necessary to synchronize the input/output mixture that
1092 happens on the user's terminal, and three system-dependent
1093 procedures are used for this
1094 purpose. The first of these, |update_terminal|, is called when we want
1095 to make sure that everything we have output to the terminal so far has
1096 actually left the computer's internal buffers and been sent.
1097 The second, |clear_terminal|, is called when we wish to cancel any
1098 input that the user may have typed ahead (since we are about to
1099 issue an unexpected error message). The third, |wake_up_terminal|,
1100 is supposed to revive the terminal if the user has disabled it by
1101 some instruction to the operating system. The following macros show how
1102 these operations can be specified in \ph:
1103 @:PASCAL H}{\ph@>
1104 @^system dependencies@>
1105
1106 @d update_terminal fflush(term_out.f) /*empty the terminal output buffer*/
1107 @d clear_terminal fflush(term_in.f) /*clear the terminal input buffer*/
1108 @d wake_up_terminal do_nothing /*cancel the user's cancellation of output*/
1109
1110 @ We need a special routine to read the first line of \TeX\ input from
1111 the user's terminal. This line is different because it is read before we
1112 have opened the transcript file; there is sort of a ``chicken and
1113 egg'' problem here. If the user types `\.{\\input paper}' on the first
1114 line, or if some macro invoked by that line does such an \.{\\input},
1115 the transcript file will be named `\.{paper.log}'; but if no \.{\\input}
1116 commands are performed during the first line of terminal input, the transcript
1117 file will acquire its default name `\.{texput.log}'. (The transcript file
1118 will not contain error messages generated by the first line before the
1119 first \.{\\input} command.)
1120 @.texput@>
1121
1122 The first line is even more special if we are lucky enough to have an operating
1123 system that treats \TeX\ differently from a run-of-the-mill \PASCAL\ object
1124 program. It's nice to let the user start running a \TeX\ job by typing
1125 a command line like `\.{tex paper}'; in such a case, \TeX\ will operate
1126 as if the first line of input were `\.{paper}', i.e., the first line will
1127 consist of the remainder of the command line, after the part that invoked
1128 \TeX.
1129
1130 The first line is special also because it may be read before \TeX\ has
1131 input a format file. In such cases, normal error messages cannot yet
1132 be given. The following code uses concepts that will be explained later.
1133 (If the \PASCAL\ compiler does not support non-local |@!goto|\unskip, the
1134 @^system dependencies@>
1135 statement `|goto exit(0)|' should be replaced by something that
1136 quietly terminates the program.)
1137
1138 @<Report overflow of the input buffer, and abort@>=
1139 if (format_ident==0)
1140 {@+write_ln(term_out,"Buffer size exceeded!");exit(0);
1141 @.Buffer size exceeded@>
1142 }
1143 else{@+cur_input.loc_field=first;cur_input.limit_field=last-1;
1144 overflow("buffer size", buf_size);
1145 @:TeX capacity exceeded buffer size}{\quad buffer size@>
1146 }
1147
1148 @ Different systems have different ways to get started. But regardless of
1149 what conventions are adopted, the routine that initializes the terminal
1150 should satisfy the following specifications:
1151
1152 \yskip\textindent{1)}It should open file |term_in| for input from the
1153 terminal. (The file |term_out| will already be open for output to the
1154 terminal.)
1155
1156 \textindent{2)}If the user has given a command line, this line should be
1157 considered the first line of terminal input. Otherwise the
1158 user should be prompted with `\.{**}', and the first line of input
1159 should be whatever is typed in response.
1160
1161 \textindent{3)}The first line of input, which might or might not be a
1162 command line, should appear in locations |first| to |last-1| of the
1163 |buffer| array.
1164
1165 \textindent{4)}The global variable |loc| should be set so that the
1166 character to be read next by \TeX\ is in |buffer[loc]|. This
1167 character should not be blank, and we should have |loc < last|.
1168
1169 \yskip\noindent(It may be necessary to prompt the user several times
1170 before a non-blank line comes in. The prompt is `\.{**}' instead of the
1171 later `\.*' because the meaning is slightly different: `\.{\\input}' need
1172 not be typed immediately after~`\.{**}'.)
1173
1174 @d loc cur_input.loc_field /*location of first unread character in |buffer|*/
1175
1176 @ The following routine calls |input_command_line|
1177 to retrieve a possible command line.
1178 @^system dependencies@>
1179
1180 @p static bool init_terminal(void) /*gets the terminal input started*/
1181 {@+
1182 t_open_in;
1183 if (input_command_line()) return true; /* \TeX\ Live */
1184 loop@+{@+wake_up_terminal;pascal_write(term_out,"**");update_terminal;
1185 @.**@>
1186 if (!input_ln(&term_in, true)) /*this shouldn't happen*/
1187 {@+write_ln(term_out);
1188 pascal_write(term_out,"! End of file on the terminal... why?");
1189 @.End of file on the terminal@>
1190 return false;
1191 }
1192 loc=first;
1193 while ((loc < last)&&(buffer[loc]==' ')) incr(loc);
1194 if (loc < last)
1195 {@+return true;
1196 /*return unless the line was all blank*/
1197 }
1198 write_ln(term_out,"Please type the name of your input file.");
1199 }
1200 }
1201
1202 @* String handling.
1203 Control sequence names and diagnostic messages are variable-length strings
1204 of eight-bit characters. Since \PASCAL\ does not have a well-developed string
1205 mechanism, \TeX\ does all of its string processing by homegrown methods.
1206
1207 Elaborate facilities for dynamic strings are not needed, so all of the
1208 necessary operations can be handled with a simple data structure.
1209 The array |str_pool| contains all of the (eight-bit) ASCII codes in all
1210 of the strings, and the array |str_start| contains indices of the starting
1211 points of each string. Strings are referred to by integer numbers, so that
1212 string number |s| comprises the characters |str_pool[j]| for
1213 |str_start[s] <= j < str_start[s+1]|. Additional integer variables
1214 |pool_ptr| and |str_ptr| indicate the number of entries used so far
1215 in |str_pool| and |str_start|, respectively; locations
1216 |str_pool[pool_ptr]| and |str_start[str_ptr]| are
1217 ready for the next string to be allocated.
1218
1219 String numbers 0 to 255 are reserved for strings that correspond to single
1220 ASCII characters. This is in accordance with the conventions of \.{WEB},
1221 @.WEB@>
1222 which converts single-character strings into the ASCII code number of the
1223 single character involved, while it converts other strings into integers
1224 and builds a string pool file. Thus, when the string constant \.{"."} appears
1225 in the program below, \.{WEB} converts it into the integer 46, which is the
1226 ASCII code for a period, while \.{WEB} will convert a string like \.{"hello"}
1227 into some integer greater than~255. String number 46 will presumably be the
1228 single character `\..'; but some ASCII codes have no standard visible
1229 representation, and \TeX\ sometimes needs to be able to print an arbitrary
1230 ASCII character, so the first 256 strings are used to specify exactly what
1231 should be printed for each of the 256 possibilities.
1232
1233 Elements of the |str_pool| array must be ASCII codes that can actually
1234 be printed; i.e., they must have an |xchr| equivalent in the local
1235 character set. (This restriction applies only to preloaded strings,
1236 not to those generated dynamically by the user.)
1237
1238 Some \PASCAL\ compilers won't pack integers into a single byte unless the
1239 integers lie in the range |-128 dotdot 127|. To accommodate such systems
1240 we access the string pool only via macros that can easily be redefined.
1241 @^system dependencies@>
1242
1243 @d si(A) A /*convert from |ASCII_code| to |packed_ASCII_code|*/
1244 @d so(A) A /*convert from |packed_ASCII_code| to |ASCII_code|*/
1245
1246 @<Types...@>=
1247 typedef int32_t pool_pointer; /*for variables that point into |str_pool|*/
1248 typedef int32_t str_number; /*for variables that point into |str_start|*/
1249 typedef uint8_t packed_ASCII_code; /*elements of |str_pool| array*/
1250
1251 @ @<Glob...@>=
1252 static packed_ASCII_code @!str_pool[pool_size+1]; /*the characters*/
1253 static pool_pointer @!str_start[max_strings+1]; /*the starting pointers*/
1254 static pool_pointer @!pool_ptr; /*first unused position in |str_pool|*/
1255 static str_number @!str_ptr; /*number of the current string being created*/
1256 static pool_pointer @!init_pool_ptr; /*the starting value of |pool_ptr|*/
1257 static str_number @!init_str_ptr; /*the starting value of |str_ptr|*/
1258
1259 @ Several of the elementary string operations are performed using \.{WEB}
1260 macros instead of \PASCAL\ procedures, because many of the
1261 operations are done quite frequently and we want to avoid the
1262 overhead of procedure calls. For example, here is
1263 a simple macro that computes the length of a string.
1264 @.WEB@>
1265
1266 @d length(A) (str_start[A+1]-str_start[A]) /*the number of characters
1267 in string number \#*/
1268
1269 @ The length of the current string is called |cur_length|:
1270
1271 @d cur_length (pool_ptr-str_start[str_ptr])
1272
1273 @ Strings are created by appending character codes to |str_pool|.
1274 The |append_char| macro, defined here, does not check to see if the
1275 value of |pool_ptr| has gotten too high; this test is supposed to be
1276 made before |append_char| is used. There is also a |flush_char|
1277 macro, which erases the last character appended.
1278
1279 To test if there is room to append |l| more characters to |str_pool|,
1280 we shall write |str_room(l)|, which aborts \TeX\ and gives an
1281 apologetic error message if there isn't enough room.
1282
1283 @d append_char(A) /*put |ASCII_code| \# at the end of |str_pool|*/
1284 {@+str_pool[pool_ptr]=si(A);incr(pool_ptr);
1285 }
1286 @d flush_char decr(pool_ptr) /*forget the last character in the pool*/
1287 @d str_room(A) /*make sure that the pool hasn't overflowed*/
1288 {@+if (pool_ptr+A > pool_size)
1289 overflow("pool size", pool_size-init_pool_ptr);
1290 @:TeX capacity exceeded pool size}{\quad pool size@>
1291 }
1292
1293 @ Once a sequence of characters has been appended to |str_pool|, it
1294 officially becomes a string when the function |make_string| is called.
1295 This function returns the identification number of the new string as its
1296 value.
1297
1298 @p static str_number make_string(void) /*current string enters the pool*/
1299 {@+if (str_ptr==max_strings)
1300 overflow("number of strings", max_strings-init_str_ptr);
1301 @:TeX capacity exceeded number of strings}{\quad number of strings@>
1302 incr(str_ptr);str_start[str_ptr]=pool_ptr;
1303 return str_ptr-1;
1304 }
1305
1306 @ To destroy the most recently made string, we say |flush_string|.
1307
1308 @d flush_string {@+decr(str_ptr);pool_ptr=str_start[str_ptr];
1309 }
1310
1311 @ The following subroutine compares string |s| with another string of the
1312 same length that appears in |buffer| starting at position |k|;
1313 the result is |true| if and only if the strings are equal.
1314 Empirical tests indicate that |str_eq_buf| is used in such a way that
1315 it tends to return |true| about 80 percent of the time.
1316
1317 @p static bool str_eq_buf(str_number @!s, int @!k)
1318 /*test equality of strings*/
1319 {@+ /*loop exit*/
1320 pool_pointer j; /*running index*/
1321 bool @!result; /*result of comparison*/
1322 j=str_start[s];
1323 while (j < str_start[s+1])
1324 {@+if (so(str_pool[j])!=buffer[k])
1325 {@+result=false;goto not_found;
1326 }
1327 incr(j);incr(k);
1328 }
1329 result=true;
1330 not_found: return result;
1331 }
1332
1333 @ Here is a similar routine, but it compares two strings in the string pool,
1334 and it does not assume that they have the same length.
1335
1336 @p static bool str_eq_str(str_number @!s, str_number @!t)
1337 /*test equality of strings*/
1338 {@+ /*loop exit*/
1339 pool_pointer j, @!k; /*running indices*/
1340 bool @!result; /*result of comparison*/
1341 result=false;
1342 if (length(s)!=length(t)) goto not_found;
1343 j=str_start[s];k=str_start[t];
1344 while (j < str_start[s+1])
1345 {@+if (str_pool[j]!=str_pool[k]) goto not_found;
1346 incr(j);incr(k);
1347 }
1348 result=true;
1349 not_found: return result;
1350 }
1351 @t\4@>@<Declare \Prote\ procedures for strings@>@;
1352
1353 @ The initial values of |str_pool|, |str_start|, |pool_ptr|,
1354 and |str_ptr| are computed by the \.{INITEX} program, based in part
1355 on the information that \.{WEB} has output while processing \TeX.
1356 @.INITEX@>
1357 @^string pool@>
1358
1359 @p
1360 static bool get_strings_started(void) /*initializes the string pool*/
1361 {@+
1362 int k, @!l; /*small indices or counters*/
1363 pool_ptr=0;str_ptr=0;str_start[0]=0;
1364 @<Make the first 256 strings@>;
1365 @<Add the empty string to the string pool@>;
1366 return true;
1367 }
1368
1369 @ @d app_lc_hex(A) l=A;
1370 if (l < 10) append_char(l+'0')@;@+else append_char(l-10+'a')
1371
1372 @<Make the first 256...@>=
1373 for (k=0; k<=255; k++)
1374 {@+if ((@<Character |k| cannot be printed@>))
1375 {@+append_char('^');append_char('^');
1376 if (k < 0100) append_char(k+0100)@;
1377 else if (k < 0200) append_char(k-0100)@;
1378 else{@+app_lc_hex(k/16);app_lc_hex(k%16);
1379 }
1380 }
1381 else append_char(k);
1382 make_string();
1383 }
1384
1385 @ The first 128 strings will contain 95 standard ASCII characters, and the
1386 other 33 characters will be printed in three-symbol form like `\.{\^\^A}'
1387 unless a system-dependent change is made here. Installations that have
1388 an extended character set, where for example |xchr[032]==@t\.{\'^^Z\'}@>|,
1389 would like string 032 to be the single character 032 instead of the
1390 three characters 0136, 0136, 0132 (\.{\^\^Z}). On the other hand,
1391 even people with an extended character set will want to represent string
1392 015 by \.{\^\^M}, since 015 is |carriage_return|; the idea is to
1393 produce visible strings instead of tabs or line-feeds or carriage-returns
1394 or bell-rings or characters that are treated anomalously in text files.
1395
1396 Unprintable characters of codes 128--255 are, similarly, rendered
1397 \.{\^\^80}--\.{\^\^ff}.
1398
1399 The boolean expression defined here should be |true| unless \TeX\
1400 internal code number~|k| corresponds to a non-troublesome visible
1401 symbol in the local character set. An appropriate formula for the
1402 extended character set recommended in {\sl The \TeX book\/} would, for
1403 example, be `|k in[0, 010 dotdot 012, 014, 015, 033, 0177 dotdot 0377]|'.
1404 If character |k| cannot be printed, and |k < 0200|, then character |k+0100| or
1405 |k-0100| must be printable; moreover, ASCII codes |[041 dotdot 046,
1406 060 dotdot 071, 0136, 0141 dotdot 0146, 0160 dotdot 0171]| must be printable.
1407 Thus, at least 80 printable characters are needed.
1408 @:TeXbook}{\sl The \TeX book@>
1409 @^character set dependencies@>
1410 @^system dependencies@>
1411
1412 @<Character |k| cannot be printed@>=
1413 (k < ' ')||(k > '~')
1414
1415 @ The |pool_file| variable is no longer needed and has been removed.
1416
1417 Instead of reading the other strings from the \.{TEX.POOL} file,
1418 it is sufficient here to add the empty string.
1419 @<Add the empty string to the string pool@>=
1420 make_string();
1421
1422 @ Without a string pool file there is no need for a pool check sum either.
1423 But this is a convenient place to define the function |s_no| that will
1424 add literal strings to the string pool at runtime, thereby obtaining their
1425 string number.
1426
1427 @p static int s_no(const char *str)
1428 {@+
1429 if (str[0]==0) return empty_string;
1430 if (str[1]==0) return str[0];
1431 str_room(strlen(str));
1432 while (*str!=0) append_char(*str++);
1433 return make_string();
1434 }
1435
1436 @ The function |s_no| is used in |initialize| and needs a forward
1437 declaration.
1438
1439 @<Forward declarations@>=
1440 static int s_no(const char *str);
1441
1442 @* On-line and off-line printing.
1443 Messages that are sent to a user's terminal and to the transcript-log file
1444 are produced by several `|print|' procedures. These procedures will
1445 direct their output to a variety of places, based on the setting of
1446 the global variable |selector|, which has the following possible
1447 values:
1448
1449 \yskip
1450 \hang |term_and_log|, the normal setting, prints on the terminal and on the
1451 transcript file.
1452
1453 \hang |log_only|, prints only on the transcript file.
1454
1455 \hang |term_only|, prints only on the terminal.
1456
1457 \hang |no_print|, doesn't print at all. This is used only in rare cases
1458 before the transcript file is open.
1459
1460 \hang |pseudo|, puts output into a cyclic buffer that is used
1461 by the |show_context| routine; when we get to that routine we shall discuss
1462 the reasoning behind this curious mode.
1463
1464 \hang |new_string|, appends the output to the current string in the
1465 string pool.
1466
1467 \hang 0 to 15, prints on one of the sixteen files for \.{\\write} output.
1468
1469 \yskip
1470 \noindent The symbolic names `|term_and_log|', etc., have been assigned
1471 numeric codes that satisfy the convenient relations |no_print+1==term_only|,
1472 |no_print+2==log_only|, |term_only+2==log_only+1==term_and_log|.
1473
1474 Three additional global variables, |tally| and |term_offset| and
1475 |file_offset|, record the number of characters that have been printed
1476 since they were most recently cleared to zero. We use |tally| to record
1477 the length of (possibly very long) stretches of printing; |term_offset|
1478 and |file_offset|, on the other hand, keep track of how many characters
1479 have appeared so far on the current line that has been output to the
1480 terminal or to the transcript file, respectively.
1481
1482 @d no_print 16 /*|selector| setting that makes data disappear*/
1483 @d term_only 17 /*printing is destined for the terminal only*/
1484 @d log_only 18 /*printing is destined for the transcript file only*/
1485 @d term_and_log 19 /*normal |selector| setting*/
1486 @d pseudo 20 /*special |selector| setting for |show_context|*/
1487 @d new_string 21 /*printing is deflected to the string pool*/
1488 @d max_selector 21 /*highest selector setting*/
1489
1490 @<Glob...@>=
1491 static alpha_file @!log_file; /*transcript of \TeX\ session*/
1492 static int @!selector; /*where to print a message*/
1493 static int8_t @!dig[23]; /*digits in a number being output*/
1494 static int @!tally; /*the number of characters recently printed*/
1495 static int @!term_offset;
1496 /*the number of characters on the current terminal line*/
1497 static int @!file_offset;
1498 /*the number of characters on the current file line*/
1499 static ASCII_code @!trick_buf[error_line+1]; /*circular buffer for
1500 pseudoprinting*/
1501 static int @!trick_count; /*threshold for pseudoprinting, explained later*/
1502 static int @!first_count; /*another variable for pseudoprinting*/
1503
1504 @ @<Initialize the output routines@>=
1505 selector=term_only;tally=0;term_offset=0;file_offset=0;
1506
1507 @ Macro abbreviations for output to the terminal and to the log file are
1508 defined here for convenience. Some systems need special conventions
1509 for terminal output, and it is possible to adhere to those conventions
1510 by changing |wterm|, |wterm_ln|, and |wterm_cr| in this section.
1511 @^system dependencies@>
1512
1513 @<Basic printing procedures@>=
1514 #define @[put(F)@] @[fwrite(&((F).d)@],@[sizeof((F).d),1,(F).f)@]@;
1515 #define @[get(F)@] @[(void)!fread(&((F).d),sizeof((F).d),1,(F).f)@]
1516
1517 #define @[pascal_close(F)@] @[fclose((F).f)@]
1518 #define @[eof(F)@] @[feof((F).f)@]
1519 #define @[eoln(F)@] @[((F).d=='\n'||eof(F))@]
1520 #define @[erstat(F)@] @[((F).f==NULL?-1:ferror((F).f))@]
1521
1522 #define @[pascal_read(F,X)@] @[((X)=(F).d,get(F))@]
1523 #define @[read_ln(F)@] do get(F); while (!eoln(F))
1524
1525 #define @[pascal_write(F, FMT,...)@] @[fprintf(F.f,FMT,## __VA_ARGS__)@]
1526 #define @[write_ln(F,...)@] @[pascal_write(F,__VA_ARGS__"\n")@]
1527
1528 #define @[wterm(FMT,...)@] @[pascal_write(term_out,FMT, ## __VA_ARGS__)@]
1529 #define @[wterm_ln(FMT,...)@] @[wterm(FMT "\n", ## __VA_ARGS__)@]
1530 #define wterm_cr @[pascal_write(term_out,"\n")@]
1531 #define @[wlog(FMT, ...)@] @[pascal_write(log_file,FMT, ## __VA_ARGS__)@]
1532 #define @[wlog_ln(FMT, ...)@] @[wlog(FMT "\n", ## __VA_ARGS__)@]
1533 #define wlog_cr @[pascal_write(log_file,"\n")@]
1534
1535 @ To end a line of text output, we call |print_ln|.
1536
1537 @<Basic print...@>=
1538 static void print_ln(void) /*prints an end-of-line*/
1539 {@+switch (selector) {
1540 case term_and_log: {@+wterm_cr;wlog_cr;
1541 term_offset=0;file_offset=0;
1542 } @+break;
1543 case log_only: {@+wlog_cr;file_offset=0;
1544 } @+break;
1545 case term_only: {@+wterm_cr;term_offset=0;
1546 } @+break;
1547 case no_print: case pseudo: case new_string: do_nothing;@+break;
1548 default:write_ln(write_file[selector]);
1549 } @/
1550 } /*|tally| is not affected*/
1551
1552 @ The |print_char| procedure sends one character to the desired destination,
1553 using the |xchr| array to map it into an external character compatible with
1554 |input_ln|. All printing comes through |print_ln| or |print_char|.
1555
1556 @<Basic printing...@>=
1557 static void print_char(ASCII_code @!s) /*prints a single character*/
1558 {@+
1559 if (@<Character |s| is the current new-line character@>)
1560 if (selector < pseudo)
1561 {@+print_ln();return;
1562 }
1563 switch (selector) {
1564 case term_and_log: {@+wterm("%c",xchr[s]);wlog("%c",xchr[s]);
1565 incr(term_offset);incr(file_offset);
1566 if (term_offset==max_print_line)
1567 {@+wterm_cr;term_offset=0;
1568 }
1569 if (file_offset==max_print_line)
1570 {@+wlog_cr;file_offset=0;
1571 }
1572 } @+break;
1573 case log_only: {@+wlog("%c",xchr[s]);incr(file_offset);
1574 if (file_offset==max_print_line) print_ln();
1575 } @+break;
1576 case term_only: {@+wterm("%c",xchr[s]);incr(term_offset);
1577 if (term_offset==max_print_line) print_ln();
1578 } @+break;
1579 case no_print: do_nothing;@+break;
1580 case pseudo: if (tally < trick_count) trick_buf[tally%error_line]=s;@+break;
1581 case new_string: {@+if (pool_ptr < pool_size) append_char(s);
1582 } @+break; /*we drop characters if the string space is full*/
1583 default:pascal_write(write_file[selector],"%c", xchr[s]);
1584 } @/
1585 incr(tally);
1586 }
1587
1588 @ An entire string is output by calling |print|. Note that if we are outputting
1589 the single standard ASCII character \.c, we could call |print('c')|, since
1590 |'c'==99| is the number of a single-character string, as explained above. But
1591 |print_char('c')| is quicker, so \TeX\ goes directly to the |print_char|
1592 routine when it knows that this is safe. (The present implementation
1593 assumes that it is always safe to print a visible ASCII character.)
1594 @^system dependencies@>
1595
1596 @<Basic print...@>=
1597 static void print(char *s) /* the simple version */
1598 { @+if (s == NULL) s="???"; /*this can't happen*/
1599 while (*s!=0) print_char(*s++);@+
1600 }
1601
1602 static void printn(int @!s) /*prints string |s|*/
1603 {@+
1604 pool_pointer j; /*current character code position*/
1605 int @!nl; /*new-line character to restore*/
1606 if (s >= str_ptr) {print("???"); return;}/*this can't happen*/
1607 @.???@>
1608 else if (s < 256)
1609 if (s < 0) { print("???");return; } /*can't happen*/
1610 else{@+if (selector > pseudo)
1611 {@+print_char(s);return; /*internal strings are not expanded*/
1612 }
1613 if ((@<Character |s| is the current new-line character@>))
1614 if (selector < pseudo)
1615 {@+print_ln();return;
1616 }
1617 nl=new_line_char;new_line_char=-1;
1618 /*temporarily disable new-line character*/
1619 j=str_start[s];
1620 while (j < str_start[s+1])
1621 {@+print_char(so(str_pool[j]));incr(j);
1622 }
1623 new_line_char=nl;return;
1624 }
1625 j=str_start[s];
1626 while (j < str_start[s+1])
1627 {@+print_char(so(str_pool[j]));incr(j);
1628 }
1629 }
1630
1631 @ Control sequence names, file names, and strings constructed with
1632 \.{\\string} might contain |ASCII_code| values that can't
1633 be printed using |print_char|. Therefore we use |slow_print| for them:
1634
1635 @<Basic print...@>=
1636 static void slow_print(int @!s) /*prints string |s|*/
1637 {@+pool_pointer j; /*current character code position*/
1638 if ((s >= str_ptr)||(s < 256)) printn(s);
1639 else{@+j=str_start[s];
1640 while (j < str_start[s+1])
1641 {@+printn(so(str_pool[j]));incr(j);
1642 }
1643 }
1644 }
1645
1646 @ Here is the very first thing that \TeX\ prints: a headline that identifies
1647 the version number and format package. The |term_offset| variable is temporarily
1648 incorrect, but the discrepancy is not serious since we assume that this
1649 part of the program is system dependent.
1650 @^system dependencies@>
1651
1652 According to the conventions of \TeX\ Live,
1653 we print the |dump_name| if no format identifier is known.
1654 @<Initialize the output...@>=
1655 wterm("%s",banner);
1656 if (format_ident==0) wterm_ln(" (preloaded format=%s)", dump_name);
1657 else{@+slow_print(format_ident);print_ln();
1658 }
1659 update_terminal;
1660
1661 @ The procedure |print_nl| is like |print|, but it makes sure that the
1662 string appears at the beginning of a new line.
1663
1664 @<Basic print...@>=
1665 static void print_nl(char *@!s) /*prints string |s| at beginning of line*/
1666 {@+if (((term_offset > 0)&&(odd(selector)))||@|
1667 ((file_offset > 0)&&(selector >= log_only))) print_ln();
1668 print(s);
1669 }
1670
1671 @ The procedure |print_esc| prints a string that is preceded by
1672 the user's escape character (which is usually a backslash).
1673
1674 @<Basic print...@>=
1675 static void printn_esc(str_number @!s) /*prints escape character, then |s|*/
1676 {@+int c; /*the escape character code*/
1677 @<Set variable |c| to the current escape character@>;
1678 if (c >= 0) if (c < 256) printn(c);
1679 slow_print(s);
1680 }
1681
1682 static void print_esc(char *@!s) /*the fast way*/
1683 {@+int c; /*the escape character code*/
1684 @<Set variable |c| to the current escape character@>;
1685 if (c >= 0) if (c < 256) printn(c);
1686 print(s);
1687 }
1688
1689 @ An array of digits in the range |0 dotdot 15| is printed by |print_the_digs|.
1690
1691 @<Basic print...@>=
1692 static void print_the_digs(eight_bits @!k)
1693 /*prints |dig[k-1]|$\,\ldots\,$|dig[0]|*/
1694 {@+while (k > 0)
1695 {@+decr(k);
1696 if (dig[k] < 10) print_char('0'+dig[k]);
1697 else print_char('A'-10+dig[k]);
1698 }
1699 }
1700
1701 @ The following procedure, which prints out the decimal representation of a
1702 given integer |n|, has been written carefully so that it works properly
1703 if |n==0| or if |(-n)| would cause overflow. It does not apply |%| or |/|
1704 to negative arguments, since such operations are not implemented consistently
1705 by all \PASCAL\ compilers.
1706
1707 @<Basic print...@>=
1708 static void print_int(int @!n) /*prints an integer in decimal form*/
1709 {@+int k; /*index to current digit; we assume that $\vert n\vert<10^{23}$*/
1710 int @!m; /*used to negate |n| in possibly dangerous cases*/
1711 k=0;
1712 if (n < 0)
1713 {@+print_char('-');
1714 if (n > -100000000) negate(n);
1715 else{@+m=-1-n;n=m/10;m=(m%10)+1;k=1;
1716 if (m < 10) dig[0]=m;
1717 else{@+dig[0]=0;incr(n);
1718 }
1719 }
1720 }
1721 @/do@+{dig[k]=n%10;n=n/10;incr(k);
1722 }@+ while (!(n==0));
1723 print_the_digs(k);
1724 }
1725
1726 @ Here is a trivial procedure to print two digits; it is usually called with
1727 a parameter in the range |0 <= n <= 99|.
1728
1729 @p static void print_two(int @!n) /*prints two least significant digits*/
1730 {@+n=abs(n)%100;print_char('0'+(n/10));
1731 print_char('0'+(n%10));
1732 }
1733
1734 @ Hexadecimal printing of nonnegative integers is accomplished by |print_hex|.
1735
1736 @p static void print_hex(int @!n)
1737 /*prints a positive integer in hexadecimal form*/
1738 {@+int k; /*index to current digit; we assume that $0\le n<16^{22}$*/
1739 k=0;print_char('"');
1740 @/do@+{dig[k]=n%16;n=n/16;incr(k);
1741 }@+ while (!(n==0));
1742 print_the_digs(k);
1743 }
1744
1745 @ Old versions of \TeX\ needed a procedure called |print_ASCII| whose function
1746 is now subsumed by |print|. We retain the old name here as a possible aid to
1747 future software arch\ae ologists.
1748
1749 @d print_ASCII printn
1750
1751 @ Roman numerals are produced by the |print_roman_int| routine. Readers
1752 who like puzzles might enjoy trying to figure out how this tricky code
1753 works; therefore no explanation will be given. Notice that 1990 yields
1754 \.{mcmxc}, not \.{mxm}.
1755
1756 @p static void print_roman_int(int @!n)
1757 {@+
1758 pool_pointer j, @!k; /*mysterious indices into |mystery|*/
1759 nonnegative_integer @!u, @!v; /*mysterious numbers*/
1760 const char mystery[] ="m2d5c2l5x2v5i";
1761 j=0;v=1000;
1762 loop@+{@+while (n >= v)
1763 {@+print_char(so(mystery[j]));n=n-v;
1764 }
1765 if (n <= 0) return; /*nonpositive input produces no output*/
1766 k=j+2;u=v/(so(mystery[k-1])-'0');
1767 if (mystery[k-1]==si('2'))
1768 {@+k=k+2;u=u/(so(mystery[k-1])-'0');
1769 }
1770 if (n+u >= v)
1771 {@+print_char(so(mystery[k]));n=n+u;
1772 }
1773 else{@+j=j+2;v=v/(so(mystery[j-1])-'0');
1774 }
1775 }
1776 }
1777
1778 @ The |print| subroutine will not print a string that is still being
1779 created. The following procedure will.
1780
1781 @p static void print_current_string(void) /*prints a yet-unmade string*/
1782 {@+pool_pointer j; /*points to current character code*/
1783 j=str_start[str_ptr];
1784 while (j < pool_ptr)
1785 {@+print_char(so(str_pool[j]));incr(j);
1786 }
1787 }
1788
1789 @ Here is a procedure that asks the user to type a line of input,
1790 assuming that the |selector| setting is either |term_only| or |term_and_log|.
1791 The input is placed into locations |first| through |last-1| of the
1792 |buffer| array, and echoed on the transcript file if appropriate.
1793
1794 This procedure is never called when |interaction < scroll_mode|.
1795
1796 @d prompt_input(A) {@+wake_up_terminal;print(A);term_input();
1797 } /*prints a string and gets a line of input*/
1798
1799 @p static void term_input(void) /*gets a line from the terminal*/
1800 {@+int k; /*index into |buffer|*/
1801 update_terminal; /*now the user sees the prompt for sure*/
1802 if (!input_ln(&term_in, true)) fatal_error("End of file on the terminal!");
1803 @.End of file on the terminal@>
1804 term_offset=0; /*the user's line ended with \<\rm return>*/
1805 decr(selector); /*prepare to echo the input*/
1806 if (last!=first) for (k=first; k<=last-1; k++) printn(buffer[k]);
1807 print_ln();incr(selector); /*restore previous status*/
1808 }
1809
1810 @* Reporting errors.
1811 When something anomalous is detected, \TeX\ typically does something like this:
1812 $$\vbox{\halign{#\hfil\cr
1813 |print_err("Something anomalous has been detected");|\cr
1814 |help3("This is the first line of my offer to help.")|\cr
1815 |("This is the second line. I'm trying to")|\cr
1816 |("explain the best way for you to proceed.");|\cr
1817 |error;|\cr}}$$
1818 A two-line help message would be given using |help2|, etc.; these informal
1819 helps should use simple vocabulary that complements the words used in the
1820 official error message that was printed. (Outside the U.S.A., the help
1821 messages should preferably be translated into the local vernacular. Each
1822 line of help is at most 60 characters long, in the present implementation,
1823 so that |max_print_line| will not be exceeded.)
1824
1825 The |print_err| procedure supplies a `\.!' before the official message,
1826 and makes sure that the terminal is awake if a stop is going to occur.
1827 The |error| procedure supplies a `\..' after the official message, then it
1828 shows the location of the error; and if |interaction==error_stop_mode|,
1829 it also enters into a dialog with the user, during which time the help
1830 message may be printed.
1831 @^system dependencies@>
1832
1833 @<Error handling...@>=
1834 static void print_err(char *s)
1835 {@+if (interaction==error_stop_mode) wake_up_terminal;
1836 if (filelineerrorstylep) print_file_line(); /* \TeX\ Live */
1837 else print_nl("! ");
1838 print(s);
1839 }
1840
1841 @ The global variable |interaction| has four settings, representing increasing
1842 amounts of user interaction:
1843
1844 @d batch_mode 0 /*omits all stops and omits terminal output*/
1845 @d nonstop_mode 1 /*omits all stops*/
1846 @d scroll_mode 2 /*omits error stops*/
1847 @d error_stop_mode 3 /*stops at every opportunity to interact*/
1848
1849 @<Glob...@>=
1850 static int @!interaction; /*current level of interaction*/
1851
1852 @ @<Set init...@>=
1853 if (interaction_option<0) interaction=error_stop_mode;
1854 else interaction=interaction_option; /* \TeX\ Live */
1855
1856 @ \TeX\ is careful not to call |error| when the print |selector| setting
1857 might be unusual. The only possible values of |selector| at the time of
1858 error messages are
1859
1860 \yskip\hang|no_print| (when |interaction==batch_mode|
1861 and |log_file| not yet open);
1862
1863 \hang|term_only| (when |interaction > batch_mode| and |log_file| not yet open);
1864
1865 \hang|log_only| (when |interaction==batch_mode| and |log_file| is open);
1866
1867 \hang|term_and_log| (when |interaction > batch_mode| and |log_file| is open).
1868
1869 @<Initialize the print |selector| based on |interaction|@>=
1870 if (interaction==batch_mode) selector=no_print;@+else selector=term_only
1871
1872 @ A global variable |deletions_allowed| is set |false| if the |get_next|
1873 routine is active when |error| is called; this ensures that |get_next|
1874 and related routines like |get_token| will never be called recursively.
1875 A similar interlock is provided by |set_box_allowed|.
1876 @^recursion@>
1877
1878 The global variable |history| records the worst level of error that
1879 has been detected. It has four possible values: |spotless|, |warning_issued|,
1880 |error_message_issued|, and |fatal_error_stop|.
1881
1882 Another global variable, |error_count|, is increased by one when an
1883 |error| occurs without an interactive dialog, and it is reset to zero at
1884 the end of every paragraph. If |error_count| reaches 100, \TeX\ decides
1885 that there is no point in continuing further.
1886
1887 @d spotless 0 /*|history| value when nothing has been amiss yet*/
1888 @d warning_issued 1 /*|history| value when |begin_diagnostic| has been called*/
1889 @d error_message_issued 2 /*|history| value when |error| has been called*/
1890 @d fatal_error_stop 3 /*|history| value when termination was premature*/
1891
1892 @<Glob...@>=
1893 static bool @!deletions_allowed; /*is it safe for |error| to call |get_token|?*/
1894 static bool @!set_box_allowed; /*is it safe to do a \.{\\setbox} assignment?*/
1895 static int @!history; /*has the source input been clean so far?*/
1896 static int @!error_count; /*the number of scrolled errors since the
1897 last paragraph ended*/
1898
1899 @ The value of |history| is initially |fatal_error_stop|, but it will
1900 be changed to |spotless| if \TeX\ survives the initialization process.
1901
1902 @<Set init...@>=
1903 deletions_allowed=true;set_box_allowed=true;
1904 error_count=0; /*|history| is initialized elsewhere*/
1905
1906 @ Since errors can be detected almost anywhere in \TeX, we want to declare the
1907 error procedures near the beginning of the program. But the error procedures
1908 in turn use some other procedures, which need to be declared |forward|
1909 before we get to |error| itself.
1910
1911 It is possible for |error| to be called recursively if some error arises
1912 when |get_token| is being used to delete a token, and/or if some fatal error
1913 occurs while \TeX\ is trying to fix a non-fatal one. But such recursion
1914 @^recursion@>
1915 is never more than two levels deep.
1916
1917 @<Error handling...@>=
1918 static void normalize_selector(void);@/
1919 static void get_token(void);@/
1920 static void term_input(void);@/
1921 static void show_context(void);@/
1922 static void begin_file_reading(void);@/
1923 static void open_log_file(void);@/
1924 static void close_files_and_terminate(void);@/
1925 static void clear_for_error_prompt(void);@/
1926 static void give_err_help(void);@/
1927 #ifdef @!DEBUG
1928 static void debug_help(void);
1929 #else
1930 #define debug_help() do_nothing
1931 #endif
1932
1933 @ Individual lines of help are recorded in the array |help_line|, which
1934 contains entries in positions |0 dotdot(help_ptr-1)|. They should be printed
1935 in reverse order, i.e., with |help_line[0]| appearing last.
1936
1937 @d hlp1(A) help_line[0]=A;@+}
1938 @d hlp2(A, B) help_line[1]=A;help_line[0]=B;@+}
1939 @d hlp3(A, B, C) help_line[2]=A;help_line[1]=B;help_line[0]=C;@+}
1940 @d hlp4(A, B, C, D) help_line[3]=A;help_line[2]=B;help_line[1]=C;help_line[0]=D;@+}
1941 @d hlp5(A, B, C, D, E) help_line[4]=A;help_line[3]=B;help_line[2]=C;help_line[1]=D;help_line[0]=E;@+}
1942 @d hlp6(A, B, C, D, E, F) help_line[5]=A;help_line[4]=B;help_line[3]=C;help_line[2]=D;help_line[1]=E;help_line[0]=F;@+}
1943 @d help0 help_ptr=0 /*sometimes there might be no help*/
1944 @d help1(A) @+{@+help_ptr=1;hlp1(A) /*use this with one help line*/
1945 @d help2(A, B) @+{@+help_ptr=2;hlp2(A, B) /*use this with two help lines*/
1946 @d help3(A, B, C) @+{@+help_ptr=3;hlp3(A, B, C) /*use this with three help lines*/
1947 @d help4(A, B, C, D) @+{@+help_ptr=4;hlp4(A, B, C, D) /*use this with four help lines*/
1948 @d help5(A, B, C, D, E) @+{@+help_ptr=5;hlp5(A, B, C, D, E) /*use this with five help lines*/
1949 @d help6(A, B, C, D, E, F) @+{@+help_ptr=6;hlp6(A, B, C, D, E, F) /*use this with six help lines*/
1950
1951 @<Glob...@>=
1952 static char *@!help_line[6]; /*helps for the next |error|*/
1953 static int @!help_ptr; /*the number of help lines present*/
1954 static bool @!use_err_help; /*should the |err_help| list be shown?*/
1955
1956 @ @<Set init...@>=
1957 help_ptr=0;use_err_help=false;
1958
1959 @ The |jump_out| procedure just cuts across all active procedure levels and
1960 goes to |end_of_TEX|. This is the only nontrivial |@!goto| statement in the
1961 whole program. It is used when there is no recovery from a particular error.
1962
1963 Some \PASCAL\ compilers do not implement non-local |goto| statements.
1964 @^system dependencies@>
1965 In such cases the body of |jump_out| should simply be
1966 `|close_files_and_terminate|;\thinspace' followed by a call on some system
1967 procedure that quietly terminates the program.
1968
1969 @<Error hand...@>=
1970 static void jump_out(void)
1971 {@+ close_files_and_terminate(); exit(0);
1972 }
1973
1974 @ Here now is the general |error| routine.
1975
1976 @<Error hand...@>=
1977 static void error(void) /*completes the job of error reporting*/
1978 {@+
1979 ASCII_code c; /*what the user types*/
1980 int @!s1, @!s2, @!s3, @!s4;
1981 /*used to save global variables when deleting tokens*/
1982 if (history < error_message_issued) history=error_message_issued;
1983 print_char('.');show_context();
1984 if (interaction==error_stop_mode)
1985 @<Get user's advice and |return|@>;
1986 incr(error_count);
1987 if (error_count==100)
1988 {@+print_nl("(That makes 100 errors; please try again.)");
1989 @.That makes 100 errors...@>
1990 history=fatal_error_stop;jump_out();
1991 }
1992 @<Put help message on the transcript file@>;
1993 }
1994
1995 @ @<Get user's advice...@>=
1996 loop@+{@+resume: if (interaction!=error_stop_mode) return;
1997 clear_for_error_prompt();prompt_input("? ");
1998 @.?\relax@>
1999 if (last==first) return;
2000 c=buffer[first];
2001 if (c >= 'a') c=c+'A'-'a'; /*convert to uppercase*/
2002 @<Interpret code |c| and |return| if done@>;
2003 }
2004
2005 @ It is desirable to provide an `\.E' option here that gives the user
2006 an easy way to return from \TeX\ to the system editor, with the offending
2007 line ready to be edited. But such an extension requires some system
2008 wizardry, so the present implementation simply types out the name of the
2009 file that should be
2010 edited and the relevant line number.
2011 @^system dependencies@>
2012
2013 There is a secret `\.D' option available when the debugging routines haven't
2014 been commented~out.
2015 @^debugging@>
2016
2017 @<Interpret code |c| and |return| if done@>=
2018 switch (c) {
2019 case '0': case '1': case '2': case '3':
2020 case '4': case '5': case '6': case '7':
2021 case '8': case '9': if (deletions_allowed)
2022 @<Delete \(c)|c-"0"| tokens and |goto resume|@>@;@+break;
2023 @t\4\4@>@;
2024 #ifdef @!DEBUG
2025 case 'D': {@+debug_help();goto resume;@+}
2026 #endif
2027 case 'E': if (base_ptr > 0) if (input_stack[base_ptr].name_field >= 256)
2028 {@+print_nl("You want to edit file ");
2029 @.You want to edit file x@>
2030 slow_print(input_stack[base_ptr].name_field);
2031 print(" at line ");print_int(line);
2032 interaction=scroll_mode;jump_out();
2033 } @+break;
2034 case 'H': @<Print the help information and |goto resume|@>@;
2035 case 'I': @<Introduce new material from the terminal and |return|@>@;
2036 case 'Q': case 'R': case 'S': @<Change the interaction level and |return|@>@;
2037 case 'X': {@+interaction=scroll_mode;jump_out();
2038 } @+break;
2039 default:do_nothing;
2040 } @/
2041 @<Print the menu of available options@>@;
2042
2043 @ @<Print the menu...@>=
2044 {@+print("Type <return> to proceed, S to scroll future error messages,");@/
2045 @.Type <return> to proceed...@>
2046 print_nl("R to run without stopping, Q to run quietly,");@/
2047 print_nl("I to insert something, ");
2048 if (base_ptr > 0) if (input_stack[base_ptr].name_field >= 256)
2049 print("E to edit your file,");
2050 if (deletions_allowed)
2051 print_nl("1 or ... or 9 to ignore the next 1 to 9 tokens of input,");
2052 print_nl("H for help, X to quit.");
2053 }
2054
2055 @ Here the author of \TeX\ apologizes for making use of the numerical
2056 relation between |'Q'|, |'R'|, |'S'|, and the desired interaction settings
2057 |batch_mode|, |nonstop_mode|, |scroll_mode|.
2058 @^Knuth, Donald Ervin@>
2059
2060 @<Change the interaction...@>=
2061 {@+error_count=0;interaction=batch_mode+c-'Q';
2062 print("OK, entering ");
2063 switch (c) {
2064 case 'Q': {@+print_esc("batchmode");decr(selector);
2065 } @+break;
2066 case 'R': print_esc("nonstopmode");@+break;
2067 case 'S': print_esc("scrollmode");
2068 } /*there are no other cases*/
2069 print("...");print_ln();update_terminal;return;
2070 }
2071
2072 @ When the following code is executed, |buffer[(first+1)dotdot(last-1)]| may
2073 contain the material inserted by the user; otherwise another prompt will
2074 be given. In order to understand this part of the program fully, you need
2075 to be familiar with \TeX's input stacks.
2076
2077 @<Introduce new material...@>=
2078 {@+begin_file_reading(); /*enter a new syntactic level for terminal input*/
2079 /*now |state==mid_line|, so an initial blank space will count as a blank*/
2080 if (last > first+1)
2081 {@+loc=first+1;buffer[first]=' ';
2082 }
2083 else{@+prompt_input("insert>");loc=first;
2084 @.insert>@>
2085 }
2086 first=last;
2087 cur_input.limit_field=last-1; /*no |end_line_char| ends this line*/
2088 return;
2089 }
2090
2091 @ We allow deletion of up to 99 tokens at a time.
2092
2093 @<Delete \(c)|c-"0"| tokens...@>=
2094 {@+s1=cur_tok;s2=cur_cmd;s3=cur_chr;s4=align_state;
2095 align_state=1000000;OK_to_interrupt=false;
2096 if ((last > first+1)&&(buffer[first+1] >= '0')&&(buffer[first+1] <= '9'))
2097 c=c*10+buffer[first+1]-'0'*11;
2098 else c=c-'0';
2099 while (c > 0)
2100 {@+get_token(); /*one-level recursive call of |error| is possible*/
2101 decr(c);
2102 }
2103 cur_tok=s1;cur_cmd=s2;cur_chr=s3;align_state=s4;OK_to_interrupt=true;
2104 help2("I have just deleted some text, as you asked.",@/
2105 "You can now delete more, or insert, or whatever.");
2106 show_context();goto resume;
2107 }
2108
2109 @ @<Print the help info...@>=
2110 {@+if (use_err_help)
2111 {@+give_err_help();use_err_help=false;
2112 }
2113 else{@+if (help_ptr==0)
2114 help2("Sorry, I don't know how to help in this situation.",@/
2115 @t\kern1em@>"Maybe you should try asking a human?");
2116 @/do@+{decr(help_ptr);print(help_line[help_ptr]);print_ln();
2117 }@+ while (!(help_ptr==0));
2118 }
2119 help4("Sorry, I already gave what help I could...",@/
2120 "Maybe you should try asking a human?",@/
2121 "An error might have occurred before I noticed any problems.",@/
2122 "``If all else fails, read the instructions.'");@/
2123 goto resume;
2124 }
2125
2126 @ @<Put help message on the transcript file@>=
2127 if (interaction > batch_mode) decr(selector); /*avoid terminal output*/
2128 if (use_err_help)
2129 {@+print_ln();give_err_help();
2130 }
2131 else while (help_ptr > 0)
2132 {@+decr(help_ptr);print_nl(help_line[help_ptr]);
2133 }
2134 print_ln();
2135 if (interaction > batch_mode) incr(selector); /*re-enable terminal output*/
2136 print_ln()
2137
2138 @ A dozen or so error messages end with a parenthesized integer, so we
2139 save a teeny bit of program space by declaring the following procedure:
2140
2141 @p static void int_error(int @!n)
2142 {@+print(" (");print_int(n);print_char(')');error();
2143 }
2144
2145 @ In anomalous cases, the print selector might be in an unknown state;
2146 the following subroutine is called to fix things just enough to keep
2147 running a bit longer.
2148
2149 @p static void normalize_selector(void)
2150 {@+if (log_opened) selector=term_and_log;
2151 else selector=term_only;
2152 if (job_name==0) open_log_file();
2153 if (interaction==batch_mode) decr(selector);
2154 }
2155
2156 @ The following procedure prints \TeX's last words before dying.
2157
2158 @d succumb {@+if (interaction==error_stop_mode)
2159 interaction=scroll_mode; /*no more interaction*/
2160 if (log_opened) error();
2161 if (interaction > batch_mode) debug_help();
2162 history=fatal_error_stop;jump_out(); /*irrecoverable error*/
2163 }
2164
2165 @<Error hand...@>=
2166 static void fatal_error(char *@!s) /*prints |s|, and that's it*/
2167 {@+normalize_selector();@/
2168 print_err("Emergency stop");help1(s);succumb;
2169 @.Emergency stop@>
2170 }
2171
2172 @ Here is the most dreaded error message.
2173
2174 @<Error hand...@>=
2175 static void overflow(char *@!s, int @!n) /*stop due to finiteness*/
2176 {@+normalize_selector();
2177 print_err("TeX capacity exceeded, sorry [");
2178 @.TeX capacity exceeded ...@>
2179 print(s);print_char('=');print_int(n);print_char(']');
2180 help2("If you really absolutely need more capacity,",@/
2181 "you can ask a wizard to enlarge me.");
2182 succumb;
2183 }
2184
2185 @ The program might sometime run completely amok, at which point there is
2186 no choice but to stop. If no previous error has been detected, that's bad
2187 news; a message is printed that is really intended for the \TeX\
2188 maintenance person instead of the user (unless the user has been
2189 particularly diabolical). The index entries for `this can't happen' may
2190 help to pinpoint the problem.
2191 @^dry rot@>
2192
2193 @<Error hand...@>=
2194 static void confusion(char *@!s)
2195 /*consistency check violated; |s| tells where*/
2196 {@+normalize_selector();
2197 if (history < error_message_issued)
2198 {@+print_err("This can't happen (");print(s);print_char(')');
2199 @.This can't happen@>
2200 help1("I'm broken. Please show this to someone who can fix can fix");
2201 }
2202 else{@+print_err("I can't go on meeting you like this");
2203 @.I can't go on...@>
2204 help2("One of your faux pas seems to have wounded me deeply...",@/
2205 "in fact, I'm barely conscious. Please fix it and try again.");
2206 }
2207 succumb;
2208 }
2209
2210 @ Users occasionally want to interrupt \TeX\ while it's running.
2211 If the \PASCAL\ runtime system allows this, one can implement
2212 a routine that sets the global variable |interrupt| to some nonzero value
2213 when such an interrupt is signalled. Otherwise there is probably at least
2214 a way to make |interrupt| nonzero using the \PASCAL\ debugger.
2215 @^system dependencies@>
2216 @^debugging@>
2217
2218 @d check_interrupt {@+if (interrupt!=0) pause_for_instructions();
2219 }
2220
2221 @<Global...@>=
2222 static int @!interrupt; /*should \TeX\ pause for instructions?*/
2223 static bool @!OK_to_interrupt; /*should interrupts be observed?*/
2224
2225 @ @<Set init...@>=
2226 interrupt=0;OK_to_interrupt=true;
2227
2228 @ When an interrupt has been detected, the program goes into its
2229 highest interaction level and lets the user have nearly the full flexibility of
2230 the |error| routine. \TeX\ checks for interrupts only at times when it is
2231 safe to do this.
2232
2233 @p static void pause_for_instructions(void)
2234 {@+if (OK_to_interrupt)
2235 {@+interaction=error_stop_mode;
2236 if ((selector==log_only)||(selector==no_print))
2237 incr(selector);
2238 print_err("Interruption");
2239 @.Interruption@>
2240 help3("You rang?",@/
2241 "Try to insert an instruction for me (e.g., `I\\showlists'),",@/
2242 "unless you just want to quit by typing `X'.");
2243 deletions_allowed=false;error();deletions_allowed=true;
2244 interrupt=0;
2245 }
2246 }
2247
2248 @* Arithmetic with scaled dimensions.
2249 The principal computations performed by \TeX\ are done entirely in terms of
2250 integers less than $2^{31}$ in magnitude; and divisions are done only when both
2251 dividend and divisor are nonnegative. Thus, the arithmetic specified in this
2252 program can be carried out in exactly the same way on a wide variety of
2253 computers, including some small ones. Why? Because the arithmetic
2254 calculations need to be spelled out precisely in order to guarantee that
2255 \TeX\ will produce identical output on different machines. If some
2256 quantities were rounded differently in different implementations, we would
2257 find that line breaks and even page breaks might occur in different places.
2258 Hence the arithmetic of \TeX\ has been designed with care, and systems that
2259 claim to be implementations of \TeX82 should follow precisely the
2260 @:TeX82}{\TeX82@>
2261 calculations as they appear in the present program.
2262
2263 (Actually there are three places where \TeX\ uses |/| with a possibly negative
2264 numerator. These are harmless; see |/| in the index. Also if the user
2265 sets the \.{\\time} or the \.{\\year} to a negative value, some diagnostic
2266 information will involve negative-numerator division. The same remarks
2267 apply for |%| as well as for |/|.)
2268
2269 @ Here is a routine that calculates half of an integer, using an
2270 unambiguous convention with respect to signed odd numbers.
2271
2272 @p static int half(int @!x)
2273 {@+if (odd(x)) return(x+1)/2;
2274 else return x/2;
2275 }
2276
2277 @ Fixed-point arithmetic is done on {\sl scaled integers\/} that are multiples
2278 of $2^{-16}$. In other words, a binary point is assumed to be sixteen bit
2279 positions from the right end of a binary computer word.
2280
2281 @d unity 0200000 /*$2^{16}$, represents 1.00000*/
2282 @d two 0400000 /*$2^{17}$, represents 2.00000*/
2283
2284 @<Types...@>=
2285 typedef int scaled; /*this type is used for scaled integers*/
2286 typedef int32_t nonnegative_integer; /*$0\le x<2^{31}$*/
2287 typedef int8_t small_number; /*this type is self-explanatory*/
2288
2289 @ The following function is used to create a scaled integer from a given decimal
2290 fraction $(.d_0d_1\ldots d_{k-1})$, where |0 <= k <= 17|. The digit $d_i$ is
2291 given in |dig[i]|, and the calculation produces a correctly rounded result.
2292
2293 @p static scaled round_decimals(small_number @!k)
2294 /*converts a decimal fraction*/
2295 {@+int a; /*the accumulator*/
2296 a=0;
2297 while (k > 0)
2298 {@+decr(k);a=(a+dig[k]*two)/10;
2299 }
2300 return(a+1)/2;
2301 }
2302
2303 @ Conversely, here is a procedure analogous to |print_int|. If the output
2304 of this procedure is subsequently read by \TeX\ and converted by the
2305 |round_decimals| routine above, it turns out that the original value will
2306 be reproduced exactly; the ``simplest'' such decimal number is output,
2307 but there is always at least one digit following the decimal point.
2308
2309 The invariant relation in the \&{repeat} loop is that a sequence of
2310 decimal digits yet to be printed will yield the original number if and only if
2311 they form a fraction~$f$ in the range $s-\delta\le 10\cdot2^{16}f<s$.
2312 We can stop if and only if $f=0$ satisfies this condition; the loop will
2313 terminate before $s$ can possibly become zero.
2314
2315 @p static void print_scaled(scaled @!s) /*prints scaled real, rounded to five
2316 digits*/
2317 {@+scaled delta; /*amount of allowable inaccuracy*/
2318 if (s < 0)
2319 {@+print_char('-');negate(s); /*print the sign, if negative*/
2320 }
2321 print_int(s/unity); /*print the integer part*/
2322 print_char('.');
2323 s=10*(s%unity)+5;delta=10;
2324 @/do@+{if (delta > unity) s=s+0100000-50000; /*round the last digit*/
2325 print_char('0'+(s/unity));s=10*(s%unity);delta=delta*10;
2326 }@+ while (!(s <= delta));
2327 }
2328
2329 @ Physical sizes that a \TeX\ user specifies for portions of documents are
2330 represented internally as scaled points. Thus, if we define an `sp' (scaled
2331 @^sp@>
2332 point) as a unit equal to $2^{-16}$ printer's points, every dimension
2333 inside of \TeX\ is an integer number of sp. There are exactly
2334 4,736,286.72 sp per inch. Users are not allowed to specify dimensions
2335 larger than $2^{30}-1$ sp, which is a distance of about 18.892 feet (5.7583
2336 meters); two such quantities can be added without overflow on a 32-bit
2337 computer.
2338
2339 The present implementation of \TeX\ does not check for overflow when
2340 @^overflow in arithmetic@>
2341 dimensions are added or subtracted. This could be done by inserting a
2342 few dozen tests of the form `\ignorespaces|if (x >= 010000000000)|
2343 \\{report\_overflow}', but the chance of overflow is so remote that
2344 such tests do not seem worthwhile.
2345
2346 \TeX\ needs to do only a few arithmetic operations on scaled quantities,
2347 other than addition and subtraction, and the following subroutines do most of
2348 the work. A single computation might use several subroutine calls, and it is
2349 desirable to avoid producing multiple error messages in case of arithmetic
2350 overflow; so the routines set the global variable |arith_error| to |true|
2351 instead of reporting errors directly to the user. Another global variable,
2352 |rem|, holds the remainder after a division.
2353
2354 @<Glob...@>=
2355 static bool @!arith_error; /*has arithmetic overflow occurred recently?*/
2356 static scaled @!rem; /*amount subtracted to get an exact division*/
2357
2358 @ The first arithmetical subroutine we need computes $nx+y$, where |x|
2359 and~|y| are |scaled| and |n| is an integer. We will also use it to
2360 multiply integers.
2361
2362 @d nx_plus_y(A, B, C) mult_and_add(A, B, C, 07777777777)
2363 @d mult_integers(A, B) mult_and_add(A, B, 0, 017777777777)
2364
2365 @p static scaled mult_and_add(int @!n, scaled @!x, scaled @!y, scaled @!max_answer)
2366 {@+if (n < 0)
2367 {@+negate(x);negate(n);
2368 }
2369 if (n==0) return y;
2370 else if (((x <= (max_answer-y)/n)&&(-x <= (max_answer+y)/n)))
2371 return n*x+y;
2372 else{@+arith_error=true;return 0;
2373 }
2374 }
2375
2376 @ We also need to divide scaled dimensions by integers.
2377
2378 @p static scaled x_over_n(scaled @!x, int @!n)
2379 {@+bool negative; /*should |rem| be negated?*/
2380 scaled x_over_n;
2381 negative=false;
2382 if (n==0)
2383 {@+arith_error=true;x_over_n=0;rem=x;
2384 }
2385 else{@+if (n < 0)
2386 {@+negate(x);negate(n);negative=true;
2387 }
2388 if (x >= 0)
2389 {@+x_over_n=x/n;rem=x%n;
2390 }
2391 else{@+x_over_n=-((-x)/n);rem=-((-x)%n);
2392 }
2393 }
2394 if (negative) negate(rem);
2395 return x_over_n;}
2396
2397 @ Then comes the multiplication of a scaled number by a fraction |n/(double)d|,
2398 where |n| and |d| are nonnegative integers | <= @t$2^{16}$@>| and |d| is
2399 positive. It would be too dangerous to multiply by~|n| and then divide
2400 by~|d|, in separate operations, since overflow might well occur; and it
2401 would be too inaccurate to divide by |d| and then multiply by |n|. Hence
2402 this subroutine simulates 1.5-precision arithmetic.
2403
2404 @p static scaled xn_over_d(scaled @!x, int @!n, int @!d)
2405 {@+bool positive; /*was |x >= 0|?*/
2406 nonnegative_integer @!t, @!u, @!v; /*intermediate quantities*/
2407 scaled xn_over_d;
2408 if (x >= 0) positive=true;
2409 else{@+negate(x);positive=false;
2410 }
2411 t=(x%0100000)*n;
2412 u=(x/0100000)*n+(t/0100000);
2413 v=(u%d)*0100000+(t%0100000);
2414 if (u/d >= 0100000) arith_error=true;
2415 else u=0100000*(u/d)+(v/d);
2416 if (positive)
2417 {@+xn_over_d=u;rem=v%d;
2418 }
2419 else{@+xn_over_d=-u;rem=-(v%d);
2420 }
2421 return xn_over_d;}
2422
2423 @ The next subroutine is used to compute the ``badness'' of glue, when a
2424 total~|t| is supposed to be made from amounts that sum to~|s|. According
2425 to {\sl The \TeX book}, the badness of this situation is $100(t/s)^3$;
2426 however, badness is simply a heuristic, so we need not squeeze out the
2427 last drop of accuracy when computing it. All we really want is an
2428 approximation that has similar properties.
2429 @:TeXbook}{\sl The \TeX book@>
2430
2431 The actual method used to compute the badness is easier to read from the
2432 program than to describe in words. It produces an integer value that is a
2433 reasonably close approximation to $100(t/s)^3$, and all implementations
2434 of \TeX\ should use precisely this method. Any badness of $2^{13}$ or more is
2435 treated as infinitely bad, and represented by 10000.
2436
2437 It is not difficult to prove that $$\hbox{|badness(t+1, s) >= badness(t, s)
2438 >= badness(t, s+1)|}.$$ The badness function defined here is capable of
2439 computing at most 1095 distinct values, but that is plenty.
2440
2441 @d inf_bad 10000 /*infinitely bad value*/
2442
2443 @p @<Declare \Prote\ arithmetic routines@>@/
2444 static halfword badness(scaled @!t, scaled @!s) /*compute badness, given |t >= 0|*/
2445 {@+int r; /*approximation to $\alpha t/s$, where $\alpha^3\approx
2446 100\cdot2^{18}$*/
2447 if (t==0) return 0;
2448 else if (s <= 0) return inf_bad;
2449 else{@+if (t <= 7230584) r=(t*297)/s; /*$297^3=99.94\times2^{18}$*/
2450 else if (s >= 1663497) r=t/(s/297);
2451 else r=t;
2452 if (r > 1290) return inf_bad; /*$1290^3<2^{31}<1291^3$*/
2453 else return(r*r*r+0400000)/01000000;
2454 } /*that was $r^3/2^{18}$, rounded to the nearest integer*/
2455 }
2456
2457 @ When \TeX\ ``packages'' a list into a box, it needs to calculate the
2458 proportionality ratio by which the glue inside the box should stretch
2459 or shrink. This calculation does not affect \TeX's decision making,
2460 so the precise details of rounding, etc., in the glue calculation are not
2461 of critical importance for the consistency of results on different computers.
2462
2463 We shall use the type |glue_ratio| for such proportionality ratios.
2464 A glue ratio should take the same amount of memory as an
2465 |int| (usually 32 bits) if it is to blend smoothly with \TeX's
2466 other data structures. Thus |glue_ratio| should be equivalent to
2467 |short_real| in some implementations of \PASCAL. Alternatively,
2468 it is possible to deal with glue ratios using nothing but fixed-point
2469 arithmetic; see {\sl TUGboat \bf3},1 (March 1982), 10--27. (But the
2470 routines cited there must be modified to allow negative glue ratios.)
2471 @^system dependencies@>
2472
2473 @d set_glue_ratio_zero(A) A=0.0 /*store the representation of zero ratio*/
2474 @d set_glue_ratio_one(A) A=1.0 /*store the representation of unit ratio*/
2475 @d unfix(A) ((double)(A)) /*convert from |glue_ratio| to type |double|*/
2476 @d fix(A) ((glue_ratio)(A)) /*convert from |double| to type |glue_ratio|*/
2477 @d float_constant(A) ((double)(A)) /*convert |int| constant to |double|*/
2478
2479 @<Types...@>=
2480 #if __SIZEOF_FLOAT__==4
2481 typedef float float32_t;
2482 #else
2483 #error @=float type must have size 4@>
2484 #endif
2485 typedef float @!glue_ratio; /*one-word representation of a glue expansion factor*/
2486
2487 @* Packed data.
2488 In order to make efficient use of storage space, \TeX\ bases its major data
2489 structures on a |memory_word|, which contains either a (signed) integer,
2490 possibly scaled, or a (signed) |glue_ratio|, or a small number of
2491 fields that are one half or one quarter of the size used for storing
2492 integers.
2493
2494 If |x| is a variable of type |memory_word|, it contains up to four
2495 fields that can be referred to as follows:
2496 $$\vbox{\halign{\hfil#&#\hfil&#\hfil\cr
2497 |x|&.|i|&(an |int|)\cr
2498 |x|&.|sc|\qquad&(a |scaled| integer)\cr
2499 |x|&.|gr|&(a |glue_ratio|)\cr
2500 |x.hh.lh|, |x.hh|&.|rh|&(two halfword fields)\cr
2501 |x.hh.b0|, |x.hh.b1|, |x.hh|&.|rh|&(two quarterword fields, one halfword
2502 field)\cr
2503 |x.qqqq.b0|, |x.qqqq.b1|, |x.qqqq|&.|b2|, |x.qqqq.b3|\hskip-100pt
2504 &\qquad\qquad\qquad(four quarterword fields)\cr}}$$
2505 This is somewhat cumbersome to write, and not very readable either, but
2506 macros will be used to make the notation shorter and more transparent.
2507 The \PASCAL\ code below gives a formal definition of |memory_word| and
2508 its subsidiary types, using packed variant records. \TeX\ makes no
2509 assumptions about the relative positions of the fields within a word.
2510
2511 Since we are assuming 32-bit integers, a halfword must contain at least
2512 16 bits, and a quarterword must contain at least 8 bits.
2513 @^system dependencies@>
2514 But it doesn't hurt to have more bits; for example, with enough 36-bit
2515 words you might be able to have |mem_max| as large as 262142, which is
2516 eight times as much memory as anybody had during the first four years of
2517 \TeX's existence.
2518
2519 N.B.: Valuable memory space will be dreadfully wasted unless \TeX\ is compiled
2520 by a \PASCAL\ that packs all of the |memory_word| variants into
2521 the space of a single integer. This means, for example, that |glue_ratio|
2522 words should be |short_real| instead of |double| on some computers. Some
2523 \PASCAL\ compilers will pack an integer whose subrange is `|0 dotdot 255|' into
2524 an eight-bit field, but others insist on allocating space for an additional
2525 sign bit; on such systems you can get 256 values into a quarterword only
2526 if the subrange is `|-128 dotdot 127|'.
2527
2528 The present implementation tries to accommodate as many variations as possible,
2529 so it makes few assumptions. If integers having the subrange
2530 `|min_quarterword dotdot max_quarterword|' can be packed into a quarterword,
2531 and if integers having the subrange `|min_halfword dotdot max_halfword|'
2532 can be packed into a halfword, everything should work satisfactorily.
2533
2534 It is usually most efficient to have |min_quarterword==min_halfword==0|,
2535 so one should try to achieve this unless it causes a severe problem.
2536 The values defined here are recommended for most 32-bit computers.
2537
2538 @d min_quarterword 0 /*smallest allowable value in a |quarterword|*/
2539 @d max_quarterword 65535 /*largest allowable value in a |quarterword|*/
2540 @d min_halfword 0 /*smallest allowable value in a |halfword|*/
2541 @d max_halfword 0x3FFFFFFF /*largest allowable value in a |halfword|*/
2542
2543 @ Here are the inequalities that the quarterword and halfword values
2544 must satisfy (or rather, the inequalities that they mustn't satisfy):
2545
2546 @<Check the ``constant''...@>=
2547 #ifdef @!INIT
2548 if ((mem_min!=mem_bot)||(mem_max!=mem_top)) bad=10;
2549 #endif
2550 @;@/
2551 if ((mem_min > mem_bot)||(mem_max < mem_top)) bad=10;
2552 if ((min_quarterword > 0)||(max_quarterword < 127)) bad=11;
2553 if ((min_halfword > 0)||(max_halfword < 32767)) bad=12;
2554 if ((min_quarterword < min_halfword)||@|
2555 (max_quarterword > max_halfword)) bad=13;
2556 if ((mem_min < min_halfword)||(mem_max >= max_halfword)||@|
2557 (mem_bot-mem_min > max_halfword+1)) bad=14;
2558 if ((font_base < min_quarterword)||(font_max > max_quarterword)) bad=15;
2559 if (font_max > font_base+256) bad=16;
2560 if ((save_size > max_halfword)||(max_strings > max_halfword)) bad=17;
2561 if (buf_size > max_halfword) bad=18;
2562 if (max_quarterword-min_quarterword < 255) bad=19;
2563
2564 @ The operation of adding or subtracting |min_quarterword| occurs quite
2565 frequently in \TeX, so it is convenient to abbreviate this operation
2566 by using the macros |qi| and |qo| for input and output to and from
2567 quarterword format.
2568
2569 The inner loop of \TeX\ will run faster with respect to compilers
2570 that don't optimize expressions like `|x+0|' and `|x-0|', if these
2571 macros are simplified in the obvious way when |min_quarterword==0|.
2572 @^inner loop@>@^system dependencies@>
2573
2574 @d qi(A) A+min_quarterword
2575 /*to put an |eight_bits| item into a quarterword*/
2576 @d qo(A) A-min_quarterword
2577 /*to take an |eight_bits| item out of a quarterword*/
2578 @d hi(A) A+min_halfword
2579 /*to put a sixteen-bit item into a halfword*/
2580 @d ho(A) A-min_halfword
2581 /*to take a sixteen-bit item from a halfword*/
2582
2583 @ The reader should study the following definitions closely:
2584 @^system dependencies@>
2585
2586 @d sc i /*|scaled| data is equivalent to |int|*/
2587
2588 @<Types...@>=
2589 typedef uint16_t quarterword; /*1/4 of a word*/
2590 typedef int32_t halfword; /*1/2 of a word*/
2591 typedef int8_t two_choices; /*used when there are two variants in a record*/
2592 typedef int8_t four_choices; /*used when there are four variants in a record*/
2593 typedef uint64_t fullword;
2594 typedef struct { @;@/
2595 halfword @!rh;
2596 union {
2597 halfword @!lh;
2598 struct { quarterword @!b0;quarterword @!b1;} ;
2599 };} two_halves;
2600 typedef struct { @;@/
2601 quarterword @!b0;
2602 quarterword @!b1;
2603 quarterword @!b2;
2604 quarterword @!b3;
2605 } four_quarters;
2606 typedef struct { @;@/
2607 union {
2608 fullword @!w;
2609 int @!i;
2610 glue_ratio @!gr;
2611 two_halves @!hh;
2612 four_quarters @!qqqq;
2613 };} memory_word;
2614 typedef struct {@+FILE *f;@+memory_word@,d;@+} word_file;
2615
2616 @ When debugging, we may want to print a |memory_word| without knowing
2617 what type it is; so we print it in all modes.
2618 @^dirty \PASCAL@>@^debugging@>
2619
2620 @p
2621 #ifdef @!DEBUG
2622 static void print_word(memory_word @!w)
2623 /*prints |w| in all ways*/
2624 {@+print_int(w.i);print_char(' ');@/
2625 print_scaled(w.sc);print_char(' ');@/
2626 print_scaled(round(unity*unfix(w.gr)));print_ln();@/
2627 @^real multiplication@>
2628 print_int(w.hh.lh);print_char('=');print_int(w.hh.b0);print_char(':');
2629 print_int(w.hh.b1);print_char(';');print_int(w.hh.rh);print_char(' ');@/
2630 print_int(w.qqqq.b0);print_char(':');print_int(w.qqqq.b1);print_char(':');
2631 print_int(w.qqqq.b2);print_char(':');print_int(w.qqqq.b3);
2632 }
2633 #endif
2634
2635 @* Dynamic memory allocation.
2636 The \TeX\ system does nearly all of its own memory allocation, so that it
2637 can readily be transported into environments that do not have automatic
2638 facilities for strings, garbage collection, etc., and so that it can be in
2639 control of what error messages the user receives. The dynamic storage
2640 requirements of \TeX\ are handled by providing a large array |mem| in
2641 which consecutive blocks of words are used as nodes by the \TeX\ routines.
2642
2643 Pointer variables are indices into this array, or into another array
2644 called |eqtb| that will be explained later. A pointer variable might
2645 also be a special flag that lies outside the bounds of |mem|, so we
2646 allow pointers to assume any |halfword| value. The minimum halfword
2647 value represents a null pointer. \TeX\ does not assume that |mem[null]| exists.
2648
2649 @s pointer int
2650 @d pointer halfword /*a flag or a location in |mem| or |eqtb|*/
2651 @d null min_halfword /*the null pointer*/
2652
2653 @<Glob...@>=
2654 static pointer @!temp_ptr; /*a pointer variable for occasional emergency use*/
2655
2656 @ The |mem| array is divided into two regions that are allocated separately,
2657 but the dividing line between these two regions is not fixed; they grow
2658 together until finding their ``natural'' size in a particular job.
2659 Locations less than or equal to |lo_mem_max| are used for storing
2660 variable-length records consisting of two or more words each. This region
2661 is maintained using an algorithm similar to the one described in exercise
2662 2.5--19 of {\sl The Art of Computer Programming}. However, no size field
2663 appears in the allocated nodes; the program is responsible for knowing the
2664 relevant size when a node is freed. Locations greater than or equal to
2665 |hi_mem_min| are used for storing one-word records; a conventional
2666 \.{AVAIL} stack is used for allocation in this region.
2667
2668 Locations of |mem| between |mem_bot| and |mem_top| may be dumped as part
2669 of preloaded format files, by the \.{INITEX} preprocessor.
2670 @.INITEX@>
2671 Production versions of \TeX\ may extend the memory at both ends in order to
2672 provide more space; locations between |mem_min| and |mem_bot| are always
2673 used for variable-size nodes, and locations between |mem_top| and |mem_max|
2674 are always used for single-word nodes.
2675
2676 The key pointers that govern |mem| allocation have a prescribed order:
2677 $$\advance\thickmuskip-2mu
2678 \hbox{|null <= mem_min <= mem_bot < lo_mem_max <
2679 hi_mem_min < mem_top <= mem_end <= mem_max|.}$$
2680
2681 Empirical tests show that the present implementation of \TeX\ tends to
2682 spend about 9\pct! of its running time allocating nodes, and about 6\pct!
2683 deallocating them after their use.
2684
2685 @<Glob...@>=
2686 static memory_word @!mem0[mem_max-mem_min+1],
2687 *const @!mem = @!mem0-mem_min; /*the big dynamic storage area*/
2688 static pointer @!lo_mem_max; /*the largest location of variable-size memory in use*/
2689 static pointer @!hi_mem_min; /*the smallest location of one-word memory in use*/
2690
2691 @ In order to study the memory requirements of particular applications, it
2692 is possible to prepare a version of \TeX\ that keeps track of current and
2693 maximum memory usage. When code between the delimiters |
2694 #ifdef @!STAT
2695 | $\ldots$
2696 |@t\#\&{endif}@>| is not ``commented out,'' \TeX\ will run a bit slower but it will
2697 report these statistics when |tracing_stats| is sufficiently large.
2698
2699 @<Glob...@>=
2700 static int @!var_used, @!dyn_used; /*how much memory is in use*/
2701 #ifdef @!STAT
2702 #define incr_dyn_used @[incr(dyn_used)@]
2703 #define decr_dyn_used @[decr(dyn_used)@]
2704 #else
2705 #define incr_dyn_used
2706 #define decr_dyn_used
2707 #endif
2708
2709 @ Let's consider the one-word memory region first, since it's the
2710 simplest. The pointer variable |mem_end| holds the highest-numbered location
2711 of |mem| that has ever been used. The free locations of |mem| that
2712 occur between |hi_mem_min| and |mem_end|, inclusive, are of type
2713 |two_halves|, and we write |info(p)| and |link(p)| for the |lh|
2714 and |rh| fields of |mem[p]| when it is of this type. The single-word
2715 free locations form a linked list
2716 $$|avail|,\;\hbox{|link(avail)|},\;\hbox{|link(link(avail))|},\;\ldots$$
2717 terminated by |null|.
2718
2719 @d link(A) mem[A].hh.rh /*the |link| field of a memory word*/
2720 @d info(A) mem[A].hh.lh /*the |info| field of a memory word*/
2721
2722 @<Glob...@>=
2723 static pointer @!avail; /*head of the list of available one-word nodes*/
2724 static pointer @!mem_end; /*the last one-word node used in |mem|*/
2725
2726 @ If memory is exhausted, it might mean that the user has forgotten
2727 a right brace. We will define some procedures later that try to help
2728 pinpoint the trouble.
2729
2730 @p @<Declare the procedure called |show_token_list|@>@/
2731 @<Declare the procedure called |runaway|@>@;
2732
2733 @ The function |get_avail| returns a pointer to a new one-word node whose
2734 |link| field is null. However, \TeX\ will halt if there is no more room left.
2735 @^inner loop@>
2736
2737 If the available-space list is empty, i.e., if |avail==null|,
2738 we try first to increase |mem_end|. If that cannot be done, i.e., if
2739 |mem_end==mem_max|, we try to decrease |hi_mem_min|. If that cannot be
2740 done, i.e., if |hi_mem_min==lo_mem_max+1|, we have to quit.
2741
2742 @p static pointer get_avail(void) /*single-word node allocation*/
2743 {@+pointer p; /*the new node being got*/
2744 p=avail; /*get top location in the |avail| stack*/
2745 if (p!=null) avail=link(avail); /*and pop it off*/
2746 else if (mem_end < mem_max) /*or go into virgin territory*/
2747 {@+incr(mem_end);p=mem_end;
2748 }
2749 else{@+decr(hi_mem_min);p=hi_mem_min;
2750 if (hi_mem_min <= lo_mem_max)
2751 {@+runaway(); /*if memory is exhausted, display possible runaway text*/
2752 overflow("main memory size", mem_max+1-mem_min);
2753 /*quit; all one-word nodes are busy*/
2754 @:TeX capacity exceeded main memory size}{\quad main memory size@>
2755 }
2756 }
2757 link(p)=null; /*provide an oft-desired initialization of the new node*/
2758 #ifdef @!STAT
2759 incr(dyn_used);
2760 #endif
2761 @; /*maintain statistics*/
2762 return p;
2763 }
2764
2765 @ Conversely, a one-word node is recycled by calling |free_avail|.
2766 This routine is part of \TeX's ``inner loop,'' so we want it to be fast.
2767 @^inner loop@>
2768
2769 @d free_avail(A) /*single-word node liberation*/
2770 {@+link(A)=avail;avail=A;
2771 decr_dyn_used;
2772 }
2773
2774 @ There's also a |fast_get_avail| routine, which saves the procedure-call
2775 overhead at the expense of extra programming. This routine is used in
2776 the places that would otherwise account for the most calls of |get_avail|.
2777 @^inner loop@>
2778
2779 @d fast_get_avail(A) @t@>@;@/
2780 {@+A=avail; /*avoid |get_avail| if possible, to save time*/
2781 if (A==null) A=get_avail();
2782 else{@+avail=link(A);link(A)=null;
2783 incr_dyn_used;
2784 }
2785 }
2786
2787 @ The procedure |flush_list(p)| frees an entire linked list of
2788 one-word nodes that starts at position |p|.
2789 @^inner loop@>
2790
2791 @p static void flush_list(pointer @!p) /*makes list of single-word nodes
2792 available*/
2793 {@+pointer @!q, @!r; /*list traversers*/
2794 if (p!=null)
2795 {@+r=p;
2796 @/do@+{q=r;r=link(r);
2797 #ifdef @!STAT
2798 decr(dyn_used);
2799 #endif
2800 }@+ while (!(r==null)); /*now |q| is the last node on the list*/
2801 link(q)=avail;avail=p;
2802 }
2803 }
2804
2805 @ The available-space list that keeps track of the variable-size portion
2806 of |mem| is a nonempty, doubly-linked circular list of empty nodes,
2807 pointed to by the roving pointer |rover|.
2808
2809 Each empty node has size 2 or more; the first word contains the special
2810 value |max_halfword| in its |link| field and the size in its |info| field;
2811 the second word contains the two pointers for double linking.
2812
2813 Each nonempty node also has size 2 or more. Its first word is of type
2814 |two_halves|\kern-1pt, and its |link| field is never equal to |max_halfword|.
2815 Otherwise there is complete flexibility with respect to the contents
2816 of its other fields and its other words.
2817
2818 (We require |mem_max < max_halfword| because terrible things can happen
2819 when |max_halfword| appears in the |link| field of a nonempty node.)
2820
2821 @d empty_flag max_halfword /*the |link| of an empty variable-size node*/
2822 @d is_empty(A) (link(A)==empty_flag) /*tests for empty node*/
2823 @d node_size(A) info(A) /*the size field in empty variable-size nodes*/
2824 @d llink(A) info(A+1) /*left link in doubly-linked list of empty nodes*/
2825 @d rlink(A) link(A+1) /*right link in doubly-linked list of empty nodes*/
2826
2827 @<Glob...@>=
2828 static pointer @!rover; /*points to some node in the list of empties*/
2829
2830 @ A call to |get_node| with argument |s| returns a pointer to a new node
2831 of size~|s|, which must be 2~or more. The |link| field of the first word
2832 of this new node is set to null. An overflow stop occurs if no suitable
2833 space exists.
2834
2835 If |get_node| is called with $s=2^{30}$, it simply merges adjacent free
2836 areas and returns the value |max_halfword|.
2837
2838 @p static pointer get_node(int @!s) /*variable-size node allocation*/
2839 {@+
2840 pointer p; /*the node currently under inspection*/
2841 pointer @!q; /*the node physically after node |p|*/
2842 int @!r; /*the newly allocated node, or a candidate for this honor*/
2843 int @!t; /*temporary register*/
2844 restart: p=rover; /*start at some free node in the ring*/
2845 @/do@+{@<Try to allocate within node |p| and its physical successors, and
2846 |goto found| if allocation was possible@>;
2847 @^inner loop@>
2848 p=rlink(p); /*move to the next node in the ring*/
2849 }@+ while (!(p==rover)); /*repeat until the whole list has been traversed*/
2850 if (s==010000000000)
2851 {@+return max_halfword;
2852 }
2853 if (lo_mem_max+2 < hi_mem_min) if (lo_mem_max+2 <= mem_bot+max_halfword)
2854 @<Grow more variable-size memory and |goto restart|@>;
2855 overflow("main memory size", mem_max+1-mem_min);
2856 /*sorry, nothing satisfactory is left*/
2857 @:TeX capacity exceeded main memory size}{\quad main memory size@>
2858 found: link(r)=null; /*this node is now nonempty*/
2859 #ifdef @!STAT
2860 var_used=var_used+s; /*maintain usage statistics*/
2861 #endif
2862 @;@/
2863 return r;
2864 }
2865
2866 @ The lower part of |mem| grows by 1000 words at a time, unless
2867 we are very close to going under. When it grows, we simply link
2868 a new node into the available-space list. This method of controlled
2869 growth helps to keep the |mem| usage consecutive when \TeX\ is
2870 implemented on ``virtual memory'' systems.
2871 @^virtual memory@>
2872
2873 @<Grow more variable-size memory and |goto restart|@>=
2874 {@+if (hi_mem_min-lo_mem_max >= 1998) t=lo_mem_max+1000;
2875 else t=lo_mem_max+1+(hi_mem_min-lo_mem_max)/2;
2876 /*|lo_mem_max+2 <= t < hi_mem_min|*/
2877 p=llink(rover);q=lo_mem_max;rlink(p)=q;llink(rover)=q;@/
2878 if (t > mem_bot+max_halfword) t=mem_bot+max_halfword;
2879 rlink(q)=rover;llink(q)=p;link(q)=empty_flag;node_size(q)=t-lo_mem_max;@/
2880 lo_mem_max=t;link(lo_mem_max)=null;info(lo_mem_max)=null;
2881 rover=q;goto restart;
2882 }
2883
2884 @ Empirical tests show that the routine in this section performs a
2885 node-merging operation about 0.75 times per allocation, on the average,
2886 after which it finds that |r > p+1| about 95\pct! of the time.
2887
2888 @<Try to allocate...@>=
2889 q=p+node_size(p); /*find the physical successor*/
2890 @^inner loop@>
2891 while (is_empty(q)) /*merge node |p| with node |q|*/
2892 {@+t=rlink(q);
2893 if (q==rover) rover=t;
2894 llink(t)=llink(q);rlink(llink(q))=t;@/
2895 q=q+node_size(q);
2896 }
2897 r=q-s;
2898 if (r > p+1) @<Allocate from the top of node |p| and |goto found|@>;
2899 if (r==p) if (rlink(p)!=p)
2900 @<Allocate entire node |p| and |goto found|@>;
2901 node_size(p)=q-p /*reset the size in case it grew*/
2902
2903 @ @<Allocate from the top...@>=
2904 {@+node_size(p)=r-p; /*store the remaining size*/
2905 @^inner loop@>
2906 rover=p; /*start searching here next time*/
2907 goto found;
2908 }
2909
2910 @ Here we delete node |p| from the ring, and let |rover| rove around.
2911
2912 @<Allocate entire...@>=
2913 {@+rover=rlink(p);t=llink(p);
2914 llink(rover)=t;rlink(t)=rover;
2915 goto found;
2916 }
2917
2918 @ Conversely, when some variable-size node |p| of size |s| is no longer needed,
2919 the operation |free_node(p, s)| will make its words available, by inserting
2920 |p| as a new empty node just before where |rover| now points.
2921 @^inner loop@>
2922
2923 @p static void free_node(pointer @!p, halfword @!s) /*variable-size node
2924 liberation*/
2925 {@+pointer q; /*|llink(rover)|*/
2926 node_size(p)=s;link(p)=empty_flag;
2927 q=llink(rover);llink(p)=q;rlink(p)=rover; /*set both links*/
2928 llink(rover)=p;rlink(q)=p; /*insert |p| into the ring*/
2929 #ifdef @!STAT
2930 var_used=var_used-s;
2931 #endif
2932 @; /*maintain statistics*/
2933 }
2934
2935 @ Just before \.{INITEX} writes out the memory, it sorts the doubly linked
2936 available space list. The list is probably very short at such times, so a
2937 simple insertion sort is used. The smallest available location will be
2938 pointed to by |rover|, the next-smallest by |rlink(rover)|, etc.
2939
2940 @p
2941 #ifdef @!INIT
2942 static void sort_avail(void) /*sorts the available variable-size nodes
2943 by location*/
2944 {@+pointer p, @!q, @!r; /*indices into |mem|*/
2945 pointer @!old_rover; /*initial |rover| setting*/
2946 p=get_node(010000000000); /*merge adjacent free areas*/
2947 p=rlink(rover);rlink(rover)=max_halfword;old_rover=rover;
2948 while (p!=old_rover) @<Sort \(p)|p| into the list starting at |rover| and
2949 advance |p| to |rlink(p)|@>;
2950 p=rover;
2951 while (rlink(p)!=max_halfword)
2952 {@+llink(rlink(p))=p;p=rlink(p);
2953 }
2954 rlink(p)=rover;llink(rover)=p;
2955 }
2956 #endif
2957
2958 @ The following |while | loop is guaranteed to
2959 terminate, since the list that starts at
2960 |rover| ends with |max_halfword| during the sorting procedure.
2961
2962 @<Sort \(p)|p|...@>=
2963 if (p < rover)
2964 {@+q=p;p=rlink(q);rlink(q)=rover;rover=q;
2965 }
2966 else{@+q=rover;
2967 while (rlink(q) < p) q=rlink(q);
2968 r=rlink(p);rlink(p)=rlink(q);rlink(q)=p;p=r;
2969 }
2970
2971 @* Data structures for boxes and their friends.
2972 From the computer's standpoint, \TeX's chief mission is to create
2973 horizontal and vertical lists. We shall now investigate how the elements
2974 of these lists are represented internally as nodes in the dynamic memory.
2975
2976 A horizontal or vertical list is linked together by |link| fields in
2977 the first word of each node. Individual nodes represent boxes, glue,
2978 penalties, or special things like discretionary hyphens; because of this
2979 variety, some nodes are longer than others, and we must distinguish different
2980 kinds of nodes. We do this by putting a `|type|' field in the first word,
2981 together with the link and an optional `|subtype|'.
2982
2983 @d type(A) mem[A].hh.b0 /*identifies what kind of node this is*/
2984 @d subtype(A) mem[A].hh.b1 /*secondary identification in some cases*/
2985
2986 @ A |@!char_node|, which represents a single character, is the most important
2987 kind of node because it accounts for the vast majority of all boxes.
2988 Special precautions are therefore taken to ensure that a |char_node| does
2989 not take up much memory space. Every such node is one word long, and in fact
2990 it is identifiable by this property, since other kinds of nodes have at least
2991 two words, and they appear in |mem| locations less than |hi_mem_min|.
2992 This makes it possible to omit the |type| field in a |char_node|, leaving
2993 us room for two bytes that identify a |font| and a |character| within
2994 that font.
2995
2996 Note that the format of a |char_node| allows for up to 256 different
2997 fonts and up to 256 characters per font; but most implementations will
2998 probably limit the total number of fonts to fewer than 75 per job,
2999 and most fonts will stick to characters whose codes are
3000 less than 128 (since higher codes
3001 are more difficult to access on most keyboards).
3002
3003 Extensions of \TeX\ intended for oriental languages will need even more
3004 than $256\times256$ possible characters, when we consider different sizes
3005 @^oriental characters@>@^Chinese characters@>@^Japanese characters@>
3006 and styles of type. It is suggested that Chinese and Japanese fonts be
3007 handled by representing such characters in two consecutive |char_node|
3008 entries: The first of these has |font==font_base|, and its |link| points
3009 to the second;
3010 the second identifies the font and the character dimensions.
3011 The saving feature about oriental characters is that most of them have
3012 the same box dimensions. The |character| field of the first |char_node|
3013 is a ``\\{charext}'' that distinguishes between graphic symbols whose
3014 dimensions are identical for typesetting purposes. (See the \MF\ manual.)
3015 Such an extension of \TeX\ would not be difficult; further details are
3016 left to the reader.
3017
3018 In order to make sure that the |character| code fits in a quarterword,
3019 \TeX\ adds the quantity |min_quarterword| to the actual code.
3020
3021 Character nodes appear only in horizontal lists, never in vertical lists.
3022
3023 @d is_char_node(A) (A >= hi_mem_min)
3024 /*does the argument point to a |char_node|?*/
3025 @d font(A) type(A) /*the font code in a |char_node|*/
3026 @d character(A) subtype(A) /*the character code in a |char_node|*/
3027
3028 @ An |hlist_node| stands for a box that was made from a horizontal list.
3029 Each |hlist_node| is seven words long, and contains the following fields
3030 (in addition to the mandatory |type| and |link|, which we shall not
3031 mention explicitly when discussing the other node types): The |height| and
3032 |width| and |depth| are scaled integers denoting the dimensions of the
3033 box. There is also a |shift_amount| field, a scaled integer indicating
3034 how much this box should be lowered (if it appears in a horizontal list),
3035 or how much it should be moved to the right (if it appears in a vertical
3036 list). There is a |list_ptr| field, which points to the beginning of the
3037 list from which this box was fabricated; if |list_ptr| is |null|, the box
3038 is empty. Finally, there are three fields that represent the setting of
3039 the glue: |glue_set(p)| is a word of type |glue_ratio| that represents
3040 the proportionality constant for glue setting; |glue_sign(p)| is
3041 |stretching| or |shrinking| or |normal| depending on whether or not the
3042 glue should stretch or shrink or remain rigid; and |glue_order(p)|
3043 specifies the order of infinity to which glue setting applies (|normal|,
3044 |fil|, |fill|, or |filll|). The |subtype| field is not used.
3045
3046 @d hlist_node 0 /*|type| of hlist nodes*/
3047 @d box_node_size 7 /*number of words to allocate for a box node*/
3048 @d width_offset 1 /*position of |width| field in a box node*/
3049 @d depth_offset 2 /*position of |depth| field in a box node*/
3050 @d height_offset 3 /*position of |height| field in a box node*/
3051 @d width(A) mem[A+width_offset].sc /*width of the box, in sp*/
3052 @d depth(A) mem[A+depth_offset].sc /*depth of the box, in sp*/
3053 @d height(A) mem[A+height_offset].sc /*height of the box, in sp*/
3054 @d shift_amount(A) mem[A+4].sc /*repositioning distance, in sp*/
3055 @d list_offset 5 /*position of |list_ptr| field in a box node*/
3056 @d list_ptr(A) link(A+list_offset) /*beginning of the list inside the box*/
3057 @d glue_order(A) subtype(A+list_offset) /*applicable order of infinity*/
3058 @d glue_sign(A) type(A+list_offset) /*stretching or shrinking*/
3059 @d normal 0 /*the most common case when several cases are named*/
3060 @d stretching 1 /*glue setting applies to the stretch components*/
3061 @d shrinking 2 /*glue setting applies to the shrink components*/
3062 @d glue_offset 6 /*position of |glue_set| in a box node*/
3063 @d glue_set(A) mem[A+glue_offset].gr
3064 /*a word of type |glue_ratio| for glue setting*/
3065
3066 @ The |new_null_box| function returns a pointer to an |hlist_node| in
3067 which all subfields have the values corresponding to `\.{\\hbox\{\}}'.
3068 (The |subtype| field is set to |min_quarterword|, for historic reasons
3069 that are no longer relevant.)
3070
3071 @p static pointer new_null_box(void) /*creates a new box node*/
3072 {@+pointer p; /*the new node*/
3073 p=get_node(box_node_size);type(p)=hlist_node;
3074 subtype(p)=min_quarterword;
3075 width(p)=0;depth(p)=0;height(p)=0;shift_amount(p)=0;list_ptr(p)=null;
3076 glue_sign(p)=normal;glue_order(p)=normal;set_glue_ratio_zero(glue_set(p));
3077 return p;
3078 }
3079
3080 @ A |vlist_node| is like an |hlist_node| in all respects except that it
3081 contains a vertical list.
3082
3083 @d vlist_node 1 /*|type| of vlist nodes*/
3084
3085 @ A |rule_node| stands for a solid black rectangle; it has |width|,
3086 |depth|, and |height| fields just as in an |hlist_node|. However, if
3087 any of these dimensions is $-2^{30}$, the actual value will be determined
3088 by running the rule up to the boundary of the innermost enclosing box.
3089 This is called a ``running dimension.'' The |width| is never running in
3090 an hlist; the |height| and |depth| are never running in a~vlist.
3091
3092 @d rule_node 2 /*|type| of rule nodes*/
3093 @d rule_node_size 4 /*number of words to allocate for a rule node*/
3094 @d null_flag -010000000000 /*$-2^{30}$, signifies a missing item*/
3095 @d is_running(A) (A==null_flag) /*tests for a running dimension*/
3096
3097 @ A new rule node is delivered by the |new_rule| function. It
3098 makes all the dimensions ``running,'' so you have to change the
3099 ones that are not allowed to run.
3100
3101 @p static pointer new_rule(void)
3102 {@+pointer p; /*the new node*/
3103 p=get_node(rule_node_size);type(p)=rule_node;
3104 subtype(p)=0; /*the |subtype| is not used*/
3105 width(p)=null_flag;depth(p)=null_flag;height(p)=null_flag;
3106 return p;
3107 }
3108
3109 @ Insertions are represented by |ins_node| records, where the |subtype|
3110 indicates the corresponding box number. For example, `\.{\\insert 250}'
3111 leads to an |ins_node| whose |subtype| is |250+min_quarterword|.
3112 The |height| field of an |ins_node| is slightly misnamed; it actually holds
3113 the natural height plus depth of the vertical list being inserted.
3114 The |depth| field holds the |split_max_depth| to be used in case this
3115 insertion is split, and the |split_top_ptr| points to the corresponding
3116 |split_top_skip|. The |float_cost| field holds the |floating_penalty| that
3117 will be used if this insertion floats to a subsequent page after a
3118 split insertion of the same class. There is one more field, the
3119 |ins_ptr|, which points to the beginning of the vlist for the insertion.
3120
3121 @d ins_node 3 /*|type| of insertion nodes*/
3122 @d ins_node_size 5 /*number of words to allocate for an insertion*/
3123 @d float_cost(A) mem[A+1].i /*the |floating_penalty| to be used*/
3124 @d ins_ptr(A) info(A+4) /*the vertical list to be inserted*/
3125 @d split_top_ptr(A) link(A+4) /*the |split_top_skip| to be used*/
3126
3127 @ A |mark_node| has a |mark_ptr| field that points to the reference count
3128 of a token list that contains the user's \.{\\mark} text.
3129 In addition there is a |mark_class| field that contains the mark class.
3130
3131 @d mark_node 4 /*|type| of a mark node*/
3132 @d small_node_size 2 /*number of words to allocate for most node types*/
3133 @d mark_ptr(A) link(A+1) /*head of the token list for a mark*/
3134 @d mark_class(A) info(A+1) /*the mark class*/
3135
3136 @ An |adjust_node|, which occurs only in horizontal lists,
3137 specifies material that will be moved out into the surrounding
3138 vertical list; i.e., it is used to implement \TeX's `\.{\\vadjust}'
3139 operation. The |adjust_ptr| field points to the vlist containing this
3140 material.
3141
3142 @d adjust_node 5 /*|type| of an adjust node*/
3143 @d adjust_ptr(A) mem[A+1].i
3144 /*vertical list to be moved out of horizontal list*/
3145
3146 @ A |ligature_node|, which occurs only in horizontal lists, specifies
3147 a character that was fabricated from the interaction of two or more
3148 actual characters. The second word of the node, which is called the
3149 |lig_char| word, contains |font| and |character| fields just as in a
3150 |char_node|. The characters that generated the ligature have not been
3151 forgotten, since they are needed for diagnostic messages and for
3152 hyphenation; the |lig_ptr| field points to a linked list of character
3153 nodes for all original characters that have been deleted. (This list
3154 might be empty if the characters that generated the ligature were
3155 retained in other nodes.)
3156
3157 The |subtype| field is 0, plus 2 and/or 1 if the original source of the
3158 ligature included implicit left and/or right boundaries.
3159
3160 @d ligature_node 6 /*|type| of a ligature node*/
3161 @d lig_char(A) A+1 /*the word where the ligature is to be found*/
3162 @d lig_ptr(A) link(lig_char(A)) /*the list of characters*/
3163
3164 @ The |new_ligature| function creates a ligature node having given
3165 contents of the |font|, |character|, and |lig_ptr| fields. We also have
3166 a |new_lig_item| function, which returns a two-word node having a given
3167 |character| field. Such nodes are used for temporary processing as ligatures
3168 are being created.
3169
3170 @p static pointer new_ligature(quarterword @!f, quarterword @!c, pointer @!q)
3171 {@+pointer p; /*the new node*/
3172 p=get_node(small_node_size);type(p)=ligature_node;
3173 font(lig_char(p))=f;character(lig_char(p))=c;lig_ptr(p)=q;
3174 subtype(p)=0;return p;
3175 }
3176 @#
3177 static pointer new_lig_item(quarterword @!c)
3178 {@+pointer p; /*the new node*/
3179 p=get_node(small_node_size);character(p)=c;lig_ptr(p)=null;
3180 return p;
3181 }
3182
3183 @ A |disc_node|, which occurs only in horizontal lists, specifies a
3184 ``dis\-cretion\-ary'' line break. If such a break occurs at node |p|, the text
3185 that starts at |pre_break(p)| will precede the break, the text that starts at
3186 |post_break(p)| will follow the break, and text that appears in the next
3187 |replace_count(p)| nodes will be ignored. For example, an ordinary
3188 discretionary hyphen, indicated by `\.{\\-}', yields a |disc_node| with
3189 |pre_break| pointing to a |char_node| containing a hyphen, |post_break==null|,
3190 and |replace_count==0|. All three of the discretionary texts must be
3191 lists that consist entirely of character, kern, box, rule, and ligature nodes.
3192
3193 If |pre_break(p)==null|, the |ex_hyphen_penalty| will be charged for this
3194 break. Otherwise the |hyphen_penalty| will be charged. The texts will
3195 actually be substituted into the list by the line-breaking algorithm if it
3196 decides to make the break, and the discretionary node will disappear at
3197 that time; thus, the output routine sees only discretionaries that were
3198 not chosen.
3199
3200 @d disc_node 7 /*|type| of a discretionary node*/
3201 @d replace_count(A) subtype(A) /*how many subsequent nodes to replace*/
3202 @d pre_break(A) llink(A) /*text that precedes a discretionary break*/
3203 @d post_break(A) rlink(A) /*text that follows a discretionary break*/
3204
3205 @p static pointer new_disc(void) /*creates an empty |disc_node|*/
3206 {@+pointer p; /*the new node*/
3207 p=get_node(small_node_size);type(p)=disc_node;
3208 replace_count(p)=0;pre_break(p)=null;post_break(p)=null;
3209 return p;
3210 }
3211
3212 @ A |whatsit_node| is a wild card reserved for extensions to \TeX. The
3213 |subtype| field in its first word says what `\\{whatsit}' it is, and
3214 implicitly determines the node size (which must be 2 or more) and the
3215 format of the remaining words. When a |whatsit_node| is encountered
3216 in a list, special actions are invoked; knowledgeable people who are
3217 careful not to mess up the rest of \TeX\ are able to make \TeX\ do new
3218 things by adding code at the end of the program. For example, there
3219 might be a `\TeX nicolor' extension to specify different colors of ink,
3220 @^extensions to \TeX@>
3221 and the whatsit node might contain the desired parameters.
3222
3223 The present implementation of \TeX\ treats the features associated with
3224 `\.{\\write}' and `\.{\\special}' as if they were extensions, in order to
3225 illustrate how such routines might be coded. We shall defer further
3226 discussion of extensions until the end of this program.
3227
3228 @d whatsit_node 8 /*|type| of special extension nodes*/
3229
3230 @ A |math_node|, which occurs only in horizontal lists, appears before and
3231 after mathematical formulas. The |subtype| field is |before| before the
3232 formula and |after| after it. There is a |width| field, which represents
3233 the amount of surrounding space inserted by \.{\\mathsurround}.
3234
3235 @d math_node 9 /*|type| of a math node*/
3236 @d before 0 /*|subtype| for math node that introduces a formula*/
3237 @d after 1 /*|subtype| for math node that winds up a formula*/
3238
3239 @p static pointer new_math(scaled @!w, small_number @!s)
3240 {@+pointer p; /*the new node*/
3241 p=get_node(small_node_size);type(p)=math_node;
3242 subtype(p)=s;width(p)=w;return p;
3243 }
3244
3245 @ \TeX\ makes use of the fact that |hlist_node|, |vlist_node|,
3246 |rule_node|, |ins_node|, |mark_node|, |adjust_node|, |ligature_node|,
3247 |disc_node|, |whatsit_node|, and |math_node| are at the low end of the
3248 type codes, by permitting a break at glue in a list if and only if the
3249 |type| of the previous node is less than |math_node|. Furthermore, a
3250 node is discarded after a break if its type is |math_node| or~more.
3251
3252 @d precedes_break(A) (type(A) < math_node)
3253 @d non_discardable(A) (type(A) < math_node)
3254
3255 @ A |glue_node| represents glue in a list. However, it is really only
3256 a pointer to a separate glue specification, since \TeX\ makes use of the
3257 fact that many essentially identical nodes of glue are usually present.
3258 If |p| points to a |glue_node|, |glue_ptr(p)| points to
3259 another packet of words that specify the stretch and shrink components, etc.
3260
3261 Glue nodes also serve to represent leaders; the |subtype| is used to
3262 distinguish between ordinary glue (which is called |normal|) and the three
3263 kinds of leaders (which are called |a_leaders|, |c_leaders|, and |x_leaders|).
3264 The |leader_ptr| field points to a rule node or to a box node containing the
3265 leaders; it is set to |null| in ordinary glue nodes.
3266
3267 Many kinds of glue are computed from \TeX's ``skip'' parameters, and
3268 it is helpful to know which parameter has led to a particular glue node.
3269 Therefore the |subtype| is set to indicate the source of glue, whenever
3270 it originated as a parameter. We will be defining symbolic names for the
3271 parameter numbers later (e.g., |line_skip_code==0|, |baseline_skip_code==1|,
3272 etc.); it suffices for now to say that the |subtype| of parametric glue
3273 will be the same as the parameter number, plus~one.
3274
3275 In math formulas there are two more possibilities for the |subtype| in a
3276 glue node: |mu_glue| denotes an \.{\\mskip} (where the units are scaled \.{mu}
3277 instead of scaled \.{pt}); and |cond_math_glue| denotes the `\.{\\nonscript}'
3278 feature that cancels the glue node immediately following if it appears
3279 in a subscript.
3280
3281 @d glue_node 10 /*|type| of node that points to a glue specification*/
3282 @d cond_math_glue 98 /*special |subtype| to suppress glue in the next node*/
3283 @d mu_glue 99 /*|subtype| for math glue*/
3284 @d a_leaders 100 /*|subtype| for aligned leaders*/
3285 @d c_leaders 101 /*|subtype| for centered leaders*/
3286 @d x_leaders 102 /*|subtype| for expanded leaders*/
3287 @d glue_ptr(A) llink(A) /*pointer to a glue specification*/
3288 @d leader_ptr(A) rlink(A) /*pointer to box or rule node for leaders*/
3289
3290 @ A glue specification has a halfword reference count in its first word,
3291 @^reference counts@>
3292 representing |null| plus the number of glue nodes that point to it (less one).
3293 Note that the reference count appears in the same position as
3294 the |link| field in list nodes; this is the field that is initialized
3295 to |null| when a node is allocated, and it is also the field that is flagged
3296 by |empty_flag| in empty nodes.
3297
3298 Glue specifications also contain three |scaled| fields, for the |width|,
3299 |stretch|, and |shrink| dimensions. Finally, there are two one-byte
3300 fields called |stretch_order| and |shrink_order|; these contain the
3301 orders of infinity (|normal|, |fil|, |fill|, or |filll|)
3302 corresponding to the stretch and shrink values.
3303
3304 @d glue_spec_size 4 /*number of words to allocate for a glue specification*/
3305 @d glue_ref_count(A) link(A) /*reference count of a glue specification*/
3306 @d stretch(A) mem[A+2].sc /*the stretchability of this glob of glue*/
3307 @d shrink(A) mem[A+3].sc /*the shrinkability of this glob of glue*/
3308 @d stretch_order(A) type(A) /*order of infinity for stretching*/
3309 @d shrink_order(A) subtype(A) /*order of infinity for shrinking*/
3310 @d fil 1 /*first-order infinity*/
3311 @d fill 2 /*second-order infinity*/
3312 @d filll 3 /*third-order infinity*/
3313
3314 @<Types...@>=
3315 typedef int8_t glue_ord; /*infinity to the 0, 1, 2, or 3 power*/
3316
3317 @ Here is a function that returns a pointer to a copy of a glue spec.
3318 The reference count in the copy is |null|, because there is assumed
3319 to be exactly one reference to the new specification.
3320
3321 @p static pointer new_spec(pointer @!p) /*duplicates a glue specification*/
3322 {@+pointer q; /*the new spec*/
3323 q=get_node(glue_spec_size);@/
3324 mem[q]=mem[p];glue_ref_count(q)=null;@/
3325 width(q)=width(p);stretch(q)=stretch(p);shrink(q)=shrink(p);
3326 return q;
3327 }
3328
3329 @ And here's a function that creates a glue node for a given parameter
3330 identified by its code number; for example,
3331 |new_param_glue(line_skip_code)| returns a pointer to a glue node for the
3332 current \.{\\lineskip}.
3333
3334 @p static pointer new_param_glue(small_number @!n)
3335 {@+pointer p; /*the new node*/
3336 pointer @!q; /*the glue specification*/
3337 p=get_node(small_node_size);type(p)=glue_node;subtype(p)=n+1;
3338 leader_ptr(p)=null;@/
3339 q=@<Current |mem| equivalent of glue parameter number |n|@>@t@>;
3340 glue_ptr(p)=q;incr(glue_ref_count(q));
3341 return p;
3342 }
3343
3344 @ Glue nodes that are more or less anonymous are created by |new_glue|,
3345 whose argument points to a glue specification.
3346
3347 @p static pointer new_glue(pointer @!q)
3348 {@+pointer p; /*the new node*/
3349 p=get_node(small_node_size);type(p)=glue_node;subtype(p)=normal;
3350 leader_ptr(p)=null;glue_ptr(p)=q;incr(glue_ref_count(q));
3351 return p;
3352 }
3353
3354 @ Still another subroutine is needed: This one is sort of a combination
3355 of |new_param_glue| and |new_glue|. It creates a glue node for one of
3356 the current glue parameters, but it makes a fresh copy of the glue
3357 specification, since that specification will probably be subject to change,
3358 while the parameter will stay put. The global variable |temp_ptr| is
3359 set to the address of the new spec.
3360
3361 @p static pointer new_skip_param(small_number @!n)
3362 {@+pointer p; /*the new node*/
3363 temp_ptr=new_spec(@<Current |mem| equivalent of glue parameter...@>);
3364 p=new_glue(temp_ptr);glue_ref_count(temp_ptr)=null;subtype(p)=n+1;
3365 return p;
3366 }
3367
3368 @ A |kern_node| has a |width| field to specify a (normally negative)
3369 amount of spacing. This spacing correction appears in horizontal lists
3370 between letters like A and V when the font designer said that it looks
3371 better to move them closer together or further apart. A kern node can
3372 also appear in a vertical list, when its `|width|' denotes additional
3373 spacing in the vertical direction. The |subtype| is either |normal| (for
3374 kerns inserted from font information or math mode calculations) or |explicit|
3375 (for kerns inserted from \.{\\kern} and \.{\\/} commands) or |acc_kern|
3376 (for kerns inserted from non-math accents) or |mu_glue| (for kerns
3377 inserted from \.{\\mkern} specifications in math formulas).
3378
3379 @d kern_node 11 /*|type| of a kern node*/
3380 @d explicit 1 /*|subtype| of kern nodes from \.{\\kern} and \.{\\/}*/
3381 @d acc_kern 2 /*|subtype| of kern nodes from accents*/
3382
3383 @ The |new_kern| function creates a kern node having a given width.
3384
3385 @p static pointer new_kern(scaled @!w)
3386 {@+pointer p; /*the new node*/
3387 p=get_node(small_node_size);type(p)=kern_node;
3388 subtype(p)=normal;
3389 width(p)=w;
3390 return p;
3391 }
3392
3393 @ A |penalty_node| specifies the penalty associated with line or page
3394 breaking, in its |penalty| field. This field is a fullword integer, but
3395 the full range of integer values is not used: Any penalty | >= 10000| is
3396 treated as infinity, and no break will be allowed for such high values.
3397 Similarly, any penalty | <= -10000| is treated as negative infinity, and a
3398 break will be forced.
3399
3400 @d penalty_node 12 /*|type| of a penalty node*/
3401 @d inf_penalty inf_bad /*``infinite'' penalty value*/
3402 @d eject_penalty (-inf_penalty) /*``negatively infinite'' penalty value*/
3403 @d penalty(A) mem[A+1].i /*the added cost of breaking a list here*/
3404
3405 @ Anyone who has been reading the last few sections of the program will
3406 be able to guess what comes next.
3407
3408 @p static pointer new_penalty(int @!m)
3409 {@+pointer p; /*the new node*/
3410 p=get_node(small_node_size);type(p)=penalty_node;
3411 subtype(p)=0; /*the |subtype| is not used*/
3412 penalty(p)=m;return p;
3413 }
3414
3415 @ You might think that we have introduced enough node types by now. Well,
3416 almost, but there is one more: An |unset_node| has nearly the same format
3417 as an |hlist_node| or |vlist_node|; it is used for entries in \.{\\halign}
3418 or \.{\\valign} that are not yet in their final form, since the box
3419 dimensions are their ``natural'' sizes before any glue adjustment has been
3420 made. The |glue_set| word is not present; instead, we have a |glue_stretch|
3421 field, which contains the total stretch of order |glue_order| that is
3422 present in the hlist or vlist being boxed.
3423 Similarly, the |shift_amount| field is replaced by a |glue_shrink| field,
3424 containing the total shrink of order |glue_sign| that is present.
3425 The |subtype| field is called |span_count|; an unset box typically
3426 contains the data for |qo(span_count)+1| columns.
3427 Unset nodes will be changed to box nodes when alignment is completed.
3428
3429 @d unset_node 13 /*|type| for an unset node*/
3430 @d glue_stretch(A) mem[A+glue_offset].sc /*total stretch in an unset node*/
3431 @d glue_shrink(A) shift_amount(A) /*total shrink in an unset node*/
3432 @d span_count(A) subtype(A) /*indicates the number of spanned columns*/
3433
3434 @ In fact, there are still more types coming. When we get to math formula
3435 processing we will see that a |style_node| has |type==14|; and a number
3436 of larger type codes will also be defined, for use in math mode only.
3437
3438 @ Warning: If any changes are made to these data structure layouts, such as
3439 changing any of the node sizes or even reordering the words of nodes,
3440 the |copy_node_list| procedure and the memory initialization code
3441 below may have to be changed. Such potentially dangerous parts of the
3442 program are listed in the index under `data structure assumptions'.
3443 @!@^data structure assumptions@>
3444 However, other references to the nodes are made symbolically in terms of
3445 the \.{WEB} macro definitions above, so that format changes will leave
3446 \TeX's other algorithms intact.
3447 @^system dependencies@>
3448
3449 @* Memory layout.
3450 Some areas of |mem| are dedicated to fixed usage, since static allocation is
3451 more efficient than dynamic allocation when we can get away with it. For
3452 example, locations |mem_bot| to |mem_bot+3| are always used to store the
3453 specification for glue that is `\.{0pt plus 0pt minus 0pt}'. The
3454 following macro definitions accomplish the static allocation by giving
3455 symbolic names to the fixed positions. Static variable-size nodes appear
3456 in locations |mem_bot| through |lo_mem_stat_max|, and static single-word nodes
3457 appear in locations |hi_mem_stat_min| through |mem_top|, inclusive. It is
3458 harmless to let |lig_trick| and |garbage| share the same location of |mem|.
3459
3460 @d zero_glue mem_bot /*specification for \.{0pt plus 0pt minus 0pt}*/
3461 @d fil_glue zero_glue+glue_spec_size /*\.{0pt plus 1fil minus 0pt}*/
3462 @d fill_glue fil_glue+glue_spec_size /*\.{0pt plus 1fill minus 0pt}*/
3463 @d ss_glue fill_glue+glue_spec_size /*\.{0pt plus 1fil minus 1fil}*/
3464 @d fil_neg_glue ss_glue+glue_spec_size /*\.{0pt plus -1fil minus 0pt}*/
3465 @d lo_mem_stat_max fil_neg_glue+glue_spec_size-1 /*largest statically
3466 allocated word in the variable-size |mem|*/
3467 @#
3468 @d page_ins_head mem_top /*list of insertion data for current page*/
3469 @d contrib_head mem_top-1 /*vlist of items not yet on current page*/
3470 @d page_head mem_top-2 /*vlist for current page*/
3471 @d temp_head mem_top-3 /*head of a temporary list of some kind*/
3472 @d hold_head mem_top-4 /*head of a temporary list of another kind*/
3473 @d adjust_head mem_top-5 /*head of adjustment list returned by |hpack|*/
3474 @d active mem_top-7 /*head of active list in |line_break|, needs two words*/
3475 @d align_head mem_top-8 /*head of preamble list for alignments*/
3476 @d end_span mem_top-9 /*tail of spanned-width lists*/
3477 @d omit_template mem_top-10 /*a constant token list*/
3478 @d null_list mem_top-11 /*permanently empty list*/
3479 @d lig_trick mem_top-12 /*a ligature masquerading as a |char_node|*/
3480 @d garbage mem_top-12 /*used for scrap information*/
3481 @d backup_head mem_top-13 /*head of token list built by |scan_keyword|*/
3482 @d hi_mem_stat_min mem_top-13 /*smallest statically allocated word in
3483 the one-word |mem|*/
3484 @d hi_mem_stat_usage 14 /*the number of one-word nodes always present*/
3485
3486 @ The following code gets |mem| off to a good start, when \TeX\ is
3487 initializing itself the slow~way.
3488
3489 @<Local variables for init...@>=
3490 int @!k; /*index into |mem|, |eqtb|, etc.*/
3491
3492 @ @<Initialize table entries...@>=
3493 for (k=mem_bot+1; k<=lo_mem_stat_max; k++) mem[k].sc=0;
3494 /*all glue dimensions are zeroed*/
3495 @^data structure assumptions@>
3496 k=mem_bot;@+while (k <= lo_mem_stat_max)
3497 /*set first words of glue specifications*/
3498 {@+glue_ref_count(k)=null+1;
3499 stretch_order(k)=normal;shrink_order(k)=normal;
3500 k=k+glue_spec_size;
3501 }
3502 stretch(fil_glue)=unity;stretch_order(fil_glue)=fil;@/
3503 stretch(fill_glue)=unity;stretch_order(fill_glue)=fill;@/
3504 stretch(ss_glue)=unity;stretch_order(ss_glue)=fil;@/
3505 shrink(ss_glue)=unity;shrink_order(ss_glue)=fil;@/
3506 stretch(fil_neg_glue)=-unity;stretch_order(fil_neg_glue)=fil;@/
3507 rover=lo_mem_stat_max+1;
3508 link(rover)=empty_flag; /*now initialize the dynamic memory*/
3509 node_size(rover)=1000; /*which is a 1000-word available node*/
3510 llink(rover)=rover;rlink(rover)=rover;@/
3511 lo_mem_max=rover+1000;link(lo_mem_max)=null;info(lo_mem_max)=null;@/
3512 for (k=hi_mem_stat_min; k<=mem_top; k++)
3513 mem[k]=mem[lo_mem_max]; /*clear list heads*/
3514 @<Initialize the special list heads and constant nodes@>;
3515 avail=null;mem_end=mem_top;
3516 hi_mem_min=hi_mem_stat_min; /*initialize the one-word memory*/
3517 var_used=lo_mem_stat_max+1-mem_bot;dyn_used=hi_mem_stat_usage;
3518 /*initialize statistics*/
3519
3520 @ If \TeX\ is extended improperly, the |mem| array might get screwed up.
3521 For example, some pointers might be wrong, or some ``dead'' nodes might not
3522 have been freed when the last reference to them disappeared. Procedures
3523 |check_mem| and |search_mem| are available to help diagnose such
3524 problems. These procedures make use of two arrays called |is_free| and
3525 |was_free| that are present only if \TeX's debugging routines have
3526 been included. (You may want to decrease the size of |mem| while you
3527 @^debugging@>
3528 are debugging.)
3529
3530 @<Glob...@>=
3531 #ifdef @!DEBUG
3532 static bool @!is_free0[mem_max-mem_min+1],
3533 *const @!is_free = @!is_free0-mem_min; /*free cells*/
3534 @t\hskip10pt@>static bool @!was_free0[mem_max-mem_min+1],
3535 *const @!was_free = @!was_free0-mem_min;
3536 /*previously free cells*/
3537 @t\hskip10pt@>static pointer @!was_mem_end, @!was_lo_max, @!was_hi_min;
3538 /*previous |mem_end|, |lo_mem_max|, and |hi_mem_min|*/
3539 @t\hskip10pt@>static bool @!panicking; /*do we want to check memory constantly?*/
3540 #endif
3541
3542 @ @<Set initial...@>=
3543 #ifdef @!DEBUG
3544 was_mem_end=mem_min; /*indicate that everything was previously free*/
3545 was_lo_max=mem_min;was_hi_min=mem_max;
3546 panicking=false;
3547 #endif
3548
3549 @ Procedure |check_mem| makes sure that the available space lists of
3550 |mem| are well formed, and it optionally prints out all locations
3551 that are reserved now but were free the last time this procedure was called.
3552
3553 @p
3554 #ifdef @!DEBUG
3555 static void check_mem(bool @!print_locs)
3556 {@+ /*loop exits*/
3557 int p, @!q; /*current locations of interest in |mem|*/
3558 bool @!clobbered; /*is something amiss?*/
3559 for (p=mem_min; p<=lo_mem_max; p++) is_free[p]=false; /*you can probably
3560 do this faster*/
3561 for (p=hi_mem_min; p<=mem_end; p++) is_free[p]=false; /*ditto*/
3562 @<Check single-word |avail| list@>;
3563 @<Check variable-size |avail| list@>;
3564 @<Check flags of unavailable nodes@>;
3565 if (print_locs) @<Print newly busy locations@>;
3566 for (p=mem_min; p<=lo_mem_max; p++) was_free[p]=is_free[p];
3567 for (p=hi_mem_min; p<=mem_end; p++) was_free[p]=is_free[p];
3568 /*|was_free=is_free| might be faster*/
3569 was_mem_end=mem_end;was_lo_max=lo_mem_max;was_hi_min=hi_mem_min;
3570 }
3571 #endif
3572
3573 @ @<Check single-word...@>=
3574 p=avail;q=null;clobbered=false;
3575 while (p!=null)
3576 {@+if ((p > mem_end)||(p < hi_mem_min)) clobbered=true;
3577 else if (is_free[p]) clobbered=true;
3578 if (clobbered)
3579 {@+print_nl("AVAIL list clobbered at ");
3580 @.AVAIL list clobbered...@>
3581 print_int(q);goto done1;
3582 }
3583 is_free[p]=true;q=p;p=link(q);
3584 }
3585 done1:
3586
3587 @ @<Check variable-size...@>=
3588 p=rover;q=null;clobbered=false;
3589 @/do@+{if ((p >= lo_mem_max)||(p < mem_min)) clobbered=true;
3590 else if ((rlink(p) >= lo_mem_max)||(rlink(p) < mem_min)) clobbered=true;
3591 else if (!(is_empty(p))||(node_size(p) < 2)||@|
3592 (p+node_size(p) > lo_mem_max)||@|(llink(rlink(p))!=p)) clobbered=true;
3593 if (clobbered)
3594 {@+print_nl("Double-AVAIL list clobbered at ");
3595 print_int(q);goto done2;
3596 }
3597 for (q=p; q<=p+node_size(p)-1; q++) /*mark all locations free*/
3598 {@+if (is_free[q])
3599 {@+print_nl("Doubly free location at ");
3600 @.Doubly free location...@>
3601 print_int(q);goto done2;
3602 }
3603 is_free[q]=true;
3604 }
3605 q=p;p=rlink(p);
3606 }@+ while (!(p==rover));
3607 done2:
3608
3609 @ @<Check flags...@>=
3610 p=mem_min;
3611 while (p <= lo_mem_max) /*node |p| should not be empty*/
3612 {@+if (is_empty(p))
3613 {@+print_nl("Bad flag at ");print_int(p);
3614 @.Bad flag...@>
3615 }
3616 while ((p <= lo_mem_max)&&!is_free[p]) incr(p);
3617 while ((p <= lo_mem_max)&&is_free[p]) incr(p);
3618 }
3619
3620 @ @<Print newly busy...@>=
3621 {@+print_nl("New busy locs:");
3622 for (p=mem_min; p<=lo_mem_max; p++)
3623 if (!is_free[p]&&((p > was_lo_max)||was_free[p]))
3624 {@+print_char(' ');print_int(p);
3625 }
3626 for (p=hi_mem_min; p<=mem_end; p++)
3627 if (!is_free[p]&&
3628 ((p < was_hi_min)||(p > was_mem_end)||was_free[p]))
3629 {@+print_char(' ');print_int(p);
3630 }
3631 }
3632
3633 @ The |search_mem| procedure attempts to answer the question ``Who points
3634 to node~|p|?'' In doing so, it fetches |link| and |info| fields of |mem|
3635 that might not be of type |two_halves|. Strictly speaking, this is
3636 @^dirty \PASCAL@>
3637 undefined in \PASCAL, and it can lead to ``false drops'' (words that seem to
3638 point to |p| purely by coincidence). But for debugging purposes, we want
3639 to rule out the places that do {\sl not\/} point to |p|, so a few false
3640 drops are tolerable.
3641
3642 @p
3643 #ifdef @!DEBUG
3644 static void search_mem(pointer @!p) /*look for pointers to |p|*/
3645 {@+int q; /*current position being searched*/
3646 for (q=mem_min; q<=lo_mem_max; q++)
3647 {@+if (link(q)==p)
3648 {@+print_nl("LINK(");print_int(q);print_char(')');
3649 }
3650 if (info(q)==p)
3651 {@+print_nl("INFO(");print_int(q);print_char(')');
3652 }
3653 }
3654 for (q=hi_mem_min; q<=mem_end; q++)
3655 {@+if (link(q)==p)
3656 {@+print_nl("LINK(");print_int(q);print_char(')');
3657 }
3658 if (info(q)==p)
3659 {@+print_nl("INFO(");print_int(q);print_char(')');
3660 }
3661 }
3662 @<Search |eqtb| for equivalents equal to |p|@>;
3663 @<Search |save_stack| for equivalents that point to |p|@>;
3664 @<Search |hyph_list| for pointers to |p|@>;
3665 }
3666 #endif
3667
3668 @* Displaying boxes.
3669 We can reinforce our knowledge of the data structures just introduced
3670 by considering two procedures that display a list in symbolic form.
3671 The first of these, called |short_display|, is used in ``overfull box''
3672 messages to give the top-level description of a list. The other one,
3673 called |show_node_list|, prints a detailed description of exactly what
3674 is in the data structure.
3675
3676 The philosophy of |short_display| is to ignore the fine points about exactly
3677 what is inside boxes, except that ligatures and discretionary breaks are
3678 expanded. As a result, |short_display| is a recursive procedure, but the
3679 recursion is never more than one level deep.
3680 @^recursion@>
3681
3682 A global variable |font_in_short_display| keeps track of the font code that
3683 is assumed to be present when |short_display| begins; deviations from this
3684 font will be printed.
3685
3686 @<Glob...@>=
3687 static int @!font_in_short_display; /*an internal font number*/
3688
3689 @ Boxes, rules, inserts, whatsits, marks, and things in general that are
3690 sort of ``complicated'' are indicated only by printing `\.{[]}'.
3691
3692 @p static void short_display(int @!p) /*prints highlights of list |p|*/
3693 {@+int n; /*for replacement counts*/
3694 while (p > mem_min)
3695 {@+if (is_char_node(p))
3696 {@+if (p <= mem_end)
3697 {@+if (font(p)!=font_in_short_display)
3698 {@+if ((font(p) < font_base)||(font(p) > font_max))
3699 print_char('*');
3700 @.*\relax@>
3701 else@<Print the font identifier for |font(p)|@>;
3702 print_char(' ');font_in_short_display=font(p);
3703 }
3704 print_ASCII(qo(character(p)));
3705 }
3706 }
3707 else@<Print a short indication of the contents of node |p|@>;
3708 p=link(p);
3709 }
3710 }
3711
3712 @ @<Print a short indication of the contents of node |p|@>=
3713 switch (type(p)) {
3714 case hlist_node: case vlist_node: case ins_node:
3715 case whatsit_node: case mark_node: case adjust_node:
3716 case unset_node: print("[]");@+break;
3717 case rule_node: print_char('|');@+break;
3718 case glue_node: if (glue_ptr(p)!=zero_glue) print_char(' ');@+break;
3719 case math_node: print_char('$');@+break;
3720 case ligature_node: short_display(lig_ptr(p));@+break;
3721 case disc_node: {@+short_display(pre_break(p));
3722 short_display(post_break(p));@/
3723 n=replace_count(p);
3724 while (n > 0)
3725 {@+if (link(p)!=null) p=link(p);
3726 decr(n);
3727 }
3728 } @+break;
3729 default:do_nothing;
3730 }
3731
3732 @ The |show_node_list| routine requires some auxiliary subroutines: one to
3733 print a font-and-character combination, one to print a token list without
3734 its reference count, and one to print a rule dimension.
3735
3736 @p static void print_font_and_char(int @!p) /*prints |char_node| data*/
3737 {@+if (p > mem_end) print_esc("CLOBBERED.");
3738 else{@+if ((font(p) < font_base)||(font(p) > font_max)) print_char('*');
3739 @.*\relax@>
3740 else@<Print the font identifier for |font(p)|@>;
3741 print_char(' ');print_ASCII(qo(character(p)));
3742 }
3743 }
3744 @#
3745 static void print_mark(int @!p) /*prints token list data in braces*/
3746 {@+print_char('{');
3747 if ((p < hi_mem_min)||(p > mem_end)) print_esc("CLOBBERED.");
3748 else show_token_list(link(p), null, max_print_line-10);
3749 print_char('}');
3750 }
3751 @#
3752 static void print_rule_dimen(scaled @!d) /*prints dimension in rule node*/
3753 {@+if (is_running(d)) print_char('*');else print_scaled(d);
3754 @.*\relax@>
3755 }
3756
3757 @ Then there is a subroutine that prints glue stretch and shrink, possibly
3758 followed by the name of finite units:
3759
3760 @p static void print_glue(scaled @!d, int @!order, char *@!s)
3761 /*prints a glue component*/
3762 {@+print_scaled(d);
3763 if ((order < normal)||(order > filll)) print("foul");
3764 else if (order > normal)
3765 {@+print("fil");
3766 while (order > fil)
3767 {@+print_char('l');decr(order);
3768 }
3769 }
3770 else if (s!=0) print(s);
3771 }
3772
3773 @ The next subroutine prints a whole glue specification.
3774
3775 @p static void print_spec(int @!p, char *@!s)
3776 /*prints a glue specification*/
3777 {@+if ((p < mem_min)||(p >= lo_mem_max)) print_char('*');
3778 @.*\relax@>
3779 else{@+print_scaled(width(p));
3780 if (s!=0) print(s);
3781 if (stretch(p)!=0)
3782 {@+print(" plus ");print_glue(stretch(p), stretch_order(p), s);
3783 }
3784 if (shrink(p)!=0)
3785 {@+print(" minus ");print_glue(shrink(p), shrink_order(p), s);
3786 }
3787 }
3788 }
3789
3790 @ We also need to declare some procedures that appear later in this
3791 documentation.
3792
3793 @p @<Declare procedures needed for displaying the elements of mlists@>@;
3794 @<Declare the procedure called |print_skip_param|@>@;
3795
3796 @ Since boxes can be inside of boxes, |show_node_list| is inherently recursive,
3797 @^recursion@>
3798 up to a given maximum number of levels. The history of nesting is indicated
3799 by the current string, which will be printed at the beginning of each line;
3800 the length of this string, namely |cur_length|, is the depth of nesting.
3801
3802 Recursive calls on |show_node_list| therefore use the following pattern:
3803
3804 @d node_list_display(A)
3805 {@+append_char('.');show_node_list(A);flush_char;
3806 } /*|str_room| need not be checked; see |show_box| below*/
3807
3808 @ A global variable called |depth_threshold| is used to record the maximum
3809 depth of nesting for which |show_node_list| will show information. If we
3810 have |depth_threshold==0|, for example, only the top level information will
3811 be given and no sublists will be traversed. Another global variable, called
3812 |breadth_max|, tells the maximum number of items to show at each level;
3813 |breadth_max| had better be positive, or you won't see anything.
3814
3815 @<Glob...@>=
3816 static int @!depth_threshold; /*maximum nesting depth in box displays*/
3817 static int @!breadth_max; /*maximum number of items shown at the same list level*/
3818
3819 @ Now we are ready for |show_node_list| itself. This procedure has been
3820 written to be ``extra robust'' in the sense that it should not crash or get
3821 into a loop even if the data structures have been messed up by bugs in
3822 the rest of the program. You can safely call its parent routine
3823 |show_box(p)| for arbitrary values of |p| when you are debugging \TeX.
3824 However, in the presence of bad data, the procedure may
3825 @^dirty \PASCAL@>@^debugging@>
3826 fetch a |memory_word| whose variant is different from the way it was stored;
3827 for example, it might try to read |mem[p].hh| when |mem[p]|
3828 contains a scaled integer, if |p| is a pointer that has been
3829 clobbered or chosen at random.
3830
3831 @p static void show_node_list(int @!p) /*prints a node list symbolically*/
3832 {@+
3833 int n; /*the number of items already printed at this level*/
3834 double @!g; /*a glue ratio, as a floating point number*/
3835 if (cur_length > depth_threshold)
3836 {@+if (p > null) print(" []");
3837 /*indicate that there's been some truncation*/
3838 return;
3839 }
3840 n=0;
3841 while (p > mem_min)
3842 {@+print_ln();print_current_string(); /*display the nesting history*/
3843 if (p > mem_end) /*pointer out of range*/
3844 {@+print("Bad link, display aborted.");return;
3845 @.Bad link...@>
3846 }
3847 incr(n);if (n > breadth_max) /*time to stop*/
3848 {@+print("etc.");return;
3849 @.etc@>
3850 }
3851 @<Display node |p|@>;
3852 p=link(p);
3853 }
3854
3855 }
3856
3857 @ @<Display node |p|@>=
3858 if (is_char_node(p)) print_font_and_char(p);
3859 else switch (type(p)) {
3860 case hlist_node: case vlist_node: case unset_node: @<Display box |p|@>@;@+break;
3861 case rule_node: @<Display rule |p|@>@;@+break;
3862 case ins_node: @<Display insertion |p|@>@;@+break;
3863 case whatsit_node: @<Display the whatsit node |p|@>@;@+break;
3864 case glue_node: @<Display glue |p|@>@;@+break;
3865 case kern_node: @<Display kern |p|@>@;@+break;
3866 case math_node: @<Display math node |p|@>@;@+break;
3867 case ligature_node: @<Display ligature |p|@>@;@+break;
3868 case penalty_node: @<Display penalty |p|@>@;@+break;
3869 case disc_node: @<Display discretionary |p|@>@;@+break;
3870 case mark_node: @<Display mark |p|@>@;@+break;
3871 case adjust_node: @<Display adjustment |p|@>@;@+break;
3872 @t\4@>@<Cases of |show_node_list| that arise in mlists only@>@;
3873 default:print("Unknown node type!");
3874 }
3875
3876 @ @<Display box |p|@>=
3877 {@+if (type(p)==hlist_node) print_esc("h");
3878 else if (type(p)==vlist_node) print_esc("v");
3879 else print_esc("unset");
3880 print("box(");print_scaled(height(p));print_char('+');
3881 print_scaled(depth(p));print(")x");print_scaled(width(p));
3882 if (type(p)==unset_node)
3883 @<Display special fields of the unset node |p|@>@;
3884 else{@+@<Display the value of |glue_set(p)|@>;
3885 if (shift_amount(p)!=0)
3886 {@+print(", shifted ");print_scaled(shift_amount(p));
3887 }
3888 }
3889 node_list_display(list_ptr(p)); /*recursive call*/
3890 }
3891
3892 @ @<Display special fields of the unset node |p|@>=
3893 {@+if (span_count(p)!=min_quarterword)
3894 {@+print(" (");print_int(qo(span_count(p))+1);
3895 print(" columns)");
3896 }
3897 if (glue_stretch(p)!=0)
3898 {@+print(", stretch ");print_glue(glue_stretch(p), glue_order(p), 0);
3899 }
3900 if (glue_shrink(p)!=0)
3901 {@+print(", shrink ");print_glue(glue_shrink(p), glue_sign(p), 0);
3902 }
3903 }
3904
3905 @ The code will have to change in this place if |glue_ratio| is
3906 a structured type instead of an ordinary |double|. Note that this routine
3907 should avoid arithmetic errors even if the |glue_set| field holds an
3908 arbitrary random value. The following code assumes that a properly
3909 formed nonzero |double| number has absolute value $2^{20}$ or more when
3910 it is regarded as an integer; this precaution was adequate to prevent
3911 floating point underflow on the author's computer.
3912 @^system dependencies@>
3913 @^dirty \PASCAL@>
3914
3915 @<Display the value of |glue_set(p)|@>=
3916 g=unfix(glue_set(p));
3917 if ((g!=float_constant(0))&&(glue_sign(p)!=normal))
3918 {@+print(", glue set ");
3919 if (glue_sign(p)==shrinking) print("- ");
3920 if (abs(mem[p+glue_offset].i) < 04000000) print("?.?");
3921 else if (abs(g) > float_constant(20000))
3922 {@+if (g > float_constant(0)) print_char('>');
3923 else print("< -");
3924 print_glue(20000*unity, glue_order(p), 0);
3925 }
3926 else print_glue(round(unity*g), glue_order(p), 0);
3927 @^real multiplication@>
3928 }
3929
3930 @ @<Display rule |p|@>=
3931 {@+print_esc("rule(");print_rule_dimen(height(p));print_char('+');
3932 print_rule_dimen(depth(p));print(")x");print_rule_dimen(width(p));
3933 }
3934
3935 @ @<Display insertion |p|@>=
3936 {@+print_esc("insert");print_int(qo(subtype(p)));
3937 print(", natural size ");print_scaled(height(p));
3938 print("; split(");print_spec(split_top_ptr(p), 0);
3939 print_char(',');print_scaled(depth(p));
3940 print("); float cost ");print_int(float_cost(p));
3941 node_list_display(ins_ptr(p)); /*recursive call*/
3942 }
3943
3944 @ @<Display glue |p|@>=
3945 if (subtype(p) >= a_leaders) @<Display leaders |p|@>@;
3946 else{@+print_esc("glue");
3947 if (subtype(p)!=normal)
3948 {@+print_char('(');
3949 if (subtype(p) < cond_math_glue)
3950 print_skip_param(subtype(p)-1);
3951 else if (subtype(p)==cond_math_glue) print_esc("nonscript");
3952 else print_esc("mskip");
3953 print_char(')');
3954 }
3955 if (subtype(p)!=cond_math_glue)
3956 {@+print_char(' ');
3957 if (subtype(p) < cond_math_glue) print_spec(glue_ptr(p), 0);
3958 else print_spec(glue_ptr(p),"mu");
3959 }
3960 }
3961
3962 @ @<Display leaders |p|@>=
3963 {@+print_esc("");
3964 if (subtype(p)==c_leaders) print_char('c');
3965 else if (subtype(p)==x_leaders) print_char('x');
3966 print("leaders ");print_spec(glue_ptr(p), 0);
3967 node_list_display(leader_ptr(p)); /*recursive call*/
3968 }
3969
3970 @ An ``explicit'' kern value is indicated implicitly by an explicit space.
3971
3972 @<Display kern |p|@>=
3973 if (subtype(p)!=mu_glue)
3974 {@+print_esc("kern");
3975 if (subtype(p)!=normal) print_char(' ');
3976 print_scaled(width(p));
3977 if (subtype(p)==acc_kern) print(" (for accent)");
3978 @.for accent@>
3979 }
3980 else{@+print_esc("mkern");print_scaled(width(p));print("mu");
3981 }
3982
3983 @ @<Display math node |p|@>=
3984 {@+print_esc("math");
3985 if (subtype(p)==before) print("on");
3986 else print("off");
3987 if (width(p)!=0)
3988 {@+print(", surrounded ");print_scaled(width(p));
3989 }
3990 }
3991
3992 @ @<Display ligature |p|@>=
3993 {@+print_font_and_char(lig_char(p));print(" (ligature ");
3994 if (subtype(p) > 1) print_char('|');
3995 font_in_short_display=font(lig_char(p));short_display(lig_ptr(p));
3996 if (odd(subtype(p))) print_char('|');
3997 print_char(')');
3998 }
3999
4000 @ @<Display penalty |p|@>=
4001 {@+print_esc("penalty ");print_int(penalty(p));
4002 }
4003
4004 @ The |post_break| list of a discretionary node is indicated by a prefixed
4005 `\.{\char'174}' instead of the `\..' before the |pre_break| list.
4006
4007 @<Display discretionary |p|@>=
4008 {@+print_esc("discretionary");
4009 if (replace_count(p) > 0)
4010 {@+print(" replacing ");print_int(replace_count(p));
4011 }
4012 node_list_display(pre_break(p)); /*recursive call*/
4013 append_char('|');show_node_list(post_break(p));flush_char; /*recursive call*/
4014 }
4015
4016 @ @<Display mark |p|@>=
4017 {@+print_esc("mark");
4018 if (mark_class(p)!=0)
4019 {@+print_char('s');print_int(mark_class(p));
4020 }
4021 print_mark(mark_ptr(p));
4022 }
4023
4024 @ @<Display adjustment |p|@>=
4025 {@+print_esc("vadjust");node_list_display(adjust_ptr(p)); /*recursive call*/
4026 }
4027
4028 @ The recursive machinery is started by calling |show_box|.
4029 @^recursion@>
4030
4031 @p static void show_box(pointer @!p)
4032 {@+@<Assign the values |depth_threshold:=show_box_depth| and |breadth_max:=show_box_breadth|@>;
4033 if (breadth_max <= 0) breadth_max=5;
4034 if (pool_ptr+depth_threshold >= pool_size)
4035 depth_threshold=pool_size-pool_ptr-1;
4036 /*now there's enough room for prefix string*/
4037 show_node_list(p); /*the show starts at |p|*/
4038 print_ln();
4039 }
4040
4041 @* Destroying boxes.
4042 When we are done with a node list, we are obliged to return it to free
4043 storage, including all of its sublists. The recursive procedure
4044 |flush_node_list| does this for us.
4045
4046 @ First, however, we shall consider two non-recursive procedures that do
4047 simpler tasks. The first of these, |delete_token_ref|, is called when
4048 a pointer to a token list's reference count is being removed. This means
4049 that the token list should disappear if the reference count was |null|,
4050 otherwise the count should be decreased by one.
4051 @^reference counts@>
4052
4053 @d token_ref_count(A) info(A) /*reference count preceding a token list*/
4054
4055 @p static void delete_token_ref(pointer @!p) /*|p| points to the reference count
4056 of a token list that is losing one reference*/
4057 {@+if (token_ref_count(p)==null) flush_list(p);
4058 else decr(token_ref_count(p));
4059 }
4060
4061 @ Similarly, |delete_glue_ref| is called when a pointer to a glue
4062 specification is being withdrawn.
4063 @^reference counts@>
4064 @d fast_delete_glue_ref(A) @t@>@;@/
4065 {@+if (glue_ref_count(A)==null) free_node(A, glue_spec_size);
4066 else decr(glue_ref_count(A));
4067 }
4068
4069 @p static void delete_glue_ref(pointer @!p) /*|p| points to a glue specification*/
4070 fast_delete_glue_ref(p)
4071
4072 @ Now we are ready to delete any node list, recursively.
4073 In practice, the nodes deleted are usually charnodes (about 2/3 of the time),
4074 and they are glue nodes in about half of the remaining cases.
4075 @^recursion@>
4076
4077 @p static void flush_node_list(pointer @!p) /*erase list of nodes starting at |p|*/
4078 {@+ /*go here when node |p| has been freed*/
4079 pointer q; /*successor to node |p|*/
4080 while (p!=null)
4081 @^inner loop@>
4082 {@+q=link(p);
4083 if (is_char_node(p)) free_avail(p)@;
4084 else{@+switch (type(p)) {
4085 case hlist_node: case vlist_node:
4086 case unset_node: {@+flush_node_list(list_ptr(p));
4087 free_node(p, box_node_size);goto done;
4088 }
4089 case rule_node: {@+free_node(p, rule_node_size);goto done;
4090 }
4091 case ins_node: {@+flush_node_list(ins_ptr(p));
4092 delete_glue_ref(split_top_ptr(p));
4093 free_node(p, ins_node_size);goto done;
4094 }
4095 case whatsit_node: @<Wipe out the whatsit node |p| and |goto done|@>@;
4096 case glue_node: {@+fast_delete_glue_ref(glue_ptr(p));
4097 if (leader_ptr(p)!=null) flush_node_list(leader_ptr(p));
4098 } @+break;
4099 case kern_node: case math_node: case penalty_node: do_nothing;@+break;
4100 case ligature_node: flush_node_list(lig_ptr(p));@+break;
4101 case mark_node: delete_token_ref(mark_ptr(p));@+break;
4102 case disc_node: {@+flush_node_list(pre_break(p));
4103 flush_node_list(post_break(p));
4104 } @+break;
4105 case adjust_node: flush_node_list(adjust_ptr(p));@+break;
4106 @t\4@>@<Cases of |flush_node_list| that arise in mlists only@>@;
4107 default:confusion("flushing");
4108 @:this can't happen flushing}{\quad flushing@>
4109 } @/
4110 free_node(p, small_node_size);
4111 done: ;}
4112 p=q;
4113 }
4114 }
4115
4116 @* Copying boxes.
4117 Another recursive operation that acts on boxes is sometimes needed: The
4118 procedure |copy_node_list| returns a pointer to another node list that has
4119 the same structure and meaning as the original. Note that since glue
4120 specifications and token lists have reference counts, we need not make
4121 copies of them. Reference counts can never get too large to fit in a
4122 halfword, since each pointer to a node is in a different memory address,
4123 and the total number of memory addresses fits in a halfword.
4124 @^recursion@>
4125 @^reference counts@>
4126
4127 (Well, there actually are also references from outside |mem|; if the
4128 |save_stack| is made arbitrarily large, it would theoretically be possible
4129 to break \TeX\ by overflowing a reference count. But who would want to do that?)
4130
4131 @d add_token_ref(A) incr(token_ref_count(A)) /*new reference to a token list*/
4132 @d add_glue_ref(A) incr(glue_ref_count(A)) /*new reference to a glue spec*/
4133
4134 @ The copying procedure copies words en masse without bothering
4135 to look at their individual fields. If the node format changes---for
4136 example, if the size is altered, or if some link field is moved to another
4137 relative position---then this code may need to be changed too.
4138 @^data structure assumptions@>
4139
4140 @p static pointer copy_node_list(pointer @!p) /*makes a duplicate of the
4141 node list that starts at |p| and returns a pointer to the new list*/
4142 {@+pointer h; /*temporary head of copied list*/
4143 pointer @!q; /*previous position in new list*/
4144 pointer @!r; /*current node being fabricated for new list*/
4145 int @!words; /*number of words remaining to be copied*/
4146 h=get_avail();q=h;
4147 while (p!=null)
4148 {@+@<Make a copy of node |p| in node |r|@>;
4149 link(q)=r;q=r;p=link(p);
4150 }
4151 link(q)=null;q=link(h);free_avail(h);
4152 return q;
4153 }
4154
4155 @ @<Make a copy of node |p|...@>=
4156 words=1; /*this setting occurs in more branches than any other*/
4157 if (is_char_node(p)) r=get_avail();
4158 else@<Case statement to copy different types and set |words| to the number
4159 of initial words not yet copied@>;
4160 while (words > 0)
4161 {@+decr(words);mem[r+words]=mem[p+words];
4162 }
4163
4164 @ @<Case statement to copy...@>=
4165 switch (type(p)) {
4166 case hlist_node: case vlist_node: case unset_node: {@+r=get_node(box_node_size);
4167 mem[r+6]=mem[p+6];mem[r+5]=mem[p+5]; /*copy the last two words*/
4168 list_ptr(r)=copy_node_list(list_ptr(p)); /*this affects |mem[r+5]|*/
4169 words=5;
4170 } @+break;
4171 case rule_node: {@+r=get_node(rule_node_size);words=rule_node_size;
4172 } @+break;
4173 case ins_node: {@+r=get_node(ins_node_size);mem[r+4]=mem[p+4];
4174 add_glue_ref(split_top_ptr(p));
4175 ins_ptr(r)=copy_node_list(ins_ptr(p)); /*this affects |mem[r+4]|*/
4176 words=ins_node_size-1;
4177 } @+break;
4178 case whatsit_node: @<Make a partial copy of the whatsit node |p| and make
4179 |r| point to it; set |words| to the number of initial words not yet copied@>@;@+break;
4180 case glue_node: {@+r=get_node(small_node_size);add_glue_ref(glue_ptr(p));
4181 glue_ptr(r)=glue_ptr(p);leader_ptr(r)=copy_node_list(leader_ptr(p));
4182 } @+break;
4183 case kern_node: case math_node: case penalty_node: {@+r=get_node(small_node_size);
4184 words=small_node_size;
4185 } @+break;
4186 case ligature_node: {@+r=get_node(small_node_size);
4187 mem[lig_char(r)]=mem[lig_char(p)]; /*copy |font| and |character|*/
4188 lig_ptr(r)=copy_node_list(lig_ptr(p));
4189 } @+break;
4190 case disc_node: {@+r=get_node(small_node_size);
4191 pre_break(r)=copy_node_list(pre_break(p));
4192 post_break(r)=copy_node_list(post_break(p));
4193 } @+break;
4194 case mark_node: {@+r=get_node(small_node_size);add_token_ref(mark_ptr(p));
4195 words=small_node_size;
4196 } @+break;
4197 case adjust_node: {@+r=get_node(small_node_size);
4198 adjust_ptr(r)=copy_node_list(adjust_ptr(p));
4199 } @+break; /*|words==1==small_node_size-1|*/
4200 default:confusion("copying");
4201 @:this can't happen copying}{\quad copying@>
4202 }
4203
4204 @* The command codes.
4205 Before we can go any further, we need to define symbolic names for the internal
4206 code numbers that represent the various commands obeyed by \TeX. These codes
4207 are somewhat arbitrary, but not completely so. For example, the command
4208 codes for character types are fixed by the language, since a user says,
4209 e.g., `\.{\\catcode \`\\\${} = 3}' to make \.{\char'44} a math delimiter,
4210 and the command code |math_shift| is equal to~3. Some other codes have
4211 been made adjacent so that |case| statements in the program need not consider
4212 cases that are widely spaced, or so that |case| statements can be replaced
4213 by |if| statements.
4214
4215 At any rate, here is the list, for future reference. First come the
4216 ``catcode'' commands, several of which share their numeric codes with
4217 ordinary commands when the catcode cannot emerge from \TeX's scanning routine.
4218
4219 @d escape 0 /*escape delimiter (called \.\\ in {\sl The \TeX book\/})*/
4220 @:TeXbook}{\sl The \TeX book@>
4221 @d relax 0 /*do nothing ( \.{\\relax} )*/
4222 @d left_brace 1 /*beginning of a group ( \.\{ )*/
4223 @d right_brace 2 /*ending of a group ( \.\} )*/
4224 @d math_shift 3 /*mathematics shift character ( \.\$ )*/
4225 @d tab_mark 4 /*alignment delimiter ( \.\&, \.{\\span} )*/
4226 @d car_ret 5 /*end of line ( |carriage_return|, \.{\\cr}, \.{\\crcr} )*/
4227 @d out_param 5 /*output a macro parameter*/
4228 @d mac_param 6 /*macro parameter symbol ( \.\# )*/
4229 @d sup_mark 7 /*superscript ( \.{\char'136} )*/
4230 @d sub_mark 8 /*subscript ( \.{\char'137} )*/
4231 @d ignore 9 /*characters to ignore ( \.{\^\^@@} )*/
4232 @d endv 9 /*end of \<v_j> list in alignment template*/
4233 @d spacer 10 /*characters equivalent to blank space ( \.{\ } )*/
4234 @d letter 11 /*characters regarded as letters ( \.{A..Z}, \.{a..z} )*/
4235 @d other_char 12 /*none of the special character types*/
4236 @d active_char 13 /*characters that invoke macros ( \.{\char`\~} )*/
4237 @d par_end 13 /*end of paragraph ( \.{\\par} )*/
4238 @d match 13 /*match a macro parameter*/
4239 @d comment 14 /*characters that introduce comments ( \.\% )*/
4240 @d end_match 14 /*end of parameters to macro*/
4241 @d stop 14 /*end of job ( \.{\\end}, \.{\\dump} )*/
4242 @d invalid_char 15 /*characters that shouldn't appear ( \.{\^\^?} )*/
4243 @d delim_num 15 /*specify delimiter numerically ( \.{\\delimiter} )*/
4244 @d max_char_code 15 /*largest catcode for individual characters*/
4245
4246 @ Next are the ordinary run-of-the-mill command codes. Codes that are
4247 |min_internal| or more represent internal quantities that might be
4248 expanded by `\.{\\the}'.
4249
4250 @d char_num 16 /*character specified numerically ( \.{\\char} )*/
4251 @d math_char_num 17 /*explicit math code ( \.{\\mathchar} )*/
4252 @d mark 18 /*mark definition ( \.{\\mark} )*/
4253 @d xray 19 /*peek inside of \TeX\ ( \.{\\show}, \.{\\showbox}, etc.~)*/
4254 @d make_box 20 /*make a box ( \.{\\box}, \.{\\copy}, \.{\\hbox}, etc.~)*/
4255 @d hmove 21 /*horizontal motion ( \.{\\moveleft}, \.{\\moveright} )*/
4256 @d vmove 22 /*vertical motion ( \.{\\raise}, \.{\\lower} )*/
4257 @d un_hbox 23 /*unglue a box ( \.{\\unhbox}, \.{\\unhcopy} )*/
4258 @d un_vbox 24 /*unglue a box ( \.{\\unvbox}, \.{\\unvcopy} )*/
4259 /*( or \.{\\pagediscards}, \.{\\splitdiscards} )*/
4260 @d remove_item 25 /*nullify last item ( \.{\\unpenalty},
4261 \.{\\unkern}, \.{\\unskip} )*/
4262 @d hskip 26 /*horizontal glue ( \.{\\hskip}, \.{\\hfil}, etc.~)*/
4263 @d vskip 27 /*vertical glue ( \.{\\vskip}, \.{\\vfil}, etc.~)*/
4264 @d mskip 28 /*math glue ( \.{\\mskip} )*/
4265 @d kern 29 /*fixed space ( \.{\\kern} )*/
4266 @d mkern 30 /*math kern ( \.{\\mkern} )*/
4267 @d leader_ship 31 /*use a box ( \.{\\shipout}, \.{\\leaders}, etc.~)*/
4268 @d halign 32 /*horizontal table alignment ( \.{\\halign} )*/
4269 @d valign 33 /*vertical table alignment ( \.{\\valign} )*/
4270 @d no_align 34 /*temporary escape from alignment ( \.{\\noalign} )*/
4271 @d vrule 35 /*vertical rule ( \.{\\vrule} )*/
4272 @d hrule 36 /*horizontal rule ( \.{\\hrule} )*/
4273 @d insert 37 /*vlist inserted in box ( \.{\\insert} )*/
4274 @d vadjust 38 /*vlist inserted in enclosing paragraph ( \.{\\vadjust} )*/
4275 @d ignore_spaces 39 /*gobble |spacer| tokens ( \.{\\ignorespaces} )*/
4276 @d after_assignment 40 /*save till assignment is done ( \.{\\afterassignment} )*/
4277 @d after_group 41 /*save till group is done ( \.{\\aftergroup} )*/
4278 @d break_penalty 42 /*additional badness ( \.{\\penalty} )*/
4279 @d start_par 43 /*begin paragraph ( \.{\\indent}, \.{\\noindent} )*/
4280 @d ital_corr 44 /*italic correction ( \.{\\/} )*/
4281 @d accent 45 /*attach accent in text ( \.{\\accent} )*/
4282 @d math_accent 46 /*attach accent in math ( \.{\\mathaccent} )*/
4283 @d discretionary 47 /*discretionary texts ( \.{\\-}, \.{\\discretionary} )*/
4284 @d eq_no 48 /*equation number ( \.{\\eqno}, \.{\\leqno} )*/
4285 @d left_right 49 /*variable delimiter ( \.{\\left}, \.{\\right} )*/
4286 /*( or \.{\\middle} )*/
4287 @d math_comp 50 /*component of formula ( \.{\\mathbin}, etc.~)*/
4288 @d limit_switch 51 /*diddle limit conventions ( \.{\\displaylimits}, etc.~)*/
4289 @d above 52 /*generalized fraction ( \.{\\above}, \.{\\atop}, etc.~)*/
4290 @d math_style 53 /*style specification ( \.{\\displaystyle}, etc.~)*/
4291 @d math_choice 54 /*choice specification ( \.{\\mathchoice} )*/
4292 @d non_script 55 /*conditional math glue ( \.{\\nonscript} )*/
4293 @d vcenter 56 /*vertically center a vbox ( \.{\\vcenter} )*/
4294 @d case_shift 57 /*force specific case ( \.{\\lowercase}, \.{\\uppercase}~)*/
4295 @d message 58 /*send to user ( \.{\\message}, \.{\\errmessage} )*/
4296 @d extension 59 /*extensions to \TeX\ ( \.{\\write}, \.{\\special}, etc.~)*/
4297 @d in_stream 60 /*files for reading ( \.{\\openin}, \.{\\closein} )*/
4298 @d begin_group 61 /*begin local grouping ( \.{\\begingroup} )*/
4299 @d end_group 62 /*end local grouping ( \.{\\endgroup} )*/
4300 @d omit 63 /*omit alignment template ( \.{\\omit} )*/
4301 @d ex_space 64 /*explicit space ( \.{\\\ } )*/
4302 @d no_boundary 65 /*suppress boundary ligatures ( \.{\\noboundary} )*/
4303 @d radical 66 /*square root and similar signs ( \.{\\radical} )*/
4304 @d end_cs_name 67 /*end control sequence ( \.{\\endcsname} )*/
4305 @d min_internal 68 /*the smallest code that can follow \.{\\the}*/
4306 @d char_given 68 /*character code defined by \.{\\chardef}*/
4307 @d math_given 69 /*math code defined by \.{\\mathchardef}*/
4308 @d last_item 70 /*most recent item ( \.{\\lastpenalty},
4309 \.{\\lastkern}, \.{\\lastskip} )*/
4310 @d max_non_prefixed_command 70 /*largest command code that can't be \.{\\global}*/
4311
4312 @ The next codes are special; they all relate to mode-independent
4313 assignment of values to \TeX's internal registers or tables.
4314 Codes that are |max_internal| or less represent internal quantities
4315 that might be expanded by `\.{\\the}'.
4316
4317 @d toks_register 71 /*token list register ( \.{\\toks} )*/
4318 @d assign_toks 72 /*special token list ( \.{\\output}, \.{\\everypar}, etc.~)*/
4319 @d assign_int 73 /*user-defined integer ( \.{\\tolerance}, \.{\\day}, etc.~)*/
4320 @d assign_dimen 74 /*user-defined length ( \.{\\hsize}, etc.~)*/
4321 @d assign_glue 75 /*user-defined glue ( \.{\\baselineskip}, etc.~)*/
4322 @d assign_mu_glue 76 /*user-defined muglue ( \.{\\thinmuskip}, etc.~)*/
4323 @d assign_font_dimen 77 /*user-defined font dimension ( \.{\\fontdimen} )*/
4324 @d assign_font_int 78 /*user-defined font integer ( \.{\\hyphenchar},
4325 \.{\\skewchar} )*/
4326 @d set_aux 79 /*specify state info ( \.{\\spacefactor}, \.{\\prevdepth} )*/
4327 @d set_prev_graf 80 /*specify state info ( \.{\\prevgraf} )*/
4328 @d set_page_dimen 81 /*specify state info ( \.{\\pagegoal}, etc.~)*/
4329 @d set_page_int 82 /*specify state info ( \.{\\deadcycles},
4330 \.{\\insertpenalties} )*/
4331 /*( or \.{\\interactionmode} )*/
4332 @d set_box_dimen 83 /*change dimension of box ( \.{\\wd}, \.{\\ht}, \.{\\dp} )*/
4333 @d set_shape 84 /*specify fancy paragraph shape ( \.{\\parshape} )*/
4334 /*(or \.{\\interlinepenalties}, etc.~)*/
4335 @d def_code 85 /*define a character code ( \.{\\catcode}, etc.~)*/
4336 @d def_family 86 /*declare math fonts ( \.{\\textfont}, etc.~)*/
4337 @d set_font 87 /*set current font ( font identifiers )*/
4338 @d def_font 88 /*define a font file ( \.{\\font} )*/
4339 @d internal_register 89 /*internal register ( \.{\\count}, \.{\\dimen}, etc.~)*/
4340 @d max_internal 89 /*the largest code that can follow \.{\\the}*/
4341 @d advance 90 /*advance a register or parameter ( \.{\\advance} )*/
4342 @d multiply 91 /*multiply a register or parameter ( \.{\\multiply} )*/
4343 @d divide 92 /*divide a register or parameter ( \.{\\divide} )*/
4344 @d prefix 93 /*qualify a definition ( \.{\\global}, \.{\\long}, \.{\\outer} )*/
4345 /*( or \.{\\protected} )*/
4346 @d let 94 /*assign a command code ( \.{\\let}, \.{\\futurelet} )*/
4347 @d shorthand_def 95 /*code definition ( \.{\\chardef}, \.{\\countdef}, etc.~)*/
4348 @d read_to_cs 96 /*read into a control sequence ( \.{\\read} )*/
4349 /*( or \.{\\readline} )*/
4350 @d def 97 /*macro definition ( \.{\\def}, \.{\\gdef}, \.{\\xdef}, \.{\\edef} )*/
4351 @d set_box 98 /*set a box ( \.{\\setbox} )*/
4352 @d hyph_data 99 /*hyphenation data ( \.{\\hyphenation}, \.{\\patterns} )*/
4353 @d set_interaction 100 /*define level of interaction ( \.{\\batchmode}, etc.~)*/
4354 @d max_command 100 /*the largest command code seen at |big_switch|*/
4355
4356 @ The remaining command codes are extra special, since they cannot get through
4357 \TeX's scanner to the main control routine. They have been given values higher
4358 than |max_command| so that their special nature is easily discernible.
4359 The ``expandable'' commands come first.
4360
4361 @d undefined_cs (max_command+1) /*initial state of most |eq_type| fields*/
4362 @d expand_after (max_command+2) /*special expansion ( \.{\\expandafter} )*/
4363 @d no_expand (max_command+3) /*special nonexpansion ( \.{\\noexpand} )*/
4364 @d input (max_command+4) /*input a source file ( \.{\\input}, \.{\\endinput} )*/
4365 /*( or \.{\\scantokens} )*/
4366 @d if_test (max_command+5) /*conditional text ( \.{\\if}, \.{\\ifcase}, etc.~)*/
4367 @d fi_or_else (max_command+6) /*delimiters for conditionals ( \.{\\else}, etc.~)*/
4368 @d cs_name (max_command+7) /*make a control sequence from tokens ( \.{\\csname} )*/
4369 @d convert (max_command+8) /*convert to text ( \.{\\number}, \.{\\string}, etc.~)*/
4370 @d the (max_command+9) /*expand an internal quantity ( \.{\\the} )*/
4371 /*( or \.{\\unexpanded}, \.{\\detokenize} )*/
4372 @d top_bot_mark (max_command+10) /*inserted mark ( \.{\\topmark}, etc.~)*/
4373 @d call (max_command+11) /*non-long, non-outer control sequence*/
4374 @d long_call (max_command+12) /*long, non-outer control sequence*/
4375 @d outer_call (max_command+13) /*non-long, outer control sequence*/
4376 @d long_outer_call (max_command+14) /*long, outer control sequence*/
4377 @d end_template (max_command+15) /*end of an alignment template*/
4378 @d dont_expand (max_command+16) /*the following token was marked by \.{\\noexpand}*/
4379 @d glue_ref (max_command+17) /*the equivalent points to a glue specification*/
4380 @d shape_ref (max_command+18) /*the equivalent points to a parshape specification*/
4381 @d box_ref (max_command+19) /*the equivalent points to a box node, or is |null|*/
4382 @d data (max_command+20) /*the equivalent is simply a halfword number*/
4383
4384 @* The semantic nest.
4385 \TeX\ is typically in the midst of building many lists at once. For example,
4386 when a math formula is being processed, \TeX\ is in math mode and
4387 working on an mlist; this formula has temporarily interrupted \TeX\ from
4388 being in horizontal mode and building the hlist of a paragraph; and this
4389 paragraph has temporarily interrupted \TeX\ from being in vertical mode
4390 and building the vlist for the next page of a document. Similarly, when a
4391 \.{\\vbox} occurs inside of an \.{\\hbox}, \TeX\ is temporarily
4392 interrupted from working in restricted horizontal mode, and it enters
4393 internal vertical mode. The ``semantic nest'' is a stack that
4394 keeps track of what lists and modes are currently suspended.
4395
4396 At each level of processing we are in one of six modes:
4397
4398 \yskip\hang|vmode| stands for vertical mode (the page builder);
4399
4400 \hang|hmode| stands for horizontal mode (the paragraph builder);
4401
4402 \hang|mmode| stands for displayed formula mode;
4403
4404 \hang|-vmode| stands for internal vertical mode (e.g., in a \.{\\vbox});
4405
4406 \hang|-hmode| stands for restricted horizontal mode (e.g., in an \.{\\hbox});
4407
4408 \hang|-mmode| stands for math formula mode (not displayed).
4409
4410 \yskip\noindent The mode is temporarily set to zero while processing \.{\\write}
4411 texts.
4412
4413 Numeric values are assigned to |vmode|, |hmode|, and |mmode| so that
4414 \TeX's ``big semantic switch'' can select the appropriate thing to
4415 do by computing the value |abs(mode)+cur_cmd|, where |mode| is the current
4416 mode and |cur_cmd| is the current command code.
4417
4418 @d vmode 1 /*vertical mode*/
4419 @d hmode (vmode+max_command+1) /*horizontal mode*/
4420 @d mmode (hmode+max_command+1) /*math mode*/
4421
4422 @p static void print_mode(int @!m) /*prints the mode represented by |m|*/
4423 {@+if (m > 0)
4424 switch (m/(max_command+1)) {
4425 case 0: print("vertical");@+break;
4426 case 1: print("horizontal");@+break;
4427 case 2: print("display math");
4428 }
4429 else if (m==0) print("no");
4430 else switch ((-m)/(max_command+1)) {
4431 case 0: print("internal vertical");@+break;
4432 case 1: print("restricted horizontal");@+break;
4433 case 2: print("math");
4434 }
4435 print(" mode");
4436 }
4437
4438 @ The state of affairs at any semantic level can be represented by
4439 five values:
4440
4441 \yskip\hang|mode| is the number representing the semantic mode, as
4442 just explained.
4443
4444 \yskip\hang|head| is a |pointer| to a list head for the list being built;
4445 |link(head)| therefore points to the first element of the list, or
4446 to |null| if the list is empty.
4447
4448 \yskip\hang|tail| is a |pointer| to the final node of the list being
4449 built; thus, |tail==head| if and only if the list is empty.
4450
4451 \yskip\hang|prev_graf| is the number of lines of the current paragraph that
4452 have already been put into the present vertical list.
4453
4454 \yskip\hang|aux| is an auxiliary |memory_word| that gives further information
4455 that is needed to characterize the situation.
4456
4457 \yskip\noindent
4458 In vertical mode, |aux| is also known as |prev_depth|; it is the scaled
4459 value representing the depth of the previous box, for use in baseline
4460 calculations, or it is | <= -1000|pt if the next box on the vertical list is to
4461 be exempt from baseline calculations. In horizontal mode, |aux| is also
4462 known as |space_factor| and |clang|; it holds the current space factor used in
4463 spacing calculations, and the current language used for hyphenation.
4464 (The value of |clang| is undefined in restricted horizontal mode.)
4465 In math mode, |aux| is also known as |incompleat_noad|; if
4466 not |null|, it points to a record that represents the numerator of a
4467 generalized fraction for which the denominator is currently being formed
4468 in the current list.
4469
4470 There is also a sixth quantity, |mode_line|, which correlates
4471 the semantic nest with the user's input; |mode_line| contains the source
4472 line number at which the current level of nesting was entered. The negative
4473 of this line number is the |mode_line| at the level of the
4474 user's output routine.
4475
4476 A seventh quantity, |eTeX_aux|, is used by the extended features \eTeX.
4477 In vertical modes it is known as |LR_save| and holds the LR stack when a
4478 paragraph is interrupted by a displayed formula. In display math mode
4479 it is known as |LR_box| and holds a pointer to a prototype box for the
4480 display. In math mode it is known as |delim_ptr| and points to the most
4481 recent |left_noad| or |middle_noad| of a |math_left_group|.
4482
4483 In horizontal mode, the |prev_graf| field is used for initial language data.
4484
4485 The semantic nest is an array called |nest| that holds the |mode|, |head|,
4486 |tail|, |prev_graf|, |aux|, and |mode_line| values for all semantic levels
4487 below the currently active one. Information about the currently active
4488 level is kept in the global quantities |mode|, |head|, |tail|, |prev_graf|,
4489 |aux|, and |mode_line|, which live in a \PASCAL\ record that is ready to
4490 be pushed onto |nest| if necessary.
4491
4492 @d ignore_depth -65536000 /*|prev_depth| value that is ignored*/
4493
4494 @<Types...@>=
4495 typedef struct { int16_t @!mode_field;@+
4496 pointer @!head_field, @!tail_field;
4497 pointer @!eTeX_aux_field;
4498 int @!pg_field, @!ml_field;@+
4499 memory_word @!aux_field;
4500 } list_state_record;
4501
4502 @ @d mode cur_list.mode_field /*current mode*/
4503 @d head cur_list.head_field /*header node of current list*/
4504 @d tail cur_list.tail_field /*final node on current list*/
4505 @d eTeX_aux cur_list.eTeX_aux_field /*auxiliary data for \eTeX*/
4506 @d LR_save eTeX_aux /*LR stack when a paragraph is interrupted*/
4507 @d LR_box eTeX_aux /*prototype box for display*/
4508 @d delim_ptr eTeX_aux /*most recent left or right noad of a math left group*/
4509 @d prev_graf cur_list.pg_field /*number of paragraph lines accumulated*/
4510 @d aux cur_list.aux_field /*auxiliary data about the current list*/
4511 @d prev_depth aux.sc /*the name of |aux| in vertical mode*/
4512 @d space_factor aux.hh.lh /*part of |aux| in horizontal mode*/
4513 @d clang aux.hh.rh /*the other part of |aux| in horizontal mode*/
4514 @d incompleat_noad aux.i /*the name of |aux| in math mode*/
4515 @d mode_line cur_list.ml_field /*source file line number at beginning of list*/
4516
4517 @<Glob...@>=
4518 static list_state_record @!nest[nest_size+1];
4519 static int @!nest_ptr; /*first unused location of |nest|*/
4520 static int @!max_nest_stack; /*maximum of |nest_ptr| when pushing*/
4521 static list_state_record @!cur_list; /*the ``top'' semantic state*/
4522 static int @!shown_mode; /*most recent mode shown by \.{\\tracingcommands}*/
4523
4524 @ Here is a common way to make the current list grow:
4525
4526 @d tail_append(A) {@+link(tail)=A;tail=link(tail);
4527 }
4528
4529 @ We will see later that the vertical list at the bottom semantic level is split
4530 into two parts; the ``current page'' runs from |page_head| to |page_tail|,
4531 and the ``contribution list'' runs from |contrib_head| to |tail| of
4532 semantic level zero. The idea is that contributions are first formed in
4533 vertical mode, then ``contributed'' to the current page (during which time
4534 the page-breaking decisions are made). For now, we don't need to know
4535 any more details about the page-building process.
4536
4537 @<Set init...@>=
4538 nest_ptr=0;max_nest_stack=0;
4539 mode=vmode;head=contrib_head;tail=contrib_head;
4540 eTeX_aux=null;
4541 prev_depth=ignore_depth;mode_line=0;
4542 prev_graf=0;shown_mode=0;
4543 @<Start a new current page@>;
4544
4545 @ When \TeX's work on one level is interrupted, the state is saved by
4546 calling |push_nest|. This routine changes |head| and |tail| so that
4547 a new (empty) list is begun; it does not change |mode| or |aux|.
4548
4549 @p static void push_nest(void) /*enter a new semantic level, save the old*/
4550 {@+if (nest_ptr > max_nest_stack)
4551 {@+max_nest_stack=nest_ptr;
4552 if (nest_ptr==nest_size) overflow("semantic nest size", nest_size);
4553 @:TeX capacity exceeded semantic nest size}{\quad semantic nest size@>
4554 }
4555 nest[nest_ptr]=cur_list; /*stack the record*/
4556 incr(nest_ptr);head=get_avail();tail=head;prev_graf=0;mode_line=line;
4557 eTeX_aux=null;
4558 }
4559
4560 @ Conversely, when \TeX\ is finished on the current level, the former
4561 state is restored by calling |pop_nest|. This routine will never be
4562 called at the lowest semantic level, nor will it be called unless |head|
4563 is a node that should be returned to free memory.
4564
4565 @p static void pop_nest(void) /*leave a semantic level, re-enter the old*/
4566 {@+free_avail(head);decr(nest_ptr);cur_list=nest[nest_ptr];
4567 }
4568
4569 @ Here is a procedure that displays what \TeX\ is working on, at all levels.
4570
4571 @p static void print_totals(void);
4572 static void show_activities(void)
4573 {@+int p; /*index into |nest|*/
4574 int @!m; /*mode*/
4575 memory_word @!a; /*auxiliary*/
4576 pointer @!q, @!r; /*for showing the current page*/
4577 int @!t; /*ditto*/
4578 nest[nest_ptr]=cur_list; /*put the top level into the array*/
4579 print_nl("");print_ln();
4580 for (p=nest_ptr; p>=0; p--)
4581 {@+m=nest[p].mode_field;a=nest[p].aux_field;
4582 print_nl("### ");print_mode(m);
4583 print(" entered at line ");print_int(abs(nest[p].ml_field));
4584 if (m==hmode) if (nest[p].pg_field!=040600000)
4585 {@+print(" (language");print_int(nest[p].pg_field%0200000);
4586 print(":hyphenmin");print_int(nest[p].pg_field/020000000);
4587 print_char(',');print_int((nest[p].pg_field/0200000)%0100);
4588 print_char(')');
4589 }
4590 if (nest[p].ml_field < 0) print(" (\\output routine)");
4591 if (p==0)
4592 {@+@<Show the status of the current page@>;
4593 if (link(contrib_head)!=null)
4594 print_nl("### recent contributions:");
4595 }
4596 show_box(link(nest[p].head_field));
4597 @<Show the auxiliary field, |a|@>;
4598 }
4599 }
4600
4601 @ @<Show the auxiliary...@>=
4602 switch (abs(m)/(max_command+1)) {
4603 case 0: {@+print_nl("prevdepth ");
4604 if (a.sc <= ignore_depth) print("ignored");
4605 else print_scaled(a.sc);
4606 if (nest[p].pg_field!=0)
4607 {@+print(", prevgraf ");
4608 print_int(nest[p].pg_field);print(" line");
4609 if (nest[p].pg_field!=1) print_char('s');
4610 }
4611 } @+break;
4612 case 1: {@+print_nl("spacefactor ");print_int(a.hh.lh);
4613 if (m > 0) @+if (a.hh.rh > 0)
4614 {@+print(", current language ");print_int(a.hh.rh);@+
4615 }
4616 } @+break;
4617 case 2: if (a.i!=null)
4618 {@+print("this will begin denominator of:");show_box(a.i);@+
4619 }
4620 } /*there are no other cases*/
4621
4622 @* The table of equivalents.
4623 Now that we have studied the data structures for \TeX's semantic routines,
4624 we ought to consider the data structures used by its syntactic routines. In
4625 other words, our next concern will be
4626 the tables that \TeX\ looks at when it is scanning
4627 what the user has written.
4628
4629 The biggest and most important such table is called |eqtb|. It holds the
4630 current ``equivalents'' of things; i.e., it explains what things mean
4631 or what their current values are, for all quantities that are subject to
4632 the nesting structure provided by \TeX's grouping mechanism. There are six
4633 parts to |eqtb|:
4634
4635 \yskip\hangg 1) |eqtb[active_base dotdot(hash_base-1)]| holds the current
4636 equivalents of single-character control sequences.
4637
4638 \yskip\hangg 2) |eqtb[hash_base dotdot(glue_base-1)]| holds the current
4639 equivalents of multiletter control sequences.
4640
4641 \yskip\hangg 3) |eqtb[glue_base dotdot(local_base-1)]| holds the current
4642 equivalents of glue parameters like the current baselineskip.
4643
4644 \yskip\hangg 4) |eqtb[local_base dotdot(int_base-1)]| holds the current
4645 equivalents of local halfword quantities like the current box registers,
4646 the current ``catcodes,'' the current font, and a pointer to the current
4647 paragraph shape.
4648
4649 \yskip\hangg 5) |eqtb[int_base dotdot(dimen_base-1)]| holds the current
4650 equivalents of fullword integer parameters like the current hyphenation
4651 penalty.
4652
4653 \yskip\hangg 6) |eqtb[dimen_base dotdot eqtb_size]| holds the current equivalents
4654 of fullword dimension parameters like the current hsize or amount of
4655 hanging indentation.
4656
4657 \yskip\noindent Note that, for example, the current amount of
4658 baselineskip glue is determined by the setting of a particular location
4659 in region~3 of |eqtb|, while the current meaning of the control sequence
4660 `\.{\\baselineskip}' (which might have been changed by \.{\\def} or
4661 \.{\\let}) appears in region~2.
4662
4663 @ Each entry in |eqtb| is a |memory_word|. Most of these words are of type
4664 |two_halves|, and subdivided into three fields:
4665
4666 \yskip\hangg 1) The |eq_level| (a quarterword) is the level of grouping at
4667 which this equivalent was defined. If the level is |level_zero|, the
4668 equivalent has never been defined; |level_one| refers to the outer level
4669 (outside of all groups), and this level is also used for global
4670 definitions that never go away. Higher levels are for equivalents that
4671 will disappear at the end of their group. @^global definitions@>
4672
4673 \yskip\hangg 2) The |eq_type| (another quarterword) specifies what kind of
4674 entry this is. There are many types, since each \TeX\ primitive like
4675 \.{\\hbox}, \.{\\def}, etc., has its own special code. The list of
4676 command codes above includes all possible settings of the |eq_type| field.
4677
4678 \yskip\hangg 3) The |equiv| (a halfword) is the current equivalent value.
4679 This may be a font number, a pointer into |mem|, or a variety of other
4680 things.
4681
4682 @d eq_level_field(A) A.hh.b1
4683 @d eq_type_field(A) A.hh.b0
4684 @d equiv_field(A) A.hh.rh
4685 @d eq_level(A) eq_level_field(eqtb[A]) /*level of definition*/
4686 @d eq_type(A) eq_type_field(eqtb[A]) /*command code for equivalent*/
4687 @d equiv(A) equiv_field(eqtb[A]) /*equivalent value*/
4688 @d level_zero min_quarterword /*level for undefined quantities*/
4689 @d level_one (level_zero+1) /*outermost level for defined quantities*/
4690
4691 @ Many locations in |eqtb| have symbolic names. The purpose of the next
4692 paragraphs is to define these names, and to set up the initial values of the
4693 equivalents.
4694
4695 In the first region we have 256 equivalents for ``active characters'' that
4696 act as control sequences, followed by 256 equivalents for single-character
4697 control sequences.
4698
4699 Then comes region~2, which corresponds to the hash table that we will
4700 define later. The maximum address in this region is used for a dummy
4701 control sequence that is perpetually undefined. There also are several
4702 locations for control sequences that are perpetually defined
4703 (since they are used in error recovery).
4704
4705 @d active_base 1 /*beginning of region 1, for active character equivalents*/
4706 @d single_base (active_base+256) /*equivalents of one-character control sequences*/
4707 @d null_cs (single_base+256) /*equivalent of \.{\\csname\\endcsname}*/
4708 @d hash_base (null_cs+1) /*beginning of region 2, for the hash table*/
4709 @d frozen_control_sequence (hash_base+hash_size) /*for error recovery*/
4710 @d frozen_protection frozen_control_sequence /*inaccessible but definable*/
4711 @d frozen_cr (frozen_control_sequence+1) /*permanent `\.{\\cr}'*/
4712 @d frozen_end_group (frozen_control_sequence+2) /*permanent `\.{\\endgroup}'*/
4713 @d frozen_right (frozen_control_sequence+3) /*permanent `\.{\\right}'*/
4714 @d frozen_fi (frozen_control_sequence+4) /*permanent `\.{\\fi}'*/
4715 @d frozen_end_template (frozen_control_sequence+5) /*permanent `\.{\\endtemplate}'*/
4716 @d frozen_endv (frozen_control_sequence+6) /*second permanent `\.{\\endtemplate}'*/
4717 @d frozen_relax (frozen_control_sequence+7) /*permanent `\.{\\relax}'*/
4718 @d end_write (frozen_control_sequence+8) /*permanent `\.{\\endwrite}'*/
4719 @d frozen_dont_expand (frozen_control_sequence+9)
4720 /*permanent `\.{\\notexpanded:}'*/
4721 @d frozen_primitive (frozen_control_sequence+10)
4722 /*permanent `\.{\\primitive:}'*/
4723 @d frozen_null_font (frozen_control_sequence+11)
4724 /*permanent `\.{\\nullfont}'*/
4725 @d font_id_base (frozen_null_font-font_base)
4726 /*begins table of 257 permanent font identifiers*/
4727 @d undefined_control_sequence (frozen_null_font+257) /*dummy location*/
4728 @d glue_base (undefined_control_sequence+1) /*beginning of region 3*/
4729
4730 @<Initialize table entries...@>=
4731 eq_type(undefined_control_sequence)=undefined_cs;
4732 equiv(undefined_control_sequence)=null;
4733 eq_level(undefined_control_sequence)=level_zero;
4734 for (k=active_base; k<=undefined_control_sequence-1; k++)
4735 eqtb[k]=eqtb[undefined_control_sequence];
4736
4737 @ Here is a routine that displays the current meaning of an |eqtb| entry
4738 in region 1 or~2. (Similar routines for the other regions will appear
4739 below.)
4740
4741 @<Show equivalent |n|, in region 1 or 2@>=
4742 {@+sprint_cs(n);print_char('=');print_cmd_chr(eq_type(n), equiv(n));
4743 if (eq_type(n) >= call)
4744 {@+print_char(':');show_token_list(link(equiv(n)), null, 32);
4745 }
4746 }
4747
4748 @ Region 3 of |eqtb| contains the 256 \.{\\skip} registers, as well as the
4749 glue parameters defined here. It is important that the ``muskip''
4750 parameters have larger numbers than the others.
4751
4752 @d line_skip_code 0 /*interline glue if |baseline_skip| is infeasible*/
4753 @d baseline_skip_code 1 /*desired glue between baselines*/
4754 @d par_skip_code 2 /*extra glue just above a paragraph*/
4755 @d above_display_skip_code 3 /*extra glue just above displayed math*/
4756 @d below_display_skip_code 4 /*extra glue just below displayed math*/
4757 @d above_display_short_skip_code 5
4758 /*glue above displayed math following short lines*/
4759 @d below_display_short_skip_code 6
4760 /*glue below displayed math following short lines*/
4761 @d left_skip_code 7 /*glue at left of justified lines*/
4762 @d right_skip_code 8 /*glue at right of justified lines*/
4763 @d top_skip_code 9 /*glue at top of main pages*/
4764 @d split_top_skip_code 10 /*glue at top of split pages*/
4765 @d tab_skip_code 11 /*glue between aligned entries*/
4766 @d space_skip_code 12 /*glue between words (if not |zero_glue|)*/
4767 @d xspace_skip_code 13 /*glue after sentences (if not |zero_glue|)*/
4768 @d par_fill_skip_code 14 /*glue on last line of paragraph*/
4769 @d thin_mu_skip_code 15 /*thin space in math formula*/
4770 @d med_mu_skip_code 16 /*medium space in math formula*/
4771 @d thick_mu_skip_code 17 /*thick space in math formula*/
4772 @d glue_pars 18 /*total number of glue parameters*/
4773 @d skip_base (glue_base+glue_pars) /*table of 256 ``skip'' registers*/
4774 @d mu_skip_base (skip_base+256) /*table of 256 ``muskip'' registers*/
4775 @d local_base (mu_skip_base+256) /*beginning of region 4*/
4776 @#
4777 @d skip(A) equiv(skip_base+A) /*|mem| location of glue specification*/
4778 @d mu_skip(A) equiv(mu_skip_base+A) /*|mem| location of math glue spec*/
4779 @d glue_par(A) equiv(glue_base+A) /*|mem| location of glue specification*/
4780 @d line_skip glue_par(line_skip_code)
4781 @d baseline_skip glue_par(baseline_skip_code)
4782 @d par_skip glue_par(par_skip_code)
4783 @d above_display_skip glue_par(above_display_skip_code)
4784 @d below_display_skip glue_par(below_display_skip_code)
4785 @d above_display_short_skip glue_par(above_display_short_skip_code)
4786 @d below_display_short_skip glue_par(below_display_short_skip_code)
4787 @d left_skip glue_par(left_skip_code)
4788 @d right_skip glue_par(right_skip_code)
4789 @d top_skip glue_par(top_skip_code)
4790 @d split_top_skip glue_par(split_top_skip_code)
4791 @d tab_skip glue_par(tab_skip_code)
4792 @d space_skip glue_par(space_skip_code)
4793 @d xspace_skip glue_par(xspace_skip_code)
4794 @d par_fill_skip glue_par(par_fill_skip_code)
4795 @d thin_mu_skip glue_par(thin_mu_skip_code)
4796 @d med_mu_skip glue_par(med_mu_skip_code)
4797 @d thick_mu_skip glue_par(thick_mu_skip_code)
4798
4799 @<Current |mem| equivalent of glue parameter number |n|@>=glue_par(n)
4800
4801 @ Sometimes we need to convert \TeX's internal code numbers into symbolic
4802 form. The |print_skip_param| routine gives the symbolic name of a glue
4803 parameter.
4804
4805 @<Declare the procedure called |print_skip_param|@>=
4806 static void print_skip_param(int @!n)
4807 {@+switch (n) {
4808 case line_skip_code: print_esc("lineskip");@+break;
4809 case baseline_skip_code: print_esc("baselineskip");@+break;
4810 case par_skip_code: print_esc("parskip");@+break;
4811 case above_display_skip_code: print_esc("abovedisplayskip");@+break;
4812 case below_display_skip_code: print_esc("belowdisplayskip");@+break;
4813 case above_display_short_skip_code: print_esc("abovedisplayshortskip");@+break;
4814 case below_display_short_skip_code: print_esc("belowdisplayshortskip");@+break;
4815 case left_skip_code: print_esc("leftskip");@+break;
4816 case right_skip_code: print_esc("rightskip");@+break;
4817 case top_skip_code: print_esc("topskip");@+break;
4818 case split_top_skip_code: print_esc("splittopskip");@+break;
4819 case tab_skip_code: print_esc("tabskip");@+break;
4820 case space_skip_code: print_esc("spaceskip");@+break;
4821 case xspace_skip_code: print_esc("xspaceskip");@+break;
4822 case par_fill_skip_code: print_esc("parfillskip");@+break;
4823 case thin_mu_skip_code: print_esc("thinmuskip");@+break;
4824 case med_mu_skip_code: print_esc("medmuskip");@+break;
4825 case thick_mu_skip_code: print_esc("thickmuskip");@+break;
4826 default:print("[unknown glue parameter!]");
4827 }
4828 }
4829
4830 @ The symbolic names for glue parameters are put into \TeX's hash table
4831 by using the routine called |primitive|, defined below. Let us enter them
4832 now, so that we don't have to list all those parameter names anywhere else.
4833
4834 @<Put each of \TeX's primitives into the hash table@>=
4835 primitive("lineskip", assign_glue, glue_base+line_skip_code);@/
4836 @!@:line\_skip\_}{\.{\\lineskip} primitive@>
4837 primitive("baselineskip", assign_glue, glue_base+baseline_skip_code);@/
4838 @!@:baseline\_skip\_}{\.{\\baselineskip} primitive@>
4839 primitive("parskip", assign_glue, glue_base+par_skip_code);@/
4840 @!@:par\_skip\_}{\.{\\parskip} primitive@>
4841 primitive("abovedisplayskip", assign_glue, glue_base+above_display_skip_code);@/
4842 @!@:above\_display\_skip\_}{\.{\\abovedisplayskip} primitive@>
4843 primitive("belowdisplayskip", assign_glue, glue_base+below_display_skip_code);@/
4844 @!@:below\_display\_skip\_}{\.{\\belowdisplayskip} primitive@>
4845 primitive("abovedisplayshortskip",
4846 assign_glue, glue_base+above_display_short_skip_code);@/
4847 @!@:above\_display\_short\_skip\_}{\.{\\abovedisplayshortskip} primitive@>
4848 primitive("belowdisplayshortskip",
4849 assign_glue, glue_base+below_display_short_skip_code);@/
4850 @!@:below\_display\_short\_skip\_}{\.{\\belowdisplayshortskip} primitive@>
4851 primitive("leftskip", assign_glue, glue_base+left_skip_code);@/
4852 @!@:left\_skip\_}{\.{\\leftskip} primitive@>
4853 primitive("rightskip", assign_glue, glue_base+right_skip_code);@/
4854 @!@:right\_skip\_}{\.{\\rightskip} primitive@>
4855 primitive("topskip", assign_glue, glue_base+top_skip_code);@/
4856 @!@:top\_skip\_}{\.{\\topskip} primitive@>
4857 primitive("splittopskip", assign_glue, glue_base+split_top_skip_code);@/
4858 @!@:split\_top\_skip\_}{\.{\\splittopskip} primitive@>
4859 primitive("tabskip", assign_glue, glue_base+tab_skip_code);@/
4860 @!@:tab\_skip\_}{\.{\\tabskip} primitive@>
4861 primitive("spaceskip", assign_glue, glue_base+space_skip_code);@/
4862 @!@:space\_skip\_}{\.{\\spaceskip} primitive@>
4863 primitive("xspaceskip", assign_glue, glue_base+xspace_skip_code);@/
4864 @!@:xspace\_skip\_}{\.{\\xspaceskip} primitive@>
4865 primitive("parfillskip", assign_glue, glue_base+par_fill_skip_code);@/
4866 @!@:par\_fill\_skip\_}{\.{\\parfillskip} primitive@>
4867 primitive("thinmuskip", assign_mu_glue, glue_base+thin_mu_skip_code);@/
4868 @!@:thin\_mu\_skip\_}{\.{\\thinmuskip} primitive@>
4869 primitive("medmuskip", assign_mu_glue, glue_base+med_mu_skip_code);@/
4870 @!@:med\_mu\_skip\_}{\.{\\medmuskip} primitive@>
4871 primitive("thickmuskip", assign_mu_glue, glue_base+thick_mu_skip_code);@/
4872 @!@:thick\_mu\_skip\_}{\.{\\thickmuskip} primitive@>
4873
4874 @ @<Cases of |print_cmd_chr| for symbolic printing of primitives@>=
4875 case assign_glue: case assign_mu_glue: if (chr_code < skip_base)
4876 print_skip_param(chr_code-glue_base);
4877 else if (chr_code < mu_skip_base)
4878 {@+print_esc("skip");print_int(chr_code-skip_base);
4879 }
4880 else{@+print_esc("muskip");print_int(chr_code-mu_skip_base);
4881 } @+break;
4882
4883 @ All glue parameters and registers are initially `\.{0pt plus0pt minus0pt}'.
4884
4885 @<Initialize table entries...@>=
4886 equiv(glue_base)=zero_glue;eq_level(glue_base)=level_one;
4887 eq_type(glue_base)=glue_ref;
4888 for (k=glue_base+1; k<=local_base-1; k++) eqtb[k]=eqtb[glue_base];
4889 glue_ref_count(zero_glue)=glue_ref_count(zero_glue)+local_base-glue_base;
4890
4891 @ @<Show equivalent |n|, in region 3@>=
4892 if (n < skip_base)
4893 {@+print_skip_param(n-glue_base);print_char('=');
4894 if (n < glue_base+thin_mu_skip_code) print_spec(equiv(n),"pt");
4895 else print_spec(equiv(n),"mu");
4896 }
4897 else if (n < mu_skip_base)
4898 {@+print_esc("skip");print_int(n-skip_base);print_char('=');
4899 print_spec(equiv(n),"pt");
4900 }
4901 else{@+print_esc("muskip");print_int(n-mu_skip_base);print_char('=');
4902 print_spec(equiv(n),"mu");
4903 }
4904
4905 @ Region 4 of |eqtb| contains the local quantities defined here. The
4906 bulk of this region is taken up by five tables that are indexed by eight-bit
4907 characters; these tables are important to both the syntactic and semantic
4908 portions of \TeX. There are also a bunch of special things like font and
4909 token parameters, as well as the tables of \.{\\toks} and \.{\\box}
4910 registers.
4911
4912 @d par_shape_loc local_base /*specifies paragraph shape*/
4913 @d output_routine_loc (local_base+1) /*points to token list for \.{\\output}*/
4914 @d every_par_loc (local_base+2) /*points to token list for \.{\\everypar}*/
4915 @d every_math_loc (local_base+3) /*points to token list for \.{\\everymath}*/
4916 @d every_display_loc (local_base+4) /*points to token list for \.{\\everydisplay}*/
4917 @d every_hbox_loc (local_base+5) /*points to token list for \.{\\everyhbox}*/
4918 @d every_vbox_loc (local_base+6) /*points to token list for \.{\\everyvbox}*/
4919 @d every_job_loc (local_base+7) /*points to token list for \.{\\everyjob}*/
4920 @d every_cr_loc (local_base+8) /*points to token list for \.{\\everycr}*/
4921 @d err_help_loc (local_base+9) /*points to token list for \.{\\errhelp}*/
4922 @d tex_toks (local_base+10) /*end of \TeX's token list parameters*/
4923 @#
4924 @d etex_toks_base pdf_toks /*base for \eTeX's token list parameters*/
4925 @d every_eof_loc etex_toks_base /*points to token list for \.{\\everyeof}*/
4926 @d etex_toks (etex_toks_base+1) /*end of \eTeX's token list parameters*/
4927 @#
4928 @d toks_base etex_toks /*table of 256 token list registers*/
4929 @#
4930 @d etex_pen_base (toks_base+256) /*start of table of \eTeX's penalties*/
4931 @d inter_line_penalties_loc etex_pen_base /*additional penalties between lines*/
4932 @d club_penalties_loc (etex_pen_base+1) /*penalties for creating club lines*/
4933 @d widow_penalties_loc (etex_pen_base+2) /*penalties for creating widow lines*/
4934 @d display_widow_penalties_loc (etex_pen_base+3) /*ditto, just before a display*/
4935 @d etex_pens (etex_pen_base+4) /*end of table of \eTeX's penalties*/
4936 @#
4937 @d box_base etex_pens /*table of 256 box registers*/
4938 @d cur_font_loc (box_base+256) /*internal font number outside math mode*/
4939 @d math_font_base (cur_font_loc+1) /*table of 48 math font numbers*/
4940 @d cat_code_base (math_font_base+48)
4941 /*table of 256 command codes (the ``catcodes'')*/
4942 @d lc_code_base (cat_code_base+256) /*table of 256 lowercase mappings*/
4943 @d uc_code_base (lc_code_base+256) /*table of 256 uppercase mappings*/
4944 @d sf_code_base (uc_code_base+256) /*table of 256 spacefactor mappings*/
4945 @d math_code_base (sf_code_base+256) /*table of 256 math mode mappings*/
4946 @d int_base (math_code_base+256) /*beginning of region 5*/
4947 @#
4948 @d par_shape_ptr equiv(par_shape_loc)
4949 @d output_routine equiv(output_routine_loc)
4950 @d every_par equiv(every_par_loc)
4951 @d every_math equiv(every_math_loc)
4952 @d every_display equiv(every_display_loc)
4953 @d every_hbox equiv(every_hbox_loc)
4954 @d every_vbox equiv(every_vbox_loc)
4955 @d every_job equiv(every_job_loc)
4956 @d every_cr equiv(every_cr_loc)
4957 @d err_help equiv(err_help_loc)
4958 @d toks(X) equiv(toks_base+X)
4959 @d box(A) equiv(box_base+A)
4960 @d cur_font equiv(cur_font_loc)
4961 @d fam_fnt(A) equiv(math_font_base+A)
4962 @d cat_code(A) equiv(cat_code_base+A)
4963 @d lc_code(A) equiv(lc_code_base+A)
4964 @d uc_code(A) equiv(uc_code_base+A)
4965 @d sf_code(A) equiv(sf_code_base+A)
4966 @d math_code(A) equiv(math_code_base+A)
4967 /*Note: |math_code(c)| is the true math code plus |min_halfword|*/
4968
4969 @<Put each...@>=
4970 primitive("output", assign_toks, output_routine_loc);
4971 @!@:output\_}{\.{\\output} primitive@>
4972 primitive("everypar", assign_toks, every_par_loc);
4973 @!@:every\_par\_}{\.{\\everypar} primitive@>
4974 primitive("everymath", assign_toks, every_math_loc);
4975 @!@:every\_math\_}{\.{\\everymath} primitive@>
4976 primitive("everydisplay", assign_toks, every_display_loc);
4977 @!@:every\_display\_}{\.{\\everydisplay} primitive@>
4978 primitive("everyhbox", assign_toks, every_hbox_loc);
4979 @!@:every\_hbox\_}{\.{\\everyhbox} primitive@>
4980 primitive("everyvbox", assign_toks, every_vbox_loc);
4981 @!@:every\_vbox\_}{\.{\\everyvbox} primitive@>
4982 primitive("everyjob", assign_toks, every_job_loc);
4983 @!@:every\_job\_}{\.{\\everyjob} primitive@>
4984 primitive("everycr", assign_toks, every_cr_loc);
4985 @!@:every\_cr\_}{\.{\\everycr} primitive@>
4986 primitive("errhelp", assign_toks, err_help_loc);
4987 @!@:err\_help\_}{\.{\\errhelp} primitive@>
4988
4989 @ @<Cases of |print_cmd_chr|...@>=
4990 case assign_toks: if (chr_code >= toks_base)
4991 {@+print_esc("toks");print_int(chr_code-toks_base);
4992 }
4993 else switch (chr_code) {
4994 case output_routine_loc: print_esc("output");@+break;
4995 case every_par_loc: print_esc("everypar");@+break;
4996 case every_math_loc: print_esc("everymath");@+break;
4997 case every_display_loc: print_esc("everydisplay");@+break;
4998 case every_hbox_loc: print_esc("everyhbox");@+break;
4999 case every_vbox_loc: print_esc("everyvbox");@+break;
5000 case every_job_loc: print_esc("everyjob");@+break;
5001 case every_cr_loc: print_esc("everycr");@+break;
5002 @/@<Cases of |assign_toks| for |print_cmd_chr|@>@/
5003 default:print_esc("errhelp");
5004 } @+break;
5005
5006 @ We initialize most things to null or undefined values. An undefined font
5007 is represented by the internal code |font_base|.
5008
5009 However, the character code tables are given initial values based on the
5010 conventional interpretation of ASCII code. These initial values should
5011 not be changed when \TeX\ is adapted for use with non-English languages;
5012 all changes to the initialization conventions should be made in format
5013 packages, not in \TeX\ itself, so that global interchange of formats is
5014 possible.
5015
5016 @d null_font font_base
5017 @d var_code 070000 /*math code meaning ``use the current family''*/
5018
5019 @<Initialize table entries...@>=
5020 par_shape_ptr=null;eq_type(par_shape_loc)=shape_ref;
5021 eq_level(par_shape_loc)=level_one;@/
5022 for (k=etex_pen_base; k<=etex_pens-1; k++)
5023 eqtb[k]=eqtb[par_shape_loc];
5024 for (k=output_routine_loc; k<=toks_base+255; k++)
5025 eqtb[k]=eqtb[undefined_control_sequence];
5026 box(0)=null;eq_type(box_base)=box_ref;eq_level(box_base)=level_one;
5027 for (k=box_base+1; k<=box_base+255; k++) eqtb[k]=eqtb[box_base];
5028 cur_font=null_font;eq_type(cur_font_loc)=data;
5029 eq_level(cur_font_loc)=level_one;@/
5030 for (k=math_font_base; k<=math_font_base+47; k++) eqtb[k]=eqtb[cur_font_loc];
5031 equiv(cat_code_base)=0;eq_type(cat_code_base)=data;
5032 eq_level(cat_code_base)=level_one;@/
5033 for (k=cat_code_base+1; k<=int_base-1; k++) eqtb[k]=eqtb[cat_code_base];
5034 for (k=0; k<=255; k++)
5035 {@+cat_code(k)=other_char;math_code(k)=hi(k);sf_code(k)=1000;
5036 }
5037 cat_code(carriage_return)=car_ret;cat_code(' ')=spacer;
5038 cat_code('\\')=escape;cat_code('%')=comment;
5039 cat_code(invalid_code)=invalid_char;cat_code(null_code)=ignore;
5040 for (k='0'; k<='9'; k++) math_code(k)=hi(k+var_code);
5041 for (k='A'; k<='Z'; k++)
5042 {@+cat_code(k)=letter;cat_code(k+'a'-'A')=letter;@/
5043 math_code(k)=hi(k+var_code+0x100);
5044 math_code(k+'a'-'A')=hi(k+'a'-'A'+var_code+0x100);@/
5045 lc_code(k)=k+'a'-'A';lc_code(k+'a'-'A')=k+'a'-'A';@/
5046 uc_code(k)=k;uc_code(k+'a'-'A')=k;@/
5047 sf_code(k)=999;
5048 }
5049
5050 @ @<Show equivalent |n|, in region 4@>=
5051 if ((n==par_shape_loc)||((n >= etex_pen_base)&&(n < etex_pens)))
5052 {@+print_cmd_chr(set_shape, n);print_char('=');
5053 if (equiv(n)==null) print_char('0');
5054 else if (n > par_shape_loc)
5055 {@+print_int(penalty(equiv(n)));print_char(' ');
5056 print_int(penalty(equiv(n)+1));
5057 if (penalty(equiv(n)) > 1) print_esc("ETC.");
5058 }
5059 else print_int(info(par_shape_ptr));
5060 }
5061 else if (n < toks_base)
5062 {@+print_cmd_chr(assign_toks, n);print_char('=');
5063 if (equiv(n)!=null) show_token_list(link(equiv(n)), null, 32);
5064 }
5065 else if (n < box_base)
5066 {@+print_esc("toks");print_int(n-toks_base);print_char('=');
5067 if (equiv(n)!=null) show_token_list(link(equiv(n)), null, 32);
5068 }
5069 else if (n < cur_font_loc)
5070 {@+print_esc("box");print_int(n-box_base);print_char('=');
5071 if (equiv(n)==null) print("void");
5072 else{@+depth_threshold=0;breadth_max=1;show_node_list(equiv(n));
5073 }
5074 }
5075 else if (n < cat_code_base) @<Show the font identifier in |eqtb[n]|@>@;
5076 else@<Show the halfword code in |eqtb[n]|@>@;
5077
5078 @ @<Show the font identifier in |eqtb[n]|@>=
5079 {@+if (n==cur_font_loc) print("current font");
5080 else if (n < math_font_base+16)
5081 {@+print_esc("textfont");print_int(n-math_font_base);
5082 }
5083 else if (n < math_font_base+32)
5084 {@+print_esc("scriptfont");print_int(n-math_font_base-16);
5085 }
5086 else{@+print_esc("scriptscriptfont");print_int(n-math_font_base-32);
5087 }
5088 print_char('=');@/
5089 printn_esc(hash[font_id_base+equiv(n)].rh);
5090 /*that's |font_id_text(equiv(n))|*/
5091 }
5092
5093 @ @<Show the halfword code in |eqtb[n]|@>=
5094 if (n < math_code_base)
5095 {@+if (n < lc_code_base)
5096 {@+print_esc("catcode");print_int(n-cat_code_base);
5097 }
5098 else if (n < uc_code_base)
5099 {@+print_esc("lccode");print_int(n-lc_code_base);
5100 }
5101 else if (n < sf_code_base)
5102 {@+print_esc("uccode");print_int(n-uc_code_base);
5103 }
5104 else{@+print_esc("sfcode");print_int(n-sf_code_base);
5105 }
5106 print_char('=');print_int(equiv(n));
5107 }
5108 else{@+print_esc("mathcode");print_int(n-math_code_base);
5109 print_char('=');print_int(ho(equiv(n)));
5110 }
5111
5112 @ Region 5 of |eqtb| contains the integer parameters and registers defined
5113 here, as well as the |del_code| table. The latter table differs from the
5114 |cat_code dotdot math_code| tables that precede it, since delimiter codes are
5115 fullword integers while the other kinds of codes occupy at most a
5116 halfword. This is what makes region~5 different from region~4. We will
5117 store the |eq_level| information in an auxiliary array of quarterwords
5118 that will be defined later.
5119
5120 @d pretolerance_code 0 /*badness tolerance before hyphenation*/
5121 @d tolerance_code 1 /*badness tolerance after hyphenation*/
5122 @d line_penalty_code 2 /*added to the badness of every line*/
5123 @d hyphen_penalty_code 3 /*penalty for break after discretionary hyphen*/
5124 @d ex_hyphen_penalty_code 4 /*penalty for break after explicit hyphen*/
5125 @d club_penalty_code 5 /*penalty for creating a club line*/
5126 @d widow_penalty_code 6 /*penalty for creating a widow line*/
5127 @d display_widow_penalty_code 7 /*ditto, just before a display*/
5128 @d broken_penalty_code 8 /*penalty for breaking a page at a broken line*/
5129 @d bin_op_penalty_code 9 /*penalty for breaking after a binary operation*/
5130 @d rel_penalty_code 10 /*penalty for breaking after a relation*/
5131 @d pre_display_penalty_code 11
5132 /*penalty for breaking just before a displayed formula*/
5133 @d post_display_penalty_code 12
5134 /*penalty for breaking just after a displayed formula*/
5135 @d inter_line_penalty_code 13 /*additional penalty between lines*/
5136 @d double_hyphen_demerits_code 14 /*demerits for double hyphen break*/
5137 @d final_hyphen_demerits_code 15 /*demerits for final hyphen break*/
5138 @d adj_demerits_code 16 /*demerits for adjacent incompatible lines*/
5139 @d mag_code 17 /*magnification ratio*/
5140 @d delimiter_factor_code 18 /*ratio for variable-size delimiters*/
5141 @d looseness_code 19 /*change in number of lines for a paragraph*/
5142 @d time_code 20 /*current time of day*/
5143 @d day_code 21 /*current day of the month*/
5144 @d month_code 22 /*current month of the year*/
5145 @d year_code 23 /*current year of our Lord*/
5146 @d show_box_breadth_code 24 /*nodes per level in |show_box|*/
5147 @d show_box_depth_code 25 /*maximum level in |show_box|*/
5148 @d hbadness_code 26 /*hboxes exceeding this badness will be shown by |hpack|*/
5149 @d vbadness_code 27 /*vboxes exceeding this badness will be shown by |vpack|*/
5150 @d pausing_code 28 /*pause after each line is read from a file*/
5151 @d tracing_online_code 29 /*show diagnostic output on terminal*/
5152 @d tracing_macros_code 30 /*show macros as they are being expanded*/
5153 @d tracing_stats_code 31 /*show memory usage if \TeX\ knows it*/
5154 @d tracing_paragraphs_code 32 /*show line-break calculations*/
5155 @d tracing_pages_code 33 /*show page-break calculations*/
5156 @d tracing_output_code 34 /*show boxes when they are shipped out*/
5157 @d tracing_lost_chars_code 35 /*show characters that aren't in the font*/
5158 @d tracing_commands_code 36 /*show command codes at |big_switch|*/
5159 @d tracing_restores_code 37 /*show equivalents when they are restored*/
5160 @d uc_hyph_code 38 /*hyphenate words beginning with a capital letter*/
5161 @d output_penalty_code 39 /*penalty found at current page break*/
5162 @d max_dead_cycles_code 40 /*bound on consecutive dead cycles of output*/
5163 @d hang_after_code 41 /*hanging indentation changes after this many lines*/
5164 @d floating_penalty_code 42 /*penalty for insertions held over after a split*/
5165 @d global_defs_code 43 /*override \.{\\global} specifications*/
5166 @d cur_fam_code 44 /*current family*/
5167 @d escape_char_code 45 /*escape character for token output*/
5168 @d default_hyphen_char_code 46 /*value of \.{\\hyphenchar} when a font is loaded*/
5169 @d default_skew_char_code 47 /*value of \.{\\skewchar} when a font is loaded*/
5170 @d end_line_char_code 48 /*character placed at the right end of the buffer*/
5171 @d new_line_char_code 49 /*character that prints as |print_ln|*/
5172 @d language_code 50 /*current hyphenation table*/
5173 @d left_hyphen_min_code 51 /*minimum left hyphenation fragment size*/
5174 @d right_hyphen_min_code 52 /*minimum right hyphenation fragment size*/
5175 @d holding_inserts_code 53 /*do not remove insertion nodes from \.{\\box255}*/
5176 @d error_context_lines_code 54 /*maximum intermediate line pairs shown*/
5177 @d tex_int_pars 55 /*total number of \TeX's integer parameters*/
5178 @#
5179 @d etex_int_base pdf_int_pars /*base for \eTeX's integer parameters*/
5180 @d tracing_assigns_code etex_int_base /*show assignments*/
5181 @d tracing_groups_code (etex_int_base+1) /*show save/restore groups*/
5182 @d tracing_ifs_code (etex_int_base+2) /*show conditionals*/
5183 @d tracing_scan_tokens_code (etex_int_base+3) /*show pseudo file open and close*/
5184 @d tracing_nesting_code (etex_int_base+4) /*show incomplete groups and ifs within files*/
5185 @d saving_vdiscards_code (etex_int_base+5) /*save items discarded from vlists*/
5186 @d saving_hyph_codes_code (etex_int_base+6) /*save hyphenation codes for languages*/
5187 @d expand_depth_code (etex_int_base+7) /*maximum depth for expansion---\eTeX*/
5188 @d eTeX_state_code (etex_int_base+8) /*\eTeX\ state variables*/
5189 @d etex_int_pars (eTeX_state_code+eTeX_states) /*total number of \eTeX's integer parameters*/
5190 @#
5191 @d int_pars etex_int_pars /*total number of integer parameters*/
5192 @d count_base (int_base+int_pars) /*256 user \.{\\count} registers*/
5193 @d del_code_base (count_base+256) /*256 delimiter code mappings*/
5194 @d dimen_base (del_code_base+256) /*beginning of region 6*/
5195 @#
5196 @d del_code(A) eqtb[del_code_base+A].i
5197 @d count(A) eqtb[count_base+A].i
5198 @d int_par(A) eqtb[int_base+A].i /*an integer parameter*/
5199 @d pretolerance int_par(pretolerance_code)
5200 @d tolerance int_par(tolerance_code)
5201 @d line_penalty int_par(line_penalty_code)
5202 @d hyphen_penalty int_par(hyphen_penalty_code)
5203 @d ex_hyphen_penalty int_par(ex_hyphen_penalty_code)
5204 @d club_penalty int_par(club_penalty_code)
5205 @d widow_penalty int_par(widow_penalty_code)
5206 @d display_widow_penalty int_par(display_widow_penalty_code)
5207 @d broken_penalty int_par(broken_penalty_code)
5208 @d bin_op_penalty int_par(bin_op_penalty_code)
5209 @d rel_penalty int_par(rel_penalty_code)
5210 @d pre_display_penalty int_par(pre_display_penalty_code)
5211 @d post_display_penalty int_par(post_display_penalty_code)
5212 @d inter_line_penalty int_par(inter_line_penalty_code)
5213 @d double_hyphen_demerits int_par(double_hyphen_demerits_code)
5214 @d final_hyphen_demerits int_par(final_hyphen_demerits_code)
5215 @d adj_demerits int_par(adj_demerits_code)
5216 @d mag int_par(mag_code)
5217 @d delimiter_factor int_par(delimiter_factor_code)
5218 @d looseness int_par(looseness_code)
5219 @d time int_par(time_code)
5220 @d day int_par(day_code)
5221 @d month int_par(month_code)
5222 @d year int_par(year_code)
5223 @d show_box_breadth int_par(show_box_breadth_code)
5224 @d show_box_depth int_par(show_box_depth_code)
5225 @d hbadness int_par(hbadness_code)
5226 @d vbadness int_par(vbadness_code)
5227 @d pausing int_par(pausing_code)
5228 @d tracing_online int_par(tracing_online_code)
5229 @d tracing_macros int_par(tracing_macros_code)
5230 @d tracing_stats int_par(tracing_stats_code)
5231 @d tracing_paragraphs int_par(tracing_paragraphs_code)
5232 @d tracing_pages int_par(tracing_pages_code)
5233 @d tracing_output int_par(tracing_output_code)
5234 @d tracing_lost_chars int_par(tracing_lost_chars_code)
5235 @d tracing_commands int_par(tracing_commands_code)
5236 @d tracing_restores int_par(tracing_restores_code)
5237 @d uc_hyph int_par(uc_hyph_code)
5238 @d output_penalty int_par(output_penalty_code)
5239 @d max_dead_cycles int_par(max_dead_cycles_code)
5240 @d hang_after int_par(hang_after_code)
5241 @d floating_penalty int_par(floating_penalty_code)
5242 @d global_defs int_par(global_defs_code)
5243 @d cur_fam int_par(cur_fam_code)
5244 @d escape_char int_par(escape_char_code)
5245 @d default_hyphen_char int_par(default_hyphen_char_code)
5246 @d default_skew_char int_par(default_skew_char_code)
5247 @d end_line_char int_par(end_line_char_code)
5248 @d new_line_char int_par(new_line_char_code)
5249 @d language int_par(language_code)
5250 @d left_hyphen_min int_par(left_hyphen_min_code)
5251 @d right_hyphen_min int_par(right_hyphen_min_code)
5252 @d holding_inserts int_par(holding_inserts_code)
5253 @d error_context_lines int_par(error_context_lines_code)
5254 @#
5255 @d tracing_assigns int_par(tracing_assigns_code)
5256 @d tracing_groups int_par(tracing_groups_code)
5257 @d tracing_ifs int_par(tracing_ifs_code)
5258 @d tracing_scan_tokens int_par(tracing_scan_tokens_code)
5259 @d tracing_nesting int_par(tracing_nesting_code)
5260 @d saving_vdiscards int_par(saving_vdiscards_code)
5261 @d saving_hyph_codes int_par(saving_hyph_codes_code)
5262 @d expand_depth int_par(expand_depth_code)
5263
5264 @<Assign the values |depth_threshold:=show_box_depth|...@>=
5265 depth_threshold=show_box_depth;
5266 breadth_max=show_box_breadth
5267
5268 @ We can print the symbolic name of an integer parameter as follows.
5269
5270 @p static void print_param(int @!n)
5271 {@+switch (n) {
5272 case pretolerance_code: print_esc("pretolerance");@+break;
5273 case tolerance_code: print_esc("tolerance");@+break;
5274 case line_penalty_code: print_esc("linepenalty");@+break;
5275 case hyphen_penalty_code: print_esc("hyphenpenalty");@+break;
5276 case ex_hyphen_penalty_code: print_esc("exhyphenpenalty");@+break;
5277 case club_penalty_code: print_esc("clubpenalty");@+break;
5278 case widow_penalty_code: print_esc("widowpenalty");@+break;
5279 case display_widow_penalty_code: print_esc("displaywidowpenalty");@+break;
5280 case broken_penalty_code: print_esc("brokenpenalty");@+break;
5281 case bin_op_penalty_code: print_esc("binoppenalty");@+break;
5282 case rel_penalty_code: print_esc("relpenalty");@+break;
5283 case pre_display_penalty_code: print_esc("predisplaypenalty");@+break;
5284 case post_display_penalty_code: print_esc("postdisplaypenalty");@+break;
5285 case inter_line_penalty_code: print_esc("interlinepenalty");@+break;
5286 case double_hyphen_demerits_code: print_esc("doublehyphendemerits");@+break;
5287 case final_hyphen_demerits_code: print_esc("finalhyphendemerits");@+break;
5288 case adj_demerits_code: print_esc("adjdemerits");@+break;
5289 case mag_code: print_esc("mag");@+break;
5290 case delimiter_factor_code: print_esc("delimiterfactor");@+break;
5291 case looseness_code: print_esc("looseness");@+break;
5292 case time_code: print_esc("time");@+break;
5293 case day_code: print_esc("day");@+break;
5294 case month_code: print_esc("month");@+break;
5295 case year_code: print_esc("year");@+break;
5296 case show_box_breadth_code: print_esc("showboxbreadth");@+break;
5297 case show_box_depth_code: print_esc("showboxdepth");@+break;
5298 case hbadness_code: print_esc("hbadness");@+break;
5299 case vbadness_code: print_esc("vbadness");@+break;
5300 case pausing_code: print_esc("pausing");@+break;
5301 case tracing_online_code: print_esc("tracingonline");@+break;
5302 case tracing_macros_code: print_esc("tracingmacros");@+break;
5303 case tracing_stats_code: print_esc("tracingstats");@+break;
5304 case tracing_paragraphs_code: print_esc("tracingparagraphs");@+break;
5305 case tracing_pages_code: print_esc("tracingpages");@+break;
5306 case tracing_output_code: print_esc("tracingoutput");@+break;
5307 case tracing_lost_chars_code: print_esc("tracinglostchars");@+break;
5308 case tracing_commands_code: print_esc("tracingcommands");@+break;
5309 case tracing_restores_code: print_esc("tracingrestores");@+break;
5310 case uc_hyph_code: print_esc("uchyph");@+break;
5311 case output_penalty_code: print_esc("outputpenalty");@+break;
5312 case max_dead_cycles_code: print_esc("maxdeadcycles");@+break;
5313 case hang_after_code: print_esc("hangafter");@+break;
5314 case floating_penalty_code: print_esc("floatingpenalty");@+break;
5315 case global_defs_code: print_esc("globaldefs");@+break;
5316 case cur_fam_code: print_esc("fam");@+break;
5317 case escape_char_code: print_esc("escapechar");@+break;
5318 case default_hyphen_char_code: print_esc("defaulthyphenchar");@+break;
5319 case default_skew_char_code: print_esc("defaultskewchar");@+break;
5320 case end_line_char_code: print_esc("endlinechar");@+break;
5321 case new_line_char_code: print_esc("newlinechar");@+break;
5322 case language_code: print_esc("language");@+break;
5323 case left_hyphen_min_code: print_esc("lefthyphenmin");@+break;
5324 case right_hyphen_min_code: print_esc("righthyphenmin");@+break;
5325 case holding_inserts_code: print_esc("holdinginserts");@+break;
5326 case error_context_lines_code: print_esc("errorcontextlines");@+break;
5327 @/@<Cases for |print_param|@>@/
5328 default:print("[unknown integer parameter!]");
5329 }
5330 }
5331
5332 @ The integer parameter names must be entered into the hash table.
5333
5334 @<Put each...@>=
5335 primitive("pretolerance", assign_int, int_base+pretolerance_code);@/
5336 @!@:pretolerance\_}{\.{\\pretolerance} primitive@>
5337 primitive("tolerance", assign_int, int_base+tolerance_code);@/
5338 @!@:tolerance\_}{\.{\\tolerance} primitive@>
5339 primitive("linepenalty", assign_int, int_base+line_penalty_code);@/
5340 @!@:line\_penalty\_}{\.{\\linepenalty} primitive@>
5341 primitive("hyphenpenalty", assign_int, int_base+hyphen_penalty_code);@/
5342 @!@:hyphen\_penalty\_}{\.{\\hyphenpenalty} primitive@>
5343 primitive("exhyphenpenalty", assign_int, int_base+ex_hyphen_penalty_code);@/
5344 @!@:ex\_hyphen\_penalty\_}{\.{\\exhyphenpenalty} primitive@>
5345 primitive("clubpenalty", assign_int, int_base+club_penalty_code);@/
5346 @!@:club\_penalty\_}{\.{\\clubpenalty} primitive@>
5347 primitive("widowpenalty", assign_int, int_base+widow_penalty_code);@/
5348 @!@:widow\_penalty\_}{\.{\\widowpenalty} primitive@>
5349 primitive("displaywidowpenalty",
5350 assign_int, int_base+display_widow_penalty_code);@/
5351 @!@:display\_widow\_penalty\_}{\.{\\displaywidowpenalty} primitive@>
5352 primitive("brokenpenalty", assign_int, int_base+broken_penalty_code);@/
5353 @!@:broken\_penalty\_}{\.{\\brokenpenalty} primitive@>
5354 primitive("binoppenalty", assign_int, int_base+bin_op_penalty_code);@/
5355 @!@:bin\_op\_penalty\_}{\.{\\binoppenalty} primitive@>
5356 primitive("relpenalty", assign_int, int_base+rel_penalty_code);@/
5357 @!@:rel\_penalty\_}{\.{\\relpenalty} primitive@>
5358 primitive("predisplaypenalty", assign_int, int_base+pre_display_penalty_code);@/
5359 @!@:pre\_display\_penalty\_}{\.{\\predisplaypenalty} primitive@>
5360 primitive("postdisplaypenalty", assign_int, int_base+post_display_penalty_code);@/
5361 @!@:post\_display\_penalty\_}{\.{\\postdisplaypenalty} primitive@>
5362 primitive("interlinepenalty", assign_int, int_base+inter_line_penalty_code);@/
5363 @!@:inter\_line\_penalty\_}{\.{\\interlinepenalty} primitive@>
5364 primitive("doublehyphendemerits",
5365 assign_int, int_base+double_hyphen_demerits_code);@/
5366 @!@:double\_hyphen\_demerits\_}{\.{\\doublehyphendemerits} primitive@>
5367 primitive("finalhyphendemerits",
5368 assign_int, int_base+final_hyphen_demerits_code);@/
5369 @!@:final\_hyphen\_demerits\_}{\.{\\finalhyphendemerits} primitive@>
5370 primitive("adjdemerits", assign_int, int_base+adj_demerits_code);@/
5371 @!@:adj\_demerits\_}{\.{\\adjdemerits} primitive@>
5372 primitive("mag", assign_int, int_base+mag_code);@/
5373 @!@:mag\_}{\.{\\mag} primitive@>
5374 primitive("delimiterfactor", assign_int, int_base+delimiter_factor_code);@/
5375 @!@:delimiter\_factor\_}{\.{\\delimiterfactor} primitive@>
5376 primitive("looseness", assign_int, int_base+looseness_code);@/
5377 @!@:looseness\_}{\.{\\looseness} primitive@>
5378 primitive("time", assign_int, int_base+time_code);@/
5379 @!@:time\_}{\.{\\time} primitive@>
5380 primitive("day", assign_int, int_base+day_code);@/
5381 @!@:day\_}{\.{\\day} primitive@>
5382 primitive("month", assign_int, int_base+month_code);@/
5383 @!@:month\_}{\.{\\month} primitive@>
5384 primitive("year", assign_int, int_base+year_code);@/
5385 @!@:year\_}{\.{\\year} primitive@>
5386 primitive("showboxbreadth", assign_int, int_base+show_box_breadth_code);@/
5387 @!@:show\_box\_breadth\_}{\.{\\showboxbreadth} primitive@>
5388 primitive("showboxdepth", assign_int, int_base+show_box_depth_code);@/
5389 @!@:show\_box\_depth\_}{\.{\\showboxdepth} primitive@>
5390 primitive("hbadness", assign_int, int_base+hbadness_code);@/
5391 @!@:hbadness\_}{\.{\\hbadness} primitive@>
5392 primitive("vbadness", assign_int, int_base+vbadness_code);@/
5393 @!@:vbadness\_}{\.{\\vbadness} primitive@>
5394 primitive("pausing", assign_int, int_base+pausing_code);@/
5395 @!@:pausing\_}{\.{\\pausing} primitive@>
5396 primitive("tracingonline", assign_int, int_base+tracing_online_code);@/
5397 @!@:tracing\_online\_}{\.{\\tracingonline} primitive@>
5398 primitive("tracingmacros", assign_int, int_base+tracing_macros_code);@/
5399 @!@:tracing\_macros\_}{\.{\\tracingmacros} primitive@>
5400 primitive("tracingstats", assign_int, int_base+tracing_stats_code);@/
5401 @!@:tracing\_stats\_}{\.{\\tracingstats} primitive@>
5402 primitive("tracingparagraphs", assign_int, int_base+tracing_paragraphs_code);@/
5403 @!@:tracing\_paragraphs\_}{\.{\\tracingparagraphs} primitive@>
5404 primitive("tracingpages", assign_int, int_base+tracing_pages_code);@/
5405 @!@:tracing\_pages\_}{\.{\\tracingpages} primitive@>
5406 primitive("tracingoutput", assign_int, int_base+tracing_output_code);@/
5407 @!@:tracing\_output\_}{\.{\\tracingoutput} primitive@>
5408 primitive("tracinglostchars", assign_int, int_base+tracing_lost_chars_code);@/
5409 @!@:tracing\_lost\_chars\_}{\.{\\tracinglostchars} primitive@>
5410 primitive("tracingcommands", assign_int, int_base+tracing_commands_code);@/
5411 @!@:tracing\_commands\_}{\.{\\tracingcommands} primitive@>
5412 primitive("tracingrestores", assign_int, int_base+tracing_restores_code);@/
5413 @!@:tracing\_restores\_}{\.{\\tracingrestores} primitive@>
5414 primitive("uchyph", assign_int, int_base+uc_hyph_code);@/
5415 @!@:uc\_hyph\_}{\.{\\uchyph} primitive@>
5416 primitive("outputpenalty", assign_int, int_base+output_penalty_code);@/
5417 @!@:output\_penalty\_}{\.{\\outputpenalty} primitive@>
5418 primitive("maxdeadcycles", assign_int, int_base+max_dead_cycles_code);@/
5419 @!@:max\_dead\_cycles\_}{\.{\\maxdeadcycles} primitive@>
5420 primitive("hangafter", assign_int, int_base+hang_after_code);@/
5421 @!@:hang\_after\_}{\.{\\hangafter} primitive@>
5422 primitive("floatingpenalty", assign_int, int_base+floating_penalty_code);@/
5423 @!@:floating\_penalty\_}{\.{\\floatingpenalty} primitive@>
5424 primitive("globaldefs", assign_int, int_base+global_defs_code);@/
5425 @!@:global\_defs\_}{\.{\\globaldefs} primitive@>
5426 primitive("fam", assign_int, int_base+cur_fam_code);@/
5427 @!@:fam\_}{\.{\\fam} primitive@>
5428 primitive("escapechar", assign_int, int_base+escape_char_code);@/
5429 @!@:escape\_char\_}{\.{\\escapechar} primitive@>
5430 primitive("defaulthyphenchar", assign_int, int_base+default_hyphen_char_code);@/
5431 @!@:default\_hyphen\_char\_}{\.{\\defaulthyphenchar} primitive@>
5432 primitive("defaultskewchar", assign_int, int_base+default_skew_char_code);@/
5433 @!@:default\_skew\_char\_}{\.{\\defaultskewchar} primitive@>
5434 primitive("endlinechar", assign_int, int_base+end_line_char_code);@/
5435 @!@:end\_line\_char\_}{\.{\\endlinechar} primitive@>
5436 primitive("newlinechar", assign_int, int_base+new_line_char_code);@/
5437 @!@:new\_line\_char\_}{\.{\\newlinechar} primitive@>
5438 primitive("language", assign_int, int_base+language_code);@/
5439 @!@:language\_}{\.{\\language} primitive@>
5440 primitive("lefthyphenmin", assign_int, int_base+left_hyphen_min_code);@/
5441 @!@:left\_hyphen\_min\_}{\.{\\lefthyphenmin} primitive@>
5442 primitive("righthyphenmin", assign_int, int_base+right_hyphen_min_code);@/
5443 @!@:right\_hyphen\_min\_}{\.{\\righthyphenmin} primitive@>
5444 primitive("holdinginserts", assign_int, int_base+holding_inserts_code);@/
5445 @!@:holding\_inserts\_}{\.{\\holdinginserts} primitive@>
5446 primitive("errorcontextlines", assign_int, int_base+error_context_lines_code);@/
5447 @!@:error\_context\_lines\_}{\.{\\errorcontextlines} primitive@>
5448
5449 @ @<Cases of |print_cmd_chr|...@>=
5450 case assign_int: if (chr_code < count_base) print_param(chr_code-int_base);
5451 else{@+print_esc("count");print_int(chr_code-count_base);
5452 } @+break;
5453
5454 @ The integer parameters should really be initialized by a macro package;
5455 the following initialization does the minimum to keep \TeX\ from
5456 complete failure.
5457 @^null delimiter@>
5458
5459 @<Initialize table entries...@>=
5460 for (k=int_base; k<=del_code_base-1; k++) eqtb[k].i=0;
5461 mag=1000;tolerance=10000;hang_after=1;max_dead_cycles=25;
5462 escape_char='\\';end_line_char=carriage_return;
5463 for (k=0; k<=255; k++) del_code(k)=-1;
5464 del_code('.')=0; /*this null delimiter is used in error recovery*/
5465
5466 @ The following procedure, which is called just before \TeX\ initializes its
5467 input and output, establishes the initial values of the date and time.
5468 This does include too, for system integrators, the creation date and
5469 the reference moment for the timer---\Prote\ extensions. If the system
5470 supports environment variables, if |FORCE_SOURCE_DATE| is set to $1$ and
5471 |SOURCE_DATE_EPOCH| is set, the date related values: year, month, day
5472 and time, including creation date, will be taken relative from the value
5473 defined by |SOURCE_DATE_EPOCH|.
5474 @^creation date@>
5475 @^reference time@>
5476 @^system dependencies@>
5477 \TeX\ Live calls |tl_now| to obtain the current time as a |tm| structure.
5478 @p static void fix_date_and_time(void)
5479 {@+ struct tm *t=tl_now();
5480 time=sys_time= t->tm_hour*60+t->tm_min;/*minutes since midnight*/
5481 day=sys_day= t->tm_mday;/*day of the month*/
5482 month=sys_month=t->tm_mon+1;/*month of the year*/
5483 year=sys_year=t->tm_year+1900;/*Anno Domini*/
5484 }
5485
5486 @ @<Show equivalent |n|, in region 5@>=
5487 {@+if (n < count_base) print_param(n-int_base);
5488 else if (n < del_code_base)
5489 {@+print_esc("count");print_int(n-count_base);
5490 }
5491 else{@+print_esc("delcode");print_int(n-del_code_base);
5492 }
5493 print_char('=');print_int(eqtb[n].i);
5494 }
5495
5496 @ @<Set variable |c| to the current escape character@>=c=escape_char
5497
5498 @ @<Character |s| is the current new-line character@>=s==new_line_char
5499
5500 @ \TeX\ is occasionally supposed to print diagnostic information that
5501 goes only into the transcript file, unless |tracing_online| is positive.
5502 Here are two routines that adjust the destination of print commands:
5503
5504 @p static void begin_diagnostic(void) /*prepare to do some tracing*/
5505 {@+old_setting=selector;
5506 if ((tracing_online <= 0)&&(selector==term_and_log))
5507 {@+decr(selector);
5508 if (history==spotless) history=warning_issued;
5509 }
5510 }
5511 @#
5512 static void end_diagnostic(bool @!blank_line)
5513 /*restore proper conditions after tracing*/
5514 {@+print_nl("");
5515 if (blank_line) print_ln();
5516 selector=old_setting;
5517 }
5518
5519 @ Of course we had better declare a few more global variables, if the previous
5520 routines are going to work.
5521
5522 @<Glob...@>=
5523 static int @!old_setting;
5524 static int @!sys_time, @!sys_day, @!sys_month, @!sys_year;
5525 /*date and time supplied by external system*/
5526
5527 @ The final region of |eqtb| contains the dimension parameters defined
5528 here, and the 256 \.{\\dimen} registers.
5529
5530 @d par_indent_code 0 /*indentation of paragraphs*/
5531 @d math_surround_code 1 /*space around math in text*/
5532 @d line_skip_limit_code 2 /*threshold for |line_skip| instead of |baseline_skip|*/
5533 @d hsize_code 3 /*line width in horizontal mode*/
5534 @d vsize_code 4 /*page height in vertical mode*/
5535 @d max_depth_code 5 /*maximum depth of boxes on main pages*/
5536 @d split_max_depth_code 6 /*maximum depth of boxes on split pages*/
5537 @d box_max_depth_code 7 /*maximum depth of explicit vboxes*/
5538 @d hfuzz_code 8 /*tolerance for overfull hbox messages*/
5539 @d vfuzz_code 9 /*tolerance for overfull vbox messages*/
5540 @d delimiter_shortfall_code 10 /*maximum amount uncovered by variable delimiters*/
5541 @d null_delimiter_space_code 11 /*blank space in null delimiters*/
5542 @d script_space_code 12 /*extra space after subscript or superscript*/
5543 @d pre_display_size_code 13 /*length of text preceding a display*/
5544 @d display_width_code 14 /*length of line for displayed equation*/
5545 @d display_indent_code 15 /*indentation of line for displayed equation*/
5546 @d overfull_rule_code 16 /*width of rule that identifies overfull hboxes*/
5547 @d hang_indent_code 17 /*amount of hanging indentation*/
5548 @d h_offset_code 18 /*amount of horizontal offset when shipping pages out*/
5549 @d v_offset_code 19 /*amount of vertical offset when shipping pages out*/
5550 @d emergency_stretch_code 20 /*reduces badnesses on final pass of line-breaking*/
5551 @d page_width_code 21 /*current paper page width*/
5552 @d page_height_code 22 /*current paper page height*/
5553 @d dimen_pars (pdftex_last_dimen_code+1) /*total number of dimension parameters*/
5554 @d scaled_base (dimen_base+dimen_pars)
5555 /*table of 256 user-defined \.{\\dimen} registers*/
5556 @d eqtb_size (scaled_base+255) /*largest subscript of |eqtb|*/
5557 @#
5558 @d dimen(A) eqtb[scaled_base+A].sc
5559 @d dimen_par(A) eqtb[dimen_base+A].sc /*a scaled quantity*/
5560 @d par_indent dimen_par(par_indent_code)
5561 @d math_surround dimen_par(math_surround_code)
5562 @d line_skip_limit dimen_par(line_skip_limit_code)
5563 @d hsize dimen_par(hsize_code)
5564 @d vsize dimen_par(vsize_code)
5565 @d max_depth dimen_par(max_depth_code)
5566 @d split_max_depth dimen_par(split_max_depth_code)
5567 @d box_max_depth dimen_par(box_max_depth_code)
5568 @d hfuzz dimen_par(hfuzz_code)
5569 @d vfuzz dimen_par(vfuzz_code)
5570 @d delimiter_shortfall dimen_par(delimiter_shortfall_code)
5571 @d null_delimiter_space dimen_par(null_delimiter_space_code)
5572 @d script_space dimen_par(script_space_code)
5573 @d pre_display_size dimen_par(pre_display_size_code)
5574 @d display_width dimen_par(display_width_code)
5575 @d display_indent dimen_par(display_indent_code)
5576 @d overfull_rule dimen_par(overfull_rule_code)
5577 @d hang_indent dimen_par(hang_indent_code)
5578 @d h_offset dimen_par(h_offset_code)
5579 @d v_offset dimen_par(v_offset_code)
5580 @d emergency_stretch dimen_par(emergency_stretch_code)
5581 @d page_height dimen_par(page_height_code)
5582
5583 @p static void print_length_param(int @!n)
5584 {@+switch (n) {
5585 case par_indent_code: print_esc("parindent");@+break;
5586 case math_surround_code: print_esc("mathsurround");@+break;
5587 case line_skip_limit_code: print_esc("lineskiplimit");@+break;
5588 case hsize_code: print_esc("hsize");@+break;
5589 case vsize_code: print_esc("vsize");@+break;
5590 case max_depth_code: print_esc("maxdepth");@+break;
5591 case split_max_depth_code: print_esc("splitmaxdepth");@+break;
5592 case box_max_depth_code: print_esc("boxmaxdepth");@+break;
5593 case hfuzz_code: print_esc("hfuzz");@+break;
5594 case vfuzz_code: print_esc("vfuzz");@+break;
5595 case delimiter_shortfall_code: print_esc("delimitershortfall");@+break;
5596 case null_delimiter_space_code: print_esc("nulldelimiterspace");@+break;
5597 case script_space_code: print_esc("scriptspace");@+break;
5598 case pre_display_size_code: print_esc("predisplaysize");@+break;
5599 case display_width_code: print_esc("displaywidth");@+break;
5600 case display_indent_code: print_esc("displayindent");@+break;
5601 case overfull_rule_code: print_esc("overfullrule");@+break;
5602 case hang_indent_code: print_esc("hangindent");@+break;
5603 case h_offset_code: print_esc("hoffset");@+break;
5604 case v_offset_code: print_esc("voffset");@+break;
5605 case emergency_stretch_code: print_esc("emergencystretch");@+break;
5606 case page_width_code:
5607 if (pdf_on) print_esc("pdfpagewidth");
5608 else print_esc("pagewidth");
5609 @+break;
5610 case page_height_code:
5611 if (pdf_on) print_esc("pdfpageheight");
5612 else print_esc("pageheight");
5613 @+break;
5614 @<Cases for |print_lenght_param|@>@;
5615 default:print("[unknown dimen parameter!]");
5616 }
5617 }
5618
5619 @ @<Put each...@>=
5620 primitive("parindent", assign_dimen, dimen_base+par_indent_code);@/
5621 @!@:par\_indent\_}{\.{\\parindent} primitive@>
5622 primitive("mathsurround", assign_dimen, dimen_base+math_surround_code);@/
5623 @!@:math\_surround\_}{\.{\\mathsurround} primitive@>
5624 primitive("lineskiplimit", assign_dimen, dimen_base+line_skip_limit_code);@/
5625 @!@:line\_skip\_limit\_}{\.{\\lineskiplimit} primitive@>
5626 primitive("hsize", assign_dimen, dimen_base+hsize_code);@/
5627 @!@:hsize\_}{\.{\\hsize} primitive@>
5628 primitive("vsize", assign_dimen, dimen_base+vsize_code);@/
5629 @!@:vsize\_}{\.{\\vsize} primitive@>
5630 primitive("maxdepth", assign_dimen, dimen_base+max_depth_code);@/
5631 @!@:max\_depth\_}{\.{\\maxdepth} primitive@>
5632 primitive("splitmaxdepth", assign_dimen, dimen_base+split_max_depth_code);@/
5633 @!@:split\_max\_depth\_}{\.{\\splitmaxdepth} primitive@>
5634 primitive("boxmaxdepth", assign_dimen, dimen_base+box_max_depth_code);@/
5635 @!@:box\_max\_depth\_}{\.{\\boxmaxdepth} primitive@>
5636 primitive("hfuzz", assign_dimen, dimen_base+hfuzz_code);@/
5637 @!@:hfuzz\_}{\.{\\hfuzz} primitive@>
5638 primitive("vfuzz", assign_dimen, dimen_base+vfuzz_code);@/
5639 @!@:vfuzz\_}{\.{\\vfuzz} primitive@>
5640 primitive("delimitershortfall",
5641 assign_dimen, dimen_base+delimiter_shortfall_code);@/
5642 @!@:delimiter\_shortfall\_}{\.{\\delimitershortfall} primitive@>
5643 primitive("nulldelimiterspace",
5644 assign_dimen, dimen_base+null_delimiter_space_code);@/
5645 @!@:null\_delimiter\_space\_}{\.{\\nulldelimiterspace} primitive@>
5646 primitive("scriptspace", assign_dimen, dimen_base+script_space_code);@/
5647 @!@:script\_space\_}{\.{\\scriptspace} primitive@>
5648 primitive("predisplaysize", assign_dimen, dimen_base+pre_display_size_code);@/
5649 @!@:pre\_display\_size\_}{\.{\\predisplaysize} primitive@>
5650 primitive("displaywidth", assign_dimen, dimen_base+display_width_code);@/
5651 @!@:display\_width\_}{\.{\\displaywidth} primitive@>
5652 primitive("displayindent", assign_dimen, dimen_base+display_indent_code);@/
5653 @!@:display\_indent\_}{\.{\\displayindent} primitive@>
5654 primitive("overfullrule", assign_dimen, dimen_base+overfull_rule_code);@/
5655 @!@:overfull\_rule\_}{\.{\\overfullrule} primitive@>
5656 primitive("hangindent", assign_dimen, dimen_base+hang_indent_code);@/
5657 @!@:hang\_indent\_}{\.{\\hangindent} primitive@>
5658 primitive("hoffset", assign_dimen, dimen_base+h_offset_code);@/
5659 @!@:h\_offset\_}{\.{\\hoffset} primitive@>
5660 primitive("voffset", assign_dimen, dimen_base+v_offset_code);@/
5661 @!@:v\_offset\_}{\.{\\voffset} primitive@>
5662 primitive("emergencystretch", assign_dimen, dimen_base+emergency_stretch_code);@/
5663 @!@:emergency\_stretch\_}{\.{\\emergencystretch} primitive@>
5664
5665 @ @<Cases of |print_cmd_chr|...@>=
5666 case assign_dimen: if (chr_code < scaled_base)
5667 print_length_param(chr_code-dimen_base);
5668 else{@+print_esc("dimen");print_int(chr_code-scaled_base);
5669 } @+break;
5670
5671 @ @<Initialize table entries...@>=
5672 for (k=dimen_base; k<=eqtb_size; k++) eqtb[k].sc=0;
5673
5674 @ @<Show equivalent |n|, in region 6@>=
5675 {@+if (n < scaled_base) print_length_param(n-dimen_base);
5676 else{@+print_esc("dimen");print_int(n-scaled_base);
5677 }
5678 print_char('=');print_scaled(eqtb[n].sc);print("pt");
5679 }
5680
5681 @ Here is a procedure that displays the contents of |eqtb[n]|
5682 symbolically.
5683
5684 @p @t\4@>@<Declare the procedure called |print_cmd_chr|@>@;@/
5685 #ifdef @!STAT
5686 static void show_eqtb(pointer @!n)
5687 {@+if (n < active_base) print_char('?'); /*this can't happen*/
5688 else if (n < glue_base) @<Show equivalent |n|, in region 1 or 2@>@;
5689 else if (n < local_base) @<Show equivalent |n|, in region 3@>@;
5690 else if (n < int_base) @<Show equivalent |n|, in region 4@>@;
5691 else if (n < dimen_base) @<Show equivalent |n|, in region 5@>@;
5692 else if (n <= eqtb_size) @<Show equivalent |n|, in region 6@>@;
5693 else print_char('?'); /*this can't happen either*/
5694 }
5695 #endif
5696
5697 @ The last two regions of |eqtb| have fullword values instead of the
5698 three fields |eq_level|, |eq_type|, and |equiv|. An |eq_type| is unnecessary,
5699 but \TeX\ needs to store the |eq_level| information in another array
5700 called |xeq_level|.
5701
5702 @<Glob...@>=
5703 static memory_word @!eqtb0[eqtb_size-active_base+1],
5704 *const @!eqtb = @!eqtb0-active_base;
5705 static quarterword @!xeq_level0[eqtb_size-int_base+1],
5706 *const @!xeq_level = @!xeq_level0-int_base;
5707
5708 @ @<Set init...@>=
5709 for (k=int_base; k<=eqtb_size; k++) xeq_level[k]=level_one;
5710
5711 @ When the debugging routine |search_mem| is looking for pointers having a
5712 given value, it is interested only in regions 1 to~3 of~|eqtb|, and in the
5713 first part of region~4.
5714
5715 @<Search |eqtb| for equivalents equal to |p|@>=
5716 for (q=active_base; q<=box_base+255; q++)
5717 {@+if (equiv(q)==p)
5718 {@+print_nl("EQUIV(");print_int(q);print_char(')');
5719 }
5720 }
5721
5722 @* The hash table.
5723 Control sequences are stored and retrieved by means of a fairly standard hash
5724 table algorithm called the method of ``coalescing lists'' (cf.\ Algorithm 6.4C
5725 in {\sl The Art of Computer Programming\/}). Once a control sequence enters the
5726 table, it is never removed, because there are complicated situations
5727 involving \.{\\gdef} where the removal of a control sequence at the end of
5728 a group would be a mistake preventable only by the introduction of a
5729 complicated reference-count mechanism.
5730
5731 The actual sequence of letters forming a control sequence identifier is
5732 stored in the |str_pool| array together with all the other strings. An
5733 auxiliary array |hash| consists of items with two halfword fields per
5734 word. The first of these, called |next(p)|, points to the next identifier
5735 belonging to the same coalesced list as the identifier corresponding to~|p|;
5736 and the other, called |text(p)|, points to the |str_start| entry for
5737 |p|'s identifier. If position~|p| of the hash table is empty, we have
5738 |text(p)==0|; if position |p| is either empty or the end of a coalesced
5739 hash list, we have |next(p)==0|. An auxiliary pointer variable called
5740 |hash_used| is maintained in such a way that all locations |p >= hash_used|
5741 are nonempty. The global variable |cs_count| tells how many multiletter
5742 control sequences have been defined, if statistics are being kept.
5743
5744 A global boolean variable called |no_new_control_sequence| is set to
5745 |true| during the time that new hash table entries are forbidden.
5746
5747 @d next(A) hash[A].lh /*link for coalesced lists*/
5748 @d text(A) hash[A].rh /*string number for control sequence name*/
5749 @d hash_is_full (hash_used==hash_base) /*test if all positions are occupied*/
5750 @d font_id_text(A) text(font_id_base+A) /*a frozen font identifier's name*/
5751
5752 @<Glob...@>=
5753 static two_halves @!hash0[undefined_control_sequence-hash_base],
5754 *const @!hash = @!hash0-hash_base;
5755 /*the hash table*/
5756 static pointer @!hash_used; /*allocation pointer for |hash|*/
5757 static bool @!no_new_control_sequence; /*are new identifiers legal?*/
5758 static int @!cs_count; /*total number of known identifiers*/
5759
5760 @ @<Set init...@>=
5761 no_new_control_sequence=true; /*new identifiers are usually forbidden*/
5762 next(hash_base)=0;text(hash_base)=0;
5763 for (k=hash_base+1; k<=undefined_control_sequence-1; k++) hash[k]=hash[hash_base];
5764
5765 @ @<Initialize table entries...@>=
5766 hash_used=frozen_control_sequence; /*nothing is used*/
5767 cs_count=0;
5768 eq_type(frozen_dont_expand)=dont_expand;
5769 text(frozen_dont_expand)=s_no("notexpanded:");
5770 @.notexpanded:@>
5771
5772 @ Here is the subroutine that searches the hash table for an identifier
5773 that matches a given string of length |l > 1| appearing in |buffer[j dotdot
5774 (j+l-1)]|. If the identifier is found, the corresponding hash table address
5775 is returned. Otherwise, if the global variable |no_new_control_sequence|
5776 is |true|, the dummy address |undefined_control_sequence| is returned.
5777 Otherwise the identifier is inserted into the hash table and its location
5778 is returned.
5779
5780 @p static pointer id_lookup(int @!j, int @!l) /*search the hash table*/
5781 {@+ /*go here if you found it*/
5782 int h; /*hash code*/
5783 int @!d; /*number of characters in incomplete current string*/
5784 pointer @!p; /*index in |hash| array*/
5785 int @!k; /*index in |buffer| array*/
5786 @<Compute the hash code |h|@>;
5787 p=h+hash_base; /*we start searching here; note that |0 <= h < hash_prime|*/
5788 loop@+{@+if (text(p) > 0) if (length(text(p))==l)
5789 if (str_eq_buf(text(p), j)) goto found;
5790 if (next(p)==0)
5791 {@+if (no_new_control_sequence)
5792 p=undefined_control_sequence;
5793 else@<Insert a new control sequence after |p|, then make |p| point to
5794 it@>;
5795 goto found;
5796 }
5797 p=next(p);
5798 }
5799 found: return p;
5800 }
5801
5802 @ @<Insert a new control...@>=
5803 {@+if (text(p) > 0)
5804 {@+@/do@+{if (hash_is_full) overflow("hash size", hash_size);
5805 @:TeX capacity exceeded hash size}{\quad hash size@>
5806 decr(hash_used);
5807 }@+ while (!(text(hash_used)==0)); /*search for an empty location in |hash|*/
5808 next(p)=hash_used;p=hash_used;
5809 }
5810 str_room(l);d=cur_length;
5811 while (pool_ptr > str_start[str_ptr])
5812 {@+decr(pool_ptr);str_pool[pool_ptr+l]=str_pool[pool_ptr];
5813 } /*move current string up to make room for another*/
5814 for (k=j; k<=j+l-1; k++) append_char(buffer[k]);
5815 text(p)=make_string();pool_ptr=pool_ptr+d;
5816 #ifdef @!STAT
5817 incr(cs_count);
5818 #endif
5819 @;@/
5820 }
5821
5822 @ The value of |hash_prime| should be roughly 85\pct! of |hash_size|, and it
5823 should be a prime number. The theory of hashing tells us to expect fewer
5824 than two table probes, on the average, when the search is successful.
5825 [See J.~S. Vitter, {\sl Journal of the ACM\/ \bf30} (1983), 231--258.]
5826 @^Vitter, Jeffrey Scott@>
5827
5828 @<Compute the hash code |h|@>=
5829 h=buffer[j];
5830 for (k=j+1; k<=j+l-1; k++)
5831 {@+h=h+h+buffer[k];
5832 while (h >= hash_prime) h=h-hash_prime;
5833 }
5834
5835 @ Single-character control sequences do not need to be looked up in a hash
5836 table, since we can use the character code itself as a direct address.
5837 The procedure |print_cs| prints the name of a control sequence, given
5838 a pointer to its address in |eqtb|. A space is printed after the name
5839 unless it is a single nonletter or an active character. This procedure
5840 might be invoked with invalid data, so it is ``extra robust.'' The
5841 individual characters must be printed one at a time using |print|, since
5842 they may be unprintable.
5843
5844 @<Basic printing...@>=
5845 static void print_cs(int @!p) /*prints a purported control sequence*/
5846 {@+if (p < hash_base) /*single character*/
5847 if (p >= single_base)
5848 if (p==null_cs)
5849 {@+print_esc("csname");print_esc("endcsname");print_char(' ');
5850 }
5851 else{@+printn_esc(p-single_base);
5852 if (cat_code(p-single_base)==letter) print_char(' ');
5853 }
5854 else if (p < active_base) print_esc("IMPOSSIBLE.");
5855 @.IMPOSSIBLE@>
5856 else printn(p-active_base);
5857 else if (p >= undefined_control_sequence) print_esc("IMPOSSIBLE.");
5858 else if ((text(p) < 0)||(text(p) >= str_ptr)) print_esc("NONEXISTENT.");
5859 @.NONEXISTENT@>
5860 else{@+if (p==frozen_primitive) print_esc("primitive");
5861 printn_esc(text(p));print_char(' ');
5862 }
5863 }
5864
5865 @ Here is a similar procedure; it avoids the error checks, and it never
5866 prints a space after the control sequence.
5867
5868 @<Basic printing procedures@>=
5869 static void sprint_cs(pointer @!p) /*prints a control sequence*/
5870 {@+if (p < hash_base)
5871 if (p < single_base) printn(p-active_base);
5872 else if (p < null_cs) printn_esc(p-single_base);
5873 else{@+print_esc("csname");print_esc("endcsname");
5874 }
5875 else printn_esc(text(p));
5876 }
5877
5878 @ We need to put \TeX's ``primitive'' control sequences into the hash
5879 table, together with their command code (which will be the |eq_type|)
5880 and an operand (which will be the |equiv|). The |primitive| procedure
5881 does this, in a way that no \TeX\ user can. The global value |cur_val|
5882 contains the new |eqtb| pointer after |primitive| has acted.
5883
5884 @p
5885 #ifdef @!INIT
5886 static void primitive(char *@!str, quarterword @!c, halfword @!o)
5887 {@+str_number s=s_no(str);
5888 int k; /*index into |str_pool|*/
5889 int @!j; /*index into |buffer|*/
5890 small_number @!l; /*length of the string*/
5891 pointer @!p; /*pointer in |ROM|*/
5892 if (s < 256) cur_val=s+single_base;
5893 else{@+k=str_start[s];l=str_start[s+1]-k;
5894 /*we will move |s| into the (possibly non-empty) |buffer|*/
5895 if (first+l > buf_size+1)
5896 overflow("buffer size", buf_size);
5897 @:TeX capacity exceeded buffer size}{\quad buffer size@>
5898 for (j=0; j<=l-1; j++) buffer[first+j]=so(str_pool[k+j]);
5899 cur_val=id_lookup(first, l); /*|no_new_control_sequence| is |false|*/
5900 flush_string;text(cur_val)=s; /*we don't want to have the string twice*/
5901 }
5902 eq_level(cur_val)=level_one;eq_type(cur_val)=c;equiv(cur_val)=o;
5903 @<Add primitive definition to the |ROM| array@>;
5904 }
5905 #endif
5906
5907 @ Many of \TeX's primitives need no |equiv|, since they are identifiable
5908 by their |eq_type| alone. These primitives are loaded into the hash table
5909 as follows:
5910
5911 @<Put each of \TeX's primitives into the hash table@>=
5912 primitive(" ", ex_space, 0);@/
5913 @!@:Single-character primitives /}{\quad\.{\\\ }@>
5914 primitive("/", ital_corr, 0);@/
5915 @!@:Single-character primitives /}{\quad\.{\\/}@>
5916 primitive("accent", accent, 0);@/
5917 @!@:accent\_}{\.{\\accent} primitive@>
5918 primitive("advance", advance, 0);@/
5919 @!@:advance\_}{\.{\\advance} primitive@>
5920 primitive("afterassignment", after_assignment, 0);@/
5921 @!@:after\_assignment\_}{\.{\\afterassignment} primitive@>
5922 primitive("aftergroup", after_group, 0);@/
5923 @!@:after\_group\_}{\.{\\aftergroup} primitive@>
5924 primitive("begingroup", begin_group, 0);@/
5925 @!@:begin\_group\_}{\.{\\begingroup} primitive@>
5926 primitive("char", char_num, 0);@/
5927 @!@:char\_}{\.{\\char} primitive@>
5928 primitive("csname", cs_name, 0);@/
5929 @!@:cs\_name\_}{\.{\\csname} primitive@>
5930 primitive("delimiter", delim_num, 0);@/
5931 @!@:delimiter\_}{\.{\\delimiter} primitive@>
5932 primitive("divide", divide, 0);@/
5933 @!@:divide\_}{\.{\\divide} primitive@>
5934 primitive("endcsname", end_cs_name, 0);@/
5935 @!@:end\_cs\_name\_}{\.{\\endcsname} primitive@>
5936 primitive("endgroup", end_group, 0);
5937 @!@:end\_group\_}{\.{\\endgroup} primitive@>
5938 text(frozen_end_group)=text(cur_val);eqtb[frozen_end_group]=eqtb[cur_val];@/
5939 primitive("expandafter", expand_after, 0);@/
5940 @!@:expand\_after\_}{\.{\\expandafter} primitive@>
5941 primitive("font", def_font, 0);@/
5942 @!@:font\_}{\.{\\font} primitive@>
5943 primitive("fontdimen", assign_font_dimen, 0);@/
5944 @!@:font\_dimen\_}{\.{\\fontdimen} primitive@>
5945 primitive("halign", halign, 0);@/
5946 @!@:halign\_}{\.{\\halign} primitive@>
5947 primitive("hrule", hrule, 0);@/
5948 @!@:hrule\_}{\.{\\hrule} primitive@>
5949 primitive("ignorespaces", ignore_spaces, 0);@/
5950 @!@:ignore\_spaces\_}{\.{\\ignorespaces} primitive@>
5951 primitive("insert", insert, 0);@/
5952 @!@:insert\_}{\.{\\insert} primitive@>
5953 primitive("mark", mark, 0);@/
5954 @!@:mark\_}{\.{\\mark} primitive@>
5955 primitive("mathaccent", math_accent, 0);@/
5956 @!@:math\_accent\_}{\.{\\mathaccent} primitive@>
5957 primitive("mathchar", math_char_num, 0);@/
5958 @!@:math\_char\_}{\.{\\mathchar} primitive@>
5959 primitive("mathchoice", math_choice, 0);@/
5960 @!@:math\_choice\_}{\.{\\mathchoice} primitive@>
5961 primitive("multiply", multiply, 0);@/
5962 @!@:multiply\_}{\.{\\multiply} primitive@>
5963 primitive("noalign", no_align, 0);@/
5964 @!@:no\_align\_}{\.{\\noalign} primitive@>
5965 primitive("noboundary", no_boundary, 0);@/
5966 @!@:no\_boundary\_}{\.{\\noboundary} primitive@>
5967 primitive("noexpand", no_expand, 0);@/
5968 @!@:no\_expand\_}{\.{\\noexpand} primitive@>
5969 primitive("nonscript", non_script, 0);@/
5970 @!@:non\_script\_}{\.{\\nonscript} primitive@>
5971 primitive("omit", omit, 0);@/
5972 @!@:omit\_}{\.{\\omit} primitive@>
5973 primitive("parshape", set_shape, par_shape_loc);@/
5974 @!@:par\_shape\_}{\.{\\parshape} primitive@>
5975 primitive("penalty", break_penalty, 0);@/
5976 @!@:penalty\_}{\.{\\penalty} primitive@>
5977 primitive("prevgraf", set_prev_graf, 0);@/
5978 @!@:prev\_graf\_}{\.{\\prevgraf} primitive@>
5979 primitive("radical", radical, 0);@/
5980 @!@:radical\_}{\.{\\radical} primitive@>
5981 primitive("read", read_to_cs, 0);@/
5982 @!@:read\_}{\.{\\read} primitive@>
5983 primitive("relax", relax, 256); /*cf.\ |scan_file_name|*/
5984 @!@:relax\_}{\.{\\relax} primitive@>
5985 text(frozen_relax)=text(cur_val);eqtb[frozen_relax]=eqtb[cur_val];@/
5986 primitive("setbox", set_box, 0);@/
5987 @!@:set\_box\_}{\.{\\setbox} primitive@>
5988 primitive("the", the, 0);@/
5989 @!@:the\_}{\.{\\the} primitive@>
5990 primitive("toks", toks_register, mem_bot);@/
5991 @!@:toks\_}{\.{\\toks} primitive@>
5992 primitive("vadjust", vadjust, 0);@/
5993 @!@:vadjust\_}{\.{\\vadjust} primitive@>
5994 primitive("valign", valign, 0);@/
5995 @!@:valign\_}{\.{\\valign} primitive@>
5996 primitive("vcenter", vcenter, 0);@/
5997 @!@:vcenter\_}{\.{\\vcenter} primitive@>
5998 primitive("vrule", vrule, 0);@/
5999 @!@:vrule\_}{\.{\\vrule} primitive@>
6000
6001 @ Each primitive has a corresponding inverse, so that it is possible to
6002 display the cryptic numeric contents of |eqtb| in symbolic form.
6003 Every call of |primitive| in this program is therefore accompanied by some
6004 straightforward code that forms part of the |print_cmd_chr| routine
6005 below.
6006
6007 @<Cases of |print_cmd_chr|...@>=
6008 case accent: print_esc("accent");@+break;
6009 case advance: print_esc("advance");@+break;
6010 case after_assignment: print_esc("afterassignment");@+break;
6011 case after_group: print_esc("aftergroup");@+break;
6012 case assign_font_dimen: print_esc("fontdimen");@+break;
6013 case begin_group: print_esc("begingroup");@+break;
6014 case break_penalty: print_esc("penalty");@+break;
6015 case char_num: print_esc("char");@+break;
6016 case cs_name: print_esc("csname");@+break;
6017 case def_font: print_esc("font");@+break;
6018 case delim_num: print_esc("delimiter");@+break;
6019 case divide: print_esc("divide");@+break;
6020 case end_cs_name: print_esc("endcsname");@+break;
6021 case end_group: print_esc("endgroup");@+break;
6022 case ex_space: print_esc(" ");@+break;
6023 case expand_after: switch (chr_code) {
6024 case 0: print_esc("expandafter");@+break;
6025 @/@<Cases of |expandafter| for |print_cmd_chr|@>@/
6026 } @+break; /*there are no other cases*/
6027 case halign: print_esc("halign");@+break;
6028 case hrule: print_esc("hrule");@+break;
6029 case ignore_spaces: print_esc("ignorespaces");@+break;
6030 case insert: print_esc("insert");@+break;
6031 case ital_corr: print_esc("/");@+break;
6032 case mark: {@+print_esc("mark");
6033 if (chr_code > 0) print_char('s');
6034 } @+break;
6035 case math_accent: print_esc("mathaccent");@+break;
6036 case math_char_num: print_esc("mathchar");@+break;
6037 case math_choice: print_esc("mathchoice");@+break;
6038 case multiply: print_esc("multiply");@+break;
6039 case no_align: print_esc("noalign");@+break;
6040 case no_boundary: print_esc("noboundary");@+break;
6041 case no_expand: print_esc("noexpand");@+break;
6042 case non_script: print_esc("nonscript");@+break;
6043 case omit: print_esc("omit");@+break;
6044 case radical: print_esc("radical");@+break;
6045 case read_to_cs: if (chr_code==0) print_esc("read")
6046 @<Cases of |read| for |print_cmd_chr|@>;@+break;
6047 case relax: print_esc("relax");@+break;
6048 case set_box: print_esc("setbox");@+break;
6049 case set_prev_graf: print_esc("prevgraf");@+break;
6050 case set_shape: switch (chr_code) {
6051 case par_shape_loc: print_esc("parshape");@+break;
6052 @<Cases of |set_shape| for |print_cmd_chr|@>@;@/
6053 } @+break; /*there are no other cases*/
6054 case the: if (chr_code==0) print_esc("the")
6055 @<Cases of |the| for |print_cmd_chr|@>;@+break;
6056 case toks_register: @<Cases of |toks_register| for |print_cmd_chr|@>@;@+break;
6057 case vadjust: print_esc("vadjust");@+break;
6058 case valign: print_esc("valign");@+break;
6059 case vcenter: print_esc("vcenter");@+break;
6060 case vrule: print_esc("vrule");@+break;
6061
6062 @ We will deal with the other primitives later, at some point in the program
6063 where their |eq_type| and |equiv| values are more meaningful. For example,
6064 the primitives for math mode will be loaded when we consider the routines
6065 that deal with formulas. It is easy to find where each particular
6066 primitive was treated by looking in the index at the end; for example, the
6067 section where |"radical"| entered |eqtb| is listed under `\.{\\radical}
6068 primitive'. (Primitives consisting of a single nonalphabetic character,
6069 @!like `\.{\\/}', are listed under `Single-character primitives'.)
6070 @!@^Single-character primitives@>
6071
6072 Meanwhile, this is a convenient place to catch up on something we were unable
6073 to do before the hash table was defined:
6074
6075 @<Print the font identifier for |font(p)|@>=
6076 printn_esc(font_id_text(font(p)))
6077
6078 @* Saving and restoring equivalents.
6079 The nested structure provided by `$\.{\char'173}\ldots\.{\char'175}$' groups
6080 in \TeX\ means that |eqtb| entries valid in outer groups should be saved
6081 and restored later if they are overridden inside the braces. When a new |eqtb|
6082 value is being assigned, the program therefore checks to see if the previous
6083 entry belongs to an outer level. In such a case, the old value is placed
6084 on the |save_stack| just before the new value enters |eqtb|. At the
6085 end of a grouping level, i.e., when the right brace is sensed, the
6086 |save_stack| is used to restore the outer values, and the inner ones are
6087 destroyed.
6088
6089 Entries on the |save_stack| are of type |memory_word|. The top item on
6090 this stack is |save_stack[p]|, where |p==save_ptr-1|; it contains three
6091 fields called |save_type|, |save_level|, and |save_index|, and it is
6092 interpreted in one of five ways:
6093
6094 \yskip\hangg 1) If |save_type(p)==restore_old_value|, then
6095 |save_index(p)| is a location in |eqtb| whose current value should
6096 be destroyed at the end of the current group and replaced by |save_stack[p-1]|.
6097 Furthermore if |save_index(p) >= int_base|, then |save_level(p)|
6098 should replace the corresponding entry in |xeq_level|.
6099
6100 \yskip\hangg 2) If |save_type(p)==restore_zero|, then |save_index(p)|
6101 is a location in |eqtb| whose current value should be destroyed at the end
6102 of the current group, when it should be
6103 replaced by the value of |eqtb[undefined_control_sequence]|.
6104
6105 \yskip\hangg 3) If |save_type(p)==insert_token|, then |save_index(p)|
6106 is a token that should be inserted into \TeX's input when the current
6107 group ends.
6108
6109 \yskip\hangg 4) If |save_type(p)==level_boundary|, then |save_level(p)|
6110 is a code explaining what kind of group we were previously in, and
6111 |save_index(p)| points to the level boundary word at the bottom of
6112 the entries for that group.
6113 Furthermore, in extended \eTeX\ mode, |save_stack[p-1]| contains the
6114 source line number at which the current level of grouping was entered.
6115
6116 \yskip\hang 5) If |save_type(p)==restore_sa|, then |sa_chain| points to a
6117 chain of sparse array entries to be restored at the end of the current
6118 group. Furthermore |save_index(p)| and |save_level(p)| should replace
6119 the values of |sa_chain| and |sa_level| respectively.
6120
6121 @d save_type(A) save_stack[A].hh.b0 /*classifies a |save_stack| entry*/
6122 @d save_level(A) save_stack[A].hh.b1
6123 /*saved level for regions 5 and 6, or group code*/
6124 @d save_index(A) save_stack[A].hh.rh
6125 /*|eqtb| location or token or |save_stack| location*/
6126 @d restore_old_value 0 /*|save_type| when a value should be restored later*/
6127 @d restore_zero 1 /*|save_type| when an undefined entry should be restored*/
6128 @d insert_token 2 /*|save_type| when a token is being saved for later use*/
6129 @d level_boundary 3 /*|save_type| corresponding to beginning of group*/
6130 @d restore_sa 4 /*|save_type| when sparse array entries should be restored*/
6131
6132 @p @t\4@>@<Declare \eTeX\ procedures for tracing and input@>@;
6133
6134 @ Here are the group codes that are used to discriminate between different
6135 kinds of groups. They allow \TeX\ to decide what special actions, if any,
6136 should be performed when a group ends.
6137 \def\grp{\.{\char'173...\char'175}}
6138
6139 Some groups are not supposed to be ended by right braces. For example,
6140 the `\.\$' that begins a math formula causes a |math_shift_group| to
6141 be started, and this should be terminated by a matching `\.\$'. Similarly,
6142 a group that starts with \.{\\left} should end with \.{\\right}, and
6143 one that starts with \.{\\begingroup} should end with \.{\\endgroup}.
6144
6145 @d bottom_level 0 /*group code for the outside world*/
6146 @d simple_group 1 /*group code for local structure only*/
6147 @d hbox_group 2 /*code for `\.{\\hbox}\grp'*/
6148 @d adjusted_hbox_group 3 /*code for `\.{\\hbox}\grp' in vertical mode*/
6149 @d vbox_group 4 /*code for `\.{\\vbox}\grp'*/
6150 @d vtop_group 5 /*code for `\.{\\vtop}\grp'*/
6151 @d align_group 6 /*code for `\.{\\halign}\grp', `\.{\\valign}\grp'*/
6152 @d no_align_group 7 /*code for `\.{\\noalign}\grp'*/
6153 @d output_group 8 /*code for output routine*/
6154 @d math_group 9 /*code for, e.g., `\.{\char'136}\grp'*/
6155 @d disc_group 10 /*code for `\.{\\discretionary}\grp\grp\grp'*/
6156 @d insert_group 11 /*code for `\.{\\insert}\grp', `\.{\\vadjust}\grp'*/
6157 @d vcenter_group 12 /*code for `\.{\\vcenter}\grp'*/
6158 @d math_choice_group 13 /*code for `\.{\\mathchoice}\grp\grp\grp\grp'*/
6159 @d semi_simple_group 14 /*code for `\.{\\begingroup...\\endgroup}'*/
6160 @d math_shift_group 15 /*code for `\.{\$...\$}'*/
6161 @d math_left_group 16 /*code for `\.{\\left...\\right}'*/
6162 @d max_group_code 16
6163
6164 @<Types...@>=
6165 typedef int8_t group_code; /*|save_level| for a level boundary*/
6166
6167 @ The global variable |cur_group| keeps track of what sort of group we are
6168 currently in. Another global variable, |cur_boundary|, points to the
6169 topmost |level_boundary| word. And |cur_level| is the current depth of
6170 nesting. The routines are designed to preserve the condition that no entry
6171 in the |save_stack| or in |eqtb| ever has a level greater than |cur_level|.
6172
6173 @ @<Glob...@>=
6174 static memory_word @!save_stack[save_size+1];
6175 static int @!save_ptr; /*first unused entry on |save_stack|*/
6176 static int @!max_save_stack; /*maximum usage of save stack*/
6177 static quarterword @!cur_level; /*current nesting level for groups*/
6178 static group_code @!cur_group; /*current group type*/
6179 static int @!cur_boundary; /*where the current level begins*/
6180
6181 @ At this time it might be a good idea for the reader to review the introduction
6182 to |eqtb| that was given above just before the long lists of parameter names.
6183 Recall that the ``outer level'' of the program is |level_one|, since
6184 undefined control sequences are assumed to be ``defined'' at |level_zero|.
6185
6186 @<Set init...@>=
6187 save_ptr=0;cur_level=level_one;cur_group=bottom_level;cur_boundary=0;
6188 max_save_stack=0;
6189
6190 @ The following macro is used to test if there is room for up to seven more
6191 entries on |save_stack|. By making a conservative test like this, we can
6192 get by with testing for overflow in only a few places.
6193
6194 @d check_full_save_stack if (save_ptr > max_save_stack)
6195 {@+max_save_stack=save_ptr;
6196 if (max_save_stack > save_size-7) overflow("save size", save_size);
6197 @:TeX capacity exceeded save size}{\quad save size@>
6198 }
6199
6200 @ Procedure |new_save_level| is called when a group begins. The
6201 argument is a group identification code like `|hbox_group|'. After
6202 calling this routine, it is safe to put five more entries on |save_stack|.
6203
6204 In some cases integer-valued items are placed onto the
6205 |save_stack| just below a |level_boundary| word, because this is a
6206 convenient place to keep information that is supposed to ``pop up'' just
6207 when the group has finished.
6208 For example, when `\.{\\hbox to 100pt}\grp' is being treated, the 100pt
6209 dimension is stored on |save_stack| just before |new_save_level| is
6210 called.
6211
6212 We use the notation |saved(k)| to stand for an integer item that
6213 appears in location |save_ptr+k| of the save stack.
6214
6215 @d saved(A) save_stack[save_ptr+A].i
6216
6217 @p static void new_save_level(group_code @!c) /*begin a new level of grouping*/
6218 {@+check_full_save_stack;
6219 if (eTeX_ex)
6220 {@+saved(0)=line;incr(save_ptr);
6221 }
6222 save_type(save_ptr)=level_boundary;save_level(save_ptr)=cur_group;
6223 save_index(save_ptr)=cur_boundary;
6224 if (cur_level==max_quarterword) overflow("grouping levels",
6225 @:TeX capacity exceeded grouping levels}{\quad grouping levels@>
6226 max_quarterword-min_quarterword);
6227 /*quit if |(cur_level+1)| is too big to be stored in |eqtb|*/
6228 cur_boundary=save_ptr;cur_group=c;
6229 #ifdef @!STAT
6230 if (tracing_groups > 0) group_trace(false);
6231 #endif
6232 @;@/
6233 incr(cur_level);incr(save_ptr);
6234 }
6235
6236 @ Just before an entry of |eqtb| is changed, the following procedure should
6237 be called to update the other data structures properly. It is important
6238 to keep in mind that reference counts in |mem| include references from
6239 within |save_stack|, so these counts must be handled carefully.
6240 @^reference counts@>
6241
6242 @p static void eq_destroy(memory_word @!w) /*gets ready to forget |w|*/
6243 {@+pointer q; /*|equiv| field of |w|*/
6244 switch (eq_type_field(w)) {
6245 case call: case long_call: case outer_call:
6246 case long_outer_call: delete_token_ref(equiv_field(w));@+break;
6247 case glue_ref: delete_glue_ref(equiv_field(w));@+break;
6248 case shape_ref: {@+q=equiv_field(w); /*we need to free a \.{\\parshape} block*/
6249 if (q!=null) free_node(q, info(q)+info(q)+1);
6250 } @+break; /*such a block is |2 n+1| words long, where |n==info(q)|*/
6251 case box_ref: flush_node_list(equiv_field(w));@+break;
6252 @/@<Cases for |eq_destroy|@>@/
6253 default:do_nothing;
6254 }
6255 }
6256
6257 @ To save a value of |eqtb[p]| that was established at level |l|, we
6258 can use the following subroutine.
6259
6260 @p static void eq_save(pointer @!p, quarterword @!l) /*saves |eqtb[p]|*/
6261 {@+check_full_save_stack;
6262 if (l==level_zero) save_type(save_ptr)=restore_zero;
6263 else{@+save_stack[save_ptr]=eqtb[p];incr(save_ptr);
6264 save_type(save_ptr)=restore_old_value;
6265 }
6266 save_level(save_ptr)=l;save_index(save_ptr)=p;incr(save_ptr);
6267 }
6268
6269 @ The procedure |eq_define| defines an |eqtb| entry having specified
6270 |eq_type| and |equiv| fields, and saves the former value if appropriate.
6271 This procedure is used only for entries in the first four regions of |eqtb|,
6272 i.e., only for entries that have |eq_type| and |equiv| fields.
6273 After calling this routine, it is safe to put four more entries on
6274 |save_stack|, provided that there was room for four more entries before
6275 the call, since |eq_save| makes the necessary test.
6276
6277 @p
6278 #ifdef @!STAT
6279 #define assign_trace(A, B) if (tracing_assigns > 0) restore_trace(A, B);
6280 #else
6281 #define assign_trace(A, B)
6282 #endif
6283
6284 static void eq_define(pointer @!p, quarterword @!t, halfword @!e)
6285 /*new data for |eqtb|*/
6286 {@+
6287 if (eTeX_ex&&(eq_type(p)==t)&&(equiv(p)==e))
6288 {@+assign_trace(p,"reassigning")@;@/
6289 eq_destroy(eqtb[p]);return;
6290 }
6291 assign_trace(p,"changing")@;@/
6292 if (eq_level(p)==cur_level) eq_destroy(eqtb[p]);
6293 else if (cur_level > level_one) eq_save(p, eq_level(p));
6294 eq_level(p)=cur_level;eq_type(p)=t;equiv(p)=e;
6295 assign_trace(p,"into")@;@/
6296 }
6297
6298 @ The counterpart of |eq_define| for the remaining (fullword) positions in
6299 |eqtb| is called |eq_word_define|. Since |xeq_level[p] >= level_one| for all
6300 |p|, a `|restore_zero|' will never be used in this case.
6301
6302 @p static void eq_word_define(pointer @!p, int @!w)
6303 {@+
6304 if (eTeX_ex&&(eqtb[p].i==w))
6305 {@+assign_trace(p,"reassigning")@;@/
6306 return;
6307 }
6308 assign_trace(p,"changing")@;@/
6309 if (xeq_level[p]!=cur_level)
6310 {@+eq_save(p, xeq_level[p]);xeq_level[p]=cur_level;
6311 }
6312 eqtb[p].i=w;
6313 assign_trace(p,"into")@;@/
6314 }
6315
6316 @ The |eq_define| and |eq_word_define| routines take care of local definitions.
6317 @^global definitions@>
6318 Global definitions are done in almost the same way, but there is no need
6319 to save old values, and the new value is associated with |level_one|.
6320
6321 @p static void geq_define(pointer @!p, quarterword @!t, halfword @!e)
6322 /*global |eq_define|*/
6323 {@+assign_trace(p,"globally changing")@;@/
6324 {@+eq_destroy(eqtb[p]);
6325 eq_level(p)=level_one;eq_type(p)=t;equiv(p)=e;
6326 }
6327 assign_trace(p,"into");@/
6328 }
6329 @#
6330 static void geq_word_define(pointer @!p, int @!w) /*global |eq_word_define|*/
6331 {@+assign_trace(p,"globally changing")@;@/
6332 {@+eqtb[p].i=w;xeq_level[p]=level_one;
6333 }
6334 assign_trace(p,"into");@/
6335 }
6336
6337 @ Subroutine |save_for_after| puts a token on the stack for save-keeping.
6338
6339 @p static void save_for_after(halfword @!t)
6340 {@+if (cur_level > level_one)
6341 {@+check_full_save_stack;
6342 save_type(save_ptr)=insert_token;save_level(save_ptr)=level_zero;
6343 save_index(save_ptr)=t;incr(save_ptr);
6344 }
6345 }
6346
6347 @ The |unsave| routine goes the other way, taking items off of |save_stack|.
6348 This routine takes care of restoration when a level ends; everything
6349 belonging to the topmost group is cleared off of the save stack.
6350
6351 @p
6352 static void back_input(void);
6353 static void unsave(void) /*pops the top level off the save stack*/
6354 {@+
6355 pointer p; /*position to be restored*/
6356 quarterword @!l; /*saved level, if in fullword regions of |eqtb|*/
6357 halfword @!t; /*saved value of |cur_tok|*/
6358 bool @!a; /*have we already processed an \.{\\aftergroup} ?*/
6359 a=false;
6360 if (cur_level > level_one)
6361 {@+decr(cur_level);
6362 @<Clear off top level from |save_stack|@>;
6363 }
6364 else confusion("curlevel"); /*|unsave| is not used when |cur_group==bottom_level|*/
6365 @:this can't happen curlevel}{\quad curlevel@>
6366 }
6367
6368 @ @<Clear off...@>=
6369 loop@+{@+decr(save_ptr);
6370 if (save_type(save_ptr)==level_boundary) goto done;
6371 p=save_index(save_ptr);
6372 if (save_type(save_ptr)==insert_token)
6373 @<Insert token |p| into \TeX's input@>@;
6374 else if (save_type(save_ptr)==restore_sa)
6375 {@+sa_restore();sa_chain=p;sa_level=save_level(save_ptr);
6376 }
6377 else{@+if (save_type(save_ptr)==restore_old_value)
6378 {@+l=save_level(save_ptr);decr(save_ptr);
6379 }
6380 else save_stack[save_ptr]=eqtb[undefined_control_sequence];
6381 @<Store \(s)|save_stack[save_ptr]| in |eqtb[p]|, unless |eqtb[p]| holds
6382 a global value@>;
6383 }
6384 }
6385 done:
6386 #ifdef @!STAT
6387 if (tracing_groups > 0) group_trace(true);
6388 #endif
6389 @;@/
6390 if (grp_stack[in_open]==cur_boundary) group_warning();
6391 /*groups possibly not properly nested with files*/
6392 cur_group=save_level(save_ptr);cur_boundary=save_index(save_ptr);
6393 if (eTeX_ex) decr(save_ptr)
6394
6395 @ A global definition, which sets the level to |level_one|,
6396 @^global definitions@>
6397 will not be undone by |unsave|. If at least one global definition of
6398 |eqtb[p]| has been carried out within the group that just ended, the
6399 last such definition will therefore survive.
6400
6401 @<Store \(s)|save...@>=
6402 if (p < int_base)
6403 if (eq_level(p)==level_one)
6404 {@+eq_destroy(save_stack[save_ptr]); /*destroy the saved value*/
6405 #ifdef @!STAT
6406 if (tracing_restores > 0) restore_trace(p,"retaining");
6407 #endif
6408 @;@/
6409 }
6410 else{@+eq_destroy(eqtb[p]); /*destroy the current value*/
6411 eqtb[p]=save_stack[save_ptr]; /*restore the saved value*/
6412 #ifdef @!STAT
6413 if (tracing_restores > 0) restore_trace(p,"restoring");
6414 #endif
6415 @;@/
6416 }
6417 else if (xeq_level[p]!=level_one)
6418 {@+eqtb[p]=save_stack[save_ptr];xeq_level[p]=l;
6419 #ifdef @!STAT
6420 if (tracing_restores > 0) restore_trace(p,"restoring");
6421 #endif
6422 @;@/
6423 }
6424 else{
6425 #ifdef @!STAT
6426 if (tracing_restores > 0) restore_trace(p,"retaining");
6427 #endif
6428 @;@/
6429 }
6430
6431 @ @<Declare \eTeX\ procedures for tr...@>=
6432 #ifdef @!STAT
6433 static void restore_trace(pointer @!p, char *@!s)
6434 /*|eqtb[p]| has just been restored or retained*/
6435 {@+begin_diagnostic();print_char('{');print(s);print_char(' ');
6436 show_eqtb(p);print_char('}');
6437 end_diagnostic(false);
6438 }
6439 #endif
6440
6441 @ When looking for possible pointers to a memory location, it is helpful
6442 to look for references from |eqtb| that might be waiting on the
6443 save stack. Of course, we might find spurious pointers too; but this
6444 routine is merely an aid when debugging, and at such times we are
6445 grateful for any scraps of information, even if they prove to be irrelevant.
6446 @^dirty \PASCAL@>
6447
6448 @<Search |save_stack| for equivalents that point to |p|@>=
6449 if (save_ptr > 0) for (q=0; q<=save_ptr-1; q++)
6450 {@+if (equiv_field(save_stack[q])==p)
6451 {@+print_nl("SAVE(");print_int(q);print_char(')');
6452 }
6453 }
6454
6455 @ Most of the parameters kept in |eqtb| can be changed freely, but there's
6456 an exception: The magnification should not be used with two different
6457 values during any \TeX\ job, since a single magnification is applied to an
6458 entire run. The global variable |mag_set| is set to the current magnification
6459 whenever it becomes necessary to ``freeze'' it at a particular value.
6460
6461 @<Glob...@>=
6462 static int @!mag_set; /*if nonzero, this magnification should be used henceforth*/
6463
6464 @ @<Set init...@>=
6465 mag_set=0;
6466
6467 @ The |prepare_mag| subroutine is called whenever \TeX\ wants to use |mag|
6468 for magnification.
6469
6470 @p static void prepare_mag(void)
6471 {@+if ((mag_set > 0)&&(mag!=mag_set))
6472 {@+print_err("Incompatible magnification (");print_int(mag);
6473 @.Incompatible magnification@>
6474 print(");");print_nl(" the previous value will be retained");
6475 help2("I can handle only one magnification ratio per job. So I've",@/
6476 "reverted to the magnification you used earlier on this run.");@/
6477 int_error(mag_set);
6478 geq_word_define(int_base+mag_code, mag_set); /*|mag=mag_set|*/
6479 }
6480 if ((mag <= 0)||(mag > 32768))
6481 {@+print_err("Illegal magnification has been changed to 1000");@/
6482 @.Illegal magnification...@>
6483 help1("The magnification ratio must be between 1 and 32768.");
6484 int_error(mag);geq_word_define(int_base+mag_code, 1000);
6485 }
6486 mag_set=mag;
6487 }
6488
6489 @* Token lists.
6490 A \TeX\ token is either a character or a control sequence, and it is
6491 @^token@>
6492 represented internally in one of two ways: (1)~A character whose ASCII
6493 code number is |c| and whose command code is |m| is represented as the
6494 number $2^8m+c$; the command code is in the range |1 <= m <= 14|. (2)~A control
6495 sequence whose |eqtb| address is |p| is represented as the number
6496 |cs_token_flag+p|. Here |cs_token_flag==@t$2^{12}-1$@>| is larger than
6497 $2^8m+c$, yet it is small enough that |cs_token_flag+p < max_halfword|;
6498 thus, a token fits comfortably in a halfword.
6499
6500 A token |t| represents a |left_brace| command if and only if
6501 |t < left_brace_limit|; it represents a |right_brace| command if and only if
6502 we have |left_brace_limit <= t < right_brace_limit|; and it represents a |match| or
6503 |end_match| command if and only if |match_token <= t <= end_match_token|.
6504 The following definitions take care of these token-oriented constants
6505 and a few others.
6506
6507 @d cs_token_flag 07777 /*amount added to the |eqtb| location in a
6508 token that stands for a control sequence; is a multiple of~256, less~1*/
6509 @d left_brace_token 00400 /*$2^8\cdot|left_brace|$*/
6510 @d left_brace_limit 01000 /*$2^8\cdot(|left_brace|+1)$*/
6511 @d right_brace_token 01000 /*$2^8\cdot|right_brace|$*/
6512 @d right_brace_limit 01400 /*$2^8\cdot(|right_brace|+1)$*/
6513 @d math_shift_token 01400 /*$2^8\cdot|math_shift|$*/
6514 @d tab_token 02000 /*$2^8\cdot|tab_mark|$*/
6515 @d out_param_token 02400 /*$2^8\cdot|out_param|$*/
6516 @d space_token 05040 /*$2^8\cdot|spacer|+|' '|$*/
6517 @d letter_token 05400 /*$2^8\cdot|letter|$*/
6518 @d other_token 06000 /*$2^8\cdot|other_char|$*/
6519 @d match_token 06400 /*$2^8\cdot|match|$*/
6520 @d end_match_token 07000 /*$2^8\cdot|end_match|$*/
6521 @d protected_token 07001 /*$2^8\cdot|end_match|+1$*/
6522
6523 @ @<Check the ``constant''...@>=
6524 if (cs_token_flag+undefined_control_sequence > max_halfword) bad=21;
6525
6526 @ A token list is a singly linked list of one-word nodes in |mem|, where
6527 each word contains a token and a link. Macro definitions, output-routine
6528 definitions, marks, \.{\\write} texts, and a few other things
6529 are remembered by \TeX\ in the form
6530 of token lists, usually preceded by a node with a reference count in its
6531 |token_ref_count| field. The token stored in location |p| is called
6532 |info(p)|.
6533
6534 Three special commands appear in the token lists of macro definitions.
6535 When |m==match|, it means that \TeX\ should scan a parameter
6536 for the current macro; when |m==end_match|, it means that parameter
6537 matching should end and \TeX\ should start reading the macro text; and
6538 when |m==out_param|, it means that \TeX\ should insert parameter
6539 number |c| into the text at this point.
6540
6541 The enclosing \.{\char'173} and \.{\char'175} characters of a macro
6542 definition are omitted, but an output routine
6543 will be enclosed in braces.
6544
6545 Here is an example macro definition that illustrates these conventions.
6546 After \TeX\ processes the text
6547 $$\.{\\def\\mac a\#1\#2 \\b \{\#1\\-a \#\#1\#2 \#2\}}$$
6548 the definition of \.{\\mac} is represented as a token list containing
6549 $$\def\,{\hskip2pt}
6550 \vbox{\halign{\hfil#\hfil\cr
6551 (reference count), |letter|\,\.a, |match|\,\#, |match|\,\#, |spacer|\,\.\ ,
6552 \.{\\b}, |end_match|,\cr
6553 |out_param|\,1, \.{\\-}, |letter|\,\.a, |spacer|\,\.\ , |mac_param|\,\#,
6554 |other_char|\,\.1,\cr
6555 |out_param|\,2, |spacer|\,\.\ , |out_param|\,2.\cr}}$$
6556 The procedure |scan_toks| builds such token lists, and |macro_call|
6557 does the parameter matching.
6558 @^reference counts@>
6559
6560 Examples such as
6561 $$\.{\\def\\m\{\\def\\m\{a\}\ b\}}$$
6562 explain why reference counts would be needed even if \TeX\ had no \.{\\let}
6563 operation: When the token list for \.{\\m} is being read, the redefinition of
6564 \.{\\m} changes the |eqtb| entry before the token list has been fully
6565 consumed, so we dare not simply destroy a token list when its
6566 control sequence is being redefined.
6567
6568 If the parameter-matching part of a definition ends with `\.{\#\{}',
6569 the corresponding token list will have `\.\{' just before the `|end_match|'
6570 and also at the very end. The first `\.\{' is used to delimit the parameter; the
6571 second one keeps the first from disappearing.
6572
6573 @ The procedure |show_token_list|, which prints a symbolic form of
6574 the token list that starts at a given node |p|, illustrates these
6575 conventions. The token list being displayed should not begin with a reference
6576 count. However, the procedure is intended to be robust, so that if the
6577 memory links are awry or if |p| is not really a pointer to a token list,
6578 nothing catastrophic will happen.
6579
6580 An additional parameter |q| is also given; this parameter is either null
6581 or it points to a node in the token list where a certain magic computation
6582 takes place that will be explained later. (Basically, |q| is non-null when
6583 we are printing the two-line context information at the time of an error
6584 message; |q| marks the place corresponding to where the second line
6585 should begin.)
6586
6587 For example, if |p| points to the node containing the first \.a in the
6588 token list above, then |show_token_list| will print the string
6589 $$\hbox{`\.{a\#1\#2\ \\b\ ->\#1\\-a\ \#\#1\#2\ \#2}';}$$
6590 and if |q| points to the node containing the second \.a,
6591 the magic computation will be performed just before the second \.a is printed.
6592
6593 The generation will stop, and `\.{\\ETC.}' will be printed, if the length
6594 of printing exceeds a given limit~|l|. Anomalous entries are printed in the
6595 form of control sequences that are not followed by a blank space, e.g.,
6596 `\.{\\BAD.}'; this cannot be confused with actual control sequences because
6597 a real control sequence named \.{BAD} would come out `\.{\\BAD\ }'.
6598
6599 @<Declare the procedure called |show_token_list|@>=
6600 static void show_token_list(int @!p, int @!q, int @!l)
6601 {@+
6602 int m, @!c; /*pieces of a token*/
6603 ASCII_code @!match_chr; /*character used in a `|match|'*/
6604 ASCII_code @!n; /*the highest parameter number, as an ASCII digit*/
6605 match_chr='#';n='0';tally=0;
6606 while ((p!=null)&&(tally < l))
6607 {@+if (p==q) @<Do magic computation@>;
6608 @<Display token |p|, and |return| if there are problems@>;
6609 p=link(p);
6610 }
6611 if (p!=null) print_esc("ETC.");
6612 @.ETC@>
6613
6614 }
6615
6616 @ @<Display token |p|...@>=
6617 if ((p < hi_mem_min)||(p > mem_end))
6618 {@+print_esc("CLOBBERED.");return;
6619 @.CLOBBERED@>
6620 }
6621 if (info(p) >= cs_token_flag) print_cs(info(p)-cs_token_flag);
6622 else{@+m=info(p)/0400;c=info(p)%0400;
6623 if (info(p) < 0) print_esc("BAD.");
6624 @.BAD@>
6625 else@<Display the token $(|m|,|c|)$@>;
6626 }
6627
6628 @ The procedure usually ``learns'' the character code used for macro
6629 parameters by seeing one in a |match| command before it runs into any
6630 |out_param| commands.
6631
6632 @<Display the token...@>=
6633 switch (m) {
6634 case left_brace: case right_brace: case math_shift:
6635 case tab_mark: case sup_mark: case sub_mark:
6636 case spacer:
6637 case letter: case other_char: printn(c);@+break;
6638 case mac_param: {@+printn(c);printn(c);
6639 } @+break;
6640 case out_param: {@+printn(match_chr);
6641 if (c <= 9) print_char(c+'0');
6642 else{@+print_char('!');return;
6643 }
6644 } @+break;
6645 case match: {@+match_chr=c;printn(c);incr(n);print_char(n);
6646 if (n > '9') return;
6647 } @+break;
6648 case end_match: if (c==0) print("->");@+break;
6649 @.->@>
6650 default:print_esc("BAD.");
6651 @.BAD@>
6652 }
6653
6654 @ Here's the way we sometimes want to display a token list, given a pointer
6655 to its reference count; the pointer may be null.
6656
6657 @p static void token_show(pointer @!p)
6658 {@+if (p!=null) show_token_list(link(p), null, 10000000);
6659 }
6660
6661 @ The |print_meaning| subroutine displays |cur_cmd| and |cur_chr| in
6662 symbolic form, including the expansion of a macro or mark.
6663
6664 @p static void print_meaning(void)
6665 {@+print_cmd_chr(cur_cmd, cur_chr);
6666 if (cur_cmd >= call)
6667 {@+print_char(':');print_ln();token_show(cur_chr);
6668 }
6669 else if ((cur_cmd==top_bot_mark)&&(cur_chr < marks_code))
6670 {@+print_char(':');print_ln();
6671 token_show(cur_mark[cur_chr]);
6672 }
6673 }
6674
6675 @* Introduction to the syntactic routines.
6676 Let's pause a moment now and try to look at the Big Picture.
6677 The \TeX\ program consists of three main parts: syntactic routines,
6678 semantic routines, and output routines. The chief purpose of the
6679 syntactic routines is to deliver the user's input to the semantic routines,
6680 one token at a time. The semantic routines act as an interpreter
6681 responding to these tokens, which may be regarded as commands. And the
6682 output routines are periodically called on to convert box-and-glue
6683 lists into a compact set of instructions that will be sent
6684 to a typesetter. We have discussed the basic data structures and utility
6685 routines of \TeX, so we are good and ready to plunge into the real activity by
6686 considering the syntactic routines.
6687
6688 Our current goal is to come to grips with the |get_next| procedure,
6689 which is the keystone of \TeX's input mechanism. Each call of |get_next|
6690 sets the value of three variables |cur_cmd|, |cur_chr|, and |cur_cs|,
6691 representing the next input token.
6692 $$\vbox{\halign{#\hfil\cr
6693 \hbox{|cur_cmd| denotes a command code from the long list of codes
6694 given above;}\cr
6695 \hbox{|cur_chr| denotes a character code or other modifier of the command
6696 code;}\cr
6697 \hbox{|cur_cs| is the |eqtb| location of the current control sequence,}\cr
6698 \hbox{\qquad if the current token was a control sequence,
6699 otherwise it's zero.}\cr}}$$
6700 Underlying this external behavior of |get_next| is all the machinery
6701 necessary to convert from character files to tokens. At a given time we
6702 may be only partially finished with the reading of several files (for
6703 which \.{\\input} was specified), and partially finished with the expansion
6704 of some user-defined macros and/or some macro parameters, and partially
6705 finished with the generation of some text in a template for \.{\\halign},
6706 and so on. When reading a character file, special characters must be
6707 classified as math delimiters, etc.; comments and extra blank spaces must
6708 be removed, paragraphs must be recognized, and control sequences must be
6709 found in the hash table. Furthermore there are occasions in which the
6710 scanning routines have looked ahead for a word like `\.{plus}' but only
6711 part of that word was found, hence a few characters must be put back
6712 into the input and scanned again.
6713
6714 To handle these situations, which might all be present simultaneously,
6715 \TeX\ uses various stacks that hold information about the incomplete
6716 activities, and there is a finite state control for each level of the
6717 input mechanism. These stacks record the current state of an implicitly
6718 recursive process, but the |get_next| procedure is not recursive.
6719 Therefore it will not be difficult to translate these algorithms into
6720 low-level languages that do not support recursion.
6721
6722 @<Glob...@>=
6723 static eight_bits @!cur_cmd; /*current command set by |get_next|*/
6724 static halfword @!cur_chr; /*operand of current command*/
6725 static pointer @!cur_cs; /*control sequence found here, zero if none found*/
6726 static halfword @!cur_tok; /*packed representative of |cur_cmd| and |cur_chr|*/
6727
6728 @ The |print_cmd_chr| routine prints a symbolic interpretation of a
6729 command code and its modifier. This is used in certain `\.{You can\'t}'
6730 error messages, and in the implementation of diagnostic routines like
6731 \.{\\show}.
6732
6733 The body of |print_cmd_chr| is a rather tedious listing of print
6734 commands, and most of it is essentially an inverse to the |primitive|
6735 routine that enters a \TeX\ primitive into |eqtb|. Therefore much of
6736 this procedure appears elsewhere in the program,
6737 together with the corresponding |primitive| calls.
6738
6739 @d chr_cmd(A) {@+print(A);print_ASCII(chr_code);
6740 }
6741
6742 @<Declare the procedure called |print_cmd_chr|@>=
6743 static void print_cmd_chr(quarterword @!cmd, halfword @!chr_code)
6744 {@+int n; /*temp variable*/
6745 switch (cmd) {
6746 case left_brace: chr_cmd("begin-group character ")@;@+break;
6747 case right_brace: chr_cmd("end-group character ")@;@+break;
6748 case math_shift: chr_cmd("math shift character ")@;@+break;
6749 case mac_param: chr_cmd("macro parameter character ")@;@+break;
6750 case sup_mark: chr_cmd("superscript character ")@;@+break;
6751 case sub_mark: chr_cmd("subscript character ")@;@+break;
6752 case endv: print("end of alignment template");@+break;
6753 case spacer: chr_cmd("blank space ")@;@+break;
6754 case letter: chr_cmd("the letter ")@;@+break;
6755 case other_char: chr_cmd("the character ")@;@+break;
6756 @t\4@>@<Cases of |print_cmd_chr| for symbolic printing of primitives@>@/
6757 default:print("[unknown command code!]");
6758 }
6759 }
6760
6761 @ Here is a procedure that displays the current command.
6762
6763 @p static void show_cur_cmd_chr(void)
6764 {@+int n; /*level of \.{\\if...\\fi} nesting*/
6765 int @!l; /*line where \.{\\if} started*/
6766 pointer @!p;
6767 begin_diagnostic();print_nl("{");
6768 if (mode!=shown_mode)
6769 {@+print_mode(mode);print(": ");shown_mode=mode;
6770 }
6771 print_cmd_chr(cur_cmd, cur_chr);
6772 if (tracing_ifs > 0)
6773 if (cur_cmd >= if_test) if (cur_cmd <= fi_or_else)
6774 {@+print(": ");
6775 if (cur_cmd==fi_or_else)
6776 {@+print_cmd_chr(if_test, cur_if);print_char(' ');
6777 n=0;l=if_line;
6778 }
6779 else{@+n=1;l=line;
6780 }
6781 p=cond_ptr;
6782 while (p!=null)
6783 {@+incr(n);p=link(p);
6784 }
6785 print("(level ");print_int(n);print_char(')');print_if_line(l);
6786 }
6787 print_char('}');
6788 end_diagnostic(false);
6789 }
6790
6791 @* Input stacks and states.
6792 This implementation of
6793 \TeX\ uses two different conventions for representing sequential stacks.
6794 @^stack conventions@>@^conventions for representing stacks@>
6795
6796 \yskip\hangg 1) If there is frequent access to the top entry, and if the
6797 stack is essentially never empty, then the top entry is kept in a global
6798 variable (even better would be a machine register), and the other entries
6799 appear in the array $\\{stack}[0\to(\\{ptr}-1)]$. For example, the
6800 semantic stack described above is handled this way, and so is the input
6801 stack that we are about to study.
6802
6803 \yskip\hangg 2) If there is infrequent top access, the entire stack contents
6804 are in the array $\\{stack}[0\to(\\{ptr}-1)]$. For example, the |save_stack|
6805 is treated this way, as we have seen.
6806
6807 \yskip\noindent
6808 The state of \TeX's input mechanism appears in the input stack, whose
6809 entries are records with six fields, called |state|, |index|, |start|, |loc|,
6810 |limit|, and |name|. This stack is maintained with
6811 convention~(1), so it is declared in the following way:
6812
6813 @<Types...@>=
6814 typedef struct {
6815 quarterword @!state_field, @!index_field;
6816 halfword @!start_field, @!loc_field, @!limit_field, @!name_field;
6817 halfword @!depth_field;
6818 } in_state_record;
6819
6820 @ @<Glob...@>=
6821 static in_state_record @!input_stack[stack_size+1];
6822 static int @!input_ptr; /*first unused location of |input_stack|*/
6823 static int @!max_in_stack; /*largest value of |input_ptr| when pushing*/
6824 static in_state_record @!cur_input;
6825 /*the ``top'' input state, according to convention (1)*/
6826
6827 @ We've already defined the special variable |loc==cur_input.loc_field|
6828 in our discussion of basic input-output routines. The other components of
6829 |cur_input| are defined in the same way:
6830
6831 @d state cur_input.state_field /*current scanner state*/
6832 @d index cur_input.index_field /*reference for buffer information*/
6833 @d start cur_input.start_field /*starting position in |buffer|*/
6834 @d limit cur_input.limit_field /*end of current line in |buffer|*/
6835 @d name cur_input.name_field /*name of the current file*/
6836 @d cur_depth cur_input.depth_field /* nesting depth of current macro */
6837
6838 @ Let's look more closely now at the control variables
6839 (|state|,~|index|,~|start|,~|loc|,~|limit|,~|name|),
6840 assuming that \TeX\ is reading a line of characters that have been input
6841 from some file or from the user's terminal. There is an array called
6842 |buffer| that acts as a stack of all lines of characters that are
6843 currently being read from files, including all lines on subsidiary
6844 levels of the input stack that are not yet completed. \TeX\ will return to
6845 the other lines when it is finished with the present input file.
6846
6847 (Incidentally, on a machine with byte-oriented addressing, it might be
6848 appropriate to combine |buffer| with the |str_pool| array,
6849 letting the buffer entries grow downward from the top of the string pool
6850 and checking that these two tables don't bump into each other.)
6851
6852 The line we are currently working on begins in position |start| of the
6853 buffer; the next character we are about to read is |buffer[loc]|; and
6854 |limit| is the location of the last character present. If |loc > limit|,
6855 the line has been completely read. Usually |buffer[limit]| is the
6856 |end_line_char|, denoting the end of a line, but this is not
6857 true if the current line is an insertion that was entered on the user's
6858 terminal in response to an error message.
6859
6860 The |name| variable is a string number that designates the name of
6861 the current file, if we are reading a text file. It is zero if we
6862 are reading from the terminal; it is |n+1| if we are reading from
6863 input stream |n|, where |0 <= n <= 16|. (Input stream 16 stands for
6864 an invalid stream number; in such cases the input is actually from
6865 the terminal, under control of the procedure |read_toks|.)
6866 Finally |18 <= name <= 19| indicates that we are reading a pseudo file
6867 created by the \.{\\scantokens} command.
6868
6869 The |state| variable has one of three values, when we are scanning such
6870 files:
6871 $$\baselineskip 15pt\vbox{\halign{#\hfil\cr
6872 1) |state==mid_line| is the normal state.\cr
6873 2) |state==skip_blanks| is like |mid_line|, but blanks are ignored.\cr
6874 3) |state==new_line| is the state at the beginning of a line.\cr}}$$
6875 These state values are assigned numeric codes so that if we add the state
6876 code to the next character's command code, we get distinct values. For
6877 example, `|mid_line+spacer|' stands for the case that a blank
6878 space character occurs in the middle of a line when it is not being
6879 ignored; after this case is processed, the next value of |state| will
6880 be |skip_blanks|.
6881
6882 @d mid_line 1 /*|state| code when scanning a line of characters*/
6883 @d skip_blanks (2+max_char_code) /*|state| code when ignoring blanks*/
6884 @d new_line (3+max_char_code+max_char_code) /*|state| code at start of line*/
6885
6886 @ Additional information about the current line is available via the
6887 |index| variable, which counts how many lines of characters are present
6888 in the buffer below the current level. We have |index==0| when reading
6889 from the terminal and prompting the user for each line; then if the user types,
6890 e.g., `\.{\\input paper}', we will have |index==1| while reading
6891 the file \.{paper.tex}. However, it does not follow that |index| is the
6892 same as the input stack pointer, since many of the levels on the input
6893 stack may come from token lists. For example, the instruction `\.{\\input
6894 paper}' might occur in a token list.
6895
6896 The global variable |in_open| is equal to the |index|
6897 value of the highest non-token-list level. Thus, the number of partially read
6898 lines in the buffer is |in_open+1|, and we have |in_open==index|
6899 when we are not reading a token list.
6900
6901 If we are not currently reading from the terminal, or from an input
6902 stream, we are reading from the file variable |input_file[index]|. We use
6903 the notation |terminal_input| as a convenient abbreviation for |name==0|,
6904 and |cur_file| as an abbreviation for |input_file[index]|.
6905
6906 The global variable |line| contains the line number in the topmost
6907 open file, for use in error messages. If we are not reading from
6908 the terminal, |line_stack[index]| holds the line number for the
6909 enclosing level, so that |line| can be restored when the current
6910 file has been read. Line numbers should never be negative, since the
6911 negative of the current line number is used to identify the user's output
6912 routine in the |mode_line| field of the semantic nest entries.
6913
6914 If more information about the input state is needed, it can be
6915 included in small arrays like those shown here. For example,
6916 the current page or segment number in the input file might be
6917 put into a variable |@!page|, maintained for enclosing levels in
6918 `\ignorespaces|@!page_stack: array[1 dotdot max_in_open]int|\unskip'
6919 by analogy with |line_stack|.
6920 @^system dependencies@>
6921
6922 @d terminal_input (name==0) /*are we reading from the terminal?*/
6923 @d cur_file input_file[index] /*the current |alpha_file| variable*/
6924
6925 @<Glob...@>=
6926 static int @!in_open; /*the number of lines in the buffer, less one*/
6927 static int @!open_parens; /*the number of open text files*/
6928 static alpha_file @!input_file0[max_in_open],
6929 *const @!input_file = @!input_file0-1;
6930 static int @!line; /*current line number in the current source file*/
6931 static int @!line_stack0[max_in_open],
6932 *const @!line_stack = @!line_stack0-1;
6933
6934 @ Users of \TeX\ sometimes forget to balance left and right braces properly,
6935 and one of the ways \TeX\ tries to spot such errors is by considering an
6936 input file as broken into subfiles by control sequences that
6937 are declared to be \.{\\outer}.
6938
6939 A variable called |scanner_status| tells \TeX\ whether or not to complain
6940 when a subfile ends. This variable has six possible values:
6941
6942 \yskip\hang|normal|, means that a subfile can safely end here without incident.
6943
6944 \yskip\hang|skipping|, means that a subfile can safely end here, but not a file,
6945 because we're reading past some conditional text that was not selected.
6946
6947 \yskip\hang|defining|, means that a subfile shouldn't end now because a
6948 macro is being defined.
6949
6950 \yskip\hang|matching|, means that a subfile shouldn't end now because a
6951 macro is being used and we are searching for the end of its arguments.
6952
6953 \yskip\hang|aligning|, means that a subfile shouldn't end now because we are
6954 not finished with the preamble of an \.{\\halign} or \.{\\valign}.
6955
6956 \yskip\hang|absorbing|, means that a subfile shouldn't end now because we are
6957 reading a balanced token list for \.{\\message}, \.{\\write}, etc.
6958
6959 \yskip\noindent
6960 If the |scanner_status| is not |normal|, the variable |warning_index| points
6961 to the |eqtb| location for the relevant control sequence name to print
6962 in an error message.
6963
6964 @d skipping 1 /*|scanner_status| when passing conditional text*/
6965 @d defining 2 /*|scanner_status| when reading a macro definition*/
6966 @d matching 3 /*|scanner_status| when reading macro arguments*/
6967 @d aligning 4 /*|scanner_status| when reading an alignment preamble*/
6968 @d absorbing 5 /*|scanner_status| when reading a balanced text*/
6969
6970 @<Glob...@>=
6971 static int @!scanner_status; /*can a subfile end now?*/
6972 static pointer @!warning_index; /*identifier relevant to non-|normal| scanner status*/
6973 static pointer @!def_ref; /*reference count of token list being defined*/
6974
6975 @ Here is a procedure that uses |scanner_status| to print a warning message
6976 when a subfile has ended, and at certain other crucial times:
6977
6978 @<Declare the procedure called |runaway|@>=
6979 static void runaway(void)
6980 {@+pointer p; /*head of runaway list*/
6981 if (scanner_status > skipping)
6982 {@+print_nl("Runaway ");
6983 @.Runaway...@>
6984 switch (scanner_status) {
6985 case defining: {@+print("definition");p=def_ref;
6986 } @+break;
6987 case matching: {@+print("argument");p=temp_head;
6988 } @+break;
6989 case aligning: {@+print("preamble");p=hold_head;
6990 } @+break;
6991 case absorbing: {@+print("text");p=def_ref;
6992 }
6993 } /*there are no other cases*/
6994 print_char('?');print_ln();show_token_list(link(p), null, error_line-10);
6995 }
6996 }
6997
6998 @ However, all this discussion about input state really applies only to the
6999 case that we are inputting from a file. There is another important case,
7000 namely when we are currently getting input from a token list. In this case
7001 |state==token_list|, and the conventions about the other state variables
7002 are different:
7003
7004 \yskip\hang|loc| is a pointer to the current node in the token list, i.e.,
7005 the node that will be read next. If |loc==null|, the token list has been
7006 fully read.
7007
7008 \yskip\hang|start| points to the first node of the token list; this node
7009 may or may not contain a reference count, depending on the type of token
7010 list involved.
7011
7012 \yskip\hang|token_type|, which takes the place of |index| in the
7013 discussion above, is a code number that explains what kind of token list
7014 is being scanned.
7015
7016 \yskip\hang|name| points to the |eqtb| address of the control sequence
7017 being expanded, if the current token list is a macro.
7018
7019 \yskip\hang|param_start|, which takes the place of |limit|, tells where
7020 the parameters of the current macro begin in the |param_stack|, if the
7021 current token list is a macro.
7022
7023 \yskip\noindent The |token_type| can take several values, depending on
7024 where the current token list came from:
7025
7026 \yskip\hang|parameter|, if a parameter is being scanned;
7027
7028 \hang|u_template|, if the \<u_j> part of an alignment
7029 template is being scanned;
7030
7031 \hang|v_template|, if the \<v_j> part of an alignment
7032 template is being scanned;
7033
7034 \hang|backed_up|, if the token list being scanned has been inserted as
7035 `to be read again';
7036
7037 \hang|inserted|, if the token list being scanned has been inserted as
7038 the text expansion of a \.{\\count} or similar variable;
7039
7040 \hang|macro|, if a user-defined control sequence is being scanned;
7041
7042 \hang|output_text|, if an \.{\\output} routine is being scanned;
7043
7044 \hang|every_par_text|, if the text of \.{\\everypar} is being scanned;
7045
7046 \hang|every_math_text|, if the text of \.{\\everymath} is being scanned;
7047
7048 \hang|every_display_text|, if the text of \.{\\everydisplay} is being scanned;
7049
7050 \hang|every_hbox_text|, if the text of \.{\\everyhbox} is being scanned;
7051
7052 \hang|every_vbox_text|, if the text of \.{\\everyvbox} is being scanned;
7053
7054 \hang|every_job_text|, if the text of \.{\\everyjob} is being scanned;
7055
7056 \hang|every_cr_text|, if the text of \.{\\everycr} is being scanned;
7057
7058 \hang|mark_text|, if the text of a \.{\\mark} is being scanned;
7059
7060 \hang|write_text|, if the text of a \.{\\write} is being scanned.
7061
7062 \yskip\noindent
7063 The codes for |output_text|, |every_par_text|, etc., are equal to a constant
7064 plus the corresponding codes for token list parameters |output_routine_loc|,
7065 |every_par_loc|, etc. The token list begins with a reference count if and
7066 only if |token_type >= macro|.
7067 @^reference counts@>
7068
7069 Since \eTeX's additional token list parameters precede |toks_base|, the
7070 corresponding token types must precede |write_text|.
7071
7072 @d token_list 0 /*|state| code when scanning a token list*/
7073 @d token_type index /*type of current token list*/
7074 @d param_start limit /*base of macro parameters in |param_stack|*/
7075 @d parameter 0 /*|token_type| code for parameter*/
7076 @d u_template 1 /*|token_type| code for \<u_j> template*/
7077 @d v_template 2 /*|token_type| code for \<v_j> template*/
7078 @d backed_up 3 /*|token_type| code for text to be reread*/
7079 @d inserted 4 /*|token_type| code for inserted texts*/
7080 @d macro 5 /*|token_type| code for defined control sequences*/
7081 @d output_text 6 /*|token_type| code for output routines*/
7082 @d every_par_text 7 /*|token_type| code for \.{\\everypar}*/
7083 @d every_math_text 8 /*|token_type| code for \.{\\everymath}*/
7084 @d every_display_text 9 /*|token_type| code for \.{\\everydisplay}*/
7085 @d every_hbox_text 10 /*|token_type| code for \.{\\everyhbox}*/
7086 @d every_vbox_text 11 /*|token_type| code for \.{\\everyvbox}*/
7087 @d every_job_text 12 /*|token_type| code for \.{\\everyjob}*/
7088 @d every_cr_text 13 /*|token_type| code for \.{\\everycr}*/
7089 @d mark_text 14 /*|token_type| code for \.{\\topmark}, etc.*/
7090 @#
7091 @d eTeX_text_offset (output_routine_loc-output_text)
7092 @d every_eof_text (every_eof_loc-eTeX_text_offset)
7093 /*|token_type| code for \.{\\everyeof}*/
7094 @#
7095 @d write_text (toks_base-eTeX_text_offset) /*|token_type| code for \.{\\write}*/
7096
7097 @ The |param_stack| is an auxiliary array used to hold pointers to the token
7098 lists for parameters at the current level and subsidiary levels of input.
7099 This stack is maintained with convention (2), and it grows at a different
7100 rate from the others.
7101
7102 @<Glob...@>=
7103 static pointer @!param_stack[param_size+1];
7104 /*token list pointers for parameters*/
7105 static int @!param_ptr; /*first unused entry in |param_stack|*/
7106 static int @!max_param_stack;
7107 /*largest value of |param_ptr|, will be | <= param_size+9|*/
7108
7109 @ The input routines must also interact with the processing of
7110 \.{\\halign} and \.{\\valign}, since the appearance of tab marks and
7111 \.{\\cr} in certain places is supposed to trigger the beginning of special
7112 \<v_j> template text in the scanner. This magic is accomplished by an
7113 |align_state| variable that is increased by~1 when a `\.{\char'173}' is
7114 scanned and decreased by~1 when a `\.{\char'175}' is scanned. The |align_state|
7115 is nonzero during the \<u_j> template, after which it is set to zero; the
7116 \<v_j> template begins when a tab mark or \.{\\cr} occurs at a time that
7117 |align_state==0|.
7118
7119 The same principle applies when entering the definition of a
7120 control sequence between \.{\\csname} and \.{\\endcsname}.
7121
7122 @<Glob...@>=
7123 static int @!align_state; /*group level with respect to current alignment*/
7124 static int @!incsname_state; /*group level with respect to in csname state*/
7125
7126 @ Thus, the ``current input state'' can be very complicated indeed; there
7127 can be many levels and each level can arise in a variety of ways. The
7128 |show_context| procedure, which is used by \TeX's error-reporting routine to
7129 print out the current input state on all levels down to the most recent
7130 line of characters from an input file, illustrates most of these conventions.
7131 The global variable |base_ptr| contains the lowest level that was
7132 displayed by this procedure.
7133
7134 @<Glob...@>=
7135 static int @!base_ptr; /*shallowest level shown by |show_context|*/
7136
7137 @ The status at each level is indicated by printing two lines, where the first
7138 line indicates what was read so far and the second line shows what remains
7139 to be read. The context is cropped, if necessary, so that the first line
7140 contains at most |half_error_line| characters, and the second contains
7141 at most |error_line|. Non-current input levels whose |token_type| is
7142 `|backed_up|' are shown only if they have not been fully read.
7143
7144 @p static void show_context(void) /*prints where the scanner is*/
7145 {@+
7146 int old_setting; /*saved |selector| setting*/
7147 int @!nn; /*number of contexts shown so far, less one*/
7148 bool @!bottom_line; /*have we reached the final context to be shown?*/
7149 @<Local variables for formatting calculations@>@/
7150 base_ptr=input_ptr;input_stack[base_ptr]=cur_input;
7151 /*store current state*/
7152 nn=-1;bottom_line=false;
7153 loop@+{@+cur_input=input_stack[base_ptr]; /*enter into the context*/
7154 if ((state!=token_list))
7155 if ((name > 19)||(base_ptr==0)) bottom_line=true;
7156 if ((base_ptr==input_ptr)||bottom_line||(nn < error_context_lines))
7157 @<Display the current context@>@;
7158 else if (nn==error_context_lines)
7159 {@+print_nl("...");incr(nn); /*omitted if |error_context_lines < 0|*/
7160 }
7161 if (bottom_line) goto done;
7162 decr(base_ptr);
7163 }
7164 done: cur_input=input_stack[input_ptr]; /*restore original state*/
7165 }
7166
7167 @ @<Display the current context@>=
7168 {@+if ((base_ptr==input_ptr)||(state!=token_list)||
7169 (token_type!=backed_up)||(loc!=null))
7170 /*we omit backed-up token lists that have already been read*/
7171 {@+tally=0; /*get ready to count characters*/
7172 old_setting=selector;
7173 if (state!=token_list)
7174 {@+@<Print location of current line@>;
7175 @<Pseudoprint the line@>;
7176 }
7177 else{@+@<Print type of token list@>;
7178 @<Pseudoprint the token list@>;
7179 }
7180 selector=old_setting; /*stop pseudoprinting*/
7181 @<Print two lines using the tricky pseudoprinted information@>;
7182 incr(nn);
7183 }
7184 }
7185
7186 @ This routine should be changed, if necessary, to give the best possible
7187 indication of where the current line resides in the input file.
7188 For example, on some systems it is best to print both a page and line number.
7189 @^system dependencies@>
7190
7191 @<Print location of current line@>=
7192 if (name <= 17)
7193 if (terminal_input)
7194 if (base_ptr==0) print_nl("<*>");else print_nl("<insert> ");
7195 else{@+print_nl("<read ");
7196 if (name==17) print_char('*');@+else print_int(name-1);
7197 @.*\relax@>
7198 print_char('>');
7199 }
7200 else{@+print_nl("l.");
7201 if (index==in_open) print_int(line);
7202 else print_int(line_stack[index+1]); /*input from a pseudo file*/
7203 }
7204 print_char(' ')
7205
7206 @ @<Print type of token list@>=
7207 switch (token_type) {
7208 case parameter: print_nl("<argument> ");@+break;
7209 case u_template: case v_template: print_nl("<template> ");@+break;
7210 case backed_up: if (loc==null) print_nl("<recently read> ");
7211 else print_nl("<to be read again> ");@+break;
7212 case inserted: print_nl("<inserted text> ");@+break;
7213 case macro: {@+print_ln();print_cs(name);
7214 } @+break;
7215 case output_text: print_nl("<output> ");@+break;
7216 case every_par_text: print_nl("<everypar> ");@+break;
7217 case every_math_text: print_nl("<everymath> ");@+break;
7218 case every_display_text: print_nl("<everydisplay> ");@+break;
7219 case every_hbox_text: print_nl("<everyhbox> ");@+break;
7220 case every_vbox_text: print_nl("<everyvbox> ");@+break;
7221 case every_job_text: print_nl("<everyjob> ");@+break;
7222 case every_cr_text: print_nl("<everycr> ");@+break;
7223 case mark_text: print_nl("<mark> ");@+break;
7224 case every_eof_text: print_nl("<everyeof> ");@+break;
7225 case write_text: print_nl("<write> ");@+break;
7226 default:print_nl("?"); /*this should never happen*/
7227 }
7228
7229 @ Here it is necessary to explain a little trick. We don't want to store a long
7230 string that corresponds to a token list, because that string might take up
7231 lots of memory; and we are printing during a time when an error message is
7232 being given, so we dare not do anything that might overflow one of \TeX's
7233 tables. So `pseudoprinting' is the answer: We enter a mode of printing
7234 that stores characters into a buffer of length |error_line|, where character
7235 $k+1$ is placed into \hbox{|trick_buf[k%error_line]|} if
7236 |k < trick_count|, otherwise character |k| is dropped. Initially we set
7237 |tally=0| and |trick_count=1000000|; then when we reach the
7238 point where transition from line 1 to line 2 should occur, we
7239 set |first_count=tally| and |trick_count=@tmax@>(error_line,
7240 tally+1+error_line-half_error_line)|. At the end of the
7241 pseudoprinting, the values of |first_count|, |tally|, and
7242 |trick_count| give us all the information we need to print the two lines,
7243 and all of the necessary text is in |trick_buf|.
7244
7245 Namely, let |l| be the length of the descriptive information that appears
7246 on the first line. The length of the context information gathered for that
7247 line is |k==first_count|, and the length of the context information
7248 gathered for line~2 is $m=\min(|tally|, |trick_count|)-k$. If |l+k <= h|,
7249 where |h==half_error_line|, we print |trick_buf[0 dotdot k-1]| after the
7250 descriptive information on line~1, and set |n=l+k|; here |n| is the
7251 length of line~1. If $l+k>h$, some cropping is necessary, so we set |n=h|
7252 and print `\.{...}' followed by
7253 $$\hbox{|trick_buf[(l+k-h+3)dotdot k-1]|,}$$
7254 where subscripts of |trick_buf| are circular modulo |error_line|. The
7255 second line consists of |n|~spaces followed by |trick_buf[k dotdot(k+m-1)]|,
7256 unless |n+m > error_line|; in the latter case, further cropping is done.
7257 This is easier to program than to explain.
7258
7259 @<Local variables for formatting...@>=
7260 int @!i; /*index into |buffer|*/
7261 int @!j; /*end of current line in |buffer|*/
7262 int @!l; /*length of descriptive information on line 1*/
7263 int @!m; /*context information gathered for line 2*/
7264 int @!n; /*length of line 1*/
7265 int @!p; /*starting or ending place in |trick_buf|*/
7266 int @!q; /*temporary index*/
7267
7268 @ The following code sets up the print routines so that they will gather
7269 the desired information.
7270
7271 @d begin_pseudoprint
7272 {@+l=tally;tally=0;selector=pseudo;
7273 trick_count=1000000;
7274 }
7275 @d set_trick_count
7276 {@+first_count=tally;
7277 trick_count=tally+1+error_line-half_error_line;
7278 if (trick_count < error_line) trick_count=error_line;
7279 }
7280
7281 @ And the following code uses the information after it has been gathered.
7282
7283 @<Print two lines using the tricky pseudoprinted information@>=
7284 if (trick_count==1000000) set_trick_count;
7285 /*|set_trick_count| must be performed*/
7286 if (tally < trick_count) m=tally-first_count;
7287 else m=trick_count-first_count; /*context on line 2*/
7288 if (l+first_count <= half_error_line)
7289 {@+p=0;n=l+first_count;
7290 }
7291 else{@+print("...");p=l+first_count-half_error_line+3;
7292 n=half_error_line;
7293 }
7294 for (q=p; q<=first_count-1; q++) print_char(trick_buf[q%error_line]);
7295 print_ln();
7296 for (q=1; q<=n; q++) print_char(' '); /*print |n| spaces to begin line~2*/
7297 if (m+n <= error_line) p=first_count+m;else p=first_count+(error_line-n-3);
7298 for (q=first_count; q<=p-1; q++) print_char(trick_buf[q%error_line]);
7299 if (m+n > error_line) print("...")
7300
7301 @ But the trick is distracting us from our current goal, which is to
7302 understand the input state. So let's concentrate on the data structures that
7303 are being pseudoprinted as we finish up the |show_context| procedure.
7304
7305 @<Pseudoprint the line@>=
7306 begin_pseudoprint;
7307 if (buffer[limit]==end_line_char) j=limit;
7308 else j=limit+1; /*determine the effective end of the line*/
7309 if (j > 0) for (i=start; i<=j-1; i++)
7310 {@+if (i==loc) set_trick_count;
7311 printn(buffer[i]);
7312 }
7313
7314 @ @<Pseudoprint the token list@>=
7315 begin_pseudoprint;
7316 if (token_type < macro) show_token_list(start, loc, 100000);
7317 else show_token_list(link(start), loc, 100000) /*avoid reference count*/
7318
7319 @ Here is the missing piece of |show_token_list| that is activated when the
7320 token beginning line~2 is about to be shown:
7321
7322 @<Do magic computation@>=set_trick_count
7323
7324 @* Maintaining the input stacks.
7325 The following subroutines change the input status in commonly needed ways.
7326
7327 First comes |push_input|, which stores the current state and creates a
7328 new level (having, initially, the same properties as the old).
7329
7330 @d push_input @t@> /*enter a new input level, save the old*/
7331 {@+if (input_ptr > max_in_stack)
7332 {@+max_in_stack=input_ptr;
7333 if (input_ptr==stack_size) overflow("input stack size", stack_size);
7334 @:TeX capacity exceeded input stack size}{\quad input stack size@>
7335 }
7336 input_stack[input_ptr]=cur_input; /*stack the record*/
7337 incr(input_ptr);
7338 }
7339
7340 @ And of course what goes up must come down.
7341
7342 @d pop_input @t@> /*leave an input level, re-enter the old*/
7343 {@+decr(input_ptr);cur_input=input_stack[input_ptr];
7344 }
7345
7346 @ Here is a procedure that starts a new level of token-list input, given
7347 a token list |p| and its type |t|. If |t==macro|, the calling routine should
7348 set |name| and |loc|.
7349
7350 @d back_list(A) begin_token_list(A, backed_up) /*backs up a simple token list*/
7351 @d ins_list(A) begin_token_list(A, inserted) /*inserts a simple token list*/
7352
7353 @p static void begin_token_list(pointer @!p, quarterword @!t)
7354 {@+push_input;state=token_list;start=p;token_type=t;
7355 if (t >= macro) /*the token list starts with a reference count*/
7356 {@+add_token_ref(p);
7357 if (t==macro) param_start=param_ptr;
7358 else{@+
7359 @<additional local variables for |begin_token_list|@>
7360 loc=link(p);
7361 if (tracing_macros > 1)
7362 {@+begin_diagnostic();print_nl("");
7363 switch (t) {
7364 case mark_text: print_esc("mark");@+break;
7365 case write_text: print_esc("write");@+break;
7366 default:print_cmd_chr(assign_toks, t-output_text+output_routine_loc);
7367 } @/
7368 print("->");token_show(p);end_diagnostic(false);
7369 }
7370 @<update the macro stack@>@;
7371 }
7372 }
7373 else loc=p;
7374 }
7375
7376 @ When a token list has been fully scanned, the following computations
7377 should be done as we leave that level of input. The |token_type| tends
7378 to be equal to either |backed_up| or |inserted| about 2/3 of the time.
7379 @^inner loop@>
7380
7381 @p static void end_token_list(void) /*leave a token-list input level*/
7382 {@+if (token_type >= backed_up) /*token list to be deleted*/
7383 {@+if (token_type <= inserted) flush_list(start);
7384 else{@+delete_token_ref(start); /*update reference count*/
7385 if (token_type==macro) /*parameters must be flushed*/
7386 while (param_ptr > param_start)
7387 {@+decr(param_ptr);
7388 flush_list(param_stack[param_ptr]);
7389 }
7390 }
7391 }
7392 else if (token_type==u_template)
7393 if (align_state > 500000) align_state=0;
7394 else fatal_error("(interwoven alignment preambles are not allowed)");
7395 @.interwoven alignment preambles...@>
7396 pop_input;
7397 check_interrupt;
7398 }
7399
7400 @ Sometimes \TeX\ has read too far and wants to ``unscan'' what it has
7401 seen. The |back_input| procedure takes care of this by putting the token
7402 just scanned back into the input stream, ready to be read again. This
7403 procedure can be used only if |cur_tok| represents the token to be
7404 replaced. Some applications of \TeX\ use this procedure a lot,
7405 so it has been slightly optimized for speed.
7406 @^inner loop@>
7407
7408 We charge the backup token to the current file and line.
7409 @^profiling@>
7410
7411 @p static void back_input(void) /*undoes one token of input*/
7412 {@+pointer p; /*a token list of length one*/
7413 while ((state==token_list)&&(loc==null)&&(token_type!=v_template))
7414 end_token_list(); /*conserve stack space*/
7415 p=get_avail();info(p)=cur_tok; fl_mem[p]=prof_file_line;
7416 if (cur_tok < right_brace_limit)
7417 if (cur_tok < left_brace_limit) decr(align_state);
7418 else incr(align_state);
7419 push_input;state=token_list;start=p;token_type=backed_up;
7420 loc=p; /*that was |back_list(p)|, without procedure overhead*/
7421 }
7422
7423 @ @<Insert token |p| into \TeX's input@>=
7424 {@+t=cur_tok;cur_tok=p;
7425 if (a)
7426 {@+p=get_avail();info(p)=cur_tok;link(p)=loc;loc=p;start=p;
7427 if (cur_tok < right_brace_limit)
7428 if (cur_tok < left_brace_limit) decr(align_state);
7429 else incr(align_state);
7430 }
7431 else{@+back_input();a=eTeX_ex;
7432 }
7433 cur_tok=t;
7434 }
7435
7436 @ The |back_error| routine is used when we want to replace an offending token
7437 just before issuing an error message. This routine, like |back_input|,
7438 requires that |cur_tok| has been set. We disable interrupts during the
7439 call of |back_input| so that the help message won't be lost.
7440
7441 @p static void back_error(void) /*back up one token and call |error|*/
7442 {@+OK_to_interrupt=false;back_input();OK_to_interrupt=true;error();
7443 }
7444 @#
7445 static void ins_error(void) /*back up one inserted token and call |error|*/
7446 {@+OK_to_interrupt=false;back_input();token_type=inserted;
7447 OK_to_interrupt=true;error();
7448 }
7449
7450 @ The |begin_file_reading| procedure starts a new level of input for lines
7451 of characters to be read from a file, or as an insertion from the
7452 terminal. It does not take care of opening the file, nor does it set |loc|
7453 or |limit| or |line|.
7454 @^system dependencies@>
7455
7456 @p static void begin_file_reading(void)
7457 {@+if (in_open==max_in_open) overflow("text input levels", max_in_open);
7458 @:TeX capacity exceeded text input levels}{\quad text input levels@>
7459 if (first==buf_size) overflow("buffer size", buf_size);
7460 @:TeX capacity exceeded buffer size}{\quad buffer size@>
7461 incr(in_open);push_input;index=in_open;@/
7462 source_filename_stack[index]=NULL; /* \TeX\ Live */
7463 full_source_filename_stack[index]=NULL; /* \TeX\ Live */
7464 eof_seen[index]=false;
7465 grp_stack[index]=cur_boundary;if_stack[index]=cond_ptr;
7466 line_stack[index]=line;start=first;state=mid_line;
7467 name=0; /*|terminal_input| is now |true|*/
7468 cur_file_num=terminal_file;
7469 }
7470
7471 @ Conversely, the variables must be downdated when such a level of input
7472 is finished:
7473
7474 @p static void end_file_reading(void)
7475 {@+first=start;line=line_stack[index];
7476 if ((name==18)||(name==19)) pseudo_close();else
7477 if (name > 17) a_close(&cur_file); /*forget it*/
7478 if (full_source_filename_stack[in_open]!=NULL)
7479 { free(full_source_filename_stack[in_open]);
7480 full_source_filename_stack[in_open]=NULL;
7481 }
7482 pop_input;decr(in_open);
7483 }
7484
7485 @ In order to keep the stack from overflowing during a long sequence of
7486 inserted `\.{\\show}' commands, the following routine removes completed
7487 error-inserted lines from memory.
7488
7489 @p static void clear_for_error_prompt(void)
7490 {@+while ((state!=token_list)&&terminal_input&&@|
7491 (input_ptr > 0)&&(loc > limit)) end_file_reading();
7492 print_ln();clear_terminal;
7493 }
7494
7495 @ To get \TeX's whole input mechanism going, we perform the following
7496 actions.
7497
7498 @<Initialize the input routines@>=
7499 {@+input_ptr=0;max_in_stack=0;
7500 in_open=0;open_parens=0;max_buf_stack=0;
7501 grp_stack[0]=0;if_stack[0]=null;
7502 param_ptr=0;max_param_stack=0;
7503 first=buf_size;@/do@+{buffer[first]=0;decr(first);}@+ while (!(first==0));
7504 scanner_status=normal;warning_index=null;first=1;
7505 state=new_line;start=1;index=0;line=0;name=0;cur_depth=0;
7506 force_eof=false;
7507 align_state=1000000;@/
7508 if (!init_terminal()) exit(0);
7509 limit=last;first=last+1; /*|init_terminal| has set |loc| and |last|*/
7510 }
7511
7512 @* Getting the next token.
7513 The heart of \TeX's input mechanism is the |get_next| procedure, which
7514 we shall develop in the next few sections of the program. Perhaps we
7515 shouldn't actually call it the ``heart,'' however, because it really acts
7516 as \TeX's eyes and mouth, reading the source files and gobbling them up.
7517 And it also helps \TeX\ to regurgitate stored token lists that are to be
7518 processed again.
7519 @^eyes and mouth@>
7520
7521 The main duty of |get_next| is to input one token and to set |cur_cmd|
7522 and |cur_chr| to that token's command code and modifier. Furthermore, if
7523 the input token is a control sequence, the |eqtb| location of that control
7524 sequence is stored in |cur_cs|; otherwise |cur_cs| is set to zero.
7525
7526 Underlying this simple description is a certain amount of complexity
7527 because of all the cases that need to be handled.
7528 However, the inner loop of |get_next| is reasonably short and fast.
7529
7530 When |get_next| is asked to get the next token of a \.{\\read} line,
7531 it sets |cur_cmd==cur_chr==cur_cs==0| in the case that no more tokens
7532 appear on that line. (There might not be any tokens at all, if the
7533 |end_line_char| has |ignore| as its catcode.)
7534
7535 @ The value of |par_loc| is the |eqtb| address of `\.{\\par}'. This quantity
7536 is needed because a blank line of input is supposed to be exactly equivalent
7537 to the appearance of \.{\\par}; we must set |cur_cs:=par_loc|
7538 when detecting a blank line.
7539
7540 The same is true for the input, for the warning message, since input
7541 is expected by default before every scanning and hence setting of
7542 |cur_cs|.
7543
7544 @<Glob...@>=
7545 static pointer @!par_loc; /*location of `\.{\\par}' in |eqtb|*/
7546 static halfword @!par_token; /*token representing `\.{\\par}'*/
7547 static pointer @!input_loc; /*location of `\.{\\input}' in |eqtb|*/
7548 static halfword @!input_token; /*token representing `\.{\\input}'*/
7549
7550 @ @<Put each...@>=
7551 primitive("par", par_end, 256); /*cf.\ |scan_file_name|*/
7552 @!@:par\_}{\.{\\par} primitive@>
7553 par_loc=cur_val;par_token=cs_token_flag+par_loc;
7554
7555 @ @<Cases of |print_cmd_chr|...@>=
7556 case par_end: print_esc("par");@+break;
7557
7558 @ Before getting into |get_next|, let's consider the subroutine that
7559 is called when an `\.{\\outer}' control sequence has been scanned or
7560 when the end of a file has been reached. These two cases are distinguished
7561 by |cur_cs|, which is zero at the end of a file.
7562
7563 @p static void check_outer_validity(void)
7564 {@+pointer p; /*points to inserted token list*/
7565 pointer @!q; /*auxiliary pointer*/
7566 if (scanner_status!=normal)
7567 {@+deletions_allowed=false;
7568 @<Back up an outer control sequence so that it can be reread@>;
7569 if (scanner_status > skipping)
7570 @<Tell the user what has run away and try to recover@>@;
7571 else{@+print_err("Incomplete ");print_cmd_chr(if_test, cur_if);
7572 @.Incomplete \\if...@>
7573 print("; all text was ignored after line ");print_int(skip_line);
7574 help3("A forbidden control sequence occurred in skipped text.",@/
7575 "This kind of error happens when you say `\\if...' and forget",@/
7576 "the matching `\\fi'. I've inserted a `\\fi'; this might work.");
7577 if (cur_cs!=0) cur_cs=0;
7578 else help_line[2]=@|
7579 "The file ended while I was skipping conditional text.";
7580 cur_tok=cs_token_flag+frozen_fi;ins_error();
7581 }
7582 deletions_allowed=true;
7583 }
7584 }
7585
7586 @ An outer control sequence that occurs in a \.{\\read} will not be reread,
7587 since the error recovery for \.{\\read} is not very powerful.
7588
7589 @<Back up an outer control sequence so that it can be reread@>=
7590 if (cur_cs!=0)
7591 {@+if ((state==token_list)||(name < 1)||(name > 17))
7592 {@+p=get_avail();info(p)=cs_token_flag+cur_cs;
7593 back_list(p); /*prepare to read the control sequence again*/
7594 }
7595 cur_cmd=spacer;cur_chr=' '; /*replace it by a space*/
7596 }
7597
7598 @ @<Tell the user what has run away...@>=
7599 {@+runaway(); /*print a definition, argument, or preamble*/
7600 if (cur_cs==0) print_err("File ended");
7601 @.File ended while scanning...@>
7602 else{@+cur_cs=0;print_err("Forbidden control sequence found");
7603 @.Forbidden control sequence...@>
7604 }
7605 print(" while scanning ");
7606 @<Print either `\.{definition}' or `\.{use}' or `\.{preamble}' or `\.{text}',
7607 and insert tokens that should lead to recovery@>;
7608 print(" of ");sprint_cs(warning_index);
7609 help4("I suspect you have forgotten a `}', causing me",@/
7610 "to read past where you wanted me to stop.",@/
7611 "I'll try to recover; but if the error is serious,",@/
7612 "you'd better type `E' or `X' now and fix your file.");@/
7613 error();
7614 }
7615
7616 @ The recovery procedure can't be fully understood without knowing more
7617 about the \TeX\ routines that should be aborted, but we can sketch the
7618 ideas here: For a runaway definition or a runaway balanced text
7619 we will insert a right brace; for a
7620 runaway preamble, we will insert a special \.{\\cr} token and a right
7621 brace; and for a runaway argument, we will set |long_state| to
7622 |outer_call| and insert \.{\\par}.
7623
7624 @<Print either `\.{definition}' or...@>=
7625 p=get_avail();
7626 switch (scanner_status) {
7627 case defining: {@+print("definition");info(p)=right_brace_token+'}';
7628 } @+break;
7629 case matching: {@+print("use");info(p)=par_token;long_state=outer_call;
7630 } @+break;
7631 case aligning: {@+print("preamble");info(p)=right_brace_token+'}';q=p;
7632 p=get_avail();link(p)=q;info(p)=cs_token_flag+frozen_cr;
7633 align_state=-1000000;
7634 } @+break;
7635 case absorbing: {@+print("text");info(p)=right_brace_token+'}';
7636 }
7637 } /*there are no other cases*/
7638 ins_list(p)
7639
7640 @ We need to mention a procedure here that may be called by |get_next|.
7641
7642 @p static void firm_up_the_line(void);
7643
7644 @ Now we're ready to take the plunge into |get_next| itself. Parts of
7645 this routine are executed more often than any other instructions of \TeX.
7646 @^mastication@>@^inner loop@>
7647
7648 @p static void get_next(void) /*sets |cur_cmd|, |cur_chr|, |cur_cs| to next token*/
7649 {@+ /*go here to get the next input token*/
7650 /*go here to eat the next character from a file*/
7651 /*go here to digest it again*/
7652 /*go here to start looking for a control sequence*/
7653 /*go here when a control sequence has been found*/
7654 /*go here when the next input token has been got*/
7655 int k; /*an index into |buffer|*/
7656 halfword @!t; /*a token*/
7657 int @!cat; /*|cat_code(cur_chr)|, usually*/
7658 ASCII_code @!c, @!cc; /*constituents of a possible expanded code*/
7659 int @!d; /*number of excess characters in an expanded code*/
7660 restart: cur_cs=0;
7661 if (state!=token_list)
7662 @<Input from external file, |goto restart| if no input found@>@;
7663 else@<Input from token list, |goto restart| if end of list or if a parameter
7664 needs to be expanded@>;
7665 @<If an alignment entry has just ended, take appropriate action@>;
7666 }
7667
7668 @ An alignment entry ends when a tab or \.{\\cr} occurs, provided that the
7669 current level of braces is the same as the level that was present at the
7670 beginning of that alignment entry; i.e., provided that |align_state| has
7671 returned to the value it had after the \<u_j> template for that entry.
7672 @^inner loop@>
7673
7674 @<If an alignment entry has just ended, take appropriate action@>=
7675 if (cur_cmd <= car_ret) if (cur_cmd >= tab_mark) if (align_state==0)
7676 @<Insert the \(v)\<v_j> template and |goto restart|@>@;
7677
7678 @ @<Input from external file, |goto restart| if no input found@>=
7679 @^inner loop@>
7680 {@+get_cur_chr: if (loc <= limit) /*current line not yet finished*/
7681 {@+cur_chr=buffer[loc];incr(loc);
7682 @<Set |cur_file_line| based on the information in |cur_input|@>@;
7683 reswitch: cur_cmd=cat_code(cur_chr);
7684 @<Change state if necessary, and |goto get_cur_chr| if the current character
7685 should be ignored, or |goto reswitch| if the current character changes to
7686 another@>;
7687 }
7688 else{@+state=new_line;@/
7689 @<Move to next line of file, or |goto restart| if there is no next line,
7690 or |return| if a \.{\\read} line has finished@>;
7691 check_interrupt;
7692 goto get_cur_chr;
7693 }
7694 }
7695
7696 @ The following 48-way switch accomplishes the scanning quickly, assuming
7697 that a decent \PASCAL\ compiler has translated the code. Note that the numeric
7698 values for |mid_line|, |skip_blanks|, and |new_line| are spaced
7699 apart from each other by |max_char_code+1|, so we can add a character's
7700 command code to the state to get a single number that characterizes both.
7701
7702 @d any_state_plus(A) case mid_line+A:
7703 case skip_blanks+A: case new_line+A
7704
7705 @<Change state if necessary...@>=
7706 switch (state+cur_cmd) {
7707 @<Cases where character is ignored@>: goto get_cur_chr;
7708 any_state_plus(escape): @<Scan a control sequence and set |state:=skip_blanks|
7709 or |mid_line|@>@;@+break;
7710 any_state_plus(active_char): @<Process an active-character control sequence
7711 and set |state:=mid_line|@>@;@+break;
7712 any_state_plus(sup_mark): @<If this |sup_mark| starts an expanded character
7713 like~\.{\^\^A} or~\.{\^\^df}, then |goto reswitch|, otherwise set |state:=mid_line|@>@;@+break;
7714 any_state_plus(invalid_char): @<Decry the invalid character and |goto restart|@>@;
7715 @t\4@>@<Handle situations involving spaces, braces, changes of state@>@;
7716 default:do_nothing;
7717 }
7718
7719 @ @<Cases where character is ignored@>=
7720 any_state_plus(ignore): case skip_blanks+spacer:
7721 case new_line+spacer
7722
7723 @ We go to |restart| instead of to |get_cur_chr|, because |state| might equal
7724 |token_list| after the error has been dealt with
7725 (cf.\ |clear_for_error_prompt|).
7726
7727 @<Decry the invalid...@>=
7728 {@+print_err("Text line contains an invalid character");
7729 @.Text line contains...@>
7730 help2("A funny symbol that I can't read has just been input.",@/
7731 "Continue, and I'll forget that it ever happened.");@/
7732 deletions_allowed=false;error();deletions_allowed=true;
7733 goto restart;
7734 }
7735
7736 @ @d add_delims_to(A) A+math_shift: A+tab_mark: A+mac_param:
7737 A+sub_mark: A+letter: A+other_char
7738
7739 @<Handle situations involving spaces, braces, changes of state@>=
7740 case mid_line+spacer: @<Enter |skip_blanks| state, emit a space@>@;@+break;
7741 case mid_line+car_ret: @<Finish line, emit a space@>@;@+break;
7742 case skip_blanks+car_ret: any_state_plus(comment):
7743 @<Finish line, |goto switch|@>@;
7744 case new_line+car_ret: @<Finish line, emit a \.{\\par}@>@;@+break;
7745 case mid_line+left_brace: incr(align_state);@+break;
7746 case skip_blanks+left_brace: case new_line+left_brace: {@+
7747 state=mid_line;incr(align_state);
7748 } @+break;
7749 case mid_line+right_brace: decr(align_state);@+break;
7750 case skip_blanks+right_brace: case new_line+right_brace: {@+
7751 state=mid_line;decr(align_state);
7752 } @+break;
7753 add_delims_to(case skip_blanks): add_delims_to(
7754 case new_line): state=mid_line;@+break;
7755
7756 @ When a character of type |spacer| gets through, its character code is
7757 changed to $\.{"\ "}=040$. This means that the ASCII codes for tab and space,
7758 and for the space inserted at the end of a line, will
7759 be treated alike when macro parameters are being matched. We do this
7760 since such characters are indistinguishable on most computer terminal displays.
7761
7762 @<Finish line, emit a space@>=
7763 {@+loc=limit+1;cur_cmd=spacer;cur_chr=' ';
7764 }
7765
7766 @ The following code is performed only when |cur_cmd==spacer|.
7767
7768 @<Enter |skip_blanks| state, emit a space@>=
7769 {@+state=skip_blanks;cur_chr=' ';
7770 }
7771
7772 @ @<Finish line, |goto switch|@>=
7773 {@+loc=limit+1;goto get_cur_chr;
7774 }
7775
7776 @ @<Finish line, emit a \.{\\par}@>=
7777 {@+loc=limit+1;cur_cs=par_loc;cur_cmd=eq_type(cur_cs);
7778 cur_chr=equiv(cur_cs);
7779 if (cur_cmd >= outer_call) check_outer_validity();
7780 }
7781
7782 @ Notice that a code like \.{\^\^8} becomes \.x if not followed by a hex digit.
7783
7784 @d is_hex(A) (((A >= '0')&&(A <= '9'))||((A >= 'a')&&(A <= 'f')))
7785 @d hex_to_cur_chr
7786 if (c <= '9') cur_chr=c-'0';@+else cur_chr=c-'a'+10;
7787 if (cc <= '9') cur_chr=16*cur_chr+cc-'0';
7788 else cur_chr=16*cur_chr+cc-'a'+10
7789
7790 @<If this |sup_mark| starts an expanded character...@>=
7791 {@+if (cur_chr==buffer[loc]) if (loc < limit)
7792 {@+c=buffer[loc+1];@+if (c < 0200) /*yes we have an expanded char*/
7793 {@+loc=loc+2;
7794 if (is_hex(c)) if (loc <= limit)
7795 {@+cc=buffer[loc];@+if (is_hex(cc))
7796 {@+incr(loc);hex_to_cur_chr;goto reswitch;
7797 }
7798 }
7799 if (c < 0100) cur_chr=c+0100;@+else cur_chr=c-0100;
7800 goto reswitch;
7801 }
7802 }
7803 state=mid_line;
7804 }
7805
7806 @ @<Process an active-character...@>=
7807 {@+cur_cs=cur_chr+active_base;
7808 cur_cmd=eq_type(cur_cs);cur_chr=equiv(cur_cs);state=mid_line;
7809 if (cur_cmd >= outer_call) check_outer_validity();
7810 }
7811
7812 @ Control sequence names are scanned only when they appear in some line of
7813 a file; once they have been scanned the first time, their |eqtb| location
7814 serves as a unique identification, so \TeX\ doesn't need to refer to the
7815 original name any more except when it prints the equivalent in symbolic form.
7816
7817 The program that scans a control sequence has been written carefully
7818 in order to avoid the blowups that might otherwise occur if a malicious
7819 user tried something like `\.{\\catcode\'15=0}'. The algorithm might
7820 look at |buffer[limit+1]|, but it never looks at |buffer[limit+2]|.
7821
7822 If expanded characters like `\.{\^\^A}' or `\.{\^\^df}'
7823 appear in or just following
7824 a control sequence name, they are converted to single characters in the
7825 buffer and the process is repeated, slowly but surely.
7826
7827 @<Scan a control...@>=
7828 {@+if (loc > limit) cur_cs=null_cs; /*|state| is irrelevant in this case*/
7829 else{@+start_cs: k=loc;cur_chr=buffer[k];cat=cat_code(cur_chr);
7830 incr(k);
7831 if (cat==letter) state=skip_blanks;
7832 else if (cat==spacer) state=skip_blanks;
7833 else state=mid_line;
7834 if ((cat==letter)&&(k <= limit))
7835 @<Scan ahead in the buffer until finding a nonletter; if an expanded code
7836 is encountered, reduce it and |goto start_cs|; otherwise if a multiletter
7837 control sequence is found, adjust |cur_cs| and |loc|, and |goto found|@>@;
7838 else@<If an expanded code is present, reduce it and |goto start_cs|@>;
7839 cur_cs=single_base+buffer[loc];incr(loc);
7840 }
7841 found: cur_cmd=eq_type(cur_cs);cur_chr=equiv(cur_cs);
7842 if (cur_cmd >= outer_call) check_outer_validity();
7843 }
7844
7845 @ Whenever we reach the following piece of code, we will have
7846 |cur_chr==buffer[k-1]| and |k <= limit+1| and |cat==cat_code(cur_chr)|. If an
7847 expanded code like \.{\^\^A} or \.{\^\^df} appears in |buffer[(k-1)dotdot(k+1)]|
7848 or |buffer[(k-1)dotdot(k+2)]|, we
7849 will store the corresponding code in |buffer[k-1]| and shift the rest of
7850 the buffer left two or three places.
7851
7852 @<If an expanded...@>=
7853 {@+if (buffer[k]==cur_chr) @+if (cat==sup_mark) @+if (k < limit)
7854 {@+c=buffer[k+1];@+if (c < 0200) /*yes, one is indeed present*/
7855 {@+d=2;
7856 if (is_hex(c)) @+if (k+2 <= limit)
7857 {@+cc=buffer[k+2];@+if (is_hex(cc)) incr(d);
7858 }
7859 if (d > 2)
7860 {@+hex_to_cur_chr;buffer[k-1]=cur_chr;
7861 }
7862 else if (c < 0100) buffer[k-1]=c+0100;
7863 else buffer[k-1]=c-0100;
7864 limit=limit-d;first=first-d;
7865 while (k <= limit)
7866 {@+buffer[k]=buffer[k+d];incr(k);
7867 }
7868 goto start_cs;
7869 }
7870 }
7871 }
7872
7873 @ @<Scan ahead in the buffer...@>=
7874 {@+@/do@+{cur_chr=buffer[k];cat=cat_code(cur_chr);incr(k);
7875 }@+ while (!((cat!=letter)||(k > limit)));
7876 @<If an expanded...@>;
7877 if (cat!=letter) decr(k);
7878 /*now |k| points to first nonletter*/
7879 if (k > loc+1) /*multiletter control sequence has been scanned*/
7880 {@+cur_cs=id_lookup(loc, k-loc);loc=k;goto found;
7881 }
7882 }
7883
7884 @ Let's consider now what happens when |get_next| is looking at a token list.
7885 We restore the file and line information.
7886 @^profiling@>
7887
7888 @<Input from token list, |goto restart| if end of list or if a parameter needs
7889 to be expanded@>=
7890 if (loc!=null) /*list not exhausted*/
7891 @^inner loop@>
7892 {@+t=info(loc); cur_file_line=fl_mem[loc];
7893 loc=link(loc); /*move to next*/
7894 if (t >= cs_token_flag) /*a control sequence token*/
7895 {@+cur_cs=t-cs_token_flag;
7896 cur_cmd=eq_type(cur_cs);cur_chr=equiv(cur_cs);
7897 if (cur_cmd >= outer_call)
7898 if (cur_cmd==dont_expand)
7899 @<Get the next token, suppressing expansion@>@;
7900 else check_outer_validity();
7901 }
7902 else{@+cur_cmd=t/0400;cur_chr=t%0400;
7903 switch (cur_cmd) {
7904 case left_brace: incr(align_state);@+break;
7905 case right_brace: decr(align_state);@+break;
7906 case out_param: @<Insert macro parameter and |goto restart|@>@;
7907 default:do_nothing;
7908 }
7909 }
7910 }
7911 else{@+ /*we are done with this token list*/
7912 end_token_list();goto restart; /*resume previous level*/
7913 }
7914
7915 @ The present point in the program is reached only when the |expand|
7916 routine has inserted a special marker into the input. In this special
7917 case, |info(loc)| is known to be a control sequence token, and |link(loc)==null|.
7918
7919 @d no_expand_flag 257 /*this characterizes a special variant of |relax|*/
7920
7921 @<Get the next token, suppressing expansion@>=
7922 {@+cur_cs=info(loc)-cs_token_flag;loc=null;@/
7923 cur_cmd=eq_type(cur_cs);cur_chr=equiv(cur_cs);
7924 if (cur_cmd > max_command)
7925 {@+cur_cmd=relax;cur_chr=no_expand_flag;
7926 }
7927 }
7928
7929 @ @<Insert macro parameter...@>=
7930 {@+begin_token_list(param_stack[param_start+cur_chr-1], parameter);
7931 goto restart;
7932 }
7933
7934 @ All of the easy branches of |get_next| have now been taken care of.
7935 There is one more branch.
7936
7937 @d end_line_char_inactive (end_line_char < 0)||(end_line_char > 255)
7938
7939 @<Move to next line of file, or |goto restart|...@>=
7940 if (name > 17) @<Read next line of file into |buffer|, or |goto restart| if
7941 the file has ended@>@;
7942 else{@+if (!terminal_input) /*\.{\\read} line has ended*/
7943 {@+cur_cmd=0;cur_chr=0;
7944 @<Set |cur_file_line| when a \.{\\read} line ends@>@;
7945 return;
7946 }
7947 if (input_ptr > 0) /*text was inserted during error recovery*/
7948 {@+end_file_reading();goto restart; /*resume previous level*/
7949 }
7950 if (selector < log_only) open_log_file();
7951 if (interaction > nonstop_mode)
7952 {@+if (end_line_char_inactive) incr(limit);
7953 if (limit==start) /*previous line was empty*/
7954 print_nl("(Please type a command or say `\\end')");
7955 @.Please type...@>
7956 print_ln();first=start;
7957 prompt_input("*"); /*input on-line into |buffer|*/
7958 @.*\relax@>
7959 limit=last;
7960 if (end_line_char_inactive) decr(limit);
7961 else buffer[limit]=end_line_char;
7962 first=limit+1;
7963 loc=start;
7964 }
7965 else fatal_error("*** (job aborted, no legal \\end found)");
7966 @.job aborted@>
7967 /*nonstop mode, which is intended for overnight batch processing,
7968 never waits for on-line input*/
7969 }
7970
7971 @ The global variable |force_eof| is normally |false|; it is set |true|
7972 by an \.{\\endinput} command.
7973
7974 @<Glob...@>=
7975 static bool @!force_eof; /*should the next \.{\\input} be aborted early?*/
7976
7977 @ @<Read next line of file into |buffer|, or |goto restart| if the file has
7978 ended@>=
7979 {@+incr(line);first=start;
7980 @<check |line| for overflow@>@;
7981 if (!force_eof)
7982 if (name <= 19)
7983 {@+if (pseudo_input()) /*not end of file*/
7984 firm_up_the_line(); /*this sets |limit|*/
7985 else if ((every_eof!=null)&&!eof_seen[index])
7986 {@+limit=first-1;eof_seen[index]=true; /*fake one empty line*/
7987 begin_token_list(every_eof, every_eof_text);goto restart;
7988 }
7989 else force_eof=true;
7990 }
7991 else
7992 {@+if (input_ln(&cur_file, true)) /*not end of file*/
7993 firm_up_the_line(); /*this sets |limit|*/
7994 else if ((every_eof!=null)&&!eof_seen[index])
7995 {@+limit=first-1;eof_seen[index]=true; /*fake one empty line*/
7996 begin_token_list(every_eof, every_eof_text);goto restart;
7997 }
7998 else force_eof=true;
7999 }
8000 if (force_eof)
8001 {@+if (tracing_nesting > 0)
8002 if ((grp_stack[in_open]!=cur_boundary)||@|
8003 (if_stack[in_open]!=cond_ptr)) file_warning();
8004 /*give warning for some unfinished groups and/or conditionals*/
8005 if (name >= 19)
8006 {@+print_char(')');decr(open_parens);
8007 update_terminal; /*show user that file has been read*/
8008 }
8009 force_eof=false;
8010 end_file_reading(); /*resume previous level*/
8011 check_outer_validity();goto restart;
8012 }
8013 if (end_line_char_inactive) decr(limit);
8014 else buffer[limit]=end_line_char;
8015 first=limit+1;loc=start; /*ready to read*/
8016 }
8017
8018 @ If the user has set the |pausing| parameter to some positive value,
8019 and if nonstop mode has not been selected, each line of input is displayed
8020 on the terminal and the transcript file, followed by `\.{=>}'.
8021 \TeX\ waits for a response. If the response is simply |carriage_return|, the
8022 line is accepted as it stands, otherwise the line typed is
8023 used instead of the line in the file.
8024
8025 @p static void firm_up_the_line(void)
8026 {@+int k; /*an index into |buffer|*/
8027 limit=last;
8028 if (pausing > 0) if (interaction > nonstop_mode)
8029 {@+wake_up_terminal;print_ln();
8030 if (start < limit) for (k=start; k<=limit-1; k++) printn(buffer[k]);
8031 first=limit;prompt_input("=>"); /*wait for user response*/
8032 @.=>@>
8033 if (last > first)
8034 {@+for (k=first; k<=last-1; k++) /*move line down in buffer*/
8035 buffer[k+start-first]=buffer[k];
8036 limit=start+last-first;
8037 }
8038 }
8039 }
8040
8041 @ Since |get_next| is used so frequently in \TeX, it is convenient
8042 to define three related procedures that do a little more:
8043
8044 \yskip\hang|get_token| not only sets |cur_cmd| and |cur_chr|, it
8045 also sets |cur_tok|, a packed halfword version of the current token.
8046
8047 \yskip\hang|get_x_token|, meaning ``get an expanded token,'' is like
8048 |get_token|, but if the current token turns out to be a user-defined
8049 control sequence (i.e., a macro call), or a conditional,
8050 or something like \.{\\topmark} or \.{\\expandafter} or \.{\\csname},
8051 it is eliminated from the input by beginning the expansion of the macro
8052 or the evaluation of the conditional.
8053
8054 \yskip\hang|x_token| is like |get_x_token| except that it assumes that
8055 |get_next| has already been called.
8056
8057 \yskip\noindent
8058 In fact, these three procedures account for almost every use of |get_next|.
8059
8060 @ No new control sequences will be defined except during a call of
8061 |get_token|, or when \.{\\csname} compresses a token list, because
8062 |no_new_control_sequence| is always |true| at other times.
8063
8064 @p static void get_token(void) /*sets |cur_cmd|, |cur_chr|, |cur_tok|*/
8065 {@+no_new_control_sequence=false;get_next();no_new_control_sequence=true;
8066 @^inner loop@>
8067 if (cur_cs==0) cur_tok=(cur_cmd*0400)+cur_chr;
8068 else cur_tok=cs_token_flag+cur_cs;
8069 }
8070
8071 @* Expanding the next token.
8072 Only a dozen or so command codes | > max_command| can possibly be returned by
8073 |get_next|; in increasing order, they are |undefined_cs|, |expand_after|,
8074 |no_expand|, |input|, |if_test|, |fi_or_else|, |cs_name|, |convert|, |the|,
8075 |top_bot_mark|, |call|, |long_call|, |outer_call|, |long_outer_call|, and
8076 |end_template|.{\emergencystretch=40pt\par}
8077
8078 The |expand| subroutine is used when |cur_cmd > max_command|. It removes a
8079 ``call'' or a conditional or one of the other special operations just
8080 listed. It follows that |expand| might invoke itself recursively. In all
8081 cases, |expand| destroys the current token, but it sets things up so that
8082 the next |get_next| will deliver the appropriate next token. The value of
8083 |cur_tok| need not be known when |expand| is called.
8084
8085 Since several of the basic scanning routines communicate via global variables,
8086 their values are saved as local variables of |expand| so that
8087 recursive calls don't invalidate them.
8088 @^recursion@>
8089
8090 @p @t\4@>@<Declare the procedure called |macro_call|@>@;@/
8091 @t\4@>@<Declare the procedure called |insert_relax|@>@;@/
8092 @t\4@>@<Declare \eTeX\ procedures for expanding@>@;@/
8093 static void pass_text(void);
8094 static void start_input(void);
8095 static void conditional(void);
8096 static void get_x_token(void);
8097 static void conv_toks(void);
8098 static void ins_the_toks(void);
8099 static void expand(void)
8100 {@+
8101 halfword t; /*token that is being ``expanded after''*/
8102 pointer @!p, @!q, @!r; /*for list manipulation*/
8103 int @!j; /*index into |buffer|*/
8104 int @!cv_backup; /*to save the global quantity |cur_val|*/
8105 small_number @!cvl_backup, @!radix_backup, @!co_backup;
8106 /*to save |cur_val_level|, etc.*/
8107 pointer @!backup_backup; /*to save |link(backup_head)|*/
8108 small_number @!save_scanner_status; /*temporary storage of |scanner_status|*/
8109 cv_backup=cur_val;cvl_backup=cur_val_level;radix_backup=radix;
8110 co_backup=cur_order;backup_backup=link(backup_head);
8111 reswitch:
8112 if (cur_cmd < call) @<Expand a nonmacro@>@;
8113 else if (cur_cmd < end_template) macro_call();
8114 else@<Insert a token containing |frozen_endv|@>;
8115 cur_val=cv_backup;cur_val_level=cvl_backup;radix=radix_backup;
8116 cur_order=co_backup;link(backup_head)=backup_backup;
8117 }
8118
8119 @ @<Expand a nonmacro@>=
8120 {@+if (tracing_commands > 1) show_cur_cmd_chr();
8121 switch (cur_cmd) {
8122 case top_bot_mark: @<Insert the \(a)appropriate mark text into the scanner@>@;@+break;
8123 case expand_after: switch (cur_chr) {
8124 case 0: @<Expand the token after the next token@>@;@+break;
8125 case 1: @<Negate a boolean conditional and |goto reswitch|@>@;@+break;
8126 @/@<Cases for |expandafter|@>@/
8127 } @+break; /*there are no other cases*/
8128 case no_expand: @<Suppress expansion of the next token@>@;@+break;
8129 case cs_name: @<Manufacture a control sequence name@>@;@+break;
8130 case convert: conv_toks();@+break; /*this procedure is discussed in Part 27 below*/
8131 case the: ins_the_toks();@+break; /*this procedure is discussed in Part 27 below*/
8132 case if_test: conditional();@+break; /*this procedure is discussed in Part 28 below*/
8133 case fi_or_else: @<Terminate the current conditional and skip to \.{\\fi}@>@;@+break;
8134 case input: @<Initiate or terminate input from a file@>;@+break;
8135 default:@<Complain about an undefined macro@>@;
8136 }
8137 }
8138
8139 @ It takes only a little shuffling to do what \TeX\ calls \.{\\expandafter}.
8140
8141 @<Expand the token after...@>=
8142 {@+get_token();t=cur_tok;get_token();
8143 if (cur_cmd > max_command) expand();@+else back_input();
8144 cur_tok=t;back_input();
8145 }
8146
8147 @ The implementation of \.{\\noexpand} is a bit trickier, because it is
8148 necessary to insert a special `|dont_expand|' marker into \TeX's reading
8149 mechanism. This special marker is processed by |get_next|, but it does
8150 not slow down the inner loop.
8151
8152 Since \.{\\outer} macros might arise here, we must also
8153 clear the |scanner_status| temporarily.
8154
8155 @<Suppress expansion...@>=
8156 {@+save_scanner_status=scanner_status;scanner_status=normal;
8157 get_token();scanner_status=save_scanner_status;t=cur_tok;
8158 back_input(); /*now |start| and |loc| point to the backed-up token |t|*/
8159 if (t >= cs_token_flag)
8160 {@+p=get_avail();info(p)=cs_token_flag+frozen_dont_expand;
8161 link(p)=loc;start=p;loc=p;
8162 }
8163 }
8164
8165 @ @<Complain about an undefined macro@>=
8166 {@+print_err("Undefined control sequence");
8167 @.Undefined control sequence@>
8168 help5("The control sequence at the end of the top line",@/
8169 "of your error message was never \\def'ed. If you have",@/
8170 "misspelled it (e.g., `\\hobx'), type `I' and the correct",@/
8171 "spelling (e.g., `I\\hbox'). Otherwise just continue,",@/
8172 "and I'll forget about whatever was undefined.");
8173 error();
8174 }
8175
8176 @ The |expand| procedure and some other routines that construct token
8177 lists find it convenient to use the following macros, which are valid only if
8178 the variables |p| and |q| are reserved for token-list building.
8179 Here we add code to store file and line information for each token.
8180 @^profiling@>
8181
8182 @d store_new_token(A) {@+q=get_avail();link(p)=q;info(q)=A;
8183 fl_mem[q]=cur_file_line;
8184 p=q; /*|link(p)| is |null|*/
8185 }
8186 @d fast_store_new_token(A) {@+fast_get_avail(q);link(p)=q;info(q)=A;
8187 fl_mem[q]=cur_file_line;
8188 p=q; /*|link(p)| is |null|*/
8189 }
8190
8191 @ @<Manufacture a control...@>=
8192 {@+r=get_avail();p=r; /*head of the list of characters*/
8193 incr(incsname_state);
8194 @/do@+{get_x_token();
8195 if (cur_cs==0) store_new_token(cur_tok);
8196 }@+ while (!(cur_cs!=0));
8197 if (cur_cmd!=end_cs_name) @<Complain about missing \.{\\endcsname}@>;
8198 decr(incsname_state);
8199 @<Look up the characters of list |r| in the hash table, and set |cur_cs|@>;
8200 flush_list(r);
8201 if (eq_type(cur_cs)==undefined_cs)
8202 {@+eq_define(cur_cs, relax, 256); /*N.B.: The |save_stack| might change*/
8203 } /*the control sequence will now match `\.{\\relax}'*/
8204 cur_tok=cur_cs+cs_token_flag;back_input();
8205 }
8206
8207 @ @<Complain about missing \.{\\endcsname}@>=
8208 {@+print_err("Missing ");print_esc("endcsname");print(" inserted");
8209 @.Missing \\endcsname...@>
8210 help2("The control sequence marked <to be read again> should",@/
8211 "not appear between \\csname and \\endcsname.");
8212 back_error();
8213 }
8214
8215 @ @<Look up the characters of list |r| in the hash table...@>=
8216 j=first;p=link(r);
8217 while (p!=null)
8218 {@+if (j >= max_buf_stack)
8219 {@+max_buf_stack=j+1;
8220 if (max_buf_stack==buf_size)
8221 overflow("buffer size", buf_size);
8222 @:TeX capacity exceeded buffer size}{\quad buffer size@>
8223 }
8224 buffer[j]=info(p)%0400;incr(j);p=link(p);
8225 }
8226 if (j==first) cur_cs=null_cs; /*the list is empty*/
8227 else if (j > first+1)
8228 {@+no_new_control_sequence=false;cur_cs=id_lookup(first, j-first);
8229 no_new_control_sequence=true;
8230 }
8231 else cur_cs=single_base+buffer[first] /*the list has length one*/
8232
8233 @ An |end_template| command is effectively changed to an |endv| command
8234 by the following code. (The reason for this is discussed below; the
8235 |frozen_end_template| at the end of the template has passed the
8236 |check_outer_validity| test, so its mission of error detection has been
8237 accomplished.)
8238
8239 @<Insert a token containing |frozen_endv|@>=
8240 {@+cur_tok=cs_token_flag+frozen_endv;back_input();
8241 }
8242
8243 @ The processing of \.{\\input} involves the |start_input| subroutine,
8244 which will be declared later; the processing of \.{\\endinput} is trivial.
8245
8246 @<Put each...@>=
8247 primitive("input", input, 0);@/
8248 @!@:input\_}{\.{\\input} primitive@>
8249 input_loc=cur_val;input_token=cs_token_flag+input_loc;
8250 primitive("endinput", input, 1);@/
8251 @!@:end\_input\_}{\.{\\endinput} primitive@>
8252
8253 @ @<Cases of |print_cmd_chr|...@>=
8254 case input: if (chr_code==0) print_esc("input")
8255 @/@<Cases of |input| for |print_cmd_chr|@>;@/
8256 else print_esc("endinput");@+break;
8257
8258 @ @<Initiate or terminate input...@>=
8259 if (cur_chr==1) force_eof=true
8260 @/@<Cases for |input|@>;@/
8261 else if (name_in_progress) insert_relax();
8262 else start_input()
8263
8264 @ Sometimes the expansion looks too far ahead, so we want to insert
8265 a harmless \.{\\relax} into the user's input.
8266
8267 @<Declare the procedure called |insert_relax|@>=
8268 static void insert_relax(void)
8269 {@+cur_tok=cs_token_flag+cur_cs;back_input();
8270 cur_tok=cs_token_flag+frozen_relax;back_input();token_type=inserted;
8271 }
8272
8273 @ Here is a recursive procedure that is \TeX's usual way to get the
8274 next token of input. It has been slightly optimized to take account of
8275 common cases.
8276
8277 @p static void get_x_token(void) /*sets |cur_cmd|, |cur_chr|, |cur_tok|,
8278 and expands macros*/
8279 {@+
8280 restart: get_next();
8281 @^inner loop@>
8282 if (cur_cmd <= max_command) goto done;
8283 if (cur_cmd >= call)
8284 if (cur_cmd < end_template) macro_call();
8285 else{@+cur_cs=frozen_endv;cur_cmd=endv;
8286 goto done; /*|cur_chr==null_list|*/
8287 }
8288 else expand();
8289 goto restart;
8290 done: if (cur_cs==0) cur_tok=(cur_cmd*0400)+cur_chr;
8291 else cur_tok=cs_token_flag+cur_cs;
8292 }
8293
8294 @ The |get_x_token| procedure is essentially equivalent to two consecutive
8295 procedure calls: |get_next;x_token|.
8296
8297 @p static void x_token(void) /*|get_x_token| without the initial |get_next|*/
8298 {@+while (cur_cmd > max_command)
8299 {@+expand();
8300 get_next();
8301 }
8302 if (cur_cs==0) cur_tok=(cur_cmd*0400)+cur_chr;
8303 else cur_tok=cs_token_flag+cur_cs;
8304 }
8305
8306 @ A control sequence that has been \.{\\def}'ed by the user is expanded by
8307 \TeX's |macro_call| procedure.
8308
8309 Before we get into the details of |macro_call|, however, let's consider the
8310 treatment of primitives like \.{\\topmark}, since they are essentially
8311 macros without parameters. The token lists for such marks are kept in a
8312 global array of five pointers; we refer to the individual entries of this
8313 array by symbolic names |top_mark|, etc. The value of |top_mark| is either
8314 |null| or a pointer to the reference count of a token list.
8315
8316 @d marks_code 5 /*add this for \.{\\topmarks} etc.*/
8317 @#
8318 @d top_mark_code 0 /*the mark in effect at the previous page break*/
8319 @d first_mark_code 1 /*the first mark between |top_mark| and |bot_mark|*/
8320 @d bot_mark_code 2 /*the mark in effect at the current page break*/
8321 @d split_first_mark_code 3 /*the first mark found by \.{\\vsplit}*/
8322 @d split_bot_mark_code 4 /*the last mark found by \.{\\vsplit}*/
8323 @d top_mark cur_mark[top_mark_code]
8324 @d first_mark cur_mark[first_mark_code]
8325 @d bot_mark cur_mark[bot_mark_code]
8326 @d split_first_mark cur_mark[split_first_mark_code]
8327 @d split_bot_mark cur_mark[split_bot_mark_code]
8328
8329 @<Glob...@>=
8330 static pointer @!cur_mark0[split_bot_mark_code-top_mark_code+1],
8331 *const @!cur_mark = @!cur_mark0-top_mark_code;
8332 /*token lists for marks*/
8333
8334 @ @<Set init...@>=
8335 top_mark=null;first_mark=null;bot_mark=null;
8336 split_first_mark=null;split_bot_mark=null;
8337
8338 @ @<Put each...@>=
8339 primitive("topmark", top_bot_mark, top_mark_code);
8340 @!@:top\_mark\_}{\.{\\topmark} primitive@>
8341 primitive("firstmark", top_bot_mark, first_mark_code);
8342 @!@:first\_mark\_}{\.{\\firstmark} primitive@>
8343 primitive("botmark", top_bot_mark, bot_mark_code);
8344 @!@:bot\_mark\_}{\.{\\botmark} primitive@>
8345 primitive("splitfirstmark", top_bot_mark, split_first_mark_code);
8346 @!@:split\_first\_mark\_}{\.{\\splitfirstmark} primitive@>
8347 primitive("splitbotmark", top_bot_mark, split_bot_mark_code);
8348 @!@:split\_bot\_mark\_}{\.{\\splitbotmark} primitive@>
8349
8350 @ @<Cases of |print_cmd_chr|...@>=
8351 case top_bot_mark: {@+switch ((chr_code%marks_code)) {
8352 case first_mark_code: print_esc("firstmark");@+break;
8353 case bot_mark_code: print_esc("botmark");@+break;
8354 case split_first_mark_code: print_esc("splitfirstmark");@+break;
8355 case split_bot_mark_code: print_esc("splitbotmark");@+break;
8356 default:print_esc("topmark");
8357 }
8358 if (chr_code >= marks_code) print_char('s');
8359 } @+break;
8360
8361 @ The following code is activated when |cur_cmd==top_bot_mark| and
8362 when |cur_chr| is a code like |top_mark_code|.
8363
8364 @<Insert the \(a)appropriate mark text into the scanner@>=
8365 {@+t=cur_chr%marks_code;
8366 if (cur_chr >= marks_code) scan_register_num();@+else cur_val=0;
8367 if (cur_val==0) cur_ptr=cur_mark[t];
8368 else@<Compute the mark pointer for mark type |t| and class |cur_val|@>;
8369 if (cur_ptr!=null) begin_token_list(cur_ptr, mark_text);
8370 }
8371
8372 @ Now let's consider |macro_call| itself, which is invoked when \TeX\ is
8373 scanning a control sequence whose |cur_cmd| is either |call|, |long_call|,
8374 |outer_call|, or |long_outer_call|. The control sequence definition
8375 appears in the token list whose reference count is in location |cur_chr|
8376 of |mem|.
8377
8378 The global variable |long_state| will be set to |call| or to |long_call|,
8379 depending on whether or not the control sequence disallows \.{\\par}
8380 in its parameters. The |get_next| routine will set |long_state| to
8381 |outer_call| and emit \.{\\par}, if a file ends or if an \.{\\outer}
8382 control sequence occurs in the midst of an argument.
8383
8384 @<Glob...@>=
8385 static int @!long_state; /*governs the acceptance of \.{\\par}*/
8386
8387 @ The parameters, if any, must be scanned before the macro is expanded.
8388 Parameters are token lists without reference counts. They are placed on
8389 an auxiliary stack called |pstack| while they are being scanned, since
8390 the |param_stack| may be losing entries during the matching process.
8391 (Note that |param_stack| can't be gaining entries, since |macro_call| is
8392 the only routine that puts anything onto |param_stack|, and it
8393 is not recursive.)
8394
8395 @<Glob...@>=
8396 static pointer @!pstack[9]; /*arguments supplied to a macro*/
8397
8398 @ After parameter scanning is complete, the parameters are moved to the
8399 |param_stack|. Then the macro body is fed to the scanner; in other words,
8400 |macro_call| places the defined text of the control sequence at the
8401 top of\/ \TeX's input stack, so that |get_next| will proceed to read it
8402 next.
8403
8404 The global variable |cur_cs| contains the |eqtb| address of the control sequence
8405 being expanded, when |macro_call| begins. If this control sequence has not been
8406 declared \.{\\long}, i.e., if its command code in the |eq_type| field is
8407 not |long_call| or |long_outer_call|, its parameters are not allowed to contain
8408 the control sequence \.{\\par}. If an illegal \.{\\par} appears, the macro
8409 call is aborted, and the \.{\\par} will be rescanned.
8410
8411 @<Declare the procedure called |macro_call|@>=
8412 static void macro_call(void) /*invokes a user-defined control sequence*/
8413 {@+
8414 pointer r; /*current node in the macro's token list*/
8415 pointer @!p; /*current node in parameter token list being built*/
8416 pointer @!q; /*new node being put into the token list*/
8417 pointer @!s; /*backup pointer for parameter matching*/
8418 pointer @!t; /*cycle pointer for backup recovery*/
8419 pointer @!u, @!v; /*auxiliary pointers for backup recovery*/
8420 pointer @!rbrace_ptr; /*one step before the last |right_brace| token*/
8421 small_number @!n; /*the number of parameters scanned*/
8422 halfword @!unbalance; /*unmatched left braces in current parameter*/
8423 int @!m; /*the number of tokens or groups (usually)*/
8424 pointer @!ref_count; /*start of the token list*/
8425 small_number @!save_scanner_status; /*|scanner_status| upon entry*/
8426 pointer @!save_warning_index; /*|warning_index| upon entry*/
8427 ASCII_code @!match_chr; /*character used in parameter*/
8428 @<additional local variables for |macro_call|@>@;
8429 save_scanner_status=scanner_status;save_warning_index=warning_index;
8430 warning_index=cur_cs;ref_count=cur_chr;r=link(ref_count);n=0;
8431 if (tracing_macros > 0) @<Show the text of the macro being expanded@>;
8432 if (info(r)==protected_token) r=link(r);
8433 if (info(r)!=end_match_token)
8434 @<Scan the parameters and make |link(r)| point to the macro body; but |goto end|
8435 if an illegal \.{\\par} is detected@>;
8436 @<Feed the macro body and its parameters to the scanner@>;
8437 end: scanner_status=save_scanner_status;warning_index=save_warning_index;
8438 @<update the macro stack@>@;
8439 }
8440
8441 @ Before we put a new token list on the input stack, it is wise to clean off
8442 all token lists that have recently been depleted. Then a user macro that ends
8443 with a call to itself will not require unbounded stack space.
8444
8445 @<Feed the macro body and its parameters to the scanner@>=
8446 while ((state==token_list)&&(loc==null)&&(token_type!=v_template))
8447 end_token_list(); /*conserve stack space*/
8448 begin_token_list(ref_count, macro);name=warning_index;loc=link(r);
8449 if (n > 0)
8450 {@+if (param_ptr+n > max_param_stack)
8451 {@+max_param_stack=param_ptr+n;
8452 if (max_param_stack > param_size)
8453 overflow("parameter stack size", param_size);
8454 @:TeX capacity exceeded parameter stack size}{\quad parameter stack size@>
8455 }
8456 for (m=0; m<=n-1; m++) param_stack[param_ptr+m]=pstack[m];
8457 param_ptr=param_ptr+n;
8458 }
8459
8460 @ At this point, the reader will find it advisable to review the explanation
8461 of token list format that was presented earlier, since many aspects of that
8462 format are of importance chiefly in the |macro_call| routine.
8463
8464 The token list might begin with a string of compulsory tokens before the
8465 first |match| or |end_match|. In that case the macro name is supposed to be
8466 followed by those tokens; the following program will set |s==null| to
8467 represent this restriction. Otherwise |s| will be set to the first token of
8468 a string that will delimit the next parameter.
8469
8470 @<Scan the parameters and make |link(r)| point to the macro body...@>=
8471 {@+scanner_status=matching;unbalance=0;
8472 long_state=eq_type(cur_cs);
8473 if (long_state >= outer_call) long_state=long_state-2;
8474 @/do@+{link(temp_head)=null;
8475 if ((info(r) > match_token+255)||(info(r) < match_token)) s=null;
8476 else{@+match_chr=info(r)-match_token;s=link(r);r=s;
8477 p=temp_head;m=0;
8478 }
8479 @<Scan a parameter until its delimiter string has been found; or, if |s=null|,
8480 simply scan the delimiter string@>;@/
8481 /*now |info(r)| is a token whose command code is either |match| or |end_match|*/
8482 }@+ while (!(info(r)==end_match_token));
8483 }
8484
8485 @ If |info(r)| is a |match| or |end_match| command, it cannot be equal to
8486 any token found by |get_token|. Therefore an undelimited parameter---i.e.,
8487 a |match| that is immediately followed by |match| or |end_match|---will
8488 always fail the test `|cur_tok==info(r)|' in the following algorithm.
8489
8490 @<Scan a parameter until its delimiter string has been found; or,...@>=
8491 resume: get_token(); /*set |cur_tok| to the next token of input*/
8492 if (cur_tok==info(r))
8493 @<Advance \(r)|r|; |goto found| if the parameter delimiter has been fully
8494 matched, otherwise |goto resume|@>;
8495 @<Contribute the recently matched tokens to the current parameter, and |goto
8496 resume| if a partial match is still in effect; but abort if |s=null|@>;
8497 if (cur_tok==par_token) if (long_state!=long_call)
8498 @<Report a runaway argument and abort@>;
8499 if (cur_tok < right_brace_limit)
8500 if (cur_tok < left_brace_limit)
8501 @<Contribute an entire group to the current parameter@>@;
8502 else@<Report an extra right brace and |goto resume|@>@;
8503 else@<Store the current token, but |goto resume| if it is a blank space
8504 that would become an undelimited parameter@>;
8505 incr(m);
8506 if (info(r) > end_match_token) goto resume;
8507 if (info(r) < match_token) goto resume;
8508 found: if (s!=null) @<Tidy up the parameter just scanned, and tuck it away@>@;
8509
8510 @ @<Store the current token, but |goto resume| if it is...@>=
8511 {@+if (cur_tok==space_token)
8512 if (info(r) <= end_match_token)
8513 if (info(r) >= match_token) goto resume;
8514 store_new_token(cur_tok);
8515 }
8516
8517 @ A slightly subtle point arises here: When the parameter delimiter ends
8518 with `\.{\#\{}', the token list will have a left brace both before and
8519 after the |end_match|\kern-.4pt. Only one of these should affect the
8520 |align_state|, but both will be scanned, so we must make a correction.
8521
8522 @<Advance \(r)|r|; |goto found| if the parameter delimiter has been fully...@>=
8523 {@+r=link(r);
8524 if ((info(r) >= match_token)&&(info(r) <= end_match_token))
8525 {@+if (cur_tok < left_brace_limit) decr(align_state);
8526 goto found;
8527 }
8528 else goto resume;
8529 }
8530
8531 @ @<Report an extra right brace and |goto resume|@>=
8532 {@+back_input();print_err("Argument of ");sprint_cs(warning_index);
8533 @.Argument of \\x has...@>
8534 print(" has an extra }");
8535 help6("I've run across a `}' that doesn't seem to match anything.",@/
8536 "For example, `\\def\\a#1{...}' and `\\a}' would produce",@/
8537 "this error. If you simply proceed now, the `\\par' that",@/
8538 "I've just inserted will cause me to report a runaway",@/
8539 "argument that might be the root of the problem. But if",@/
8540 "your `}' was spurious, just type `2' and it will go away.");
8541 incr(align_state);long_state=call;cur_tok=par_token;ins_error();
8542 goto resume;
8543 } /*a white lie; the \.{\\par} won't always trigger a runaway*/
8544
8545 @ If |long_state==outer_call|, a runaway argument has already been reported.
8546
8547 @<Report a runaway argument and abort@>=
8548 {@+if (long_state==call)
8549 {@+runaway();print_err("Paragraph ended before ");
8550 @.Paragraph ended before...@>
8551 sprint_cs(warning_index);print(" was complete");
8552 help3("I suspect you've forgotten a `}', causing me to apply this",@/
8553 "control sequence to too much text. How can we recover?",@/
8554 "My plan is to forget the whole thing and hope for the best.");
8555 back_error();
8556 }
8557 pstack[n]=link(temp_head);align_state=align_state-unbalance;
8558 for (m=0; m<=n; m++) flush_list(pstack[m]);
8559 goto end;
8560 }
8561
8562 @ When the following code becomes active, we have matched tokens from |s| to
8563 the predecessor of |r|, and we have found that |cur_tok!=info(r)|. An
8564 interesting situation now presents itself: If the parameter is to be
8565 delimited by a string such as `\.{ab}', and if we have scanned `\.{aa}',
8566 we want to contribute one `\.a' to the current parameter and resume
8567 looking for a `\.b'. The program must account for such partial matches and
8568 for others that can be quite complex. But most of the time we have |s==r|
8569 and nothing needs to be done.
8570
8571 Incidentally, it is possible for \.{\\par} tokens to sneak in to certain
8572 parameters of non-\.{\\long} macros. For example, consider a case like
8573 `\.{\\def\\a\#1\\par!\{...\}}' where the first \.{\\par} is not followed
8574 by an exclamation point. In such situations it does not seem appropriate
8575 to prohibit the \.{\\par}, so \TeX\ keeps quiet about this bending of
8576 the rules.
8577
8578 @<Contribute the recently matched tokens to the current parameter...@>=
8579 if (s!=r)
8580 if (s==null) @<Report an improper use of the macro and abort@>@;
8581 else{@+t=s;
8582 @/do@+{store_new_token(info(t));incr(m);u=link(t);v=s;
8583 loop@+{@+if (u==r)
8584 if (cur_tok!=info(v)) goto done;
8585 else{@+r=link(v);goto resume;
8586 }
8587 if (info(u)!=info(v)) goto done;
8588 u=link(u);v=link(v);
8589 }
8590 done: t=link(t);
8591 }@+ while (!(t==r));
8592 r=s; /*at this point, no tokens are recently matched*/
8593 }
8594
8595 @ @<Report an improper use...@>=
8596 {@+print_err("Use of ");sprint_cs(warning_index);
8597 @.Use of x doesn't match...@>
8598 print(" doesn't match its definition");
8599 help4("If you say, e.g., `\\def\\a1{...}', then you must always",@/
8600 "put `1' after `\\a', since control sequence names are",@/
8601 "made up of letters only. The macro here has not been",@/
8602 "followed by the required stuff, so I'm ignoring it.");
8603 error();goto end;
8604 }
8605
8606 @ @<Contribute an entire group to the current parameter@>=
8607 {@+unbalance=1;
8608 @^inner loop@>
8609 loop@+{@+fast_store_new_token(cur_tok);get_token();
8610 if (cur_tok==par_token) if (long_state!=long_call)
8611 @<Report a runaway argument and abort@>;
8612 if (cur_tok < right_brace_limit)
8613 if (cur_tok < left_brace_limit) incr(unbalance);
8614 else{@+decr(unbalance);
8615 if (unbalance==0) goto done1;
8616 }
8617 }
8618 done1: rbrace_ptr=p;store_new_token(cur_tok);
8619 }
8620
8621 @ If the parameter consists of a single group enclosed in braces, we must
8622 strip off the enclosing braces. That's why |rbrace_ptr| was introduced.
8623
8624 @<Tidy up the parameter just scanned, and tuck it away@>=
8625 {@+if ((m==1)&&(info(p) < right_brace_limit))
8626 {@+link(rbrace_ptr)=null;free_avail(p);
8627 p=link(temp_head);pstack[n]=link(p);free_avail(p);
8628 }
8629 else pstack[n]=link(temp_head);
8630 incr(n);
8631 if (tracing_macros > 0)
8632 {@+begin_diagnostic();print_nl("");printn(match_chr);print_int(n);
8633 print("<-");show_token_list(pstack[n-1], null, 1000);
8634 end_diagnostic(false);
8635 }
8636 }
8637
8638 @ @<Show the text of the macro being expanded@>=
8639 {@+begin_diagnostic();print_ln();print_cs(warning_index);
8640 token_show(ref_count);end_diagnostic(false);
8641 }
8642
8643 @* Basic scanning subroutines.
8644 Let's turn now to some procedures that \TeX\ calls upon frequently to digest
8645 certain kinds of patterns in the input. Most of these are quite simple;
8646 some are quite elaborate. Almost all of the routines call |get_x_token|,
8647 which can cause them to be invoked recursively.
8648 @^stomach@>
8649 @^recursion@>
8650
8651 @ The |scan_left_brace| routine is called when a left brace is supposed to be
8652 the next non-blank token. (The term ``left brace'' means, more precisely,
8653 a character whose catcode is |left_brace|.) \TeX\ allows \.{\\relax} to
8654 appear before the |left_brace|.
8655
8656 @p static void scan_left_brace(void) /*reads a mandatory |left_brace|*/
8657 {@+@<Get the next non-blank non-relax non-call token@>;
8658 if (cur_cmd!=left_brace)
8659 {@+print_err("Missing { inserted");
8660 @.Missing \{ inserted@>
8661 help4("A left brace was mandatory here, so I've put one in.",@/
8662 "You might want to delete and/or insert some corrections",@/
8663 "so that I will find a matching right brace soon.",@/
8664 "(If you're confused by all this, try typing `I}' now.)");
8665 back_error();cur_tok=left_brace_token+'{';cur_cmd=left_brace;
8666 cur_chr='{';incr(align_state);
8667 }
8668 }
8669
8670 @ @<Get the next non-blank non-relax non-call token@>=
8671 @/do@+{get_x_token();
8672 }@+ while (!((cur_cmd!=spacer)&&(cur_cmd!=relax)))
8673
8674 @ The |scan_optional_equals| routine looks for an optional `\.=' sign preceded
8675 by optional spaces; `\.{\\relax}' is not ignored here.
8676
8677 @p static void scan_optional_equals(void)
8678 {@+@<Get the next non-blank non-call token@>;
8679 if (cur_tok!=other_token+'=') back_input();
8680 }
8681
8682 @ @<Get the next non-blank non-call token@>=
8683 @/do@+{get_x_token();
8684 }@+ while (!(cur_cmd!=spacer))
8685
8686 @ In case you are getting bored, here is a slightly less trivial routine:
8687 Given a string of lowercase letters, like `\.{pt}' or `\.{plus}' or
8688 `\.{width}', the |scan_keyword| routine checks to see whether the next
8689 tokens of input match this string. The match must be exact, except that
8690 uppercase letters will match their lowercase counterparts; uppercase
8691 equivalents are determined by subtracting |'a'-'A'|, rather than using the
8692 |uc_code| table, since \TeX\ uses this routine only for its own limited
8693 set of keywords.
8694
8695 If a match is found, the characters are effectively removed from the input
8696 and |true| is returned. Otherwise |false| is returned, and the input
8697 is left essentially unchanged (except for the fact that some macros
8698 may have been expanded, etc.).
8699 @^inner loop@>
8700
8701 @p static bool scan_keyword(char *@!s) /*look for a given string*/
8702 {@+
8703 pointer p; /*tail of the backup list*/
8704 pointer @!q; /*new node being added to the token list via |store_new_token|*/
8705 p=backup_head;link(p)=null;
8706 while (*s!=0)
8707 {@+get_x_token(); /*recursion is possible here*/
8708 @^recursion@>
8709 if ((cur_cs==0)&&@|
8710 ((cur_chr==so(*s))||(cur_chr==so(*s)-'a'+'A')))
8711 {@+store_new_token(cur_tok);incr(s);
8712 }
8713 else if ((cur_cmd!=spacer)||(p!=backup_head))
8714 {@+back_input();
8715 if (p!=backup_head) back_list(link(backup_head));
8716 return false;
8717 }
8718 }
8719 flush_list(link(backup_head));return true;
8720 }
8721
8722 @ Here is a procedure that sounds an alarm when mu and non-mu units
8723 are being switched.
8724
8725 @p static void mu_error(void)
8726 {@+print_err("Incompatible glue units");
8727 @.Incompatible glue units@>
8728 help1("I'm going to assume that 1mu=1pt when they're mixed.");
8729 error();
8730 }
8731
8732 @ The next routine `|scan_something_internal|' is used to fetch internal
8733 numeric quantities like `\.{\\hsize}', and also to handle the `\.{\\the}'
8734 when expanding constructions like `\.{\\the\\toks0}' and
8735 `\.{\\the\\baselineskip}'. Soon we will be considering the |scan_int|
8736 procedure, which calls |scan_something_internal|; on the other hand,
8737 |scan_something_internal| also calls |scan_int|, for constructions like
8738 `\.{\\catcode\`\\\$}' or `\.{\\fontdimen} \.3 \.{\\ff}'. So we
8739 have to declare |scan_int| as a |forward| procedure. A few other
8740 procedures are also declared at this point.
8741
8742 @p static void scan_int(void); /*scans an integer value*/
8743 @t\4\4@>@<Declare procedures that scan restricted classes of integers@>@;
8744 @t\4\4@>@<Declare \eTeX\ procedures for scanning@>@;
8745 @t\4\4@>@<Declare procedures that scan font-related stuff@>@;
8746
8747 @ \TeX\ doesn't know exactly what to expect when |scan_something_internal|
8748 begins. For example, an integer or dimension or glue value could occur
8749 immediately after `\.{\\hskip}'; and one can even say \.{\\the} with
8750 respect to token lists in constructions like
8751 `\.{\\xdef\\o\{\\the\\output\}}'. On the other hand, only integers are
8752 allowed after a construction like `\.{\\count}'. To handle the various
8753 possibilities, |scan_something_internal| has a |level| parameter, which
8754 tells the ``highest'' kind of quantity that |scan_something_internal| is
8755 allowed to produce. Six levels are distinguished, namely |int_val|,
8756 |dimen_val|, |glue_val|, |mu_val|, |ident_val|, and |tok_val|.
8757
8758 The output of |scan_something_internal| (and of the other routines
8759 |scan_int|, |scan_dimen|, and |scan_glue| below) is put into the global
8760 variable |cur_val|, and its level is put into |cur_val_level|. The highest
8761 values of |cur_val_level| are special: |mu_val| is used only when
8762 |cur_val| points to something in a ``muskip'' register, or to one of the
8763 three parameters \.{\\thinmuskip}, \.{\\medmuskip}, \.{\\thickmuskip};
8764 |ident_val| is used only when |cur_val| points to a font identifier;
8765 |tok_val| is used only when |cur_val| points to |null| or to the reference
8766 count of a token list. The last two cases are allowed only when
8767 |scan_something_internal| is called with |level==tok_val|.
8768
8769 If the output is glue, |cur_val| will point to a glue specification, and
8770 the reference count of that glue will have been updated to reflect this
8771 reference; if the output is a nonempty token list, |cur_val| will point to
8772 its reference count, but in this case the count will not have been updated.
8773 Otherwise |cur_val| will contain the integer or scaled value in question.
8774
8775 @d int_val 0 /*integer values*/
8776 @d dimen_val 1 /*dimension values*/
8777 @d glue_val 2 /*glue specifications*/
8778 @d mu_val 3 /*math glue specifications*/
8779 @d ident_val 4 /*font identifier*/
8780 @d tok_val 5 /*token lists*/
8781
8782 @<Glob...@>=
8783 static int @!cur_val; /*value returned by numeric scanners*/
8784 static int @!cur_val_level; /*the ``level'' of this value*/
8785
8786 @ The hash table is initialized with `\.{\\count}', `\.{\\dimen}', `\.{\\skip}',
8787 and `\.{\\muskip}' all having |internal_register| as their command code; they are
8788 distinguished by the |chr_code|, which is either |int_val|, |dimen_val|,
8789 |glue_val|, or |mu_val| more than |mem_bot| (dynamic variable-size nodes
8790 cannot have these values)
8791
8792 @<Put each...@>=
8793 primitive("count", internal_register, mem_bot+int_val);
8794 @!@:count\_}{\.{\\count} primitive@>
8795 primitive("dimen", internal_register, mem_bot+dimen_val);
8796 @!@:dimen\_}{\.{\\dimen} primitive@>
8797 primitive("skip", internal_register, mem_bot+glue_val);
8798 @!@:skip\_}{\.{\\skip} primitive@>
8799 primitive("muskip", internal_register, mem_bot+mu_val);
8800 @!@:mu\_skip\_}{\.{\\muskip} primitive@>
8801
8802 @ @<Cases of |print_cmd_chr|...@>=
8803 case internal_register: @<Cases of |register| for |print_cmd_chr|@>@;@+break;
8804
8805 @ OK, we're ready for |scan_something_internal| itself. A second parameter,
8806 |negative|, is set |true| if the value that is found should be negated.
8807 It is assumed that |cur_cmd| and |cur_chr| represent the first token of
8808 the internal quantity to be scanned; an error will be signalled if
8809 |cur_cmd < min_internal| or |cur_cmd > max_internal|.
8810
8811 @d scanned_result(A, B) @+{@+cur_val=A;cur_val_level=B;@+}
8812
8813 @p static void scan_something_internal(small_number @!level, bool @!negative)
8814 /*fetch an internal parameter*/
8815 {@+
8816 halfword m; /*|chr_code| part of the operand token*/
8817 pointer @!q, @!r; /*general purpose indices*/
8818 pointer @!tx; /*effective tail node*/
8819 four_quarters @!i; /*character info*/
8820 int @!p; /*index into |nest|*/
8821 m=cur_chr;
8822 switch (cur_cmd) {
8823 case def_code: @<Fetch a character code from some table@>@;@+break;
8824 case toks_register: case assign_toks:
8825 case def_family: case set_font: case def_font: @<Fetch a token list or font
8826 identifier, provided that |level=tok_val|@>@;@+break;
8827 case assign_int: scanned_result(eqtb[m].i, int_val)@;@+break;
8828 case assign_dimen: scanned_result(eqtb[m].sc, dimen_val)@;@+break;
8829 case assign_glue: scanned_result(equiv(m), glue_val)@;@+break;
8830 case assign_mu_glue: scanned_result(equiv(m), mu_val)@;@+break;
8831 case set_aux: @<Fetch the |space_factor| or the |prev_depth|@>@;@+break;
8832 case set_prev_graf: @<Fetch the |prev_graf|@>@;@+break;
8833 case set_page_int: @<Fetch the |dead_cycles| or the |insert_penalties|@>@;@+break;
8834 case set_page_dimen: @<Fetch something on the |page_so_far|@>@;@+break;
8835 case set_shape: @<Fetch the |par_shape| size@>@;@+break;
8836 case set_box_dimen: @<Fetch a box dimension@>@;@+break;
8837 case char_given: case math_given: scanned_result(cur_chr, int_val)@;@+break;
8838 case assign_font_dimen: @<Fetch a font dimension@>@;@+break;
8839 case assign_font_int: @<Fetch a font integer@>@;@+break;
8840 case internal_register: @<Fetch a register@>@;@+break;
8841 case last_item: @<Fetch an item in the current node, if appropriate@>@;@+break;
8842 default:@<Complain that \.{\\the} can't do this; give zero result@>@;
8843 } @/
8844 while (cur_val_level > level) @<Convert \(c)|cur_val| to a lower level@>;
8845 @<Fix the reference count, if any, and negate |cur_val| if |negative|@>;
8846 }
8847
8848 @ @<Fetch a character code from some table@>=
8849 {@+scan_char_num();
8850 if (m==math_code_base) scanned_result(ho(math_code(cur_val)), int_val)@;
8851 else if (m < math_code_base) scanned_result(equiv(m+cur_val), int_val)@;
8852 else scanned_result(eqtb[m+cur_val].i, int_val);
8853 }
8854
8855 @ @<Fetch a token list...@>=
8856 if (level!=tok_val)
8857 {@+print_err("Missing number, treated as zero");
8858 @.Missing number...@>
8859 help3("A number should have been here; I inserted `0'.",@/
8860 "(If you can't figure out why I needed to see a number,",@/
8861 "look up `weird error' in the index to The TeXbook.)");
8862 @:TeXbook}{\sl The \TeX book@>
8863 back_error();scanned_result(0, dimen_val);
8864 }
8865 else if (cur_cmd <= assign_toks)
8866 {@+if (cur_cmd < assign_toks) /*|cur_cmd==toks_register|*/
8867 if (m==mem_bot)
8868 {@+scan_register_num();
8869 if (cur_val < 256) cur_val=equiv(toks_base+cur_val);
8870 else{@+find_sa_element(tok_val, cur_val, false);
8871 if (cur_ptr==null) cur_val=null;
8872 else cur_val=sa_ptr(cur_ptr);
8873 }
8874 }
8875 else cur_val=sa_ptr(m);
8876 else cur_val=equiv(m);
8877 cur_val_level=tok_val;
8878 }
8879 else{@+back_input();scan_font_ident();
8880 scanned_result(font_id_base+cur_val, ident_val);
8881 }
8882
8883 @ Users refer to `\.{\\the\\spacefactor}' only in horizontal
8884 mode, and to `\.{\\the\\prevdepth}' only in vertical mode; so we put the
8885 associated mode in the modifier part of the |set_aux| command.
8886 The |set_page_int| command has modifier 0 or 1, for `\.{\\deadcycles}' and
8887 `\.{\\insertpenalties}', respectively. The |set_box_dimen| command is
8888 modified by either |width_offset|, |height_offset|, or |depth_offset|.
8889 And the |last_item| command is modified by either |int_val|, |dimen_val|,
8890 |glue_val|, |input_line_no_code|, or |badness_code|.
8891 \eTeX\ inserts |last_node_type_code| after |glue_val| and adds
8892 the codes for its extensions: |eTeX_version_code|, \dots\ .
8893
8894 @d last_node_type_code (glue_val+1) /*code for \.{\\lastnodetype}*/
8895 @d input_line_no_code (glue_val+2) /*code for \.{\\inputlineno}*/
8896 @d badness_code (input_line_no_code+1) /*code for \.{\\badness}*/
8897 @#
8898 @d eTeX_int (pdftex_last_item_codes+1) /*first of \eTeX\ codes for integers*/
8899 @d eTeX_dim (eTeX_int+8) /*first of \eTeX\ codes for dimensions*/
8900 @d eTeX_glue (eTeX_dim+9) /*first of \eTeX\ codes for glue*/
8901 @d eTeX_mu (eTeX_glue+1) /*first of \eTeX\ codes for muglue*/
8902 @d eTeX_expr (eTeX_mu+1) /*first of \eTeX\ codes for expressions*/
8903 @d eTeX_last_last_item_cmd_mod (eTeX_expr-int_val+mu_val) /*\.{\\muexpr}*/
8904
8905 @<Put each...@>=
8906 primitive("spacefactor", set_aux, hmode);
8907 @!@:space\_factor\_}{\.{\\spacefactor} primitive@>
8908 primitive("prevdepth", set_aux, vmode);@/
8909 @!@:prev\_depth\_}{\.{\\prevdepth} primitive@>
8910 primitive("deadcycles", set_page_int, 0);
8911 @!@:dead\_cycles\_}{\.{\\deadcycles} primitive@>
8912 primitive("insertpenalties", set_page_int, 1);
8913 @!@:insert\_penalties\_}{\.{\\insertpenalties} primitive@>
8914 primitive("wd", set_box_dimen, width_offset);
8915 @!@:wd\_}{\.{\\wd} primitive@>
8916 primitive("ht", set_box_dimen, height_offset);
8917 @!@:ht\_}{\.{\\ht} primitive@>
8918 primitive("dp", set_box_dimen, depth_offset);
8919 @!@:dp\_}{\.{\\dp} primitive@>
8920 primitive("lastpenalty", last_item, int_val);
8921 @!@:last\_penalty\_}{\.{\\lastpenalty} primitive@>
8922 primitive("lastkern", last_item, dimen_val);
8923 @!@:last\_kern\_}{\.{\\lastkern} primitive@>
8924 primitive("lastskip", last_item, glue_val);
8925 @!@:last\_skip\_}{\.{\\lastskip} primitive@>
8926 primitive("inputlineno", last_item, input_line_no_code);
8927 @!@:input\_line\_no\_}{\.{\\inputlineno} primitive@>
8928 primitive("badness", last_item, badness_code);
8929 @!@:badness\_}{\.{\\badness} primitive@>
8930
8931 @ @<Cases of |print_cmd_chr|...@>=
8932 case set_aux: if (chr_code==vmode) print_esc("prevdepth");
8933 @+else print_esc("spacefactor");@+break;
8934 case set_page_int: if (chr_code==0) print_esc("deadcycles")
8935 @/@<Cases of |set_page_int| for |print_cmd_chr|@>;@/
8936 @+else print_esc("insertpenalties");@+break;
8937 case set_box_dimen: if (chr_code==width_offset) print_esc("wd");
8938 else if (chr_code==height_offset) print_esc("ht");
8939 else print_esc("dp");@+break;
8940 case last_item: switch (chr_code) {
8941 case int_val: print_esc("lastpenalty");@+break;
8942 case dimen_val: print_esc("lastkern");@+break;
8943 case glue_val: print_esc("lastskip");@+break;
8944 case input_line_no_code: print_esc("inputlineno");@+break;
8945 @/@<Cases of |last_item| for |print_cmd_chr|@>@/
8946 default:print_esc("badness");
8947 } @+break;
8948
8949 @ @<Fetch the |space_factor| or the |prev_depth|@>=
8950 if (abs(mode)!=m)
8951 {@+print_err("Improper ");print_cmd_chr(set_aux, m);
8952 @.Improper \\spacefactor@>
8953 @.Improper \\prevdepth@>
8954 help4("You can refer to \\spacefactor only in horizontal mode;",@/
8955 "you can refer to \\prevdepth only in vertical mode; and",@/
8956 "neither of these is meaningful inside \\write. So",@/
8957 "I'm forgetting what you said and using zero instead.");
8958 error();
8959 if (level!=tok_val) scanned_result(0, dimen_val)@;
8960 else scanned_result(0, int_val);
8961 }
8962 else if (m==vmode) scanned_result(prev_depth, dimen_val)@;
8963 else scanned_result(space_factor, int_val)
8964
8965 @ @<Fetch the |dead_cycles| or the |insert_penalties|@>=
8966 {@+if (m==0) cur_val=dead_cycles
8967 @/@<Cases for `Fetch the |dead_cycles| or the |insert_penalties|'@>;@/
8968 else cur_val=insert_penalties;
8969 cur_val_level=int_val;
8970 }
8971
8972 @ @<Fetch a box dimension@>=
8973 {@+scan_register_num();fetch_box(q);
8974 if (q==null) cur_val=0;@+else cur_val=mem[q+m].sc;
8975 cur_val_level=dimen_val;
8976 }
8977
8978 @ Inside an \.{\\output} routine, a user may wish to look at the page totals
8979 that were present at the moment when output was triggered.
8980
8981 @d max_dimen 07777777777 /*$2^{30}-1$*/
8982
8983 @<Fetch something on the |page_so_far|@>=
8984 {@+if ((page_contents==empty)&&(!output_active))
8985 if (m==0) cur_val=max_dimen;@+else cur_val=0;
8986 else cur_val=page_so_far[m];
8987 cur_val_level=dimen_val;
8988 }
8989
8990 @ @<Fetch the |prev_graf|@>=
8991 if (mode==0) scanned_result(0, int_val)@; /*|prev_graf==0| within \.{\\write}*/
8992 else{@+nest[nest_ptr]=cur_list;p=nest_ptr;
8993 while (abs(nest[p].mode_field)!=vmode) decr(p);
8994 scanned_result(nest[p].pg_field, int_val);
8995 }
8996
8997 @ @<Fetch the |par_shape| size@>=
8998 {@+if (m > par_shape_loc) @<Fetch a penalties array element@>@;
8999 else if (par_shape_ptr==null) cur_val=0;
9000 else cur_val=info(par_shape_ptr);
9001 cur_val_level=int_val;
9002 }
9003
9004 @ Here is where \.{\\lastpenalty}, \.{\\lastkern}, \.{\\lastskip}, and
9005 \.{\\lastnodetype} are
9006 implemented. The reference count for \.{\\lastskip} will be updated later.
9007
9008 We also handle \.{\\inputlineno} and \.{\\badness} here, because they are
9009 legal in similar contexts.
9010
9011 @<Fetch an item in the current node...@>=
9012 if (m > eTeX_last_last_item_cmd_mod)
9013 {@+switch (m) {
9014 @/@<Cases for fetching a \Prote\ int value@>@/
9015 } /*there are no other cases*/
9016 cur_val_level=int_val;
9017 }
9018 else if (m >= input_line_no_code)
9019 {if (m >= eTeX_glue) @<Process an expression and |return|@>@;
9020 else if (m >= eTeX_dim)
9021 {@+switch (m) {
9022 @/@<Cases for fetching a dimension value@>@/
9023 } /*there are no other cases*/
9024 cur_val_level=dimen_val;
9025 }
9026 else
9027 {@+switch (m) {
9028 case input_line_no_code: cur_val=line;@+break;
9029 case badness_code: cur_val=last_badness;@+break;
9030 @/@<Cases for fetching an integer value@>@/
9031 } /*there are no other cases*/
9032 cur_val_level=int_val;
9033 }
9034 }
9035 else{@+if (cur_chr==glue_val) cur_val=zero_glue;@+else cur_val=0;
9036 tx=tail;
9037 if (cur_chr==last_node_type_code)
9038 {@+cur_val_level=int_val;
9039 if ((tx==head)||(mode==0)) cur_val=-1;
9040 }
9041 else cur_val_level=cur_chr;
9042 if (!is_char_node(tx)&&(mode!=0))
9043 switch (cur_chr) {
9044 case int_val: if (type(tx)==penalty_node) cur_val=penalty(tx);@+break;
9045 case dimen_val: if (type(tx)==kern_node) cur_val=width(tx);@+break;
9046 case glue_val: if (type(tx)==glue_node)
9047 {@+cur_val=glue_ptr(tx);
9048 if (subtype(tx)==mu_glue) cur_val_level=mu_val;
9049 } @+break;
9050 case last_node_type_code: if (type(tx) <= unset_node) cur_val=type(tx)+1;
9051 else cur_val=unset_node+2;
9052 } /*there are no other cases*/
9053 else if ((mode==vmode)&&(tx==head))
9054 switch (cur_chr) {
9055 case int_val: cur_val=last_penalty;@+break;
9056 case dimen_val: cur_val=last_kern;@+break;
9057 case glue_val: if (last_glue!=max_halfword) cur_val=last_glue;@+break;
9058 case last_node_type_code: cur_val=last_node_type;
9059 } /*there are no other cases*/
9060 }
9061
9062 @ @<Fetch a font dimension@>=
9063 {@+find_font_dimen(false);font_info[fmem_ptr].sc=0;
9064 scanned_result(font_info[cur_val].sc, dimen_val);
9065 }
9066
9067 @ @<Fetch a font integer@>=
9068 {@+scan_font_ident();
9069 if (m==0) scanned_result(hyphen_char[cur_val], int_val)@;
9070 else scanned_result(skew_char[cur_val], int_val);
9071 }
9072
9073 @ @<Fetch a register@>=
9074 {@+if ((m < mem_bot)||(m > lo_mem_stat_max))
9075 {@+cur_val_level=sa_type(m);
9076 if (cur_val_level < glue_val) cur_val=sa_int(m);
9077 else cur_val=sa_ptr(m);
9078 }
9079 else{@+scan_register_num();cur_val_level=m-mem_bot;
9080 if (cur_val > 255)
9081 {@+find_sa_element(cur_val_level, cur_val, false);
9082 if (cur_ptr==null)
9083 if (cur_val_level < glue_val) cur_val=0;
9084 else cur_val=zero_glue;
9085 else if (cur_val_level < glue_val) cur_val=sa_int(cur_ptr);
9086 else cur_val=sa_ptr(cur_ptr);
9087 }
9088 else
9089 switch (cur_val_level) {
9090 case int_val: cur_val=count(cur_val);@+break;
9091 case dimen_val: cur_val=dimen(cur_val);@+break;
9092 case glue_val: cur_val=skip(cur_val);@+break;
9093 case mu_val: cur_val=mu_skip(cur_val);
9094 } /*there are no other cases*/
9095 }
9096 }
9097
9098 @ @<Complain that \.{\\the} can't do this; give zero result@>=
9099 {@+print_err("You can't use `");print_cmd_chr(cur_cmd, cur_chr);
9100 @.You can't use x after ...@>
9101 print("' after ");print_esc("the");
9102 help1("I'm forgetting what you said and using zero instead.");
9103 error();
9104 if (level!=tok_val) scanned_result(0, dimen_val)@;
9105 else scanned_result(0, int_val);
9106 }
9107
9108 @ When a |glue_val| changes to a |dimen_val|, we use the width component
9109 of the glue; there is no need to decrease the reference count, since it
9110 has not yet been increased. When a |dimen_val| changes to an |int_val|,
9111 we use scaled points so that the value doesn't actually change. And when a
9112 |mu_val| changes to a |glue_val|, the value doesn't change either.
9113
9114 @<Convert \(c)|cur_val| to a lower level@>=
9115 {@+if (cur_val_level==glue_val) cur_val=width(cur_val);
9116 else if (cur_val_level==mu_val) mu_error();
9117 decr(cur_val_level);
9118 }
9119
9120 @ If |cur_val| points to a glue specification at this point, the reference
9121 count for the glue does not yet include the reference by |cur_val|.
9122 If |negative| is |true|, |cur_val_level| is known to be | <= mu_val|.
9123
9124 @<Fix the reference count, if any,...@>=
9125 if (negative)
9126 if (cur_val_level >= glue_val)
9127 {@+cur_val=new_spec(cur_val);
9128 @<Negate all three glue components of |cur_val|@>;
9129 }
9130 else negate(cur_val);
9131 else if ((cur_val_level >= glue_val)&&(cur_val_level <= mu_val))
9132 add_glue_ref(cur_val)
9133
9134 @ @<Negate all three...@>=
9135 {@+negate(width(cur_val));
9136 negate(stretch(cur_val));
9137 negate(shrink(cur_val));
9138 }
9139
9140 @ Our next goal is to write the |scan_int| procedure, which scans anything that
9141 \TeX\ treats as an integer. But first we might as well look at some simple
9142 applications of |scan_int| that have already been made inside of
9143 |scan_something_internal|.
9144
9145 @ @<Declare procedures that scan restricted classes of integers@>=
9146 static void scan_eight_bit_int(void)
9147 {@+scan_int();
9148 if ((cur_val < 0)||(cur_val > 255))
9149 {@+print_err("Bad register code");
9150 @.Bad register code@>
9151 help2("A register number must be between 0 and 255.",@/
9152 "I changed this one to zero.");int_error(cur_val);cur_val=0;
9153 }
9154 }
9155
9156 @ @<Declare procedures that scan restricted classes of integers@>=
9157 static void scan_char_num(void)
9158 {@+scan_int();
9159 if ((cur_val < 0)||(cur_val > 255))
9160 {@+print_err("Bad character code");
9161 @.Bad character code@>
9162 help2("A character number must be between 0 and 255.",@/
9163 "I changed this one to zero.");int_error(cur_val);cur_val=0;
9164 }
9165 }
9166
9167 @ While we're at it, we might as well deal with similar routines that
9168 will be needed later.
9169
9170 @<Declare procedures that scan restricted classes of integers@>=
9171 static void scan_four_bit_int(void)
9172 {@+scan_int();
9173 if ((cur_val < 0)||(cur_val > 15))
9174 {@+print_err("Bad number");
9175 @.Bad number@>
9176 help2("Since I expected to read a number between 0 and 15,",@/
9177 "I changed this one to zero.");int_error(cur_val);cur_val=0;
9178 }
9179 }
9180
9181 @ @<Declare procedures that scan restricted classes of integers@>=
9182 static void scan_fifteen_bit_int(void)
9183 {@+scan_int();
9184 if ((cur_val < 0)||(cur_val > 077777))
9185 {@+print_err("Bad mathchar");
9186 @.Bad mathchar@>
9187 help2("A mathchar number must be between 0 and 32767.",@/
9188 "I changed this one to zero.");int_error(cur_val);cur_val=0;
9189 }
9190 }
9191
9192 @ @<Declare procedures that scan restricted classes of integers@>=
9193 static void scan_twenty_seven_bit_int(void)
9194 {@+scan_int();
9195 if ((cur_val < 0)||(cur_val > 0777777777))
9196 {@+print_err("Bad delimiter code");
9197 @.Bad delimiter code@>
9198 help2("A numeric delimiter code must be between 0 and 2^{27}-1.",@/
9199 "I changed this one to zero.");int_error(cur_val);cur_val=0;
9200 }
9201 }
9202
9203 @ An integer number can be preceded by any number of spaces and `\.+' or
9204 `\.-' signs. Then comes either a decimal constant (i.e., radix 10), an
9205 octal constant (i.e., radix 8, preceded by~\.\'), a hexadecimal constant
9206 (radix 16, preceded by~\."), an alphabetic constant (preceded by~\.\`), or
9207 an internal variable. After scanning is complete,
9208 |cur_val| will contain the answer, which must be at most
9209 $2^{31}-1=2147483647$ in absolute value. The value of |radix| is set to
9210 10, 8, or 16 in the cases of decimal, octal, or hexadecimal constants,
9211 otherwise |radix| is set to zero. An optional space follows a constant.
9212
9213 @d octal_token (other_token+'\'') /*apostrophe, indicates an octal constant*/
9214 @d hex_token (other_token+'"') /*double quote, indicates a hex constant*/
9215 @d alpha_token (other_token+'`') /*reverse apostrophe, precedes alpha constants*/
9216 @d point_token (other_token+'.') /*decimal point*/
9217 @d continental_point_token (other_token+',') /*decimal point, Eurostyle*/
9218
9219 @<Glob...@>=
9220 static small_number @!radix; /*|scan_int| sets this to 8, 10, 16, or zero*/
9221
9222 @ We initialize the following global variables just in case |expand|
9223 comes into action before any of the basic scanning routines has assigned
9224 them a value.
9225
9226 @<Set init...@>=
9227 cur_val=0;cur_val_level=int_val;radix=0;cur_order=normal;
9228
9229 @ The |scan_int| routine is used also to scan the integer part of a
9230 fraction; for example, the `\.3' in `\.{3.14159}' will be found by
9231 |scan_int|. The |scan_dimen| routine assumes that |cur_tok==point_token|
9232 after the integer part of such a fraction has been scanned by |scan_int|,
9233 and that the decimal point has been backed up to be scanned again.
9234
9235 @p static void scan_int(void) /*sets |cur_val| to an integer*/
9236 {@+
9237 bool negative; /*should the answer be negated?*/
9238 int @!m; /*|@t$2^{31}$@>/radix|, the threshold of danger*/
9239 small_number @!d; /*the digit just scanned*/
9240 bool @!vacuous; /*have no digits appeared?*/
9241 bool @!OK_so_far; /*has an error message been issued?*/
9242 radix=0;OK_so_far=true;@/
9243 @<Get the next non-blank non-sign token; set |negative| appropriately@>;
9244 if (cur_tok==alpha_token) @<Scan an alphabetic character code into |cur_val|@>@;
9245 else if ((cur_cmd >= min_internal)&&(cur_cmd <= max_internal))
9246 scan_something_internal(int_val, false);
9247 else@<Scan a numeric constant@>;
9248 if (negative) negate(cur_val);
9249 }
9250
9251 @ @<Get the next non-blank non-sign token...@>=
9252 negative=false;
9253 @/do@+{@<Get the next non-blank non-call token@>;
9254 if (cur_tok==other_token+'-')
9255 {@+negative=!negative;cur_tok=other_token+'+';
9256 }
9257 }@+ while (!(cur_tok!=other_token+'+'))
9258
9259 @ A space is ignored after an alphabetic character constant, so that
9260 such constants behave like numeric ones.
9261
9262 @<Scan an alphabetic character code into |cur_val|@>=
9263 {@+get_token(); /*suppress macro expansion*/
9264 if (cur_tok < cs_token_flag)
9265 {@+cur_val=cur_chr;
9266 if (cur_cmd <= right_brace)
9267 if (cur_cmd==right_brace) incr(align_state);
9268 else decr(align_state);
9269 }
9270 else if (cur_tok < cs_token_flag+single_base)
9271 cur_val=cur_tok-cs_token_flag-active_base;
9272 else cur_val=cur_tok-cs_token_flag-single_base;
9273 if (cur_val > 255)
9274 {@+print_err("Improper alphabetic constant");
9275 @.Improper alphabetic constant@>
9276 help2("A one-character control sequence belongs after a ` mark.",@/
9277 "So I'm essentially inserting \\0 here.");
9278 cur_val='0';back_error();
9279 }
9280 else@<Scan an optional space@>;
9281 }
9282
9283 @ @<Scan an optional space@>=
9284 {@+get_x_token();if (cur_cmd!=spacer) back_input();
9285 }
9286
9287 @ @<Scan a numeric constant@>=
9288 {@+radix=10;m=214748364;
9289 if (cur_tok==octal_token)
9290 {@+radix=8;m=02000000000;get_x_token();
9291 }
9292 else if (cur_tok==hex_token)
9293 {@+radix=16;m=01000000000;get_x_token();
9294 }
9295 vacuous=true;cur_val=0;@/
9296 @<Accumulate the constant until |cur_tok| is not a suitable digit@>;
9297 if (vacuous) @<Express astonishment that no number was here@>@;
9298 else if (cur_cmd!=spacer) back_input();
9299 }
9300
9301 @ @d infinity 017777777777 /*the largest positive value that \TeX\ knows*/
9302 @d zero_token (other_token+'0') /*zero, the smallest digit*/
9303 @d A_token (letter_token+'A') /*the smallest special hex digit*/
9304 @d other_A_token (other_token+'A') /*special hex digit of type |other_char|*/
9305
9306 @<Accumulate the constant...@>=
9307 loop@+{@+if ((cur_tok < zero_token+radix)&&(cur_tok >= zero_token)&&
9308 (cur_tok <= zero_token+9)) d=cur_tok-zero_token;
9309 else if (radix==16)
9310 if ((cur_tok <= A_token+5)&&(cur_tok >= A_token)) d=cur_tok-A_token+10;
9311 else if ((cur_tok <= other_A_token+5)&&(cur_tok >= other_A_token))
9312 d=cur_tok-other_A_token+10;
9313 else goto done;
9314 else goto done;
9315 vacuous=false;
9316 if ((cur_val >= m)&&((cur_val > m)||(d > 7)||(radix!=10)))
9317 {@+if (OK_so_far)
9318 {@+print_err("Number too big");
9319 @.Number too big@>
9320 help2("I can only go up to 2147483647='17777777777=\"7FFFFFFF,",@/
9321 "so I'm using that number instead of yours.");
9322 error();cur_val=infinity;OK_so_far=false;
9323 }
9324 }
9325 else cur_val=cur_val*radix+d;
9326 get_x_token();
9327 }
9328 done:
9329
9330 @ @<Express astonishment...@>=
9331 {@+print_err("Missing number, treated as zero");
9332 @.Missing number...@>
9333 help3("A number should have been here; I inserted `0'.",@/
9334 "(If you can't figure out why I needed to see a number,",@/
9335 "look up `weird error' in the index to The TeXbook.)");
9336 @:TeXbook}{\sl The \TeX book@>
9337 back_error();
9338 }
9339
9340 @ The |scan_dimen| routine is similar to |scan_int|, but it sets |cur_val| to
9341 a |scaled| value, i.e., an integral number of sp. One of its main tasks
9342 is therefore to interpret the abbreviations for various kinds of units and
9343 to convert measurements to scaled points.
9344
9345 There are three parameters: |mu| is |true| if the finite units must be
9346 `\.{mu}', while |mu| is |false| if `\.{mu}' units are disallowed;
9347 |inf| is |true| if the infinite units `\.{fil}', `\.{fill}', `\.{filll}'
9348 are permitted; and |shortcut| is |true| if |cur_val| already contains
9349 an integer and only the units need to be considered.
9350
9351 The order of infinity that was found in the case of infinite glue is returned
9352 in the global variable |cur_order|.
9353
9354 @<Glob...@>=
9355 static glue_ord @!cur_order; /*order of infinity found by |scan_dimen|*/
9356
9357 @ Constructions like `\.{-\'77 pt}' are legal dimensions, so |scan_dimen|
9358 may begin with |scan_int|. This explains why it is convenient to use
9359 |scan_int| also for the integer part of a decimal fraction.
9360
9361 Several branches of |scan_dimen| work with |cur_val| as an integer and
9362 with an auxiliary fraction |f|, so that the actual quantity of interest is
9363 $|cur_val|+|f|/2^{16}$. At the end of the routine, this ``unpacked''
9364 representation is put into the single word |cur_val|, which suddenly
9365 switches significance from |int| to |scaled|.
9366
9367 @d scan_normal_dimen scan_dimen(false, false, false)
9368
9369 @p static void scan_dimen(bool @!mu, bool @!inf, bool @!shortcut)
9370 /*sets |cur_val| to a dimension*/
9371 {@+
9372 bool negative; /*should the answer be negated?*/
9373 int @!f; /*numerator of a fraction whose denominator is $2^{16}$*/
9374 @<Local variables for dimension calculations@>@;
9375 f=0;arith_error=false;cur_order=normal;negative=false;
9376 if (!shortcut)
9377 {@+@<Get the next non-blank non-sign...@>;
9378 if ((cur_cmd >= min_internal)&&(cur_cmd <= max_internal))
9379 @<Fetch an internal dimension and |goto attach_sign|, or fetch an internal
9380 integer@>@;
9381 else{@+back_input();
9382 if (cur_tok==continental_point_token) cur_tok=point_token;
9383 if (cur_tok!=point_token) scan_int();
9384 else{@+radix=10;cur_val=0;
9385 }
9386 if (cur_tok==continental_point_token) cur_tok=point_token;
9387 if ((radix==10)&&(cur_tok==point_token)) @<Scan decimal fraction@>;
9388 }
9389 }
9390 if (cur_val < 0) /*in this case |f==0|*/
9391 {@+negative=!negative;negate(cur_val);
9392 }
9393 @<Scan units and set |cur_val| to $x\cdot(|cur_val|+f/2^{16})$, where there
9394 are |x| sp per unit; |goto attach_sign| if the units are internal@>;
9395 @<Scan an optional space@>;
9396 attach_sign: if (arith_error||(abs(cur_val) >= 010000000000))
9397 @<Report that this dimension is out of range@>;
9398 if (negative) negate(cur_val);
9399 }
9400
9401 @ @<Fetch an internal dimension and |goto attach_sign|...@>=
9402 if (mu)
9403 {@+scan_something_internal(mu_val, false);
9404 @<Coerce glue to a dimension@>;
9405 if (cur_val_level==mu_val) goto attach_sign;
9406 if (cur_val_level!=int_val) mu_error();
9407 }
9408 else{@+scan_something_internal(dimen_val, false);
9409 if (cur_val_level==dimen_val) goto attach_sign;
9410 }
9411
9412 @ @<Local variables for dimension calculations@>=
9413 int @!num, @!denom; /*conversion ratio for the scanned units*/
9414 int @!k, @!kk; /*number of digits in a decimal fraction*/
9415 pointer @!p, @!q; /*top of decimal digit stack*/
9416 scaled @!v; /*an internal dimension*/
9417 int @!save_cur_val; /*temporary storage of |cur_val|*/
9418
9419 @ The following code is executed when |scan_something_internal| was
9420 called asking for |mu_val|, when we really wanted a ``mudimen'' instead
9421 of ``muglue.''
9422
9423 @<Coerce glue to a dimension@>=
9424 if (cur_val_level >= glue_val)
9425 {@+v=width(cur_val);delete_glue_ref(cur_val);cur_val=v;
9426 }
9427
9428 @ When the following code is executed, we have |cur_tok==point_token|, but this
9429 token has been backed up using |back_input|; we must first discard it.
9430
9431 It turns out that a decimal point all by itself is equivalent to `\.{0.0}'.
9432 Let's hope people don't use that fact.
9433
9434 @<Scan decimal fraction@>=
9435 {@+k=0;p=null;get_token(); /*|point_token| is being re-scanned*/
9436 loop@+{@+get_x_token();
9437 if ((cur_tok > zero_token+9)||(cur_tok < zero_token)) goto done1;
9438 if (k < 17) /*digits for |k >= 17| cannot affect the result*/
9439 {@+q=get_avail();link(q)=p;info(q)=cur_tok-zero_token;
9440 p=q;incr(k);
9441 }
9442 }
9443 done1: for (kk=k; kk>=1; kk--)
9444 {@+dig[kk-1]=info(p);q=p;p=link(p);free_avail(q);
9445 }
9446 f=round_decimals(k);
9447 if (cur_cmd!=spacer) back_input();
9448 }
9449
9450 @ Now comes the harder part: At this point in the program, |cur_val| is a
9451 nonnegative integer and $f/2^{16}$ is a nonnegative fraction less than 1;
9452 we want to multiply the sum of these two quantities by the appropriate
9453 factor, based on the specified units, in order to produce a |scaled|
9454 result, and we want to do the calculation with fixed point arithmetic that
9455 does not overflow.
9456
9457 @<Scan units and set |cur_val| to $x\cdot(|cur_val|+f/2^{16})$...@>=
9458 if (inf) @<Scan for \(f)\.{fil} units; |goto attach_fraction| if found@>;
9459 @<Scan for \(u)units that are internal dimensions; |goto attach_sign| with
9460 |cur_val| set if found@>;
9461 if (mu) @<Scan for \(m)\.{mu} units and |goto attach_fraction|@>;
9462 if (scan_keyword("true")) @<Adjust \(f)for the magnification ratio@>;
9463 @.true@>
9464 if (scan_keyword("pt")) goto attach_fraction; /*the easy case*/
9465 @.pt@>
9466 @<Scan for \(a)all other units and adjust |cur_val| and |f| accordingly; |goto
9467 done| in the case of scaled points@>;
9468 attach_fraction: if (cur_val >= 040000) arith_error=true;
9469 else cur_val=cur_val*unity+f;
9470 done:
9471
9472 @ A specification like `\.{filllll}' or `\.{fill L L L}' will lead to two
9473 error messages (one for each additional keyword \.{"l"}).
9474
9475 @<Scan for \(f)\.{fil} units...@>=
9476 if (scan_keyword("fil"))
9477 @.fil@>
9478 {@+cur_order=fil;
9479 while (scan_keyword("l"))
9480 {@+if (cur_order==filll)
9481 {@+print_err("Illegal unit of measure (");
9482 @.Illegal unit of measure@>
9483 print("replaced by filll)");
9484 help1("I dddon't go any higher than filll.");error();
9485 }
9486 else incr(cur_order);
9487 }
9488 goto attach_fraction;
9489 }
9490
9491 @ @<Scan for \(u)units that are internal dimensions...@>=
9492 save_cur_val=cur_val;
9493 @<Get the next non-blank non-call...@>;
9494 if ((cur_cmd < min_internal)||(cur_cmd > max_internal)) back_input();
9495 else{@+if (mu)
9496 {@+scan_something_internal(mu_val, false);@<Coerce glue...@>;
9497 if (cur_val_level!=mu_val) mu_error();
9498 }
9499 else scan_something_internal(dimen_val, false);
9500 v=cur_val;goto found;
9501 }
9502 if (mu) goto not_found;
9503 if (scan_keyword("em")) v=(@<The em width for |cur_font|@>);
9504 @.em@>
9505 else if (scan_keyword("ex")) v=(@<The x-height for |cur_font|@>);
9506 @.ex@>
9507 else goto not_found;
9508 @<Scan an optional space@>;
9509 found: cur_val=nx_plus_y(save_cur_val, v, xn_over_d(v, f, 0200000));
9510 goto attach_sign;
9511 not_found:
9512
9513 @ @<Scan for \(m)\.{mu} units and |goto attach_fraction|@>=
9514 if (scan_keyword("mu")) goto attach_fraction;
9515 @.mu@>
9516 else{@+print_err("Illegal unit of measure (");print("mu inserted)");
9517 @.Illegal unit of measure@>
9518 help4("The unit of measurement in math glue must be mu.",@/
9519 "To recover gracefully from this error, it's best to",@/
9520 "delete the erroneous units; e.g., type `2' to delete",@/
9521 "two letters. (See Chapter 27 of The TeXbook.)");
9522 @:TeXbook}{\sl The \TeX book@>
9523 error();goto attach_fraction;
9524 }
9525
9526 @ @<Adjust \(f)for the magnification ratio@>=
9527 {@+prepare_mag();
9528 if (mag!=1000)
9529 {@+cur_val=xn_over_d(cur_val, 1000, mag);
9530 f=(1000*f+0200000*rem)/mag;
9531 cur_val=cur_val+(f/0200000);f=f%0200000;
9532 }
9533 }
9534
9535 @ The necessary conversion factors can all be specified exactly as
9536 fractions whose numerator and denominator sum to 32768 or less.
9537 According to the definitions here, $\rm2660\,dd\approx1000.33297\,mm$;
9538 this agrees well with the value $\rm1000.333\,mm$ cited by Bosshard
9539 @^Bosshard, Hans Rudolf@>
9540 in {\sl Technische Grundlagen zur Satzherstellung\/} (Bern, 1980).
9541
9542 @d set_conversion(A, B) @+{@+num=A;denom=B;}
9543
9544 @<Scan for \(a)all other units and adjust |cur_val| and |f|...@>=
9545 if (scan_keyword("in")) set_conversion(7227, 100)@;
9546 @.in@>
9547 else if (scan_keyword("pc")) set_conversion(12, 1)@;
9548 @.pc@>
9549 else if (scan_keyword("cm")) set_conversion(7227, 254)@;
9550 @.cm@>
9551 else if (scan_keyword("mm")) set_conversion(7227, 2540)@;
9552 @.mm@>
9553 else if (scan_keyword("bp")) set_conversion(7227, 7200)@;
9554 @.bp@>
9555 else if (scan_keyword("dd")) set_conversion(1238, 1157)@;
9556 @.dd@>
9557 else if (scan_keyword("cc")) set_conversion(14856, 1157)@;
9558 @.cc@>
9559 else if (scan_keyword("sp")) goto done;
9560 @.sp@>
9561 else@<Complain about unknown unit and |goto done2|@>;
9562 cur_val=xn_over_d(cur_val, num, denom);
9563 f=(num*f+0200000*rem)/denom;@/
9564 cur_val=cur_val+(f/0200000);f=f%0200000;
9565 done2:
9566
9567 @ @<Complain about unknown unit...@>=
9568 {@+print_err("Illegal unit of measure (");print("pt inserted)");
9569 @.Illegal unit of measure@>
9570 help6("Dimensions can be in units of em, ex, in, pt, pc,",@/
9571 "cm, mm, dd, cc, bp, or sp; but yours is a new one!",@/
9572 "I'll assume that you meant to say pt, for printer's points.",@/
9573 "To recover gracefully from this error, it's best to",@/
9574 "delete the erroneous units; e.g., type `2' to delete",@/
9575 "two letters. (See Chapter 27 of The TeXbook.)");
9576 @:TeXbook}{\sl The \TeX book@>
9577 error();goto done2;
9578 }
9579
9580
9581 @ @<Report that this dimension is out of range@>=
9582 {@+print_err("Dimension too large");
9583 @.Dimension too large@>
9584 help2("I can't work with sizes bigger than about 19 feet.",@/
9585 "Continue and I'll use the largest value I can.");@/
9586 error();cur_val=max_dimen;arith_error=false;
9587 }
9588
9589 @ The final member of \TeX's value-scanning trio is |scan_glue|, which
9590 makes |cur_val| point to a glue specification. The reference count of that
9591 glue spec will take account of the fact that |cur_val| is pointing to~it.
9592
9593 The |level| parameter should be either |glue_val| or |mu_val|.
9594
9595 Since |scan_dimen| was so much more complex than |scan_int|, we might expect
9596 |scan_glue| to be even worse. But fortunately, it is very simple, since
9597 most of the work has already been done.
9598
9599 @p static void scan_glue(small_number @!level)
9600 /*sets |cur_val| to a glue spec pointer*/
9601 {@+
9602 bool negative; /*should the answer be negated?*/
9603 pointer @!q; /*new glue specification*/
9604 bool @!mu; /*does |level==mu_val|?*/
9605 mu=(level==mu_val);@<Get the next non-blank non-sign...@>;
9606 if ((cur_cmd >= min_internal)&&(cur_cmd <= max_internal))
9607 {@+scan_something_internal(level, negative);
9608 if (cur_val_level >= glue_val)
9609 {@+if (cur_val_level!=level) mu_error();
9610 return;
9611 }
9612 if (cur_val_level==int_val) scan_dimen(mu, false, true);
9613 else if (level==mu_val) mu_error();
9614 }
9615 else{@+back_input();scan_dimen(mu, false, false);
9616 if (negative) negate(cur_val);
9617 }
9618 @<Create a new glue specification whose width is |cur_val|; scan for its stretch
9619 and shrink components@>;
9620 }
9621 @#
9622 @<Declare procedures needed for expressions@>@;
9623
9624 @ @<Create a new glue specification whose width is |cur_val|...@>=
9625 q=new_spec(zero_glue);width(q)=cur_val;
9626 if (scan_keyword("plus"))
9627 @.plus@>
9628 {@+scan_dimen(mu, true, false);
9629 stretch(q)=cur_val;stretch_order(q)=cur_order;
9630 }
9631 if (scan_keyword("minus"))
9632 @.minus@>
9633 {@+scan_dimen(mu, true, false);
9634 shrink(q)=cur_val;shrink_order(q)=cur_order;
9635 }
9636 cur_val=q
9637
9638 @ Here's a similar procedure that returns a pointer to a rule node. This
9639 routine is called just after \TeX\ has seen \.{\\hrule} or \.{\\vrule};
9640 therefore |cur_cmd| will be either |hrule| or |vrule|. The idea is to store
9641 the default rule dimensions in the node, then to override them if
9642 `\.{height}' or `\.{width}' or `\.{depth}' specifications are
9643 found (in any order).
9644
9645 @d default_rule 26214 /*0.4\thinspace pt*/
9646
9647 @p static pointer scan_rule_spec(void)
9648 {@+
9649 pointer q; /*the rule node being created*/
9650 q=new_rule(); /*|width|, |depth|, and |height| all equal |null_flag| now*/
9651 if (cur_cmd==vrule) width(q)=default_rule;
9652 else{@+height(q)=default_rule;depth(q)=0;
9653 }
9654 reswitch: if (scan_keyword("width"))
9655 @.width@>
9656 {@+scan_normal_dimen;width(q)=cur_val;goto reswitch;
9657 }
9658 if (scan_keyword("height"))
9659 @.height@>
9660 {@+scan_normal_dimen;height(q)=cur_val;goto reswitch;
9661 }
9662 if (scan_keyword("depth"))
9663 @.depth@>
9664 {@+scan_normal_dimen;depth(q)=cur_val;goto reswitch;
9665 }
9666 return q;
9667 }
9668
9669 @* Building token lists.
9670 The token lists for macros and for other things like \.{\\mark} and \.{\\output}
9671 and \.{\\write} are produced by a procedure called |scan_toks|.
9672
9673 Before we get into the details of |scan_toks|, let's consider a much
9674 simpler task, that of converting the current string into a token list.
9675 The |str_toks| function does this; it classifies spaces as type |spacer|
9676 and everything else as type |other_char|.
9677
9678 The token list created by |str_toks| begins at |link(temp_head)| and ends
9679 at the value |p| that is returned. (If |p==temp_head|, the list is empty.)
9680
9681 @p @t\4@>@<Declare \eTeX\ procedures for token lists@>@;@/
9682 static pointer str_toks(pool_pointer @!b)
9683 /*converts |str_pool[b dotdot pool_ptr-1]| to a token list*/
9684 {@+pointer p; /*tail of the token list*/
9685 pointer @!q; /*new node being added to the token list via |store_new_token|*/
9686 halfword @!t; /*token being appended*/
9687 pool_pointer @!k; /*index into |str_pool|*/
9688 str_room(1);
9689 p=temp_head;link(p)=null;k=b;
9690 while (k < pool_ptr)
9691 {@+t=so(str_pool[k]);
9692 if (t==' ') t=space_token;
9693 else t=other_token+t;
9694 fast_store_new_token(t);
9695 incr(k);
9696 }
9697 pool_ptr=b;return p;
9698 }
9699
9700 @ The main reason for wanting |str_toks| is the next function,
9701 |the_toks|, which has similar input/output characteristics.
9702
9703 This procedure is supposed to scan something like `\.{\\skip\\count12}',
9704 i.e., whatever can follow `\.{\\the}', and it constructs a token list
9705 containing something like `\.{-3.0pt minus 0.5fill}'.
9706
9707 @p static pointer the_toks(void)
9708 {@+
9709 int old_setting; /*holds |selector| setting*/
9710 pointer @!p, @!q, @!r; /*used for copying a token list*/
9711 pool_pointer @!b; /*base of temporary string*/
9712 small_number @!c; /*value of |cur_chr|*/
9713 @<Handle \.{\\unexpanded} or \.{\\detokenize} and |return|@>;@/
9714 get_x_token();scan_something_internal(tok_val, false);
9715 if (cur_val_level >= ident_val) @<Copy the token list@>@;
9716 else{@+old_setting=selector;selector=new_string;b=pool_ptr;
9717 switch (cur_val_level) {
9718 case int_val: print_int(cur_val);@+break;
9719 case dimen_val: {@+print_scaled(cur_val);print("pt");
9720 } @+break;
9721 case glue_val: {@+print_spec(cur_val,"pt");delete_glue_ref(cur_val);
9722 } @+break;
9723 case mu_val: {@+print_spec(cur_val,"mu");delete_glue_ref(cur_val);
9724 }
9725 } /*there are no other cases*/
9726 selector=old_setting;return str_toks(b);
9727 }
9728 }
9729
9730 @ @<Copy the token list@>=
9731 {@+p=temp_head;link(p)=null;
9732 if (cur_val_level==ident_val) store_new_token(cs_token_flag+cur_val)@;
9733 else if (cur_val!=null)
9734 {@+r=link(cur_val); /*do not copy the reference count*/
9735 while (r!=null)
9736 {@+fast_store_new_token(info(r));r=link(r);
9737 }
9738 }
9739 return p;
9740 }
9741
9742 @ Here's part of the |expand| subroutine that we are now ready to complete:
9743
9744 @p static void ins_the_toks(void)
9745 {@+link(garbage)=the_toks();ins_list(link(temp_head));
9746 }
9747
9748 @ The primitives \.{\\number}, \.{\\romannumeral}, \.{\\string}, \.{\\meaning},
9749 \.{\\fontname}, and \.{\\jobname} are defined as follows.
9750
9751 @d number_code 0 /*command code for \.{\\number}*/
9752 @d roman_numeral_code 1 /*command code for \.{\\romannumeral}*/
9753 @d string_code 2 /*command code for \.{\\string}*/
9754 @d meaning_code 3 /*command code for \.{\\meaning}*/
9755 @d font_name_code 4 /*command code for \.{\\fontname}*/
9756 @d etex_convert_base 5 /*base for \eTeX's command codes*/
9757 @d eTeX_revision_code etex_convert_base /*command code for \.{\\eTeXrevision}*/
9758 @d etex_convert_codes (etex_convert_base+1) /*end of \eTeX's command codes*/
9759 @d eTeX_last_convert_cmd_mod etex_convert_codes /* prote codes follow */
9760
9761
9762 @#
9763 @d job_name_code pdftex_convert_codes /*command code for \.{\\jobname}*/
9764
9765 @<Put each...@>=
9766 primitive("number", convert, number_code);@/
9767 @!@:number\_}{\.{\\number} primitive@>
9768 primitive("romannumeral", convert, roman_numeral_code);@/
9769 @!@:roman\_numeral\_}{\.{\\romannumeral} primitive@>
9770 primitive("string", convert, string_code);@/
9771 @!@:string\_}{\.{\\string} primitive@>
9772 primitive("meaning", convert, meaning_code);@/
9773 @!@:meaning\_}{\.{\\meaning} primitive@>
9774 primitive("fontname", convert, font_name_code);@/
9775 @!@:font\_name\_}{\.{\\fontname} primitive@>
9776 primitive("jobname", convert, job_name_code);@/
9777 @!@:job\_name\_}{\.{\\jobname} primitive@>
9778
9779 @ @<Cases of |print_cmd_chr|...@>=
9780 case convert: switch (chr_code) {
9781 case number_code: print_esc("number");@+break;
9782 case roman_numeral_code: print_esc("romannumeral");@+break;
9783 case string_code: print_esc("string");@+break;
9784 case meaning_code: print_esc("meaning");@+break;
9785 case font_name_code: print_esc("fontname");@+break;
9786 case job_name_code: print_esc("jobname");@+break;
9787 case eTeX_revision_code: print_esc("eTeXrevision");@+break;
9788 @/@<Cases of |convert| for |print_cmd_chr|@>@/
9789 } @+break;
9790
9791 @ The procedure |conv_toks| uses |str_toks| to insert the token list
9792 for |convert| functions into the scanner; `\.{\\outer}' control sequences
9793 are allowed to follow `\.{\\string}' and `\.{\\meaning}'.
9794
9795 @p static void scan_pdf_ext_toks(void);
9796 static void conv_toks(void)
9797 {@+int old_setting; /*holds |selector| setting*/
9798 int @!c; /*desired type of conversion*/
9799 small_number @!save_scanner_status; /*|scanner_status| upon entry*/
9800 pool_pointer @!b; /*base of temporary string*/
9801 int @!i, @!k, @!l; /*general purpose index*/
9802 pool_pointer @!m, @!n; /*general purpose pool pointer*/
9803 bool @!r; /*general purpose refraction i.e. changing the way*/
9804 str_number @!s, @!t; /*general purpose; de dicto*/
9805 c=cur_chr;@<Scan the argument for command |c|@>;
9806 old_setting=selector;selector=new_string;b=pool_ptr;
9807 @<Print the result of command |c|@>;
9808 selector=old_setting;link(garbage)=str_toks(b);ins_list(link(temp_head));
9809 }
9810
9811 @ @<Scan the argument for command |c|@>=
9812 switch (c) {
9813 case number_code: case roman_numeral_code: scan_int();@+break;
9814 case string_code: case meaning_code: {@+save_scanner_status=scanner_status;
9815 scanner_status=normal;get_token();scanner_status=save_scanner_status;
9816 } @+break;
9817 case font_name_code: scan_font_ident();@+break;
9818 case job_name_code: if (job_name==0) open_log_file();@+break;
9819 case eTeX_revision_code: do_nothing;@+break;
9820 @/@<Cases of `Scan the argument for command |c|'@>@/
9821 } /*there are no other cases*/
9822
9823 @ @<Print the result of command |c|@>=
9824 switch (c) {
9825 case number_code: print_int(cur_val);@+break;
9826 case roman_numeral_code: print_roman_int(cur_val);@+break;
9827 case string_code: if (cur_cs!=0) sprint_cs(cur_cs);
9828 else print_char(cur_chr);@+break;
9829 case meaning_code: print_meaning();@+break;
9830 case font_name_code: {@+printn(font_name[cur_val]);
9831 if (font_size[cur_val]!=font_dsize[cur_val])
9832 {@+print(" at ");print_scaled(font_size[cur_val]);
9833 print("pt");
9834 }
9835 } @+break;
9836 case eTeX_revision_code: print(eTeX_revision);@+break;
9837 case job_name_code: printn(job_name);@+break;
9838 @/@<Cases of `Print the result of command |c|'@>@/
9839 } /*there are no other cases*/
9840
9841 @ Now we can't postpone the difficulties any longer; we must bravely tackle
9842 |scan_toks|. This function returns a pointer to the tail of a new token
9843 list, and it also makes |def_ref| point to the reference count at the
9844 head of that list.
9845
9846 There are two boolean parameters, |macro_def| and |xpand|. If |macro_def|
9847 is true, the goal is to create the token list for a macro definition;
9848 otherwise the goal is to create the token list for some other \TeX\
9849 primitive: \.{\\mark}, \.{\\output}, \.{\\everypar}, \.{\\lowercase},
9850 \.{\\uppercase}, \.{\\message}, \.{\\errmessage}, \.{\\write}, or
9851 \.{\\special}. In the latter cases a left brace must be scanned next; this
9852 left brace will not be part of the token list, nor will the matching right
9853 brace that comes at the end. If |xpand| is false, the token list will
9854 simply be copied from the input using |get_token|. Otherwise all expandable
9855 tokens will be expanded until unexpandable tokens are left, except that
9856 the results of expanding `\.{\\the}' are not expanded further.
9857 If both |macro_def| and |xpand| are true, the expansion applies
9858 only to the macro body (i.e., to the material following the first
9859 |left_brace| character).
9860
9861 The value of |cur_cs| when |scan_toks| begins should be the |eqtb|
9862 address of the control sequence to display in ``runaway'' error
9863 messages.
9864
9865 @p static pointer scan_toks(bool @!macro_def, bool @!xpand)
9866 {@+
9867 halfword t; /*token representing the highest parameter number*/
9868 halfword @!s; /*saved token*/
9869 pointer @!p; /*tail of the token list being built*/
9870 pointer @!q; /*new node being added to the token list via |store_new_token|*/
9871 halfword @!unbalance; /*number of unmatched left braces*/
9872 halfword @!hash_brace; /*possible `\.{\#\{}' token*/
9873 if (macro_def) scanner_status=defining;
9874 @+else scanner_status=absorbing;
9875 warning_index=cur_cs;def_ref=get_avail();token_ref_count(def_ref)=null;
9876 p=def_ref;hash_brace=0;t=zero_token;
9877 if (macro_def) @<Scan and build the parameter part of the macro definition@>@;
9878 else scan_left_brace(); /*remove the compulsory left brace*/
9879 @<Scan and build the body of the token list; |goto found| when finished@>;
9880 found: scanner_status=normal;
9881 if (hash_brace!=0) store_new_token(hash_brace);
9882 return p;
9883 }
9884 @t\4@>@<Declare \Prote\ procedures for token lists@>@;@/
9885
9886 @ @<Scan and build the parameter part...@>=
9887 {@+loop{@+resume: get_token(); /*set |cur_cmd|, |cur_chr|, |cur_tok|*/
9888 if (cur_tok < right_brace_limit) goto done1;
9889 if (cur_cmd==mac_param)
9890 @<If the next character is a parameter number, make |cur_tok| a |match|
9891 token; but if it is a left brace, store `|left_brace|, |end_match|', set |hash_brace|,
9892 and |goto done|@>;
9893 store_new_token(cur_tok);
9894 }
9895 done1: store_new_token(end_match_token);
9896 if (cur_cmd==right_brace)
9897 @<Express shock at the missing left brace; |goto found|@>;
9898 done: ;}
9899
9900 @ @<Express shock...@>=
9901 {@+print_err("Missing { inserted");incr(align_state);
9902 @.Missing \{ inserted@>
9903 help2("Where was the left brace? You said something like `\\def\\a}',",@/
9904 "which I'm going to interpret as `\\def\\a{}'.");error();goto found;
9905 }
9906
9907 @ @<If the next character is a parameter number...@>=
9908 {@+s=match_token+cur_chr;get_token();
9909 if (cur_tok < left_brace_limit)
9910 {@+hash_brace=cur_tok;
9911 store_new_token(cur_tok);store_new_token(end_match_token);
9912 goto done;
9913 }
9914 if (t==zero_token+9)
9915 {@+print_err("You already have nine parameters");
9916 @.You already have nine...@>
9917 help2("I'm going to ignore the # sign you just used,",@/
9918 "as well as the token that followed it.");error();goto resume;
9919 }
9920 else{@+incr(t);
9921 if (cur_tok!=t)
9922 {@+print_err("Parameters must be numbered consecutively");
9923 @.Parameters...consecutively@>
9924 help2("I've inserted the digit you should have used after the #.",@/
9925 "Type `1' to delete what you did use.");back_error();
9926 }
9927 cur_tok=s;
9928 }
9929 }
9930
9931 @ @<Scan and build the body of the token list; |goto found| when finished@>=
9932 unbalance=1;
9933 loop@+{@+if (xpand) @<Expand the next part of the input@>@;
9934 else get_token();
9935 if (cur_tok < right_brace_limit)
9936 if (cur_cmd < right_brace) incr(unbalance);
9937 else{@+decr(unbalance);
9938 if (unbalance==0) goto found;
9939 }
9940 else if (cur_cmd==mac_param)
9941 if (macro_def) @<Look for parameter number or \.{\#\#}@>;
9942 store_new_token(cur_tok);
9943 }
9944
9945 @ Here we insert an entire token list created by |the_toks| without
9946 expanding it further.
9947
9948 @<Expand the next part of the input@>=
9949 {@+loop{@+get_next();
9950 if (cur_cmd >= call)
9951 if (info(link(cur_chr))==protected_token)
9952 {@+cur_cmd=relax;cur_chr=no_expand_flag;
9953 }
9954 if (cur_cmd <= max_command) goto done2;
9955 if (cur_cmd!=the) expand();
9956 else{@+q=the_toks();
9957 if (link(temp_head)!=null)
9958 {@+link(p)=link(temp_head);p=q;
9959 }
9960 }
9961 }
9962 done2: x_token();
9963 }
9964
9965 @ @<Look for parameter number...@>=
9966 {@+s=cur_tok;
9967 if (xpand) get_x_token();else get_token();
9968 if (cur_cmd!=mac_param)
9969 if ((cur_tok <= zero_token)||(cur_tok > t))
9970 {@+print_err("Illegal parameter number in definition of ");
9971 @.Illegal parameter number...@>
9972 sprint_cs(warning_index);
9973 help3("You meant to type ## instead of #, right?",@/
9974 "Or maybe a } was forgotten somewhere earlier, and things",@/
9975 "are all screwed up? I'm going to assume that you meant ##.");
9976 back_error();cur_tok=s;
9977 }
9978 else cur_tok=out_param_token-'0'+cur_chr;
9979 }
9980
9981 @ Another way to create a token list is via the \.{\\read} command. The
9982 sixteen files potentially usable for reading appear in the following
9983 global variables. The value of |read_open[n]| will be |closed| if
9984 stream number |n| has not been opened or if it has been fully read;
9985 |just_open| if an \.{\\openin} but not a \.{\\read} has been done;
9986 and |normal| if it is open and ready to read the next line.
9987
9988 @d closed 2 /*not open, or at end of file*/
9989 @d just_open 1 /*newly opened, first line not yet read*/
9990
9991 @<Glob...@>=
9992 static alpha_file @!read_file[16]; /*used for \.{\\read}*/
9993 static int8_t @!read_open[17]; /*state of |read_file[n]|*/
9994
9995 @ @<Set init...@>=
9996 for (k=0; k<=16; k++) read_open[k]=closed;
9997
9998 @ The |read_toks| procedure constructs a token list like that for any
9999 macro definition, and makes |cur_val| point to it. Parameter |r| points
10000 to the control sequence that will receive this token list.
10001
10002 @p static void read_toks(int @!n, pointer @!r, halfword @!j)
10003 {@+
10004 pointer p; /*tail of the token list*/
10005 pointer @!q; /*new node being added to the token list via |store_new_token|*/
10006 int @!s; /*saved value of |align_state|*/
10007 small_number @!m; /*stream number*/
10008 scanner_status=defining;warning_index=r;
10009 def_ref=get_avail();token_ref_count(def_ref)=null;
10010 p=def_ref; /*the reference count*/
10011 store_new_token(end_match_token);
10012 if ((n < 0)||(n > 15)) m=16;@+else m=n;
10013 s=align_state;align_state=1000000; /*disable tab marks, etc.*/
10014 @/do@+{@<Input and store tokens from the next line of the file@>;
10015 }@+ while (!(align_state==1000000));
10016 cur_val=def_ref;scanner_status=normal;align_state=s;
10017 }
10018
10019 @ @<Input and store tokens from the next line of the file@>=
10020 begin_file_reading();name=m+1;
10021 if (read_open[m]==closed) @<Input for \.{\\read} from the terminal@>;
10022 else if (read_open[m]==just_open) @<Input the first line of |read_file[m]|@>@;
10023 else@<Input the next line of |read_file[m]|@>;
10024 limit=last;
10025 if (end_line_char_inactive) decr(limit);
10026 else buffer[limit]=end_line_char;
10027 first=limit+1;loc=start;state=new_line;@/
10028 @<Handle \.{\\readline} and |goto done|@>;@/
10029 loop@+{@+get_token();
10030 if (cur_tok==0) goto done;
10031 /*|cur_cmd==cur_chr==0| will occur at the end of the line*/
10032 if (align_state < 1000000) /*unmatched `\.\}' aborts the line*/
10033 {@+@/do@+{get_token();}@+ while (!(cur_tok==0));
10034 align_state=1000000;goto done;
10035 }
10036 store_new_token(cur_tok);
10037 }
10038 done: end_file_reading()
10039
10040 @ Here we input on-line into the |buffer| array, prompting the user explicitly
10041 if |n >= 0|. The value of |n| is set negative so that additional prompts
10042 will not be given in the case of multi-line input.
10043
10044 @<Input for \.{\\read} from the terminal@>=
10045 if (interaction > nonstop_mode)
10046 if (n < 0) prompt_input("")@;
10047 else{@+wake_up_terminal;
10048 print_ln();sprint_cs(r);prompt_input("=");n=-1;
10049 }
10050 else fatal_error("*** (cannot \\read from terminal in nonstop modes)")
10051 @.cannot \\read@>
10052
10053 @ The first line of a file must be treated specially, since |input_ln|
10054 must be told not to start with |get|.
10055 @^system dependencies@>
10056
10057 @<Input the first line of |read_file[m]|@>=
10058 if (input_ln(&read_file[m], false)) read_open[m]=normal;
10059 else{@+a_close(&read_file[m]);read_open[m]=closed;
10060 }
10061
10062 @ An empty line is appended at the end of a |read_file|.
10063 @^empty line at end of file@>
10064
10065 @<Input the next line of |read_file[m]|@>=
10066 {@+if (!input_ln(&read_file[m], true))
10067 {@+a_close(&read_file[m]);read_open[m]=closed;
10068 if (align_state!=1000000)
10069 {@+runaway();
10070 print_err("File ended within ");print_esc("read");
10071 @.File ended within \\read@>
10072 help1("This \\read has unbalanced braces.");
10073 align_state=1000000;limit=0;error();
10074 }
10075 }
10076 }
10077
10078 @* Conditional processing.
10079 We consider now the way \TeX\ handles various kinds of \.{\\if} commands.
10080
10081 @d unless_code 32 /*amount added for `\.{\\unless}' prefix*/
10082 @#
10083 @d if_char_code 0 /* `\.{\\if}' */
10084 @d if_cat_code 1 /* `\.{\\ifcat}' */
10085 @d if_int_code 2 /* `\.{\\ifnum}' */
10086 @d if_dim_code 3 /* `\.{\\ifdim}' */
10087 @d if_odd_code 4 /* `\.{\\ifodd}' */
10088 @d if_vmode_code 5 /* `\.{\\ifvmode}' */
10089 @d if_hmode_code 6 /* `\.{\\ifhmode}' */
10090 @d if_mmode_code 7 /* `\.{\\ifmmode}' */
10091 @d if_inner_code 8 /* `\.{\\ifinner}' */
10092 @d if_void_code 9 /* `\.{\\ifvoid}' */
10093 @d if_hbox_code 10 /* `\.{\\ifhbox}' */
10094 @d if_vbox_code 11 /* `\.{\\ifvbox}' */
10095 @d ifx_code 12 /* `\.{\\ifx}' */
10096 @d if_eof_code 13 /* `\.{\\ifeof}' */
10097 @d if_true_code 14 /* `\.{\\iftrue}' */
10098 @d if_false_code 15 /* `\.{\\iffalse}' */
10099 @d if_case_code 16 /* `\.{\\ifcase}' */
10100
10101 @<Put each...@>=
10102 primitive("if", if_test, if_char_code);
10103 @!@:if\_char\_}{\.{\\if} primitive@>
10104 primitive("ifcat", if_test, if_cat_code);
10105 @!@:if\_cat\_code\_}{\.{\\ifcat} primitive@>
10106 primitive("ifnum", if_test, if_int_code);
10107 @!@:if\_int\_}{\.{\\ifnum} primitive@>
10108 primitive("ifdim", if_test, if_dim_code);
10109 @!@:if\_dim\_}{\.{\\ifdim} primitive@>
10110 primitive("ifodd", if_test, if_odd_code);
10111 @!@:if\_odd\_}{\.{\\ifodd} primitive@>
10112 primitive("ifvmode", if_test, if_vmode_code);
10113 @!@:if\_vmode\_}{\.{\\ifvmode} primitive@>
10114 primitive("ifhmode", if_test, if_hmode_code);
10115 @!@:if\_hmode\_}{\.{\\ifhmode} primitive@>
10116 primitive("ifmmode", if_test, if_mmode_code);
10117 @!@:if\_mmode\_}{\.{\\ifmmode} primitive@>
10118 primitive("ifinner", if_test, if_inner_code);
10119 @!@:if\_inner\_}{\.{\\ifinner} primitive@>
10120 primitive("ifvoid", if_test, if_void_code);
10121 @!@:if\_void\_}{\.{\\ifvoid} primitive@>
10122 primitive("ifhbox", if_test, if_hbox_code);
10123 @!@:if\_hbox\_}{\.{\\ifhbox} primitive@>
10124 primitive("ifvbox", if_test, if_vbox_code);
10125 @!@:if\_vbox\_}{\.{\\ifvbox} primitive@>
10126 primitive("ifx", if_test, ifx_code);
10127 @!@:ifx\_}{\.{\\ifx} primitive@>
10128 primitive("ifeof", if_test, if_eof_code);
10129 @!@:if\_eof\_}{\.{\\ifeof} primitive@>
10130 primitive("iftrue", if_test, if_true_code);
10131 @!@:if\_true\_}{\.{\\iftrue} primitive@>
10132 primitive("iffalse", if_test, if_false_code);
10133 @!@:if\_false\_}{\.{\\iffalse} primitive@>
10134 primitive("ifcase", if_test, if_case_code);
10135 @!@:if\_case\_}{\.{\\ifcase} primitive@>
10136
10137 @ @<Cases of |print_cmd_chr|...@>=
10138 case if_test: {@+if (chr_code >= unless_code) print_esc("unless");
10139 switch (chr_code%unless_code) {
10140 case if_cat_code: print_esc("ifcat");@+break;
10141 case if_int_code: print_esc("ifnum");@+break;
10142 case if_dim_code: print_esc("ifdim");@+break;
10143 case if_odd_code: print_esc("ifodd");@+break;
10144 case if_vmode_code: print_esc("ifvmode");@+break;
10145 case if_hmode_code: print_esc("ifhmode");@+break;
10146 case if_mmode_code: print_esc("ifmmode");@+break;
10147 case if_inner_code: print_esc("ifinner");@+break;
10148 case if_void_code: print_esc("ifvoid");@+break;
10149 case if_hbox_code: print_esc("ifhbox");@+break;
10150 case if_vbox_code: print_esc("ifvbox");@+break;
10151 case ifx_code: print_esc("ifx");@+break;
10152 case if_eof_code: print_esc("ifeof");@+break;
10153 case if_true_code: print_esc("iftrue");@+break;
10154 case if_false_code: print_esc("iffalse");@+break;
10155 case if_case_code: print_esc("ifcase");@+break;
10156 @/@<Cases of |if_test| for |print_cmd_chr|@>@/
10157 default:print_esc("if");
10158 }
10159 } @+break;
10160
10161 @ Conditions can be inside conditions, and this nesting has a stack
10162 that is independent of the |save_stack|.
10163
10164 Four global variables represent the top of the condition stack:
10165 |cond_ptr| points to pushed-down entries, if any; |if_limit| specifies
10166 the largest code of a |fi_or_else| command that is syntactically legal;
10167 |cur_if| is the name of the current type of conditional; and |if_line|
10168 is the line number at which it began.
10169
10170 If no conditions are currently in progress, the condition stack has the
10171 special state |cond_ptr==null|, |if_limit==normal|, |cur_if==0|, |if_line==0|.
10172 Otherwise |cond_ptr| points to a two-word node; the |type|, |subtype|, and
10173 |link| fields of the first word contain |if_limit|, |cur_if|, and
10174 |cond_ptr| at the next level, and the second word contains the
10175 corresponding |if_line|.
10176
10177 @d if_node_size 2 /*number of words in stack entry for conditionals*/
10178 @d if_line_field(A) mem[A+1].i
10179 @d if_code 1 /*code for \.{\\if...} being evaluated*/
10180 @d fi_code 2 /*code for \.{\\fi}*/
10181 @d else_code 3 /*code for \.{\\else}*/
10182 @d or_code 4 /*code for \.{\\or}*/
10183
10184 @<Glob...@>=
10185 static pointer @!cond_ptr; /*top of the condition stack*/
10186 static int @!if_limit; /*upper bound on |fi_or_else| codes*/
10187 static small_number @!cur_if; /*type of conditional being worked on*/
10188 static int @!if_line; /*line where that conditional began*/
10189
10190 @ @<Set init...@>=
10191 cond_ptr=null;if_limit=normal;cur_if=0;if_line=0;
10192
10193 @ @<Put each...@>=
10194 primitive("fi", fi_or_else, fi_code);
10195 @!@:fi\_}{\.{\\fi} primitive@>
10196 text(frozen_fi)=text(cur_val);eqtb[frozen_fi]=eqtb[cur_val];
10197 primitive("or", fi_or_else, or_code);
10198 @!@:or\_}{\.{\\or} primitive@>
10199 primitive("else", fi_or_else, else_code);
10200 @!@:else\_}{\.{\\else} primitive@>
10201
10202 @ @<Cases of |print_cmd_chr|...@>=
10203 case fi_or_else: if (chr_code==fi_code) print_esc("fi");
10204 else if (chr_code==or_code) print_esc("or");
10205 else print_esc("else");@+break;
10206
10207 @ When we skip conditional text, we keep track of the line number
10208 where skipping began, for use in error messages.
10209
10210 @<Glob...@>=
10211 static int @!skip_line; /*skipping began here*/
10212
10213 @ Here is a procedure that ignores text until coming to an \.{\\or},
10214 \.{\\else}, or \.{\\fi} at the current level of $\.{\\if}\ldots\.{\\fi}$
10215 nesting. After it has acted, |cur_chr| will indicate the token that
10216 was found, but |cur_tok| will not be set (because this makes the
10217 procedure run faster).
10218
10219 @p static void pass_text(void)
10220 {@+
10221 int l; /*level of $\.{\\if}\ldots\.{\\fi}$ nesting*/
10222 small_number @!save_scanner_status; /*|scanner_status| upon entry*/
10223 save_scanner_status=scanner_status;scanner_status=skipping;l=0;
10224 skip_line=line;
10225 loop@+{@+get_next();
10226 if (cur_cmd==fi_or_else)
10227 {@+if (l==0) goto done;
10228 if (cur_chr==fi_code) decr(l);
10229 }
10230 else if (cur_cmd==if_test) incr(l);
10231 }
10232 done: scanner_status=save_scanner_status;
10233 if (tracing_ifs > 0) show_cur_cmd_chr();
10234 }
10235
10236 @ When we begin to process a new \.{\\if}, we set |if_limit=if_code|; then
10237 if\/ \.{\\or} or \.{\\else} or \.{\\fi} occurs before the current \.{\\if}
10238 condition has been evaluated, \.{\\relax} will be inserted.
10239 For example, a sequence of commands like `\.{\\ifvoid1\\else...\\fi}'
10240 would otherwise require something after the `\.1'.
10241
10242 @<Push the condition stack@>=
10243 {@+p=get_node(if_node_size);link(p)=cond_ptr;type(p)=if_limit;
10244 subtype(p)=cur_if;if_line_field(p)=if_line;
10245 cond_ptr=p;cur_if=cur_chr;if_limit=if_code;if_line=line;
10246 }
10247
10248 @ @<Pop the condition stack@>=
10249 {@+if (if_stack[in_open]==cond_ptr) if_warning();
10250 /*conditionals possibly not properly nested with files*/
10251 p=cond_ptr;if_line=if_line_field(p);
10252 cur_if=subtype(p);if_limit=type(p);cond_ptr=link(p);
10253 free_node(p, if_node_size);
10254 }
10255
10256 @ Here's a procedure that changes the |if_limit| code corresponding to
10257 a given value of |cond_ptr|.
10258
10259 @p static void change_if_limit(small_number @!l, pointer @!p)
10260 {@+
10261 pointer q;
10262 if (p==cond_ptr) if_limit=l; /*that's the easy case*/
10263 else{@+q=cond_ptr;
10264 loop@+{@+if (q==null) confusion("if");
10265 @:this can't happen if}{\quad if@>
10266 if (link(q)==p)
10267 {@+type(q)=l;return;
10268 }
10269 q=link(q);
10270 }
10271 }
10272 }
10273
10274 @ A condition is started when the |expand| procedure encounters
10275 an |if_test| command; in that case |expand| reduces to |conditional|,
10276 which is a recursive procedure.
10277 @^recursion@>
10278
10279 @p static void conditional(void)
10280 {@+
10281 bool b; /*is the condition true?*/
10282 int @!r; /*relation to be evaluated*/
10283 int @!m, @!n; /*to be tested against the second operand*/
10284 pointer @!p, @!q; /*for traversing token lists in \.{\\ifx} tests*/
10285 small_number @!save_scanner_status; /*|scanner_status| upon entry*/
10286 pointer @!save_cond_ptr; /*|cond_ptr| corresponding to this conditional*/
10287 small_number @!this_if; /*type of this conditional*/
10288 bool @!is_unless; /*was this if preceded by `\.{\\unless}' ?*/
10289 if (tracing_ifs > 0) if (tracing_commands <= 1) show_cur_cmd_chr();
10290 @<Push the condition stack@>;@+save_cond_ptr=cond_ptr;
10291 is_unless=(cur_chr >= unless_code);this_if=cur_chr%unless_code;@/
10292 @<Either process \.{\\ifcase} or set |b| to the value of a boolean condition@>;
10293 if (is_unless) b=!b;
10294 if (tracing_commands > 1) @<Display the value of |b|@>;
10295 if (b)
10296 {@+change_if_limit(else_code, save_cond_ptr);
10297 return; /*wait for \.{\\else} or \.{\\fi}*/
10298 }
10299 @<Skip to \.{\\else} or \.{\\fi}, then |goto common_ending|@>;
10300 common_ending: if (cur_chr==fi_code) @<Pop the condition stack@>@;
10301 else if_limit=fi_code; /*wait for \.{\\fi}*/
10302 }
10303
10304 @ In a construction like `\.{\\if\\iftrue abc\\else d\\fi}', the first
10305 \.{\\else} that we come to after learning that the \.{\\if} is false is
10306 not the \.{\\else} we're looking for. Hence the following curious
10307 logic is needed.
10308
10309 @ @<Skip to \.{\\else} or \.{\\fi}...@>=
10310 loop@+{@+pass_text();
10311 if (cond_ptr==save_cond_ptr)
10312 {@+if (cur_chr!=or_code) goto common_ending;
10313 print_err("Extra ");print_esc("or");
10314 @.Extra \\or@>
10315 help1("I'm ignoring this; it doesn't match any \\if.");
10316 error();
10317 }
10318 else if (cur_chr==fi_code) @<Pop the condition stack@>;
10319 }
10320
10321 @ @<Either process \.{\\ifcase} or set |b|...@>=
10322 switch (this_if) {
10323 case if_char_code: case if_cat_code: @<Test if two characters match@>@;@+break;
10324 case if_int_code: case if_dim_code: @<Test relation between integers or dimensions@>@;@+break;
10325 case if_odd_code: @<Test if an integer is odd@>@;@+break;
10326 case if_vmode_code: b=(abs(mode)==vmode);@+break;
10327 case if_hmode_code: b=(abs(mode)==hmode);@+break;
10328 case if_mmode_code: b=(abs(mode)==mmode);@+break;
10329 case if_inner_code: b=(mode < 0);@+break;
10330 case if_void_code: case if_hbox_code:
10331 case if_vbox_code: @<Test box register status@>@;@+break;
10332 case ifx_code: @<Test if two tokens match@>@;@+break;
10333 case if_eof_code: {@+scan_four_bit_int();b=(read_open[cur_val]==closed);
10334 } @+break;
10335 case if_true_code: b=true;@+break;
10336 case if_false_code: b=false;@+break;
10337 @/@<Cases for |conditional|@>@/
10338 case if_case_code: @<Select the appropriate case and |return| or |goto common_ending|@>;
10339 } /*there are no other cases*/
10340
10341 @ @<Display the value of |b|@>=
10342 {@+begin_diagnostic();
10343 if (b) print("{true}");@+else print("{false}");
10344 end_diagnostic(false);
10345 }
10346
10347 @ Here we use the fact that |'<'|, |'='|, and |'>'| are consecutive ASCII
10348 codes.
10349 @^ASCII code@>
10350
10351 @<Test relation between integers or dimensions@>=
10352 {@+if (this_if==if_int_code) scan_int();@+else scan_normal_dimen;
10353 n=cur_val;@<Get the next non-blank non-call...@>;
10354 if ((cur_tok >= other_token+'<')&&(cur_tok <= other_token+'>'))
10355 r=cur_tok-other_token;
10356 else{@+print_err("Missing = inserted for ");
10357 @.Missing = inserted@>
10358 print_cmd_chr(if_test, this_if);
10359 help1("I was expecting to see `<', `=', or `>'. Didn't.");
10360 back_error();r='=';
10361 }
10362 if (this_if==if_int_code) scan_int();@+else scan_normal_dimen;
10363 switch (r) {
10364 case '<': b=(n < cur_val);@+break;
10365 case '=': b=(n==cur_val);@+break;
10366 case '>': b=(n > cur_val);
10367 }
10368 }
10369
10370 @ @<Test if an integer is odd@>=
10371 {@+scan_int();b=odd(cur_val);
10372 }
10373
10374 @ @<Test box register status@>=
10375 {@+scan_register_num();fetch_box(p);
10376 if (this_if==if_void_code) b=(p==null);
10377 else if (p==null) b=false;
10378 else if (this_if==if_hbox_code) b=(type(p)==hlist_node);
10379 else b=(type(p)==vlist_node);
10380 }
10381
10382 @ An active character will be treated as category 13 following
10383 \.{\\if\\noexpand} or following \.{\\ifcat\\noexpand}. We use the fact that
10384 active characters have the smallest tokens, among all control sequences.
10385
10386 @d get_x_token_or_active_char @t@>@;
10387 {@+get_x_token();
10388 if (cur_cmd==relax) if (cur_chr==no_expand_flag)
10389 {@+cur_cmd=active_char;
10390 cur_chr=cur_tok-cs_token_flag-active_base;
10391 }
10392 }
10393
10394 @<Test if two characters match@>=
10395 {@+get_x_token_or_active_char;
10396 if ((cur_cmd > active_char)||(cur_chr > 255)) /*not a character*/
10397 {@+m=relax;n=256;
10398 }
10399 else{@+m=cur_cmd;n=cur_chr;
10400 }
10401 get_x_token_or_active_char;
10402 if ((cur_cmd > active_char)||(cur_chr > 255))
10403 {@+cur_cmd=relax;cur_chr=256;
10404 }
10405 if (this_if==if_char_code) b=(n==cur_chr);@+else b=(m==cur_cmd);
10406 }
10407
10408 @ Note that `\.{\\ifx}' will declare two macros different if one is \\{long}
10409 or \\{outer} and the other isn't, even though the texts of the macros are
10410 the same.
10411
10412 We need to reset |scanner_status|, since \.{\\outer} control sequences
10413 are allowed, but we might be scanning a macro definition or preamble.
10414
10415 @<Test if two tokens match@>=
10416 {@+save_scanner_status=scanner_status;scanner_status=normal;
10417 get_next();n=cur_cs;p=cur_cmd;q=cur_chr;
10418 get_next();if (cur_cmd!=p) b=false;
10419 else if (cur_cmd < call) b=(cur_chr==q);
10420 else@<Test if two macro texts match@>;
10421 scanner_status=save_scanner_status;
10422 }
10423
10424 @ Note also that `\.{\\ifx}' decides that macros \.{\\a} and \.{\\b} are
10425 different in examples like this:
10426 $$\vbox{\halign{\.{#}\hfil&\qquad\.{#}\hfil\cr
10427 {}\\def\\a\{\\c\}&
10428 {}\\def\\c\{\}\cr
10429 {}\\def\\b\{\\d\}&
10430 {}\\def\\d\{\}\cr}}$$
10431
10432 @<Test if two macro texts match@>=
10433 {@+p=link(cur_chr);q=link(equiv(n)); /*omit reference counts*/
10434 if (p==q) b=true;
10435 else{@+while ((p!=null)&&(q!=null))
10436 if (info(p)!=info(q)) p=null;
10437 else{@+p=link(p);q=link(q);
10438 }
10439 b=((p==null)&&(q==null));
10440 }
10441 }
10442
10443 @ @<Select the appropriate case and |return| or |goto common_ending|@>=
10444 {@+scan_int();n=cur_val; /*|n| is the number of cases to pass*/
10445 if (tracing_commands > 1)
10446 {@+begin_diagnostic();print("{case ");print_int(n);print_char('}');
10447 end_diagnostic(false);
10448 }
10449 while (n!=0)
10450 {@+pass_text();
10451 if (cond_ptr==save_cond_ptr)
10452 if (cur_chr==or_code) decr(n);
10453 else goto common_ending;
10454 else if (cur_chr==fi_code) @<Pop the condition stack@>;
10455 }
10456 change_if_limit(or_code, save_cond_ptr);
10457 return; /*wait for \.{\\or}, \.{\\else}, or \.{\\fi}*/
10458 }
10459
10460 @ The processing of conditionals is complete except for the following
10461 code, which is actually part of |expand|. It comes into play when
10462 \.{\\or}, \.{\\else}, or \.{\\fi} is scanned.
10463
10464 @<Terminate the current conditional and skip to \.{\\fi}@>=
10465 {@+if (tracing_ifs > 0) if (tracing_commands <= 1) show_cur_cmd_chr();
10466 if (cur_chr > if_limit)
10467 if (if_limit==if_code) insert_relax(); /*condition not yet evaluated*/
10468 else{@+print_err("Extra ");print_cmd_chr(fi_or_else, cur_chr);
10469 @.Extra \\or@>
10470 @.Extra \\else@>
10471 @.Extra \\fi@>
10472 help1("I'm ignoring this; it doesn't match any \\if.");
10473 error();
10474 }
10475 else{@+while (cur_chr!=fi_code) pass_text(); /*skip to \.{\\fi}*/
10476 @<Pop the condition stack@>;
10477 }
10478 }
10479
10480 @* File names.
10481 It's time now to fret about file names. Besides the fact that different
10482 operating systems treat files in different ways, we must cope with the
10483 fact that completely different naming conventions are used by different
10484 groups of people. The following programs show what is required for one
10485 particular operating system; similar routines for other systems are not
10486 difficult to devise.
10487 @^fingers@>
10488 @^system dependencies@>
10489
10490 \TeX\ assumes that a file name has three parts: the name proper; its
10491 ``extension''; and a ``file area'' where it is found in an external file
10492 system. The extension of an input file or a write file is assumed to be
10493 `\.{.tex}' unless otherwise specified; it is `\.{.log}' on the
10494 transcript file that records each run of \TeX; it is `\.{.tfm}' on the font
10495 metric files that describe characters in the fonts \TeX\ uses; it is
10496 `\.{.dvi}' on the output files that specify typesetting information; and it
10497 is `\.{.fmt}' on the format files written by \.{INITEX} to initialize \TeX.
10498 The file area can be arbitrary on input files, but files are usually
10499 output to the user's current area. If an input file cannot be
10500 found on the specified area, \TeX\ will look for it on a special system
10501 area; this special area is intended for commonly used input files like
10502 \.{webmac.tex}.
10503
10504 Simple uses of \TeX\ refer only to file names that have no explicit
10505 extension or area. For example, a person usually says `\.{\\input} \.{paper}'
10506 or `\.{\\font\\tenrm} \.= \.{helvetica}' instead of `\.{\\input}
10507 \.{paper.new}' or `\.{\\font\\tenrm} \.= \.{<csd.knuth>test}'. Simple file
10508 names are best, because they make the \TeX\ source files portable;
10509 whenever a file name consists entirely of letters and digits, it should be
10510 treated in the same way by all implementations of \TeX. However, users
10511 need the ability to refer to other files in their environment, especially
10512 when responding to error messages concerning unopenable files; therefore
10513 we want to let them use the syntax that appears in their favorite
10514 operating system.
10515
10516 The following procedures don't allow spaces to be part of
10517 file names; but some users seem to like names that are spaced-out.
10518 System-dependent changes to allow such things should probably
10519 be made with reluctance, and only when an entire file name that
10520 includes spaces is ``quoted'' somehow.
10521
10522 @ In order to isolate the system-dependent aspects of file names, the
10523 @^system dependencies@>
10524 system-independent parts of \TeX\ are expressed in terms
10525 of three system-dependent
10526 procedures called |begin_name|, |more_name|, and |end_name|. In
10527 essence, if the user-specified characters of the file name are $c_1\ldots c_n$,
10528 the system-independent driver program does the operations
10529 $$|begin_name|;\,|more_name|(c_1);\,\ldots\,;\,|more_name|(c_n);
10530 \,|end_name|.$$
10531 These three procedures communicate with each other via global variables.
10532 Afterwards the file name will appear in the string pool as three strings
10533 called |cur_name|\penalty10000\hskip-.05em,
10534 |cur_area|, and |cur_ext|; the latter two are null (i.e.,
10535 |""|), unless they were explicitly specified by the user.
10536
10537 Actually the situation is slightly more complicated, because \TeX\ needs
10538 to know when the file name ends. The |more_name| routine is a function
10539 (with side effects) that returns |true| on the calls |more_name|$(c_1)$,
10540 \dots, |more_name|$(c_{n-1})$. The final call |more_name|$(c_n)$
10541 returns |false|; or, it returns |true| and the token following $c_n$ is
10542 something like `\.{\\hbox}' (i.e., not a character). In other words,
10543 |more_name| is supposed to return |true| unless it is sure that the
10544 file name has been completely scanned; and |end_name| is supposed to be able
10545 to finish the assembly of |cur_name|, |cur_area|, and |cur_ext| regardless of
10546 whether $|more_name|(c_n)$ returned |true| or |false|.
10547
10548 @<Glob...@>=
10549 static str_number @!cur_name; /*name of file just scanned*/
10550 static str_number @!cur_area; /*file area just scanned, or \.{""}*/
10551 static str_number @!cur_ext; /*file extension just scanned, or \.{""}*/
10552
10553 @ The file names we shall deal with for illustrative purposes have the
10554 following structure: If the name contains `\.>' or `\.:', the file area
10555 consists of all characters up to and including the final such character;
10556 otherwise the file area is null. If the remaining file name contains
10557 `\..', the file extension consists of all such characters from the first
10558 remaining `\..' to the end, otherwise the file extension is null.
10559 @^system dependencies@>
10560
10561 We can scan such file names easily by using two global variables that keep track
10562 of the occurrences of area and extension delimiters:
10563
10564 @<Glob...@>=
10565 static pool_pointer @!area_delimiter; /*the most recent `\.>' or `\.:', if any*/
10566 static pool_pointer @!ext_delimiter; /*the relevant `\..', if any*/
10567
10568 @ Input files that can't be found in the user's area may appear in a standard
10569 system area called |TEX_area|. Font metric files whose areas are not given
10570 explicitly are assumed to appear in a standard system area called
10571 |TEX_font_area|. These system area names will, of course, vary from place
10572 to place.
10573 @^system dependencies@>
10574
10575 @d TEX_area "TeXinputs/"
10576 @.TeXinputs@>
10577 @d TEX_font_area "TeXfonts/"
10578 @.TeXfonts@>
10579
10580 @ Here now is the first of the system-dependent routines for file name scanning.
10581 @^system dependencies@>
10582
10583 @p static bool quoted_filename;
10584 static void begin_name(void)
10585 {@+area_delimiter=0;ext_delimiter=0; quoted_filename=false;
10586 }
10587
10588 @ And here's the second. The string pool might change as the file name is
10589 being scanned, since a new \.{\\csname} might be entered; therefore we keep
10590 |area_delimiter| and |ext_delimiter| relative to the beginning of the current
10591 string, instead of assigning an absolute address like |pool_ptr| to them.
10592 @^system dependencies@>
10593
10594 @p static bool more_name(ASCII_code @!c)
10595 {@+if (c==' ' && !quoted_filename) return false;
10596 else if (c=='"') {@+quoted_filename=!quoted_filename; return true; }
10597 else {@+str_room(1);append_char(c); /*contribute |c| to the current string*/
10598 if (IS_DIR_SEP(c)) {@+area_delimiter=cur_length;ext_delimiter=0; }
10599 else if (c=='.') ext_delimiter=cur_length;
10600 return true;
10601 }
10602 }
10603
10604 @ The third.
10605 @^system dependencies@>
10606
10607 @p static void end_name(void)
10608 {@+if (str_ptr+3 > max_strings)
10609 overflow("number of strings", max_strings-init_str_ptr);
10610 @:TeX capacity exceeded number of strings}{\quad number of strings@>
10611 if (area_delimiter==0) cur_area=empty_string;
10612 else{@+cur_area=str_ptr;
10613 str_start[str_ptr+1]=str_start[str_ptr]+area_delimiter;incr(str_ptr);
10614 }
10615 if (ext_delimiter==0)
10616 {@+cur_ext=empty_string;cur_name=make_string();
10617 }
10618 else{@+cur_name=str_ptr;
10619 str_start[str_ptr+1]=str_start[str_ptr]+ext_delimiter-area_delimiter-1;
10620 incr(str_ptr);cur_ext=make_string();
10621 }
10622 }
10623
10624 @ Conversely, here is a routine that takes three strings and prints a file
10625 name that might have produced them. (The routine is system dependent, because
10626 some operating systems put the file area last instead of first.)
10627 @^system dependencies@>
10628
10629 @<Basic printing...@>=
10630 static void print_file_name(int @!n, int @!a, int @!e)
10631 {@+slow_print(a);slow_print(n);slow_print(e);
10632 }
10633
10634 @ Another system-dependent routine is needed to convert three internal
10635 \TeX\ strings
10636 into the |name_of_file| value that is used to open files. The present code
10637 allows both lowercase and uppercase letters in the file name.
10638 @^system dependencies@>
10639
10640 @d append_to_name(A) {@+c=A;incr(k);
10641 if (k <= file_name_size) name_of_file[k]=xchr[c];
10642 }
10643
10644 @p static void pack_file_name(str_number @!n, str_number @!a, str_number @!e, char *@!f)
10645 {@+int k; /*number of positions filled in |name_of_file|*/
10646 ASCII_code @!c; /*character being packed*/
10647 int @!j; /*index into |str_pool|*/
10648 k=0;
10649 for (j=str_start[a]; j<=str_start[a+1]-1; j++) append_to_name(so(str_pool[j]))@;
10650 for (j=str_start[n]; j<=str_start[n+1]-1; j++) append_to_name(so(str_pool[j]))@;
10651 if (f==NULL)
10652 for (j=str_start[e]; j<=str_start[e+1]-1; j++) append_to_name(so(str_pool[j]))@;
10653 else
10654 while(*f!=0) append_to_name(so(*f++))@;
10655 if (k <= file_name_size) name_length=k;@+else name_length=file_name_size;
10656 name_of_file[name_length+1]=0;
10657 }
10658
10659
10660
10661 @ \TeX\ Live does not use the global variable |TEX_format_default|. It is no longer needed
10662 to supply the text for default system areas
10663 and extensions related to format files.
10664
10665 @ Consequently \TeX\ Live does not need the initialization of |TEX_format_default| either.
10666
10667 @ And \TeX\ Live does not check the length of |TEX_format_default|.
10668
10669 @ The |format_extension|, however, is needed by \TeX\ Live
10670 to create the format name from the job name.
10671
10672 @d format_extension ".fmt"
10673
10674 @ This part of the program
10675 becomes active when a ``virgin'' \TeX\ is trying to get going, just after
10676 the preliminary initialization, or when the user is substituting another
10677 format file by typing `\.\&' after the initial `\.{**}' prompt. The buffer
10678 contains the first line of input in |buffer[loc dotdot(last-1)]|, where
10679 |loc < last| and |buffer[loc]!=' '|.
10680
10681 \TeX\ Live uses the {\tt kpathsearch} library to implement access to files.
10682 |open_fmt_file| is declared here and the
10683 actual implementation is in the section on \TeX\ Live Integration.
10684
10685 @<Declare the function called |open_fmt_file|@>=
10686 static bool open_fmt_file(void);
10687
10688 @ Operating systems often make it possible to determine the exact name (and
10689 possible version number) of a file that has been opened. The following routine,
10690 which simply makes a \TeX\ string from the value of |name_of_file|, should
10691 ideally be changed to deduce the full name of file~|f|, which is the file
10692 most recently opened, if it is possible to do this in a \PASCAL\ program.
10693 @^system dependencies@>
10694
10695 This routine might be called after string memory has overflowed, hence
10696 we dare not use `|str_room|'.
10697
10698 @p static str_number make_name_string(void)
10699 {@+int k; /*index into |name_of_file|*/
10700 if ((pool_ptr+name_length > pool_size)||(str_ptr==max_strings)||
10701 (cur_length > 0))
10702 return'?';
10703 else{@+for (k=1; k<=name_length; k++) append_char(xord[name_of_file[k]]);
10704 return make_string();
10705 }
10706 }
10707 static str_number a_make_name_string(alpha_file *f)
10708 {@+return make_name_string();
10709 }
10710 static str_number b_make_name_string(byte_file *f)
10711 {@+return make_name_string();
10712 }
10713 #ifdef @!INIT
10714 static str_number w_make_name_string(word_file *f)
10715 {@+return make_name_string();
10716 }
10717 #endif
10718
10719 @ Now let's consider the ``driver''
10720 routines by which \TeX\ deals with file names
10721 in a system-independent manner. First comes a procedure that looks for a
10722 file name.
10723 There are two ways to specify the file name: as a general text argument
10724 or as a token (after expansion).
10725 The traditional token delimiter is the space. For a file name, however,
10726 a double quote is used as the token delimiter if the token starts
10727 with a double quote.
10728
10729 Once the |area_delimiter| and the |ext_delimiter| are defined,
10730 the final processing is shared for all variants.
10731
10732 When starting, \.{\\relax} is skipped as well as blanks and non-calls.
10733 Then a test for the |left_brace| will branch to the code for scanning
10734 a general text.
10735 % consider the case where a double quote is made an active character
10736 % equivalent to a left brace!
10737
10738 @p static void scan_file_name(void)
10739 {@+
10740 pool_pointer @!j, k; /*index into |str_pool|*/
10741 int @!old_setting; /*holds |selector| setting*/
10742 name_in_progress=true;begin_name();
10743 @<Get the next non-blank non-relax...@>;
10744 if (cur_cmd==left_brace)
10745 @<Define a general text file name and |goto done|@>@;
10746 loop@+{@+if ((cur_cmd > other_char)||(cur_chr > 255)) /*not a character*/
10747 {@+back_input();goto done;
10748 }
10749 #if 0
10750 /* This is from pdftex-final.ch. I don't know these `some cases',
10751 and I am not sure whether the name should end even if quoting is on.*/
10752 /*If |cur_chr| is a space and we're not scanning a token list, check
10753 whether we're at the end of the buffer. Otherwise we end up adding
10754 spurious spaces to file names in some cases.*/
10755 if (cur_chr==' ' && state!=token_list && loc>limit) goto done;
10756 #endif
10757 if (!more_name(cur_chr)) goto done;
10758 get_x_token();
10759 }
10760 done: end_name();name_in_progress=false;
10761 }
10762
10763 @ The global variable |name_in_progress| is used to prevent recursive
10764 use of |scan_file_name|, since the |begin_name| and other procedures
10765 communicate via global variables. Recursion would arise only by
10766 devious tricks like `\.{\\input\\input f}'; such attempts at sabotage
10767 must be thwarted. Furthermore, |name_in_progress| prevents \.{\\input}
10768 @^recursion@>
10769 from being initiated when a font size specification is being scanned.
10770
10771 Another global variable, |job_name|, contains the file name that was first
10772 \.{\\input} by the user. This name is extended by `\.{.log}' and `\.{.dvi}'
10773 and `\.{.fmt}' in the names of \TeX's output files.
10774
10775 @<Glob...@>=
10776 static bool @!name_in_progress; /*is a file name being scanned?*/
10777 static str_number @!job_name; /*principal file name*/
10778 static bool @!log_opened; /*has the transcript file been opened?*/
10779
10780 @ Initially |job_name==0|; it becomes nonzero as soon as the true name is known.
10781 We have |job_name==0| if and only if the `\.{log}' file has not been opened,
10782 except of course for a short time just after |job_name| has become nonzero.
10783
10784 @<Initialize the output...@>=
10785 job_name=0;name_in_progress=false;log_opened=false;
10786
10787 @ Here is a routine that manufactures the output file names, assuming that
10788 |job_name!=0|. It ignores and changes the current settings of |cur_area|
10789 and |cur_ext|.
10790
10791 @d pack_cur_name(A) if (cur_ext==empty_string) pack_file_name(cur_name, cur_area, cur_ext,A);
10792 else pack_file_name(cur_name, cur_area, cur_ext,NULL)
10793
10794 @p static void pack_job_name(char *@!s) /*|s==".log"|, |".dvi"|, or
10795 |format_extension|*/
10796 {@+cur_area=empty_string;cur_ext=empty_string;
10797 cur_name=job_name;pack_cur_name(s);
10798 }
10799
10800 @ If some trouble arises when \TeX\ tries to open a file, the following
10801 routine calls upon the user to supply another file name. Parameter~|s|
10802 is used in the error message to identify the type of file; parameter~|e|
10803 is the default extension if none is given.
10804 We handle the specification of a file name with possibly spaces in
10805 double quotes (the last one is optional if this is the end of line
10806 i.e. the end of the buffer).
10807 Upon exit from the routine,
10808 variables |cur_name|, |cur_area|, |cur_ext|, and |name_of_file| are
10809 ready for another attempt at file opening.
10810
10811 @p static void prompt_file_name(char *@!s, char *@!e)
10812 {@+
10813 int k; /*index into |buffer|*/
10814 if (interaction==scroll_mode) wake_up_terminal;
10815 if (strcmp(s,"input file name")==0) print_err("I can't find file `");
10816 @.I can't find file x@>
10817 else print_err("I can't write on file `");
10818 @.I can't write on file x@>
10819 print_file_name(cur_name, cur_area, cur_ext);print("'.");
10820 if (strcmp(e,".tex")==0) show_context();
10821 print_nl("Please type another ");print(s);
10822 @.Please type...@>
10823 if (interaction < scroll_mode)
10824 fatal_error("*** (job aborted, file error in nonstop mode)");
10825 @.job aborted, file error...@>
10826 clear_terminal;prompt_input(": ");@<Scan file name in the buffer@>;
10827 pack_cur_name(e);
10828 }
10829
10830 @ @<Scan file name in the buffer@>=
10831 {@+
10832 begin_name();k=first;
10833 while ((buffer[k]==' ')&&(k < last)) incr(k);
10834 loop@+{@+if (k==last) goto done;
10835 if (!more_name(buffer[k])) goto done;
10836 incr(k);
10837 }
10838 done: end_name();
10839 }
10840
10841 @ Here's an example of how these conventions are used. Whenever it is time to
10842 ship out a box of stuff, we shall use the macro |ensure_dvi_open|.
10843
10844 @d ensure_dvi_open if (output_file_name==0)
10845 {@+if (job_name==0) open_log_file();
10846 pack_job_name(".dvi");
10847 while (!b_open_out(&dvi_file))
10848 prompt_file_name("file name for output",".dvi");
10849 output_file_name=b_make_name_string(&dvi_file);
10850 }
10851
10852 @<Glob...@>=
10853 static byte_file @!dvi_file; /*the device-independent output goes here*/
10854 static str_number @!output_file_name; /*full name of the output file*/
10855 static str_number @!log_name; /*full name of the log file*/
10856
10857 @ @<Initialize the output...@>=output_file_name=0;
10858
10859 @ The |open_log_file| routine is used to open the transcript file and to help
10860 it catch up to what has previously been printed on the terminal.
10861
10862 @p static void open_log_file(void)
10863 {@+int old_setting; /*previous |selector| setting*/
10864 int @!k; /*index into |months| and |buffer|*/
10865 int @!l; /*end of first input line*/
10866 char @!months[]=" JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"; /*abbreviations of month names*/
10867 old_setting=selector;
10868 if (job_name==0) job_name=s_no(c_job_name?c_job_name:"texput"); /* \TeX\ Live */
10869 pack_job_name(".fls");
10870 recorder_change_filename((char *)name_of_file+1);
10871 @.texput@>
10872 pack_job_name(".log");
10873 while (!a_open_out(&log_file)) @<Try to get a different log file name@>;
10874 log_name=a_make_name_string(&log_file);
10875 selector=log_only;log_opened=true;
10876 @<Print the banner line, including the date and time@>;
10877 input_stack[input_ptr]=cur_input; /*make sure bottom level is in memory*/
10878 print_nl("**");
10879 @.**@>
10880 l=input_stack[0].limit_field; /*last position of first line*/
10881 if (buffer[l]==end_line_char) decr(l);
10882 for (k=1; k<=l; k++) printn(buffer[k]);
10883 print_ln(); /*now the transcript file contains the first line of input*/
10884 selector=old_setting+2; /*|log_only| or |term_and_log|*/
10885 }
10886
10887 @ Sometimes |open_log_file| is called at awkward moments when \TeX\ is
10888 unable to print error messages or even to |show_context|.
10889 The |prompt_file_name| routine can result in a |fatal_error|, but the |error|
10890 routine will not be invoked because |log_opened| will be false.
10891
10892 The normal idea of |batch_mode| is that nothing at all should be written
10893 on the terminal. However, in the unusual case that
10894 no log file could be opened, we make an exception and allow
10895 an explanatory message to be seen.
10896
10897 Incidentally, the program always refers to the log file as a `\.{transcript
10898 file}', because some systems cannot use the extension `\.{.log}' for
10899 this file.
10900
10901 @<Try to get a different log file name@>=
10902 {@+selector=term_only;
10903 prompt_file_name("transcript file name",".log");
10904 }
10905
10906 @ @<Print the banner...@>=
10907 {@+wlog("%s",banner);
10908 slow_print(format_ident);print(" ");
10909 print_int(sys_day);print_char(' ');
10910 for (k=3*sys_month-2; k<=3*sys_month; k++) wlog("%c",months[k]);
10911 print_char(' ');print_int(sys_year);print_char(' ');
10912 print_two(sys_time/60);print_char(':');print_two(sys_time%60);
10913 if (eTeX_ex)
10914 {@+;wlog_cr;wlog("entering extended mode");
10915 }
10916 if (Prote_ex)
10917 {@+;wlog_cr;wlog("entering Prote mode");
10918 }
10919 }
10920
10921 @ Let's turn now to the procedure that is used to initiate file reading
10922 when an `\.{\\input}' command is being processed.
10923 Beware: For historic reasons, this code foolishly conserves a tiny bit
10924 of string pool space; but that can confuse the interactive `\.E' option.
10925 @^system dependencies@>
10926
10927 @p static void start_input(void) /*\TeX\ will \.{\\input} something*/
10928 {@+
10929 scan_file_name(); /*set |cur_name| to desired file name*/
10930 pack_cur_name("");
10931 loop@+{@+begin_file_reading(); /*set up |cur_file| and new level of input*/
10932 if (kpse_in_name_ok((char*)name_of_file+1) && a_open_in(&cur_file)) goto done;
10933 end_file_reading(); /*remove the level that didn't work*/
10934 prompt_file_name("input file name",".tex");
10935 }
10936 done: name=a_make_name_string(&cur_file);@/
10937 if (source_filename_stack[in_open]!=NULL)
10938 free(source_filename_stack[in_open]);
10939 source_filename_stack[in_open]=strdup((char *)name_of_file+1); /*\TeX\ Live*/
10940 if (full_source_filename_stack[in_open]!=NULL)
10941 free(full_source_filename_stack[in_open]);
10942 full_source_filename_stack[in_open]=strdup(full_name_of_file);
10943 @<Set new |cur_file_num|@>@;
10944 /* new entry on the macro stack */
10945 { @<additional local variables for |start_input|@>
10946 @<update the macro stack@>@;
10947 }
10948 if (job_name==0)
10949 {@+if (c_job_name==NULL) job_name=cur_name;
10950 else job_name=s_no(c_job_name); open_log_file(); /* \TeX\ Live*/
10951 } /*|open_log_file| doesn't |show_context|, so |limit|
10952 and |loc| needn't be set to meaningful values yet*/
10953 if (term_offset+strlen(full_source_filename_stack[in_open]) > max_print_line-2)
10954 print_ln();
10955 else if ((term_offset > 0)||(file_offset > 0)) print_char(' ');
10956 print_char('(');incr(open_parens);
10957 print(full_source_filename_stack[in_open]);update_terminal;
10958 state=new_line;
10959 if (name==str_ptr-1) /*conserve string pool space (but see note above)*/
10960 {@+flush_string;name=cur_name;
10961 }
10962 @<Read the first line of the new file@>;
10963 }
10964
10965 @ Here we have to remember to tell the |input_ln| routine not to
10966 start with a |get|. If the file is empty, it is considered to
10967 contain a single blank line.
10968 @^system dependencies@>
10969 @^empty line at end of file@>
10970
10971 @<Read the first line...@>=
10972 {@+line=1;
10973 if (input_ln(&cur_file, false)) do_nothing;
10974 firm_up_the_line();
10975 if (end_line_char_inactive) decr(limit);
10976 else buffer[limit]=end_line_char;
10977 first=limit+1;loc=start;
10978 }
10979
10980 @* Font metric data.
10981 \TeX\ gets its knowledge about fonts from font metric files, also called
10982 \.{TFM} files; the `\.T' in `\.{TFM}' stands for \TeX,
10983 but other programs know about them too.
10984 @:TFM files}{\.{TFM} files@>
10985 @^font metric files@>
10986
10987 The information in a \.{TFM} file appears in a sequence of 8-bit bytes.
10988 Since the number of bytes is always a multiple of 4, we could
10989 also regard the file as a sequence of 32-bit words, but \TeX\ uses the
10990 byte interpretation. The format of \.{TFM} files was designed by
10991 Lyle Ramshaw in 1980. The intent is to convey a lot of different kinds
10992 @^Ramshaw, Lyle Harold@>
10993 of information in a compact but useful form.
10994
10995 @<Glob...@>=
10996 static byte_file @!tfm_file;
10997
10998 @ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit
10999 integers that give the lengths of the various subsequent portions
11000 of the file. These twelve integers are, in order:
11001 $$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr
11002 |lf|&length of the entire file, in words;\cr
11003 |lh|&length of the header data, in words;\cr
11004 |bc|&smallest character code in the font;\cr
11005 |ec|&largest character code in the font;\cr
11006 |nw|&number of words in the width table;\cr
11007 |nh|&number of words in the height table;\cr
11008 |nd|&number of words in the depth table;\cr
11009 |ni|&number of words in the italic correction table;\cr
11010 |nl|&number of words in the lig/kern table;\cr
11011 |nk|&number of words in the kern table;\cr
11012 |ne|&number of words in the extensible character table;\cr
11013 |np|&number of font parameter words.\cr}}$$
11014 They are all nonnegative and less than $2^{15}$. We must have |bc-1 <= ec <= 255|,
11015 and
11016 $$\hbox{|lf==6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$
11017 Note that a font may contain as many as 256 characters (if |bc==0| and |ec==255|),
11018 and as few as 0 characters (if |bc==ec+1|).
11019
11020 Incidentally, when two or more 8-bit bytes are combined to form an integer of
11021 16 or more bits, the most significant bytes appear first in the file.
11022 This is called BigEndian order.
11023 @!@^BigEndian order@>
11024
11025 @ The rest of the \.{TFM} file may be regarded as a sequence of ten data
11026 arrays having the informal specification
11027 $$\def\arr$[#1]#2${\&{array} $[#1]$ \&{of} #2}
11028 \def\PB#1{\arr#1}
11029 \vbox{\halign{\hfil\\{#}&$\,:\,$#\hfil\cr
11030 header&|[0 dotdot lh-1]@t\\{stuff}@>|\cr
11031 char\_info&|[bc dotdot ec]char_info_word|\cr
11032 width&|[0 dotdot nw-1]fix_word|\cr
11033 height&|[0 dotdot nh-1]fix_word|\cr
11034 depth&|[0 dotdot nd-1]fix_word|\cr
11035 italic&|[0 dotdot ni-1]fix_word|\cr
11036 lig\_kern&|[0 dotdot nl-1]lig_kern_command|\cr
11037 kern&|[0 dotdot nk-1]fix_word|\cr
11038 exten&|[0 dotdot ne-1]extensible_recipe|\cr
11039 param&|[1 dotdot np]fix_word|\cr}}$$
11040 The most important data type used here is a |@!fix_word|, which is
11041 a 32-bit representation of a binary fraction. A |fix_word| is a signed
11042 quantity, with the two's complement of the entire word used to represent
11043 negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the
11044 binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and
11045 the smallest is $-2048$. We will see below, however, that all but two of
11046 the |fix_word| values must lie between $-16$ and $+16$.
11047
11048 @ The first data array is a block of header information, which contains
11049 general facts about the font. The header must contain at least two words,
11050 |header[0]| and |header[1]|, whose meaning is explained below.
11051 Additional header information of use to other software routines might
11052 also be included, but \TeX82 does not need to know about such details.
11053 For example, 16 more words of header information are in use at the Xerox
11054 Palo Alto Research Center; the first ten specify the character coding
11055 scheme used (e.g., `\.{XEROX text}' or `\.{TeX math symbols}'), the next five
11056 give the font identifier (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the
11057 last gives the ``face byte.'' The program that converts \.{DVI} files
11058 to Xerox printing format gets this information by looking at the \.{TFM}
11059 file, which it needs to read anyway because of other information that
11060 is not explicitly repeated in \.{DVI}~format.
11061
11062 \yskip\hang|header[0]| is a 32-bit check sum that \TeX\ will copy into
11063 the \.{DVI} output file. Later on when the \.{DVI} file is printed,
11064 possibly on another computer, the actual font that gets used is supposed
11065 to have a check sum that agrees with the one in the \.{TFM} file used by
11066 \TeX. In this way, users will be warned about potential incompatibilities.
11067 (However, if the check sum is zero in either the font file or the \.{TFM}
11068 file, no check is made.) The actual relation between this check sum and
11069 the rest of the \.{TFM} file is not important; the check sum is simply an
11070 identification number with the property that incompatible fonts almost
11071 always have distinct check sums.
11072 @^check sum@>
11073
11074 \yskip\hang|header[1]| is a |fix_word| containing the design size of
11075 the font, in units of \TeX\ points. This number must be at least 1.0; it is
11076 fairly arbitrary, but usually the design size is 10.0 for a ``10 point''
11077 font, i.e., a font that was designed to look best at a 10-point size,
11078 whatever that really means. When a \TeX\ user asks for a font
11079 `\.{at} $\delta$ \.{pt}', the effect is to override the design size
11080 and replace it by $\delta$, and to multiply the $x$ and~$y$ coordinates
11081 of the points in the font image by a factor of $\delta$ divided by the
11082 design size. {\sl All other dimensions in the\/ \.{TFM} file are
11083 |fix_word|\kern-1pt\ numbers in design-size units}, with the exception of
11084 |param[1]| (which denotes the slant ratio). Thus, for example, the value
11085 of |param[6]|, which defines the \.{em} unit, is often the |fix_word| value
11086 $2^{20}=1.0$, since many fonts have a design size equal to one em.
11087 The other dimensions must be less than 16 design-size units in absolute
11088 value; thus, |header[1]| and |param[1]| are the only |fix_word|
11089 entries in the whole \.{TFM} file whose first byte might be something
11090 besides 0 or 255.
11091
11092 @ Next comes the |char_info| array, which contains one |@!char_info_word|
11093 per character. Each word in this part of the file contains six fields
11094 packed into four bytes as follows.
11095
11096 \yskip\hang first byte: |@!width_index| (8 bits)\par
11097 \hang second byte: |@!height_index| (4 bits) times 16, plus |@!depth_index|
11098 (4~bits)\par
11099 \hang third byte: |@!italic_index| (6 bits) times 4, plus |@!tag|
11100 (2~bits)\par
11101 \hang fourth byte: |@!rem| (8 bits)\par
11102 \yskip\noindent
11103 The actual width of a character is \\{width}|[width_index]|, in design-size
11104 units; this is a device for compressing information, since many characters
11105 have the same width. Since it is quite common for many characters
11106 to have the same height, depth, or italic correction, the \.{TFM} format
11107 imposes a limit of 16 different heights, 16 different depths, and
11108 64 different italic corrections.
11109
11110 @!@^italic correction@>
11111 The italic correction of a character has two different uses.
11112 (a)~In ordinary text, the italic correction is added to the width only if
11113 the \TeX\ user specifies `\.{\\/}' after the character.
11114 (b)~In math formulas, the italic correction is always added to the width,
11115 except with respect to the positioning of subscripts.
11116
11117 Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]=
11118 \\{italic}[0]=0$ should always hold, so that an index of zero implies a
11119 value of zero. The |width_index| should never be zero unless the
11120 character does not exist in the font, since a character is valid if and
11121 only if it lies between |bc| and |ec| and has a nonzero |width_index|.
11122
11123 @ The |tag| field in a |char_info_word| has four values that explain how to
11124 interpret the |rem| field.
11125
11126 \yskip\hangg|tag==0| (|no_tag|) means that |rem| is unused.\par
11127 \hangg|tag==1| (|lig_tag|) means that this character has a ligature/kerning
11128 program starting at position |rem| in the |lig_kern| array.\par
11129 \hangg|tag==2| (|list_tag|) means that this character is part of a chain of
11130 characters of ascending sizes, and not the largest in the chain. The
11131 |rem| field gives the character code of the next larger character.\par
11132 \hangg|tag==3| (|ext_tag|) means that this character code represents an
11133 extensible character, i.e., a character that is built up of smaller pieces
11134 so that it can be made arbitrarily large. The pieces are specified in
11135 |@!exten[rem]|.\par
11136 \yskip\noindent
11137 Characters with |tag==2| and |tag==3| are treated as characters with |tag==0|
11138 unless they are used in special circumstances in math formulas. For example,
11139 the \.{\\sum} operation looks for a |list_tag|, and the \.{\\left}
11140 operation looks for both |list_tag| and |ext_tag|.
11141
11142 @d no_tag 0 /*vanilla character*/
11143 @d lig_tag 1 /*character has a ligature/kerning program*/
11144 @d list_tag 2 /*character has a successor in a charlist*/
11145 @d ext_tag 3 /*character is extensible*/
11146
11147 @ The |lig_kern| array contains instructions in a simple programming language
11148 that explains what to do for special letter pairs. Each word in this array is a
11149 |@!lig_kern_command| of four bytes.
11150
11151 \yskip\hang first byte: |skip_byte|, indicates that this is the final program
11152 step if the byte is 128 or more, otherwise the next step is obtained by
11153 skipping this number of intervening steps.\par
11154 \hang second byte: |next_char|, ``if |next_char| follows the current character,
11155 then perform the operation and stop, otherwise continue.''\par
11156 \hang third byte: |op_byte|, indicates a ligature step if less than~128,
11157 a kern step otherwise.\par
11158 \hang fourth byte: |rem|.\par
11159 \yskip\noindent
11160 In a kern step, an
11161 additional space equal to |kern[256*(op_byte-128)+rem]| is inserted
11162 between the current character and |next_char|. This amount is
11163 often negative, so that the characters are brought closer together
11164 by kerning; but it might be positive.
11165
11166 There are eight kinds of ligature steps, having |op_byte| codes $4a+2b+c$ where
11167 $0\le a\le b+c$ and $0\le b,c\le1$. The character whose code is
11168 |rem| is inserted between the current character and |next_char|;
11169 then the current character is deleted if $b=0$, and |next_char| is
11170 deleted if $c=0$; then we pass over $a$~characters to reach the next
11171 current character (which may have a ligature/kerning program of its own).
11172
11173 If the very first instruction of the |lig_kern| array has |skip_byte==255|,
11174 the |next_char| byte is the so-called boundary character of this font;
11175 the value of |next_char| need not lie between |bc| and~|ec|.
11176 If the very last instruction of the |lig_kern| array has |skip_byte==255|,
11177 there is a special ligature/kerning program for a boundary character at the
11178 left, beginning at location |256*op_byte+rem|.
11179 The interpretation is that \TeX\ puts implicit boundary characters
11180 before and after each consecutive string of characters from the same font.
11181 These implicit characters do not appear in the output, but they can affect
11182 ligatures and kerning.
11183
11184 If the very first instruction of a character's |lig_kern| program has
11185 |skip_byte > 128|, the program actually begins in location
11186 |256*op_byte+rem|. This feature allows access to large |lig_kern|
11187 arrays, because the first instruction must otherwise
11188 appear in a location | <= 255|.
11189
11190 Any instruction with |skip_byte > 128| in the |lig_kern| array must satisfy
11191 the condition
11192 $$\hbox{|256*op_byte+rem < nl|.}$$
11193 If such an instruction is encountered during
11194 normal program execution, it denotes an unconditional halt; no ligature
11195 or kerning command is performed.
11196
11197 @d stop_flag qi(128) /*value indicating `\.{STOP}' in a lig/kern program*/
11198 @d kern_flag qi(128) /*op code for a kern step*/
11199 @d skip_byte(A) A.b0
11200 @d next_char(A) A.b1
11201 @d op_byte(A) A.b2
11202 @d rem_byte(A) A.b3
11203
11204 @ Extensible characters are specified by an |@!extensible_recipe|, which
11205 consists of four bytes called |@!top|, |@!mid|, |@!bot|, and |@!rep| (in this
11206 order). These bytes are the character codes of individual pieces used to
11207 build up a large symbol. If |top|, |mid|, or |bot| are zero, they are not
11208 present in the built-up result. For example, an extensible vertical line is
11209 like an extensible bracket, except that the top and bottom pieces are missing.
11210
11211 Let $T$, $M$, $B$, and $R$ denote the respective pieces, or an empty box
11212 if the piece isn't present. Then the extensible characters have the form
11213 $TR^kMR^kB$ from top to bottom, for some |k >= 0|, unless $M$ is absent;
11214 in the latter case we can have $TR^kB$ for both even and odd values of~|k|.
11215 The width of the extensible character is the width of $R$; and the
11216 height-plus-depth is the sum of the individual height-plus-depths of the
11217 components used, since the pieces are butted together in a vertical list.
11218
11219 @d ext_top(A) A.b0 /*|top| piece in a recipe*/
11220 @d ext_mid(A) A.b1 /*|mid| piece in a recipe*/
11221 @d ext_bot(A) A.b2 /*|bot| piece in a recipe*/
11222 @d ext_rep(A) A.b3 /*|rep| piece in a recipe*/
11223
11224 @ The final portion of a \.{TFM} file is the |param| array, which is another
11225 sequence of |fix_word| values.
11226
11227 \yskip\hang|param[1]==slant| is the amount of italic slant, which is used
11228 to help position accents. For example, |slant==.25| means that when you go
11229 up one unit, you also go .25 units to the right. The |slant| is a pure
11230 number; it's the only |fix_word| other than the design size itself that is
11231 not scaled by the design size.
11232
11233 \hang|param[2]==space| is the normal spacing between words in text.
11234 Note that character |' '| in the font need not have anything to do with
11235 blank spaces.
11236
11237 \hang|param[3]==space_stretch| is the amount of glue stretching between words.
11238
11239 \hang|param[4]==space_shrink| is the amount of glue shrinking between words.
11240
11241 \hang|param[5]==x_height| is the size of one ex in the font; it is also
11242 the height of letters for which accents don't have to be raised or lowered.
11243
11244 \hang|param[6]==quad| is the size of one em in the font.
11245
11246 \hang|param[7]==extra_space| is the amount added to |param[2]| at the
11247 ends of sentences.
11248
11249 \yskip\noindent
11250 If fewer than seven parameters are present, \TeX\ sets the missing parameters
11251 to zero. Fonts used for math symbols are required to have
11252 additional parameter information, which is explained later.
11253
11254 @d slant_code 1
11255 @d space_code 2
11256 @d space_stretch_code 3
11257 @d space_shrink_code 4
11258 @d x_height_code 5
11259 @d quad_code 6
11260 @d extra_space_code 7
11261
11262 @ So that is what \.{TFM} files hold. Since \TeX\ has to absorb such information
11263 about lots of fonts, it stores most of the data in a large array called
11264 |font_info|. Each item of |font_info| is a |memory_word|; the |fix_word|
11265 data gets converted into |scaled| entries, while everything else goes into
11266 words of type |four_quarters|.
11267
11268 When the user defines \.{\\font\\f}, say, \TeX\ assigns an internal number
11269 to the user's font~\.{\\f}. Adding this number to |font_id_base| gives the
11270 |eqtb| location of a ``frozen'' control sequence that will always select
11271 the font.
11272
11273 @<Types...@>=
11274 typedef uint8_t internal_font_number; /*|font| in a |char_node|*/
11275 typedef int32_t font_index; /*index into |font_info|*/
11276
11277 @ Here now is the (rather formidable) array of font arrays.
11278
11279 @d non_char qi(256) /*a |halfword| code that can't match a real character*/
11280 @d non_address 0 /*a spurious |bchar_label|*/
11281
11282 @<Glob...@>=
11283 static memory_word @!font_info[font_mem_size+1];
11284 /*the big collection of font data*/
11285 static font_index @!fmem_ptr; /*first unused word of |font_info|*/
11286 static internal_font_number @!font_ptr; /*largest internal font number in use*/
11287 static four_quarters @!font_check0[font_max-font_base+1],
11288 *const @!font_check = @!font_check0-font_base; /*check sum*/
11289 static scaled @!font_size0[font_max-font_base+1],
11290 *const @!font_size = @!font_size0-font_base; /*``at'' size*/
11291 static scaled @!font_dsize0[font_max-font_base+1],
11292 *const @!font_dsize = @!font_dsize0-font_base; /*``design'' size*/
11293 static font_index @!font_params0[font_max-font_base+1],
11294 *const @!font_params = @!font_params0-font_base; /*how many font
11295 parameters are present*/
11296 static str_number @!font_name0[font_max-font_base+1],
11297 *const @!font_name = @!font_name0-font_base; /*name of the font*/
11298 static str_number @!font_area0[font_max-font_base+1],
11299 *const @!font_area = @!font_area0-font_base; /*area of the font*/
11300 static eight_bits @!font_bc0[font_max-font_base+1],
11301 *const @!font_bc = @!font_bc0-font_base;
11302 /*beginning (smallest) character code*/
11303 static eight_bits @!font_ec0[font_max-font_base+1],
11304 *const @!font_ec = @!font_ec0-font_base;
11305 /*ending (largest) character code*/
11306 static pointer @!font_glue0[font_max-font_base+1],
11307 *const @!font_glue = @!font_glue0-font_base;
11308 /*glue specification for interword space, |null| if not allocated*/
11309 static bool @!font_used0[font_max-font_base+1],
11310 *const @!font_used = @!font_used0-font_base;
11311 /*has a character from this font actually appeared in the output?*/
11312 static int @!hyphen_char0[font_max-font_base+1],
11313 *const @!hyphen_char = @!hyphen_char0-font_base;
11314 /*current \.{\\hyphenchar} values*/
11315 static int @!skew_char0[font_max-font_base+1],
11316 *const @!skew_char = @!skew_char0-font_base;
11317 /*current \.{\\skewchar} values*/
11318 static font_index @!bchar_label0[font_max-font_base+1],
11319 *const @!bchar_label = @!bchar_label0-font_base;
11320 /*start of |lig_kern| program for left boundary character,
11321 |non_address| if there is none*/
11322 static int16_t @!font_bchar0[font_max-font_base+1],
11323 *const @!font_bchar = @!font_bchar0-font_base;
11324 /*boundary character, |non_char| if there is none*/
11325 static int16_t @!font_false_bchar0[font_max-font_base+1],
11326 *const @!font_false_bchar = @!font_false_bchar0-font_base;
11327 /*|font_bchar| if it doesn't exist in the font, otherwise |non_char|*/
11328
11329 @ Besides the arrays just enumerated, we have directory arrays that make it
11330 easy to get at the individual entries in |font_info|. For example, the
11331 |char_info| data for character |c| in font |f| will be in
11332 |font_info[char_base[f]+c].qqqq|; and if |w| is the |width_index|
11333 part of this word (the |b0| field), the width of the character is
11334 |font_info[width_base[f]+w].sc|. (These formulas assume that
11335 |min_quarterword| has already been added to |c| and to |w|, since \TeX\
11336 stores its quarterwords that way.)
11337
11338 @<Glob...@>=
11339 static int @!char_base0[font_max-font_base+1],
11340 *const @!char_base = @!char_base0-font_base;
11341 /*base addresses for |char_info|*/
11342 static int @!width_base0[font_max-font_base+1],
11343 *const @!width_base = @!width_base0-font_base;
11344 /*base addresses for widths*/
11345 static int @!height_base0[font_max-font_base+1],
11346 *const @!height_base = @!height_base0-font_base;
11347 /*base addresses for heights*/
11348 static int @!depth_base0[font_max-font_base+1],
11349 *const @!depth_base = @!depth_base0-font_base;
11350 /*base addresses for depths*/
11351 static int @!italic_base0[font_max-font_base+1],
11352 *const @!italic_base = @!italic_base0-font_base;
11353 /*base addresses for italic corrections*/
11354 static int @!lig_kern_base0[font_max-font_base+1],
11355 *const @!lig_kern_base = @!lig_kern_base0-font_base;
11356 /*base addresses for ligature/kerning programs*/
11357 static int @!kern_base0[font_max-font_base+1],
11358 *const @!kern_base = @!kern_base0-font_base;
11359 /*base addresses for kerns*/
11360 static int @!exten_base0[font_max-font_base+1],
11361 *const @!exten_base = @!exten_base0-font_base;
11362 /*base addresses for extensible recipes*/
11363 static int @!param_base0[font_max-font_base+1],
11364 *const @!param_base = @!param_base0-font_base;
11365 /*base addresses for font parameters*/
11366
11367 @ @<Set init...@>=
11368 for (k=font_base; k<=font_max; k++) font_used[k]=false;
11369
11370 @ \TeX\ always knows at least one font, namely the null font. It has no
11371 characters, and its seven parameters are all equal to zero.
11372
11373 @<Initialize table...@>=
11374 font_ptr=null_font;fmem_ptr=7;
11375 font_name[null_font]=s_no("nullfont");font_area[null_font]=empty_string;
11376 hyphen_char[null_font]='-';skew_char[null_font]=-1;
11377 bchar_label[null_font]=non_address;
11378 font_bchar[null_font]=non_char;font_false_bchar[null_font]=non_char;
11379 font_bc[null_font]=1;font_ec[null_font]=0;
11380 font_size[null_font]=0;font_dsize[null_font]=0;
11381 char_base[null_font]=0;width_base[null_font]=0;
11382 height_base[null_font]=0;depth_base[null_font]=0;
11383 italic_base[null_font]=0;lig_kern_base[null_font]=0;
11384 kern_base[null_font]=0;exten_base[null_font]=0;
11385 font_glue[null_font]=null;font_params[null_font]=7;
11386 param_base[null_font]=-1;
11387 for (k=0; k<=6; k++) font_info[k].sc=0;
11388
11389 @ @<Put each...@>=
11390 primitive("nullfont", set_font, null_font);
11391 @!@:null\_font\_}{\.{\\nullfont} primitive@>
11392 text(frozen_null_font)=text(cur_val);eqtb[frozen_null_font]=eqtb[cur_val];
11393
11394 @ Of course we want to define macros that suppress the detail of how font
11395 information is actually packed, so that we don't have to write things like
11396 $$\hbox{|font_info[width_base[f]+font_info[char_base[f]+c].qqqq.b0].sc|}$$
11397 too often. The \.{WEB} definitions here make |char_info(f)(c)| the
11398 |four_quarters| word of font information corresponding to character
11399 |c| of font |f|. If |q| is such a word, |char_width(f)(q)| will be
11400 the character's width; hence the long formula above is at least
11401 abbreviated to
11402 $$\hbox{|char_width(f)(char_info(f)(c))|.}$$
11403 Usually, of course, we will fetch |q| first and look at several of its
11404 fields at the same time.
11405
11406 The italic correction of a character will be denoted by
11407 |char_italic(f)(q)|, so it is analogous to |char_width|. But we will get
11408 at the height and depth in a slightly different way, since we usually want
11409 to compute both height and depth if we want either one. The value of
11410 |height_depth(q)| will be the 8-bit quantity
11411 $$b=|height_index|\times16+|depth_index|,$$ and if |b| is such a byte we
11412 will write |char_height(f)(b)| and |char_depth(f)(b)| for the height and
11413 depth of the character |c| for which |q==char_info(f)(c)|. Got that?
11414
11415 The tag field will be called |char_tag(q)|; the remainder byte will be
11416 called |rem_byte(q)|, using a macro that we have already defined above.
11417
11418 Access to a character's |width|, |height|, |depth|, and |tag| fields is
11419 part of \TeX's inner loop, so we want these macros to produce code that is
11420 as fast as possible under the circumstances.
11421 @^inner loop@>
11422
11423 @d char_info(A, B) font_info[char_base[A]+B].qqqq
11424 @d char_width(A, B) font_info[width_base[A]+B.b0].sc
11425 @d char_exists(A) (A.b0 > min_quarterword)
11426 @d char_italic(A, B) font_info[italic_base[A]+(qo(B.b2))/4].sc
11427 @d height_depth(A) qo(A.b1)
11428 @d char_height(A, B) font_info[height_base[A]+(B)/16].sc
11429 @d char_depth(A, B) font_info[depth_base[A]+(B)%16].sc
11430 @d char_tag(A) ((qo(A.b2))%4)
11431
11432 @ The global variable |null_character| is set up to be a word of
11433 |char_info| for a character that doesn't exist. Such a word provides a
11434 convenient way to deal with erroneous situations.
11435
11436 @<Glob...@>=
11437 static four_quarters @!null_character; /*nonexistent character information*/
11438
11439 @ @<Set init...@>=
11440 null_character.b0=min_quarterword;null_character.b1=min_quarterword;
11441 null_character.b2=min_quarterword;null_character.b3=min_quarterword;
11442
11443 @ Here are some macros that help process ligatures and kerns.
11444 We write |char_kern(f)(j)| to find the amount of kerning specified by
11445 kerning command~|j| in font~|f|. If |j| is the |char_info| for a character
11446 with a ligature/kern program, the first instruction of that program is either
11447 |i==font_info[lig_kern_start(f)(j)]| or |font_info[lig_kern_restart(f)(i)]|,
11448 depending on whether or not |skip_byte(i) <= stop_flag|.
11449
11450 The constant |kern_base_offset| should be simplified, for \PASCAL\ compilers
11451 that do not do local optimization.
11452 @^system dependencies@>
11453
11454 @d char_kern(A, B) font_info[kern_base[A]+256*op_byte(B)+rem_byte(B)].sc
11455 @d kern_base_offset 256*(128+min_quarterword)
11456 @d lig_kern_start(A, B) lig_kern_base[A]+B.b3 /*beginning of lig/kern program*/
11457 @d lig_kern_restart(A, B) lig_kern_base[A]+256*op_byte(B)+rem_byte(B)+32768-kern_base_offset
11458
11459 @ Font parameters are referred to as |slant(f)|, |space(f)|, etc.
11460
11461 @d param_end(A) param_base[A]].sc
11462 @d param(A) font_info[A+param_end
11463 @d slant param(slant_code) /*slant to the right, per unit distance upward*/
11464 @d space param(space_code) /*normal space between words*/
11465 @d space_stretch param(space_stretch_code) /*stretch between words*/
11466 @d space_shrink param(space_shrink_code) /*shrink between words*/
11467 @d x_height param(x_height_code) /*one ex*/
11468 @d quad param(quad_code) /*one em*/
11469 @d extra_space param(extra_space_code) /*additional space at end of sentence*/
11470
11471 @<The em width for |cur_font|@>=quad(cur_font)
11472
11473 @ @<The x-height for |cur_font|@>=x_height(cur_font)
11474
11475 @ \TeX\ checks the information of a \.{TFM} file for validity as the
11476 file is being read in, so that no further checks will be needed when
11477 typesetting is going on. The somewhat tedious subroutine that does this
11478 is called |read_font_info|. It has four parameters: the user font
11479 identifier~|u|, the file name and area strings |nom| and |aire|, and the
11480 ``at'' size~|s|. If |s|~is negative, it's the negative of a scale factor
11481 to be applied to the design size; |s==-1000| is the normal case.
11482 Otherwise |s| will be substituted for the design size; in this
11483 case, |s| must be positive and less than $2048\rm\,pt$
11484 (i.e., it must be less than $2^{27}$ when considered as an integer).
11485
11486 The subroutine opens and closes a global file variable called |tfm_file|.
11487 It returns the value of the internal font number that was just loaded.
11488 If an error is detected, an error message is issued and no font
11489 information is stored; |null_font| is returned in this case.
11490
11491 @d abort goto bad_tfm /*do this when the \.{TFM} data is wrong*/
11492
11493 @p static internal_font_number read_font_info(pointer @!u, str_number @!nom, str_number @!aire,
11494 scaled @!s) /*input a \.{TFM} file*/
11495 {@+
11496 int k; /*index into |font_info|*/
11497 bool @!file_opened; /*was |tfm_file| successfully opened?*/
11498 halfword @!lf, @!lh, @!bc, @!ec, @!nw, @!nh, @!nd, @!ni, @!nl, @!nk, @!ne, @!np;
11499 /*sizes of subfiles*/
11500 internal_font_number @!f; /*the new font's number*/
11501 internal_font_number @!g; /*the number to return*/
11502 eight_bits @!a, @!b, @!c, @!d; /*byte variables*/
11503 four_quarters @!qw;scaled @!sw; /*accumulators*/
11504 int @!bch_label; /*left boundary start location, or infinity*/
11505 int @!bchar; /*boundary character, or 256*/
11506 scaled @!z; /*the design size or the ``at'' size*/
11507 int @!alpha;int @!beta;
11508 /*auxiliary quantities used in fixed-point multiplication*/
11509 g=null_font;@/
11510 @<Read and check the font data; |abort| if the \.{TFM} file is malformed;
11511 if there's no room for this font, say so and |goto done|; otherwise |incr(font_ptr)|
11512 and |goto done|@>;
11513 bad_tfm: @<Report that the font won't be loaded@>;
11514 done: if (file_opened) b_close(&tfm_file);
11515 return g;
11516 }
11517
11518 @ There are programs called \.{TFtoPL} and \.{PLtoTF} that convert
11519 between the \.{TFM} format and a symbolic property-list format
11520 that can be easily edited. These programs contain extensive
11521 diagnostic information, so \TeX\ does not have to bother giving
11522 precise details about why it rejects a particular \.{TFM} file.
11523 @.TFtoPL@> @.PLtoTF@>
11524
11525 @d start_font_error_message print_err("Font ");sprint_cs(u);
11526 print_char('=');print_file_name(nom, aire, empty_string);
11527 if (s >= 0)
11528 {@+print(" at ");print_scaled(s);print("pt");
11529 }
11530 else if (s!=-1000)
11531 {@+print(" scaled ");print_int(-s);
11532 }
11533
11534 @<Report that the font won't be loaded@>=
11535 start_font_error_message;
11536 @.Font x=xx not loadable...@>
11537 if (file_opened) print(" not loadable: Bad metric (TFM) file");
11538 else print(" not loadable: Metric (TFM) file not found");
11539 help5("I wasn't able to read the size data for this font,",@/
11540 "so I will ignore the font specification.",@/
11541 "[Wizards can fix TFM files using TFtoPL/PLtoTF.]",@/
11542 "You might try inserting a different font spec;",@/
11543 "e.g., type `I\\font<same font id>=<substitute font name>'.");
11544 error()
11545
11546 @ @<Read and check...@>=
11547 @<Open |tfm_file| for input@>;
11548 @<Read the {\.{TFM}} size fields@>;
11549 @<Use size fields to allocate font information@>;
11550 @<Read the {\.{TFM}} header@>;
11551 @<Read character data@>;
11552 @<Read box dimensions@>;
11553 @<Read ligature/kern program@>;
11554 @<Read extensible character recipes@>;
11555 @<Read font parameters@>;
11556 @<Make final adjustments and |goto done|@>@;
11557
11558 @ @<Open |tfm_file| for input@>=
11559 file_opened=false;
11560 pack_file_name(nom, empty_string,empty_string,".tfm"); /* \TeX\ Live */
11561 if (!b_open_in(&tfm_file)) abort;
11562 file_opened=true
11563
11564 @ Note: A malformed \.{TFM} file might be shorter than it claims to be;
11565 thus |eof(tfm_file)| might be true when |read_font_info| refers to
11566 |tfm_file.d| or when it says |get(tfm_file)|. If such circumstances
11567 cause system error messages, you will have to defeat them somehow,
11568 for example by defining |fget| to be `\ignorespaces|{@+get(tfm_file);|
11569 |if (eof(tfm_file)) abort;} |\unskip'.
11570 @^system dependencies@>
11571
11572 @d fget get(tfm_file)
11573 @d fbyte tfm_file.d
11574 @d read_sixteen(A) {@+A=fbyte;
11575 if (A > 127) abort;
11576 fget;A=A*0400+fbyte;
11577 }
11578 @d store_four_quarters(A) {@+fget;a=fbyte;qw.b0=qi(a);
11579 fget;b=fbyte;qw.b1=qi(b);
11580 fget;c=fbyte;qw.b2=qi(c);
11581 fget;d=fbyte;qw.b3=qi(d);
11582 A=qw;
11583 }
11584
11585 @ @<Read the {\.{TFM}} size fields@>=
11586 {@+read_sixteen(lf);
11587 fget;read_sixteen(lh);
11588 fget;read_sixteen(bc);
11589 fget;read_sixteen(ec);
11590 if ((bc > ec+1)||(ec > 255)) abort;
11591 if (bc > 255) /*|bc==256| and |ec==255|*/
11592 {@+bc=1;ec=0;
11593 }
11594 fget;read_sixteen(nw);
11595 fget;read_sixteen(nh);
11596 fget;read_sixteen(nd);
11597 fget;read_sixteen(ni);
11598 fget;read_sixteen(nl);
11599 fget;read_sixteen(nk);
11600 fget;read_sixteen(ne);
11601 fget;read_sixteen(np);
11602 if (lf!=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np) abort;
11603 if ((nw==0)||(nh==0)||(nd==0)||(ni==0)) abort;
11604 }
11605
11606 @ The preliminary settings of the index-offset variables |char_base|,
11607 |width_base|, |lig_kern_base|, |kern_base|, and |exten_base| will be
11608 corrected later by subtracting |min_quarterword| from them; and we will
11609 subtract 1 from |param_base| too. It's best to forget about such anomalies
11610 until later.
11611
11612 @<Use size fields to allocate font information@>=
11613 lf=lf-6-lh; /*|lf| words should be loaded into |font_info|*/
11614 if (np < 7) lf=lf+7-np; /*at least seven parameters will appear*/
11615 if ((font_ptr==font_max)||(fmem_ptr+lf > font_mem_size))
11616 @<Apologize for not loading the font, |goto done|@>;
11617 f=font_ptr+1;
11618 char_base[f]=fmem_ptr-bc;
11619 width_base[f]=char_base[f]+ec+1;
11620 height_base[f]=width_base[f]+nw;
11621 depth_base[f]=height_base[f]+nh;
11622 italic_base[f]=depth_base[f]+nd;
11623 lig_kern_base[f]=italic_base[f]+ni;
11624 kern_base[f]=lig_kern_base[f]+nl-kern_base_offset;
11625 exten_base[f]=kern_base[f]+kern_base_offset+nk;
11626 param_base[f]=exten_base[f]+ne
11627
11628 @ @<Apologize for not loading...@>=
11629 {@+start_font_error_message;
11630 print(" not loaded: Not enough room left");
11631 @.Font x=xx not loaded...@>
11632 help4("I'm afraid I won't be able to make use of this font,",@/
11633 "because my memory for character-size data is too small.",@/
11634 "If you're really stuck, ask a wizard to enlarge me.",@/
11635 "Or maybe try `I\\font<same font id>=<name of loaded font>'.");
11636 error();goto done;
11637 }
11638
11639 @ Only the first two words of the header are needed by \TeX82.
11640
11641 @<Read the {\.{TFM}} header@>=
11642 {@+if (lh < 2) abort;
11643 store_four_quarters(font_check[f]);
11644 fget;read_sixteen(z); /*this rejects a negative design size*/
11645 fget;z=z*0400+fbyte;fget;z=(z*020)+(fbyte/020);
11646 if (z < unity) abort;
11647 while (lh > 2)
11648 {@+fget;fget;fget;fget;decr(lh); /*ignore the rest of the header*/
11649 }
11650 font_dsize[f]=z;
11651 if (s!=-1000)
11652 if (s >= 0) z=s;
11653 else z=xn_over_d(z,-s, 1000);
11654 font_size[f]=z;
11655 }
11656
11657 @ @<Read character data@>=
11658 for (k=fmem_ptr; k<=width_base[f]-1; k++)
11659 {@+store_four_quarters(font_info[k].qqqq);
11660 if ((a >= nw)||(b/020 >= nh)||(b%020 >= nd)||
11661 (c/4 >= ni)) abort;
11662 switch (c%4) {
11663 case lig_tag: if (d >= nl) abort;@+break;
11664 case ext_tag: if (d >= ne) abort;@+break;
11665 case list_tag: @<Check for charlist cycle@>@;@+break;
11666 default:do_nothing; /*|no_tag|*/
11667 }
11668 }
11669
11670 @ We want to make sure that there is no cycle of characters linked together
11671 by |list_tag| entries, since such a cycle would get \TeX\ into an endless
11672 loop. If such a cycle exists, the routine here detects it when processing
11673 the largest character code in the cycle.
11674
11675 @d check_byte_range(A) {@+if ((A < bc)||(A > ec)) abort;@+}
11676 @d current_character_being_worked_on k+bc-fmem_ptr
11677
11678 @<Check for charlist cycle@>=
11679 {@+check_byte_range(d);
11680 while (d < current_character_being_worked_on)
11681 {@+qw=char_info(f, d);
11682 /*N.B.: not |qi(d)|, since |char_base[f]| hasn't been adjusted yet*/
11683 if (char_tag(qw)!=list_tag) goto not_found;
11684 d=qo(rem_byte(qw)); /*next character on the list*/
11685 }
11686 if (d==current_character_being_worked_on) abort; /*yes, there's a cycle*/
11687 not_found: ;}
11688
11689 @ A |fix_word| whose four bytes are $(a,b,c,d)$ from left to right represents
11690 the number
11691 $$x=\left\{\vcenter{\halign{$#$,\hfil\qquad&if $#$\hfil\cr
11692 b\cdot2^{-4}+c\cdot2^{-12}+d\cdot2^{-20}&a=0;\cr
11693 -16+b\cdot2^{-4}+c\cdot2^{-12}+d\cdot2^{-20}&a=255.\cr}}\right.$$
11694 (No other choices of |a| are allowed, since the magnitude of a number in
11695 design-size units must be less than 16.) We want to multiply this
11696 quantity by the integer~|z|, which is known to be less than $2^{27}$.
11697 If $|z|<2^{23}$, the individual multiplications $b\cdot z$,
11698 $c\cdot z$, $d\cdot z$ cannot overflow; otherwise we will divide |z| by 2,
11699 4, 8, or 16, to obtain a multiplier less than $2^{23}$, and we can
11700 compensate for this later. If |z| has thereby been replaced by
11701 $|z|^\prime=|z|/2^e$, let $\beta=2^{4-e}$; we shall compute
11702 $$\lfloor(b+c\cdot2^{-8}+d\cdot2^{-16})\,z^\prime/\beta\rfloor$$
11703 if $a=0$, or the same quantity minus $\alpha=2^{4+e}z^\prime$ if $a=255$.
11704 This calculation must be done exactly, in order to guarantee portability
11705 of \TeX\ between computers.
11706
11707 @d store_scaled(A) {@+fget;a=fbyte;fget;b=fbyte;
11708 fget;c=fbyte;fget;d=fbyte;@/
11709 sw=(((((d*z)/0400)+(c*z))/0400)+(b*z))/beta;
11710 if (a==0) A=sw;@+else if (a==255) A=sw-alpha;@+else abort;
11711 }
11712
11713 @<Read box dimensions@>=
11714 {@+@<Replace |z| by $|z|^\prime$ and compute $\alpha,\beta$@>;
11715 for (k=width_base[f]; k<=lig_kern_base[f]-1; k++)
11716 store_scaled(font_info[k].sc);
11717 if (font_info[width_base[f]].sc!=0) abort; /*\\{width}[0] must be zero*/
11718 if (font_info[height_base[f]].sc!=0) abort; /*\\{height}[0] must be zero*/
11719 if (font_info[depth_base[f]].sc!=0) abort; /*\\{depth}[0] must be zero*/
11720 if (font_info[italic_base[f]].sc!=0) abort; /*\\{italic}[0] must be zero*/
11721 }
11722
11723 @ @<Replace |z|...@>=
11724 {@+alpha=16;
11725 while (z >= 040000000)
11726 {@+z=z/2;alpha=alpha+alpha;
11727 }
11728 beta=256/alpha;alpha=alpha*z;
11729 }
11730
11731 @ @d check_existence(A) @t@>@;@/
11732 {@+check_byte_range(A);
11733 qw=char_info(f, A); /*N.B.: not |qi(A)|*/
11734 if (!char_exists(qw)) abort;
11735 }
11736
11737 @<Read ligature/kern program@>=
11738 bch_label=077777;bchar=256;
11739 if (nl > 0)
11740 {@+for (k=lig_kern_base[f]; k<=kern_base[f]+kern_base_offset-1; k++)
11741 {@+store_four_quarters(font_info[k].qqqq);
11742 if (a > 128)
11743 {@+if (256*c+d >= nl) abort;
11744 if (a==255) if (k==lig_kern_base[f]) bchar=b;
11745 }
11746 else{@+if (b!=bchar) check_existence(b);
11747 if (c < 128) check_existence(d)@; /*check ligature*/
11748 else if (256*(c-128)+d >= nk) abort; /*check kern*/
11749 if (a < 128) if (k-lig_kern_base[f]+a+1 >= nl) abort;
11750 }
11751 }
11752 if (a==255) bch_label=256*c+d;
11753 }
11754 for (k=kern_base[f]+kern_base_offset; k<=exten_base[f]-1; k++)
11755 store_scaled(font_info[k].sc);
11756
11757 @ @<Read extensible character recipes@>=
11758 for (k=exten_base[f]; k<=param_base[f]-1; k++)
11759 {@+store_four_quarters(font_info[k].qqqq);
11760 if (a!=0) check_existence(a);
11761 if (b!=0) check_existence(b);
11762 if (c!=0) check_existence(c);
11763 check_existence(d);
11764 }
11765
11766 @ We check to see that the \.{TFM} file doesn't end prematurely; but
11767 no error message is given for files having more than |lf| words.
11768
11769 @<Read font parameters@>=
11770 {@+for (k=1; k<=np; k++)
11771 if (k==1) /*the |slant| parameter is a pure number*/
11772 {@+fget;sw=fbyte;if (sw > 127) sw=sw-256;
11773 fget;sw=sw*0400+fbyte;fget;sw=sw*0400+fbyte;
11774 fget;font_info[param_base[f]].sc=
11775 (sw*020)+(fbyte/020);
11776 }
11777 else store_scaled(font_info[param_base[f]+k-1].sc);
11778 if (eof(tfm_file)) abort;
11779 for (k=np+1; k<=7; k++) font_info[param_base[f]+k-1].sc=0;
11780 }
11781
11782 @ Now to wrap it up, we have checked all the necessary things about the \.{TFM}
11783 file, and all we need to do is put the finishing touches on the data for
11784 the new font.
11785
11786 @d adjust(A) A[f]=qo(A[f])
11787 /*correct for the excess |min_quarterword| that was added*/
11788
11789 @<Make final adjustments...@>=
11790 if (np >= 7) font_params[f]=np;@+else font_params[f]=7;
11791 hyphen_char[f]=default_hyphen_char;skew_char[f]=default_skew_char;
11792 if (bch_label < nl) bchar_label[f]=bch_label+lig_kern_base[f];
11793 else bchar_label[f]=non_address;
11794 font_bchar[f]=qi(bchar);
11795 font_false_bchar[f]=qi(bchar);
11796 if (bchar <= ec) if (bchar >= bc)
11797 {@+qw=char_info(f, bchar); /*N.B.: not |qi(bchar)|*/
11798 if (char_exists(qw)) font_false_bchar[f]=non_char;
11799 }
11800 font_name[f]=nom;
11801 font_area[f]=aire;
11802 font_bc[f]=bc;font_ec[f]=ec;font_glue[f]=null;
11803 adjust(char_base);adjust(width_base);adjust(lig_kern_base);
11804 adjust(kern_base);adjust(exten_base);
11805 decr(param_base[f]);
11806 fmem_ptr=fmem_ptr+lf;font_ptr=f;g=f;goto done
11807
11808 @ Before we forget about the format of these tables, let's deal with two
11809 of \TeX's basic scanning routines related to font information.
11810
11811 @<Declare procedures that scan font-related stuff@>=
11812 static void scan_font_ident(void)
11813 {@+internal_font_number f;
11814 halfword @!m;
11815 @<Get the next non-blank non-call...@>;
11816 if (cur_cmd==def_font) f=cur_font;
11817 else if (cur_cmd==set_font) f=cur_chr;
11818 else if (cur_cmd==def_family)
11819 {@+m=cur_chr;scan_four_bit_int();f=equiv(m+cur_val);
11820 }
11821 else{@+print_err("Missing font identifier");
11822 @.Missing font identifier@>
11823 help2("I was looking for a control sequence whose",@/
11824 "current meaning has been defined by \\font.");
11825 back_error();f=null_font;
11826 }
11827 cur_val=f;
11828 }
11829
11830 @ The following routine is used to implement `\.{\\fontdimen} |n| |f|'.
11831 The boolean parameter |writing| is set |true| if the calling program
11832 intends to change the parameter value.
11833
11834 @<Declare procedures that scan font-related stuff@>=
11835 static void find_font_dimen(bool @!writing)
11836 /*sets |cur_val| to |font_info| location*/
11837 {@+internal_font_number f;
11838 int @!n; /*the parameter number*/
11839 scan_int();n=cur_val;scan_font_ident();f=cur_val;
11840 if (n <= 0) cur_val=fmem_ptr;
11841 else{@+if (writing&&(n <= space_shrink_code)&&@|
11842 (n >= space_code)&&(font_glue[f]!=null))
11843 {@+delete_glue_ref(font_glue[f]);
11844 font_glue[f]=null;
11845 }
11846 if (n > font_params[f])
11847 if (f < font_ptr) cur_val=fmem_ptr;
11848 else@<Increase the number of parameters in the last font@>@;
11849 else cur_val=n+param_base[f];
11850 }
11851 @<Issue an error message if |cur_val=fmem_ptr|@>;
11852 }
11853
11854 @ @<Issue an error message if |cur_val=fmem_ptr|@>=
11855 if (cur_val==fmem_ptr)
11856 {@+print_err("Font ");printn_esc(font_id_text(f));
11857 print(" has only ");print_int(font_params[f]);
11858 print(" fontdimen parameters");
11859 @.Font x has only...@>
11860 help2("To increase the number of font parameters, you must",@/
11861 "use \\fontdimen immediately after the \\font is loaded.");
11862 error();
11863 }
11864
11865 @ @<Increase the number of parameters...@>=
11866 {@+@/do@+{if (fmem_ptr==font_mem_size)
11867 overflow("font memory", font_mem_size);
11868 @:TeX capacity exceeded font memory}{\quad font memory@>
11869 font_info[fmem_ptr].sc=0;incr(fmem_ptr);incr(font_params[f]);
11870 }@+ while (!(n==font_params[f]));
11871 cur_val=fmem_ptr-1; /*this equals |param_base[f]+font_params[f]|*/
11872 }
11873
11874 @ When \TeX\ wants to typeset a character that doesn't exist, the
11875 character node is not created; thus the output routine can assume
11876 that characters exist when it sees them. The following procedure
11877 prints a warning message unless the user has suppressed it.
11878
11879 @p static void char_warning(internal_font_number @!f, eight_bits @!c)
11880 {@+int old_setting; /*saved value of |tracing_online|*/
11881 if (tracing_lost_chars > 0)
11882 {@+old_setting=tracing_online;
11883 if (eTeX_ex&&(tracing_lost_chars > 1)) tracing_online=1;
11884 {@+begin_diagnostic();
11885 print_nl("Missing character: There is no ");
11886 @.Missing character@>
11887 print_ASCII(c);print(" in font ");
11888 slow_print(font_name[f]);print_char('!');end_diagnostic(false);
11889 }
11890 tracing_online=old_setting;
11891 }
11892 }
11893
11894 @ Here is a function that returns a pointer to a character node for a
11895 given character in a given font. If that character doesn't exist,
11896 |null| is returned instead.
11897
11898 @p static pointer new_character(internal_font_number @!f, eight_bits @!c)
11899 {@+
11900 pointer p; /*newly allocated node*/
11901 if (font_bc[f] <= c) if (font_ec[f] >= c)
11902 if (char_exists(char_info(f, qi(c))))
11903 {@+p=get_avail();font(p)=f;character(p)=qi(c);
11904 return p;
11905 }
11906 char_warning(f, c);
11907 return null;
11908 }
11909
11910 @* Device-independent file format.
11911 The most important output produced by a run of \TeX\ is the ``device
11912 independent'' (\.{DVI}) file that specifies where characters and rules
11913 are to appear on printed pages. The form of these files was designed by
11914 David R. Fuchs in 1979. Almost any reasonable typesetting device can be
11915 @^Fuchs, David Raymond@>
11916 @:DVI\_files}{\.{DVI} files@>
11917 driven by a program that takes \.{DVI} files as input, and dozens of such
11918 \.{DVI}-to-whatever programs have been written. Thus, it is possible to
11919 print the output of \TeX\ on many different kinds of equipment, using \TeX\
11920 as a device-independent ``front end.''
11921
11922 A \.{DVI} file is a stream of 8-bit bytes, which may be regarded as a
11923 series of commands in a machine-like language. The first byte of each command
11924 is the operation code, and this code is followed by zero or more bytes
11925 that provide parameters to the command. The parameters themselves may consist
11926 of several consecutive bytes; for example, the `|set_rule|' command has two
11927 parameters, each of which is four bytes long. Parameters are usually
11928 regarded as nonnegative integers; but four-byte-long parameters,
11929 and shorter parameters that denote distances, can be
11930 either positive or negative. Such parameters are given in two's complement
11931 notation. For example, a two-byte-long distance parameter has a value between
11932 $-2^{15}$ and $2^{15}-1$. As in \.{TFM} files, numbers that occupy
11933 more than one byte position appear in BigEndian order.
11934
11935 A \.{DVI} file consists of a ``preamble,'' followed by a sequence of one
11936 or more ``pages,'' followed by a ``postamble.'' The preamble is simply a
11937 |pre| command, with its parameters that define the dimensions used in the
11938 file; this must come first. Each ``page'' consists of a |bop| command,
11939 followed by any number of other commands that tell where characters are to
11940 be placed on a physical page, followed by an |eop| command. The pages
11941 appear in the order that \TeX\ generated them. If we ignore |nop| commands
11942 and \\{fnt\_def} commands (which are allowed between any two commands in
11943 the file), each |eop| command is immediately followed by a |bop| command,
11944 or by a |post| command; in the latter case, there are no more pages in the
11945 file, and the remaining bytes form the postamble. Further details about
11946 the postamble will be explained later.
11947
11948 Some parameters in \.{DVI} commands are ``pointers.'' These are four-byte
11949 quantities that give the location number of some other byte in the file;
11950 the first byte is number~0, then comes number~1, and so on. For example,
11951 one of the parameters of a |bop| command points to the previous |bop|;
11952 this makes it feasible to read the pages in backwards order, in case the
11953 results are being directed to a device that stacks its output face up.
11954 Suppose the preamble of a \.{DVI} file occupies bytes 0 to 99. Now if the
11955 first page occupies bytes 100 to 999, say, and if the second
11956 page occupies bytes 1000 to 1999, then the |bop| that starts in byte 1000
11957 points to 100 and the |bop| that starts in byte 2000 points to 1000. (The
11958 very first |bop|, i.e., the one starting in byte 100, has a pointer of~$-1$.)
11959
11960 @ The \.{DVI} format is intended to be both compact and easily interpreted
11961 by a machine. Compactness is achieved by making most of the information
11962 implicit instead of explicit. When a \.{DVI}-reading program reads the
11963 commands for a page, it keeps track of several quantities: (a)~The current
11964 font |f| is an integer; this value is changed only
11965 by \\{fnt} and \\{fnt\_num} commands. (b)~The current position on the page
11966 is given by two numbers called the horizontal and vertical coordinates,
11967 |h| and |v|. Both coordinates are zero at the upper left corner of the page;
11968 moving to the right corresponds to increasing the horizontal coordinate, and
11969 moving down corresponds to increasing the vertical coordinate. Thus, the
11970 coordinates are essentially Cartesian, except that vertical directions are
11971 flipped; the Cartesian version of |(h, v)| would be |(h,-v)|. (c)~The
11972 current spacing amounts are given by four numbers |w|, |x|, |y|, and |z|,
11973 where |w| and~|x| are used for horizontal spacing and where |y| and~|z|
11974 are used for vertical spacing. (d)~There is a stack containing
11975 |(h, v, w, x, y, z)| values; the \.{DVI} commands |push| and |pop| are used to
11976 change the current level of operation. Note that the current font~|f| is
11977 not pushed and popped; the stack contains only information about
11978 positioning.
11979
11980 The values of |h|, |v|, |w|, |x|, |y|, and |z| are signed integers having up
11981 to 32 bits, including the sign. Since they represent physical distances,
11982 there is a small unit of measurement such that increasing |h| by~1 means
11983 moving a certain tiny distance to the right. The actual unit of
11984 measurement is variable, as explained below; \TeX\ sets things up so that
11985 its \.{DVI} output is in sp units, i.e., scaled points, in agreement with
11986 all the |scaled| dimensions in \TeX's data structures.
11987
11988 @ Here is a list of all the commands that may appear in a \.{DVI} file. Each
11989 command is specified by its symbolic name (e.g., |bop|), its opcode byte
11990 (e.g., 139), and its parameters (if any). The parameters are followed
11991 by a bracketed number telling how many bytes they occupy; for example,
11992 `|p[4]|' means that parameter |p| is four bytes long.
11993
11994 \yskip\hang|set_char_0| 0. Typeset character number~0 from font~|f|
11995 such that the reference point of the character is at |(h, v)|. Then
11996 increase |h| by the width of that character. Note that a character may
11997 have zero or negative width, so one cannot be sure that |h| will advance
11998 after this command; but |h| usually does increase.
11999
12000 \yskip\hang\\{set\_char\_1} through \\{set\_char\_127} (opcodes 1 to 127).
12001 Do the operations of |set_char_0|; but use the character whose number
12002 matches the opcode, instead of character~0.
12003
12004 \yskip\hang|set1| 128 |c[1]|. Same as |set_char_0|, except that character
12005 number~|c| is typeset. \TeX82 uses this command for characters in the
12006 range |128 <= c < 256|.
12007
12008 \yskip\hang|@!set2| 129 |c[2]|. Same as |set1|, except that |c|~is two
12009 bytes long, so it is in the range |0 <= c < 65536|. \TeX82 never uses this
12010 command, but it should come in handy for extensions of \TeX\ that deal
12011 with oriental languages.
12012 @^oriental characters@>@^Chinese characters@>@^Japanese characters@>
12013
12014 \yskip\hang|@!set3| 130 |c[3]|. Same as |set1|, except that |c|~is three
12015 bytes long, so it can be as large as $2^{24}-1$. Not even the Chinese
12016 language has this many characters, but this command might prove useful
12017 in some yet unforeseen extension.
12018
12019 \yskip\hang|@!set4| 131 |c[4]|. Same as |set1|, except that |c|~is four
12020 bytes long. Imagine that.
12021
12022 \yskip\hang|set_rule| 132 |a[4]| |b[4]|. Typeset a solid black rectangle
12023 of height~|a| and width~|b|, with its bottom left corner at |(h, v)|. Then
12024 set |h=h+b|. If either |a <= 0| or |b <= 0|, nothing should be typeset. Note
12025 that if |b < 0|, the value of |h| will decrease even though nothing else happens.
12026 See below for details about how to typeset rules so that consistency with
12027 \MF\ is guaranteed.
12028
12029 \yskip\hang|@!put1| 133 |c[1]|. Typeset character number~|c| from font~|f|
12030 such that the reference point of the character is at |(h, v)|. (The `put'
12031 commands are exactly like the `set' commands, except that they simply put out a
12032 character or a rule without moving the reference point afterwards.)
12033
12034 \yskip\hang|@!put2| 134 |c[2]|. Same as |set2|, except that |h| is not changed.
12035
12036 \yskip\hang|@!put3| 135 |c[3]|. Same as |set3|, except that |h| is not changed.
12037
12038 \yskip\hang|@!put4| 136 |c[4]|. Same as |set4|, except that |h| is not changed.
12039
12040 \yskip\hang|put_rule| 137 |a[4]| |b[4]|. Same as |set_rule|, except that
12041 |h| is not changed.
12042
12043 \yskip\hang|nop| 138. No operation, do nothing. Any number of |nop|'s
12044 may occur between \.{DVI} commands, but a |nop| cannot be inserted between
12045 a command and its parameters or between two parameters.
12046
12047 \yskip\hang|bop| 139 $c_0[4]$ $c_1[4]$ $\ldots$ $c_9[4]$ $p[4]$. Beginning
12048 of a page: Set |(h, v, w, x, y, z)=(0, 0, 0, 0, 0, 0)| and set the stack empty. Set
12049 the current font |f| to an undefined value. The ten $c_i$ parameters hold
12050 the values of \.{\\count0} $\ldots$ \.{\\count9} in \TeX\ at the time
12051 \.{\\shipout} was invoked for this page; they can be used to identify
12052 pages, if a user wants to print only part of a \.{DVI} file. The parameter
12053 |p| points to the previous |bop| in the file; the first
12054 |bop| has $p=-1$.
12055
12056 \yskip\hang|eop| 140. End of page: Print what you have read since the
12057 previous |bop|. At this point the stack should be empty. (The \.{DVI}-reading
12058 programs that drive most output devices will have kept a buffer of the
12059 material that appears on the page that has just ended. This material is
12060 largely, but not entirely, in order by |v| coordinate and (for fixed |v|) by
12061 |h|~coordinate; so it usually needs to be sorted into some order that is
12062 appropriate for the device in question.)
12063
12064 \yskip\hang|push| 141. Push the current values of |(h, v, w, x, y, z)| onto the
12065 top of the stack; do not change any of these values. Note that |f| is
12066 not pushed.
12067
12068 \yskip\hang|pop| 142. Pop the top six values off of the stack and assign
12069 them respectively to |(h, v, w, x, y, z)|. The number of pops should never
12070 exceed the number of pushes, since it would be highly embarrassing if the
12071 stack were empty at the time of a |pop| command.
12072
12073 \yskip\hang|right1| 143 |b[1]|. Set |h=h+b|, i.e., move right |b| units.
12074 The parameter is a signed number in two's complement notation, |-128 <= b < 128|;
12075 if |b < 0|, the reference point moves left.
12076
12077 \yskip\hang|@!right2| 144 |b[2]|. Same as |right1|, except that |b| is a
12078 two-byte quantity in the range |-32768 <= b < 32768|.
12079
12080 \yskip\hang|@!right3| 145 |b[3]|. Same as |right1|, except that |b| is a
12081 three-byte quantity in the range |@t$-2^{23}$@> <= b < @t$2^{23}$@>|.
12082
12083 \yskip\hang|@!right4| 146 |b[4]|. Same as |right1|, except that |b| is a
12084 four-byte quantity in the range |@t$-2^{31}$@> <= b < @t$2^{31}$@>|.
12085
12086 \yskip\hang|w0| 147. Set |h=h+w|; i.e., move right |w| units. With luck,
12087 this parameterless command will usually suffice, because the same kind of motion
12088 will occur several times in succession; the following commands explain how
12089 |w| gets particular values.
12090
12091 \yskip\hang|w1| 148 |b[1]|. Set |w=b| and |h=h+b|. The value of |b| is a
12092 signed quantity in two's complement notation, |-128 <= b < 128|. This command
12093 changes the current |w|~spacing and moves right by |b|.
12094
12095 \yskip\hang|@!w2| 149 |b[2]|. Same as |w1|, but |b| is two bytes long,
12096 |-32768 <= b < 32768|.
12097
12098 \yskip\hang|@!w3| 150 |b[3]|. Same as |w1|, but |b| is three bytes long,
12099 |@t$-2^{23}$@> <= b < @t$2^{23}$@>|.
12100
12101 \yskip\hang|@!w4| 151 |b[4]|. Same as |w1|, but |b| is four bytes long,
12102 |@t$-2^{31}$@> <= b < @t$2^{31}$@>|.
12103
12104 \yskip\hang|x0| 152. Set |h=h+x|; i.e., move right |x| units. The `|x|'
12105 commands are like the `|w|' commands except that they involve |x| instead
12106 of |w|.
12107
12108 \yskip\hang|x1| 153 |b[1]|. Set |x=b| and |h=h+b|. The value of |b| is a
12109 signed quantity in two's complement notation, |-128 <= b < 128|. This command
12110 changes the current |x|~spacing and moves right by |b|.
12111
12112 \yskip\hang|@!x2| 154 |b[2]|. Same as |x1|, but |b| is two bytes long,
12113 |-32768 <= b < 32768|.
12114
12115 \yskip\hang|@!x3| 155 |b[3]|. Same as |x1|, but |b| is three bytes long,
12116 |@t$-2^{23}$@> <= b < @t$2^{23}$@>|.
12117
12118 \yskip\hang|@!x4| 156 |b[4]|. Same as |x1|, but |b| is four bytes long,
12119 |@t$-2^{31}$@> <= b < @t$2^{31}$@>|.
12120
12121 \yskip\hang|down1| 157 |a[1]|. Set |v=v+a|, i.e., move down |a| units.
12122 The parameter is a signed number in two's complement notation, |-128 <= a < 128|;
12123 if |a < 0|, the reference point moves up.
12124
12125 \yskip\hang|@!down2| 158 |a[2]|. Same as |down1|, except that |a| is a
12126 two-byte quantity in the range |-32768 <= a < 32768|.
12127
12128 \yskip\hang|@!down3| 159 |a[3]|. Same as |down1|, except that |a| is a
12129 three-byte quantity in the range |@t$-2^{23}$@> <= a < @t$2^{23}$@>|.
12130
12131 \yskip\hang|@!down4| 160 |a[4]|. Same as |down1|, except that |a| is a
12132 four-byte quantity in the range |@t$-2^{31}$@> <= a < @t$2^{31}$@>|.
12133
12134 \yskip\hang|y0| 161. Set |v=v+y|; i.e., move down |y| units. With luck,
12135 this parameterless command will usually suffice, because the same kind of motion
12136 will occur several times in succession; the following commands explain how
12137 |y| gets particular values.
12138
12139 \yskip\hang|y1| 162 |a[1]|. Set |y=a| and |v=v+a|. The value of |a| is a
12140 signed quantity in two's complement notation, |-128 <= a < 128|. This command
12141 changes the current |y|~spacing and moves down by |a|.
12142
12143 \yskip\hang|@!y2| 163 |a[2]|. Same as |y1|, but |a| is two bytes long,
12144 |-32768 <= a < 32768|.
12145
12146 \yskip\hang|@!y3| 164 |a[3]|. Same as |y1|, but |a| is three bytes long,
12147 |@t$-2^{23}$@> <= a < @t$2^{23}$@>|.
12148
12149 \yskip\hang|@!y4| 165 |a[4]|. Same as |y1|, but |a| is four bytes long,
12150 |@t$-2^{31}$@> <= a < @t$2^{31}$@>|.
12151
12152 \yskip\hang|z0| 166. Set |v=v+z|; i.e., move down |z| units. The `|z|' commands
12153 are like the `|y|' commands except that they involve |z| instead of |y|.
12154
12155 \yskip\hang|z1| 167 |a[1]|. Set |z=a| and |v=v+a|. The value of |a| is a
12156 signed quantity in two's complement notation, |-128 <= a < 128|. This command
12157 changes the current |z|~spacing and moves down by |a|.
12158
12159 \yskip\hang|@!z2| 168 |a[2]|. Same as |z1|, but |a| is two bytes long,
12160 |-32768 <= a < 32768|.
12161
12162 \yskip\hang|@!z3| 169 |a[3]|. Same as |z1|, but |a| is three bytes long,
12163 |@t$-2^{23}$@> <= a < @t$2^{23}$@>|.
12164
12165 \yskip\hang|@!z4| 170 |a[4]|. Same as |z1|, but |a| is four bytes long,
12166 |@t$-2^{31}$@> <= a < @t$2^{31}$@>|.
12167
12168 \yskip\hang|fnt_num_0| 171. Set |f=0|. Font 0 must previously have been
12169 defined by a \\{fnt\_def} instruction, as explained below.
12170
12171 \yskip\hang\\{fnt\_num\_1} through \\{fnt\_num\_63} (opcodes 172 to 234). Set
12172 |f=1|, \dots, \hbox{|f=63|}, respectively.
12173
12174 \yskip\hang|fnt1| 235 |k[1]|. Set |f=k|. \TeX82 uses this command for font
12175 numbers in the range |64 <= k < 256|.
12176
12177 \yskip\hang|@!fnt2| 236 |k[2]|. Same as |fnt1|, except that |k|~is two
12178 bytes long, so it is in the range |0 <= k < 65536|. \TeX82 never generates this
12179 command, but large font numbers may prove useful for specifications of
12180 color or texture, or they may be used for special fonts that have fixed
12181 numbers in some external coding scheme.
12182
12183 \yskip\hang|@!fnt3| 237 |k[3]|. Same as |fnt1|, except that |k|~is three
12184 bytes long, so it can be as large as $2^{24}-1$.
12185
12186 \yskip\hang|@!fnt4| 238 |k[4]|. Same as |fnt1|, except that |k|~is four
12187 bytes long; this is for the really big font numbers (and for the negative ones).
12188
12189 \yskip\hang|xxx1| 239 |k[1]| |x[k]|. This command is undefined in
12190 general; it functions as a $(k+2)$-byte |nop| unless special \.{DVI}-reading
12191 programs are being used. \TeX82 generates |xxx1| when a short enough
12192 \.{\\special} appears, setting |k| to the number of bytes being sent. It
12193 is recommended that |x| be a string having the form of a keyword followed
12194 by possible parameters relevant to that keyword.
12195
12196 \yskip\hang|@!xxx2| 240 |k[2]| |x[k]|. Like |xxx1|, but |0 <= k < 65536|.
12197
12198 \yskip\hang|@!xxx3| 241 |k[3]| |x[k]|. Like |xxx1|, but |0 <= k < @t$2^{24}$@>|.
12199
12200 \yskip\hang|xxx4| 242 |k[4]| |x[k]|. Like |xxx1|, but |k| can be ridiculously
12201 large. \TeX82 uses |xxx4| when sending a string of length 256 or more.
12202
12203 \yskip\hang|fnt_def1| 243 |k[1]| |c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.
12204 Define font |k|, where |0 <= k < 256|; font definitions will be explained shortly.
12205
12206 \yskip\hang|@!fnt_def2| 244 |k[2]| |c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.
12207 Define font |k|, where |0 <= k < 65536|.
12208
12209 \yskip\hang|@!fnt_def3| 245 |k[3]| |c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.
12210 Define font |k|, where |0 <= k < @t$2^{24}$@>|.
12211
12212 \yskip\hang|@!fnt_def4| 246 |k[4]| |c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.
12213 Define font |k|, where |@t$-2^{31}$@> <= k < @t$2^{31}$@>|.
12214
12215 \yskip\hang|pre| 247 |i[1]| |num[4]| |den[4]| |mag[4]| |k[1]| |x[k]|.
12216 Beginning of the preamble; this must come at the very beginning of the
12217 file. Parameters |i|, |num|, |den|, |mag|, |k|, and |x| are explained below.
12218
12219 \yskip\hang|post| 248. Beginning of the postamble, see below.
12220
12221 \yskip\hang|post_post| 249. Ending of the postamble, see below.
12222
12223 \yskip\noindent Commands 250--255 are undefined at the present time.
12224
12225 @ @d set_char_0 0 /*typeset character 0 and move right*/
12226 @d set1 128 /*typeset a character and move right*/
12227 @d set_rule 132 /*typeset a rule and move right*/
12228 @d put_rule 137 /*typeset a rule*/
12229 @d nop 138 /*no operation*/
12230 @d bop 139 /*beginning of page*/
12231 @d eop 140 /*ending of page*/
12232 @d push 141 /*save the current positions*/
12233 @d pop 142 /*restore previous positions*/
12234 @d right1 143 /*move right*/
12235 @d w0 147 /*move right by |w|*/
12236 @d w1 148 /*move right and set |w|*/
12237 @d x0 152 /*move right by |x|*/
12238 @d x1 153 /*move right and set |x|*/
12239 @d down1 157 /*move down*/
12240 @d y0 161 /*move down by |y|*/
12241 @d y1 162 /*move down and set |y|*/
12242 @d z0 166 /*move down by |z|*/
12243 @d z1 167 /*move down and set |z|*/
12244 @d fnt_num_0 171 /*set current font to 0*/
12245 @d fnt1 235 /*set current font*/
12246 @d xxx1 239 /*extension to \.{DVI} primitives*/
12247 @d xxx4 242 /*potentially long extension to \.{DVI} primitives*/
12248 @d fnt_def1 243 /*define the meaning of a font number*/
12249 @d pre 247 /*preamble*/
12250 @d post 248 /*postamble beginning*/
12251 @d post_post 249 /*postamble ending*/
12252
12253 @ The preamble contains basic information about the file as a whole. As
12254 stated above, there are six parameters:
12255 $$\hbox{|@!i[1]| |@!num[4]| |@!den[4]| |@!mag[4]| |@!k[1]| |@!x[k]|.}$$
12256 The |i| byte identifies \.{DVI} format; currently this byte is always set
12257 to~2. (The value |i==3| is currently used for an extended format that
12258 allows a mixture of right-to-left and left-to-right typesetting.
12259 Some day we will set |i==4|, when \.{DVI} format makes another
12260 incompatible change---perhaps in the year 2048.)
12261
12262 The next two parameters, |num| and |den|, are positive integers that define
12263 the units of measurement; they are the numerator and denominator of a
12264 fraction by which all dimensions in the \.{DVI} file could be multiplied
12265 in order to get lengths in units of $10^{-7}$ meters. Since $\rm 7227{pt} =
12266 254{cm}$, and since \TeX\ works with scaled points where there are $2^{16}$
12267 sp in a point, \TeX\ sets
12268 $|num|/|den|=(254\cdot10^5)/(7227\cdot2^{16})=25400000/473628672$.
12269 @^sp@>
12270
12271 The |mag| parameter is what \TeX\ calls \.{\\mag}, i.e., 1000 times the
12272 desired magnification. The actual fraction by which dimensions are
12273 multiplied is therefore $|mag|\cdot|num|/1000|den|$. Note that if a \TeX\
12274 source document does not call for any `\.{true}' dimensions, and if you
12275 change it only by specifying a different \.{\\mag} setting, the \.{DVI}
12276 file that \TeX\ creates will be completely unchanged except for the value
12277 of |mag| in the preamble and postamble. (Fancy \.{DVI}-reading programs allow
12278 users to override the |mag|~setting when a \.{DVI} file is being printed.)
12279
12280 Finally, |k| and |x| allow the \.{DVI} writer to include a comment, which is not
12281 interpreted further. The length of comment |x| is |k|, where |0 <= k < 256|.
12282
12283 @d id_byte 2 /*identifies the kind of \.{DVI} files described here*/
12284
12285 @ Font definitions for a given font number |k| contain further parameters
12286 $$\hbox{|c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.}$$
12287 The four-byte value |c| is the check sum that \TeX\ found in the \.{TFM}
12288 file for this font; |c| should match the check sum of the font found by
12289 programs that read this \.{DVI} file.
12290 @^check sum@>
12291
12292 Parameter |s| contains a fixed-point scale factor that is applied to
12293 the character widths in font |k|; font dimensions in \.{TFM} files and
12294 other font files are relative to this quantity, which is called the
12295 ``at size'' elsewhere in this documentation. The value of |s| is
12296 always positive and less than $2^{27}$. It is given in the same units
12297 as the other \.{DVI} dimensions, i.e., in sp when \TeX82 has made the
12298 file. Parameter |d| is similar to |s|; it is the ``design size,'' and
12299 (like~|s|) it is given in \.{DVI} units. Thus, font |k| is to be used
12300 at $|mag|\cdot s/1000d$ times its normal size.
12301
12302 The remaining part of a font definition gives the external name of the font,
12303 which is an ASCII string of length |a+l|. The number |a| is the length
12304 of the ``area'' or directory, and |l| is the length of the font name itself;
12305 the standard local system font area is supposed to be used when |a==0|.
12306 The |n| field contains the area in its first |a| bytes.
12307
12308 Font definitions must appear before the first use of a particular font number.
12309 Once font |k| is defined, it must not be defined again; however, we
12310 shall see below that font definitions appear in the postamble as well as
12311 in the pages, so in this sense each font number is defined exactly twice,
12312 if at all. Like |nop| commands, font definitions can
12313 appear before the first |bop|, or between an |eop| and a |bop|.
12314
12315 @ Sometimes it is desirable to make horizontal or vertical rules line up
12316 precisely with certain features in characters of a font. It is possible to
12317 guarantee the correct matching between \.{DVI} output and the characters
12318 generated by \MF\ by adhering to the following principles: (1)~The \MF\
12319 characters should be positioned so that a bottom edge or left edge that is
12320 supposed to line up with the bottom or left edge of a rule appears at the
12321 reference point, i.e., in row~0 and column~0 of the \MF\ raster. This
12322 ensures that the position of the rule will not be rounded differently when
12323 the pixel size is not a perfect multiple of the units of measurement in
12324 the \.{DVI} file. (2)~A typeset rule of height $a>0$ and width $b>0$
12325 should be equivalent to a \MF-generated character having black pixels in
12326 precisely those raster positions whose \MF\ coordinates satisfy
12327 |0 <= x < @t$\alpha$@>b| and |0 <= y < @t$\alpha$@>a|, where $\alpha$ is the number
12328 of pixels per \.{DVI} unit.
12329 @:METAFONT}{\MF@>
12330 @^alignment of rules with characters@>
12331 @^rules aligning with characters@>
12332
12333 @ The last page in a \.{DVI} file is followed by `|post|'; this command
12334 introduces the postamble, which summarizes important facts that \TeX\ has
12335 accumulated about the file, making it possible to print subsets of the data
12336 with reasonable efficiency. The postamble has the form
12337 $$\vbox{\halign{\hbox{#\hfil}\cr
12338 |post| |p[4]| |num[4]| |den[4]| |mag[4]| |l[4]| |u[4]| |s[2]| |t[2]|\cr
12339 $\langle\,$font definitions$\,\rangle$\cr
12340 |post_post| |q[4]| |i[1]| 223's$[{\G}4]$\cr}}$$
12341 Here |p| is a pointer to the final |bop| in the file. The next three
12342 parameters, |num|, |den|, and |mag|, are duplicates of the quantities that
12343 appeared in the preamble.
12344
12345 Parameters |l| and |u| give respectively the height-plus-depth of the tallest
12346 page and the width of the widest page, in the same units as other dimensions
12347 of the file. These numbers might be used by a \.{DVI}-reading program to
12348 position individual ``pages'' on large sheets of film or paper; however,
12349 the standard convention for output on normal size paper is to position each
12350 page so that the upper left-hand corner is exactly one inch from the left
12351 and the top. Experience has shown that it is unwise to design \.{DVI}-to-printer
12352 software that attempts cleverly to center the output; a fixed position of
12353 the upper left corner is easiest for users to understand and to work with.
12354 Therefore |l| and~|u| are often ignored.
12355
12356 Parameter |s| is the maximum stack depth (i.e., the largest excess of
12357 |push| commands over |pop| commands) needed to process this file. Then
12358 comes |t|, the total number of pages (|bop| commands) present.
12359
12360 The postamble continues with font definitions, which are any number of
12361 \\{fnt\_def} commands as described above, possibly interspersed with |nop|
12362 commands. Each font number that is used in the \.{DVI} file must be defined
12363 exactly twice: Once before it is first selected by a \\{fnt} command, and once
12364 in the postamble.
12365
12366 @ The last part of the postamble, following the |post_post| byte that
12367 signifies the end of the font definitions, contains |q|, a pointer to the
12368 |post| command that started the postamble. An identification byte, |i|,
12369 comes next; this currently equals~2, as in the preamble.
12370
12371 The |i| byte is followed by four or more bytes that are all equal to
12372 the decimal number 223 (i.e., 0337 in octal). \TeX\ puts out four to seven of
12373 these trailing bytes, until the total length of the file is a multiple of
12374 four bytes, since this works out best on machines that pack four bytes per
12375 word; but any number of 223's is allowed, as long as there are at least four
12376 of them. In effect, 223 is a sort of signature that is added at the very end.
12377 @^Fuchs, David Raymond@>
12378
12379 This curious way to finish off a \.{DVI} file makes it feasible for
12380 \.{DVI}-reading programs to find the postamble first, on most computers,
12381 even though \TeX\ wants to write the postamble last. Most operating
12382 systems permit random access to individual words or bytes of a file, so
12383 the \.{DVI} reader can start at the end and skip backwards over the 223's
12384 until finding the identification byte. Then it can back up four bytes, read
12385 |q|, and move to byte |q| of the file. This byte should, of course,
12386 contain the value 248 (|post|); now the postamble can be read, so the
12387 \.{DVI} reader can discover all the information needed for typesetting the
12388 pages. Note that it is also possible to skip through the \.{DVI} file at
12389 reasonably high speed to locate a particular page, if that proves
12390 desirable. This saves a lot of time, since \.{DVI} files used in production
12391 jobs tend to be large.
12392
12393 Unfortunately, however, standard \PASCAL\ does not include the ability to
12394 @^system dependencies@>
12395 access a random position in a file, or even to determine the length of a file.
12396 Almost all systems nowadays provide the necessary capabilities, so \.{DVI}
12397 format has been designed to work most efficiently with modern operating systems.
12398 But if \.{DVI} files have to be processed under the restrictions of standard
12399 \PASCAL, one can simply read them from front to back, since the necessary
12400 header information is present in the preamble and in the font definitions.
12401 (The |l| and |u| and |s| and |t| parameters, which appear only in the
12402 postamble, are ``frills'' that are handy but not absolutely necessary.)
12403
12404 @* Shipping pages out.
12405 After considering \TeX's eyes and stomach, we come now to the bowels.
12406 @^bowels@>
12407
12408 The |ship_out| procedure is given a pointer to a box; its mission is
12409 to describe that box in \.{DVI} form, outputting a ``page'' to |dvi_file|.
12410 The \.{DVI} coordinates $(h,v)=(0,0)$ should correspond to the upper left
12411 corner of the box being shipped.
12412
12413 Since boxes can be inside of boxes inside of boxes, the main work of
12414 |ship_out| is done by two mutually recursive routines, |hlist_out|
12415 and |vlist_out|, which traverse the hlists and vlists inside of horizontal
12416 and vertical boxes.
12417
12418 As individual pages are being processed, we need to accumulate
12419 information about the entire set of pages, since such statistics must be
12420 reported in the postamble. The global variables |total_pages|, |max_v|,
12421 |max_h|, |max_push|, and |last_bop| are used to record this information.
12422
12423 The variable |doing_leaders| is |true| while leaders are being output.
12424 The variable |dead_cycles| contains the number of times an output routine
12425 has been initiated since the last |ship_out|.
12426
12427 A few additional global variables are also defined here for use in
12428 |vlist_out| and |hlist_out|. They could have been local variables, but
12429 that would waste stack space when boxes are deeply nested, since the
12430 values of these variables are not needed during recursive calls.
12431 @^recursion@>
12432
12433 @<Glob...@>=
12434 static int @!total_pages; /*the number of pages that have been shipped out*/
12435 static scaled @!max_v; /*maximum height-plus-depth of pages shipped so far*/
12436 static scaled @!max_h; /*maximum width of pages shipped so far*/
12437 static int @!max_push; /*deepest nesting of |push| commands encountered so far*/
12438 static int @!last_bop; /*location of previous |bop| in the \.{DVI} output*/
12439 static int @!dead_cycles; /*recent outputs that didn't ship anything out*/
12440 static bool @!doing_leaders; /*are we inside a leader box?*/
12441 @#
12442 static quarterword @!c, @!f; /*character and font in current |char_node|*/
12443 static scaled @!rule_ht, @!rule_dp, @!rule_wd; /*size of current rule being output*/
12444 static pointer @!g; /*current glue specification*/
12445 static int @!lq, @!lr; /*quantities used in calculations for leaders*/
12446
12447 @ @<Set init...@>=
12448 total_pages=0;max_v=0;max_h=0;max_push=0;last_bop=-1;
12449 doing_leaders=false;dead_cycles=0;cur_s=-1;
12450
12451 @ The \.{DVI} bytes are output to a buffer instead of being written directly
12452 to the output file. This makes it possible to reduce the overhead of
12453 subroutine calls, thereby measurably speeding up the computation, since
12454 output of \.{DVI} bytes is part of \TeX's inner loop. And it has another
12455 advantage as well, since we can change instructions in the buffer in order to
12456 make the output more compact. For example, a `|down2|' command can be
12457 changed to a `|y2|', thereby making a subsequent `|y0|' command possible,
12458 saving two bytes.
12459
12460 The output buffer is divided into two parts of equal size; the bytes found
12461 in |dvi_buf[0 dotdot half_buf-1]| constitute the first half, and those in
12462 |dvi_buf[half_buf dotdot dvi_buf_size-1]| constitute the second. The global
12463 variable |dvi_ptr| points to the position that will receive the next
12464 output byte. When |dvi_ptr| reaches |dvi_limit|, which is always equal
12465 to one of the two values |half_buf| or |dvi_buf_size|, the half buffer that
12466 is about to be invaded next is sent to the output and |dvi_limit| is
12467 changed to its other value. Thus, there is always at least a half buffer's
12468 worth of information present, except at the very beginning of the job.
12469
12470 Bytes of the \.{DVI} file are numbered sequentially starting with 0;
12471 the next byte to be generated will be number |dvi_offset+dvi_ptr|.
12472 A byte is present in the buffer only if its number is | >= dvi_gone|.
12473
12474 @<Types...@>=
12475 typedef int16_t dvi_index; /*an index into the output buffer*/
12476
12477 @ Some systems may find it more efficient to make |dvi_buf| a ||
12478 array, since output of four bytes at once may be facilitated.
12479 @^system dependencies@>
12480
12481 @<Glob...@>=
12482 static eight_bits @!dvi_buf[dvi_buf_size+1]; /*buffer for \.{DVI} output*/
12483 static dvi_index @!half_buf; /*half of |dvi_buf_size|*/
12484 static dvi_index @!dvi_limit; /*end of the current half buffer*/
12485 static dvi_index @!dvi_ptr; /*the next available buffer address*/
12486 static int @!dvi_offset; /*|dvi_buf_size| times the number of times the
12487 output buffer has been fully emptied*/
12488 static int @!dvi_gone; /*the number of bytes already output to |dvi_file|*/
12489
12490 @ Initially the buffer is all in one piece; we will output half of it only
12491 after it first fills up.
12492
12493 @<Set init...@>=
12494 half_buf=dvi_buf_size/2;dvi_limit=dvi_buf_size;dvi_ptr=0;
12495 dvi_offset=0;dvi_gone=0;
12496
12497 @ The actual output of |dvi_buf[a dotdot b]| to |dvi_file| is performed by calling
12498 |write_dvi(a, b)|. For best results, this procedure should be optimized to
12499 run as fast as possible on each particular system, since it is part of
12500 \TeX's inner loop. It is safe to assume that |a| and |b+1| will both be
12501 multiples of 4 when |write_dvi(a, b)| is called; therefore it is possible on
12502 many machines to use efficient methods to pack four bytes per word and to
12503 output an array of words with one system call.
12504 @^system dependencies@>
12505 @^inner loop@>
12506 @^defecation@>
12507
12508 @p static void write_dvi(dvi_index @!a, dvi_index @!b)
12509 {@+int k;
12510 for (k=a; k<=b; k++) pascal_write(dvi_file, "%c", dvi_buf[k]);
12511 }
12512
12513 @ To put a byte in the buffer without paying the cost of invoking a procedure
12514 each time, we use the macro |dvi_out|.
12515
12516 @d dvi_out(A) @+{@+dvi_buf[dvi_ptr]=A;incr(dvi_ptr);
12517 if (dvi_ptr==dvi_limit) dvi_swap();
12518 }
12519
12520 @p static void dvi_swap(void) /*outputs half of the buffer*/
12521 {@+if (dvi_limit==dvi_buf_size)
12522 {@+write_dvi(0, half_buf-1);dvi_limit=half_buf;
12523 dvi_offset=dvi_offset+dvi_buf_size;dvi_ptr=0;
12524 }
12525 else{@+write_dvi(half_buf, dvi_buf_size-1);dvi_limit=dvi_buf_size;
12526 }
12527 dvi_gone=dvi_gone+half_buf;
12528 }
12529
12530 @ Here is how we clean out the buffer when \TeX\ is all through; |dvi_ptr|
12531 will be a multiple of~4.
12532
12533 @<Empty the last bytes out of |dvi_buf|@>=
12534 if (dvi_limit==half_buf) write_dvi(half_buf, dvi_buf_size-1);
12535 if (dvi_ptr > 0) write_dvi(0, dvi_ptr-1)
12536
12537 @ The |dvi_four| procedure outputs four bytes in two's complement notation,
12538 without risking arithmetic overflow.
12539
12540 @p static void dvi_four(int @!x)
12541 {@+if (x >= 0) dvi_out(x/0100000000)@;
12542 else{@+x=x+010000000000;
12543 x=x+010000000000;
12544 dvi_out((x/0100000000)+128);
12545 }
12546 x=x%0100000000;dvi_out(x/0200000);
12547 x=x%0200000;dvi_out(x/0400);
12548 dvi_out(x%0400);
12549 }
12550
12551 @ A mild optimization of the output is performed by the |dvi_pop|
12552 routine, which issues a |pop| unless it is possible to cancel a
12553 `|push| |pop|' pair. The parameter to |dvi_pop| is the byte address
12554 following the old |push| that matches the new |pop|.
12555
12556 @p static void dvi_pop(int @!l)
12557 {@+if ((l==dvi_offset+dvi_ptr)&&(dvi_ptr > 0)) decr(dvi_ptr);
12558 else dvi_out(pop);
12559 }
12560
12561 @ Here's a procedure that outputs a font definition. Since \TeX82 uses at
12562 most 256 different fonts per job, |fnt_def1| is always used as the command code.
12563
12564 @p static void dvi_font_def(internal_font_number @!f)
12565 {@+int k; /*index into |str_pool|*/
12566 dvi_out(fnt_def1);
12567 dvi_out(f-font_base-1);@/
12568 dvi_out(qo(font_check[f].b0));
12569 dvi_out(qo(font_check[f].b1));
12570 dvi_out(qo(font_check[f].b2));
12571 dvi_out(qo(font_check[f].b3));@/
12572 dvi_four(font_size[f]);
12573 dvi_four(font_dsize[f]);@/
12574 dvi_out(length(font_area[f]));
12575 dvi_out(length(font_name[f]));
12576 @<Output the font name whose internal number is |f|@>;
12577 }
12578
12579 @ @<Output the font name whose internal number is |f|@>=
12580 for (k=str_start[font_area[f]]; k<=str_start[font_area[f]+1]-1; k++)
12581 dvi_out(so(str_pool[k]));
12582 for (k=str_start[font_name[f]]; k<=str_start[font_name[f]+1]-1; k++)
12583 dvi_out(so(str_pool[k]))
12584
12585 @ Versions of \TeX\ intended for small computers might well choose to omit
12586 the ideas in the next few parts of this program, since it is not really
12587 necessary to optimize the \.{DVI} code by making use of the |w0|, |x0|,
12588 |y0|, and |z0| commands. Furthermore, the algorithm that we are about to
12589 describe does not pretend to give an optimum reduction in the length
12590 of the \.{DVI} code; after all, speed is more important than compactness.
12591 But the method is surprisingly effective, and it takes comparatively little
12592 time.
12593
12594 We can best understand the basic idea by first considering a simpler problem
12595 that has the same essential characteristics. Given a sequence of digits,
12596 say $3\,1\,4\,1\,5\,9\,2\,6\,5\,3\,5\,8\,9$, we want to assign subscripts
12597 $d$, $y$, or $z$ to each digit so as to maximize the number of ``$y$-hits''
12598 and ``$z$-hits''; a $y$-hit is an instance of two appearances of the same
12599 digit with the subscript $y$, where no $y$'s intervene between the two
12600 appearances, and a $z$-hit is defined similarly. For example, the sequence
12601 above could be decorated with subscripts as follows:
12602 $$3_z\,1_y\,4_d\,1_y\,5_y\,9_d\,2_d\,6_d\,5_y\,3_z\,5_y\,8_d\,9_d.$$
12603 There are three $y$-hits ($1_y\ldots1_y$ and $5_y\ldots5_y\ldots5_y$) and
12604 one $z$-hit ($3_z\ldots3_z$); there are no $d$-hits, since the two appearances
12605 of $9_d$ have $d$'s between them, but we don't count $d$-hits so it doesn't
12606 matter how many there are. These subscripts are analogous to the \.{DVI}
12607 commands called \\{down}, $y$, and $z$, and the digits are analogous to
12608 different amounts of vertical motion; a $y$-hit or $z$-hit corresponds to
12609 the opportunity to use the one-byte commands |y0| or |z0| in a \.{DVI} file.
12610
12611 \TeX's method of assigning subscripts works like this: Append a new digit,
12612 say $\delta$, to the right of the sequence. Now look back through the
12613 sequence until one of the following things happens: (a)~You see
12614 $\delta_y$ or $\delta_z$, and this was the first time you encountered a
12615 $y$ or $z$ subscript, respectively. Then assign $y$ or $z$ to the new
12616 $\delta$; you have scored a hit. (b)~You see $\delta_d$, and no $y$
12617 subscripts have been encountered so far during this search. Then change
12618 the previous $\delta_d$ to $\delta_y$ (this corresponds to changing a
12619 command in the output buffer), and assign $y$ to the new $\delta$; it's
12620 another hit. (c)~You see $\delta_d$, and a $y$ subscript has been seen
12621 but not a $z$. Change the previous $\delta_d$ to $\delta_z$ and assign
12622 $z$ to the new $\delta$. (d)~You encounter both $y$ and $z$ subscripts
12623 before encountering a suitable $\delta$, or you scan all the way to the
12624 front of the sequence. Assign $d$ to the new $\delta$; this assignment may
12625 be changed later.
12626
12627 The subscripts $3_z\,1_y\,4_d\ldots\,$ in the example above were, in fact,
12628 produced by this procedure, as the reader can verify. (Go ahead and try it.)
12629
12630 @ In order to implement such an idea, \TeX\ maintains a stack of pointers
12631 to the \\{down}, $y$, and $z$ commands that have been generated for the
12632 current page. And there is a similar stack for \\{right}, |w|, and |x|
12633 commands. These stacks are called the down stack and right stack, and their
12634 top elements are maintained in the variables |down_ptr| and |right_ptr|.
12635
12636 Each entry in these stacks contains four fields: The |width| field is
12637 the amount of motion down or to the right; the |location| field is the
12638 byte number of the \.{DVI} command in question (including the appropriate
12639 |dvi_offset|); the |link| field points to the next item below this one
12640 on the stack; and the |info| field encodes the options for possible change
12641 in the \.{DVI} command.
12642
12643 @d movement_node_size 3 /*number of words per entry in the down and right stacks*/
12644 @d location(A) mem[A+2].i /*\.{DVI} byte number for a movement command*/
12645
12646 @<Glob...@>=
12647 static pointer @!down_ptr, @!right_ptr; /*heads of the down and right stacks*/
12648
12649 @ @<Set init...@>=
12650 down_ptr=null;right_ptr=null;
12651
12652 @ Here is a subroutine that produces a \.{DVI} command for some specified
12653 downward or rightward motion. It has two parameters: |w| is the amount
12654 of motion, and |o| is either |down1| or |right1|. We use the fact that
12655 the command codes have convenient arithmetic properties: |y1-down1==w1-right1|
12656 and |z1-down1==x1-right1|.
12657
12658 @p static void movement(scaled @!w, eight_bits @!o)
12659 {@+
12660 small_number mstate; /*have we seen a |y| or |z|?*/
12661 pointer @!p, @!q; /*current and top nodes on the stack*/
12662 int @!k; /*index into |dvi_buf|, modulo |dvi_buf_size|*/
12663 q=get_node(movement_node_size); /*new node for the top of the stack*/
12664 width(q)=w;location(q)=dvi_offset+dvi_ptr;
12665 if (o==down1)
12666 {@+link(q)=down_ptr;down_ptr=q;
12667 }
12668 else{@+link(q)=right_ptr;right_ptr=q;
12669 }
12670 @<Look at the other stack entries until deciding what sort of \.{DVI} command
12671 to generate; |goto found| if node |p| is a ``hit''@>;
12672 @<Generate a |down| or |right| command for |w| and |return|@>;
12673 found: @<Generate a |y0| or |z0| command in order to reuse a previous appearance
12674 of~|w|@>;
12675 }
12676
12677 @ The |info| fields in the entries of the down stack or the right stack
12678 have six possible settings: |y_here| or |z_here| mean that the \.{DVI}
12679 command refers to |y| or |z|, respectively (or to |w| or |x|, in the
12680 case of horizontal motion); |yz_OK| means that the \.{DVI} command is
12681 \\{down} (or \\{right}) but can be changed to either |y| or |z| (or
12682 to either |w| or |x|); |y_OK| means that it is \\{down} and can be changed
12683 to |y| but not |z|; |z_OK| is similar; and |d_fixed| means it must stay
12684 \\{down}.
12685
12686 The four settings |yz_OK|, |y_OK|, |z_OK|, |d_fixed| would not need to
12687 be distinguished from each other if we were simply solving the
12688 digit-subscripting problem mentioned above. But in \TeX's case there is
12689 a complication because of the nested structure of |push| and |pop|
12690 commands. Suppose we add parentheses to the digit-subscripting problem,
12691 redefining hits so that $\delta_y\ldots \delta_y$ is a hit if all $y$'s between
12692 the $\delta$'s are enclosed in properly nested parentheses, and if the
12693 parenthesis level of the right-hand $\delta_y$ is deeper than or equal to
12694 that of the left-hand one. Thus, `(' and `)' correspond to `|push|'
12695 and `|pop|'. Now if we want to assign a subscript to the final 1 in the
12696 sequence
12697 $$2_y\,7_d\,1_d\,(\,8_z\,2_y\,8_z\,)\,1$$
12698 we cannot change the previous $1_d$ to $1_y$, since that would invalidate
12699 the $2_y\ldots2_y$ hit. But we can change it to $1_z$, scoring a hit
12700 since the intervening $8_z$'s are enclosed in parentheses.
12701
12702 The program below removes movement nodes that are introduced after a |push|,
12703 before it outputs the corresponding |pop|.
12704
12705 @d y_here 1 /*|info| when the movement entry points to a |y| command*/
12706 @d z_here 2 /*|info| when the movement entry points to a |z| command*/
12707 @d yz_OK 3 /*|info| corresponding to an unconstrained \\{down} command*/
12708 @d y_OK 4 /*|info| corresponding to a \\{down} that can't become a |z|*/
12709 @d z_OK 5 /*|info| corresponding to a \\{down} that can't become a |y|*/
12710 @d d_fixed 6 /*|info| corresponding to a \\{down} that can't change*/
12711
12712 @ When the |movement| procedure gets to the label |found|, the value of
12713 |info(p)| will be either |y_here| or |z_here|. If it is, say, |y_here|,
12714 the procedure generates a |y0| command (or a |w0| command), and marks
12715 all |info| fields between |q| and |p| so that |y| is not OK in that range.
12716
12717 @<Generate a |y0| or |z0| command...@>=
12718 info(q)=info(p);
12719 if (info(q)==y_here)
12720 {@+dvi_out(o+y0-down1); /*|y0| or |w0|*/
12721 while (link(q)!=p)
12722 {@+q=link(q);
12723 switch (info(q)) {
12724 case yz_OK: info(q)=z_OK;@+break;
12725 case y_OK: info(q)=d_fixed;@+break;
12726 default:do_nothing;
12727 }
12728 }
12729 }
12730 else{@+dvi_out(o+z0-down1); /*|z0| or |x0|*/
12731 while (link(q)!=p)
12732 {@+q=link(q);
12733 switch (info(q)) {
12734 case yz_OK: info(q)=y_OK;@+break;
12735 case z_OK: info(q)=d_fixed;@+break;
12736 default:do_nothing;
12737 }
12738 }
12739 }
12740
12741 @ @<Generate a |down| or |right|...@>=
12742 info(q)=yz_OK;
12743 if (abs(w) >= 040000000)
12744 {@+dvi_out(o+3); /*|down4| or |right4|*/
12745 dvi_four(w);return;
12746 }
12747 if (abs(w) >= 0100000)
12748 {@+dvi_out(o+2); /*|down3| or |right3|*/
12749 if (w < 0) w=w+0100000000;
12750 dvi_out(w/0200000);w=w%0200000;goto label2;
12751 }
12752 if (abs(w) >= 0200)
12753 {@+dvi_out(o+1); /*|down2| or |right2|*/
12754 if (w < 0) w=w+0200000;
12755 goto label2;
12756 }
12757 dvi_out(o); /*|down1| or |right1|*/
12758 if (w < 0) w=w+0400;
12759 goto label1;
12760 label2: dvi_out(w/0400);
12761 label1: dvi_out(w%0400);return
12762
12763 @ As we search through the stack, we are in one of three states,
12764 |y_seen|, |z_seen|, or |none_seen|, depending on whether we have
12765 encountered |y_here| or |z_here| nodes. These states are encoded as
12766 multiples of 6, so that they can be added to the |info| fields for quick
12767 decision-making.
12768 @^inner loop@>
12769
12770 @d none_seen 0 /*no |y_here| or |z_here| nodes have been encountered yet*/
12771 @d y_seen 6 /*we have seen |y_here| but not |z_here|*/
12772 @d z_seen 12 /*we have seen |z_here| but not |y_here|*/
12773
12774 @<Look at the other stack entries until deciding...@>=
12775 p=link(q);mstate=none_seen;
12776 while (p!=null)
12777 {@+if (width(p)==w) @<Consider a node with matching width; |goto found|
12778 if it's a hit@>@;
12779 else switch (mstate+info(p)) {
12780 case none_seen+y_here: mstate=y_seen;@+break;
12781 case none_seen+z_here: mstate=z_seen;@+break;
12782 case y_seen+z_here: case z_seen+y_here: goto not_found;
12783 default:do_nothing;
12784 }
12785 p=link(p);
12786 }
12787 not_found:
12788
12789 @ We might find a valid hit in a |y| or |z| byte that is already gone
12790 from the buffer. But we can't change bytes that are gone forever; ``the
12791 moving finger writes, $\ldots\,\,$.''
12792
12793 @<Consider a node with matching width...@>=
12794 switch (mstate+info(p)) {
12795 case none_seen+yz_OK: case none_seen+y_OK:
12796 case z_seen+yz_OK: case z_seen+y_OK: @t@>@;@/
12797 if (location(p) < dvi_gone) goto not_found;
12798 else@<Change buffered instruction to |y| or |w| and |goto found|@>@;@+break;
12799 case none_seen+z_OK: case y_seen+yz_OK:
12800 case y_seen+z_OK: @t@>@;@/
12801 if (location(p) < dvi_gone) goto not_found;
12802 else@<Change buffered instruction to |z| or |x| and |goto found|@>@;@+break;
12803 case none_seen+y_here: case none_seen+z_here:
12804 case y_seen+z_here: case z_seen+y_here: goto found;
12805 default:do_nothing;
12806 }
12807
12808 @ @<Change buffered instruction to |y| or |w| and |goto found|@>=
12809 {@+k=location(p)-dvi_offset;
12810 if (k < 0) k=k+dvi_buf_size;
12811 dvi_buf[k]=dvi_buf[k]+y1-down1;
12812 info(p)=y_here;goto found;
12813 }
12814
12815 @ @<Change buffered instruction to |z| or |x| and |goto found|@>=
12816 {@+k=location(p)-dvi_offset;
12817 if (k < 0) k=k+dvi_buf_size;
12818 dvi_buf[k]=dvi_buf[k]+z1-down1;
12819 info(p)=z_here;goto found;
12820 }
12821
12822 @ In case you are wondering when all the movement nodes are removed from
12823 \TeX's memory, the answer is that they are recycled just before
12824 |hlist_out| and |vlist_out| finish outputting a box. This restores the
12825 down and right stacks to the state they were in before the box was output,
12826 except that some |info|'s may have become more restrictive.
12827
12828 @p static void prune_movements(int @!l)
12829 /*delete movement nodes with |location >= l|*/
12830 {@+
12831 pointer p; /*node being deleted*/
12832 while (down_ptr!=null)
12833 {@+if (location(down_ptr) < l) goto done;
12834 p=down_ptr;down_ptr=link(p);free_node(p, movement_node_size);
12835 }
12836 done: while (right_ptr!=null)
12837 {@+if (location(right_ptr) < l) return;
12838 p=right_ptr;right_ptr=link(p);free_node(p, movement_node_size);
12839 }
12840 }
12841
12842 @ The actual distances by which we want to move might be computed as the
12843 sum of several separate movements. For example, there might be several
12844 glue nodes in succession, or we might want to move right by the width of
12845 some box plus some amount of glue. More importantly, the baselineskip
12846 distances are computed in terms of glue together with the depth and
12847 height of adjacent boxes, and we want the \.{DVI} file to lump these
12848 three quantities together into a single motion.
12849
12850 Therefore, \TeX\ maintains two pairs of global variables: |dvi_h| and |dvi_v|
12851 are the |h| and |v| coordinates corresponding to the commands actually
12852 output to the \.{DVI} file, while |cur_h| and |cur_v| are the coordinates
12853 corresponding to the current state of the output routines. Coordinate
12854 changes will accumulate in |cur_h| and |cur_v| without being reflected
12855 in the output, until such a change becomes necessary or desirable; we
12856 can call the |movement| procedure whenever we want to make |dvi_h==cur_h|
12857 or |dvi_v==cur_v|.
12858
12859 The current font reflected in the \.{DVI} output is called |dvi_f|;
12860 there is no need for a `\\{cur\_f}' variable.
12861
12862 The depth of nesting of |hlist_out| and |vlist_out| is called |cur_s|;
12863 this is essentially the depth of |push| commands in the \.{DVI} output.
12864
12865 @d synch_h if (cur_h!=dvi_h)
12866 {@+movement(cur_h-dvi_h, right1);dvi_h=cur_h;
12867 }
12868 @d synch_v if (cur_v!=dvi_v)
12869 {@+movement(cur_v-dvi_v, down1);dvi_v=cur_v;
12870 }
12871
12872 @<Glob...@>=
12873 static scaled @!dvi_h, @!dvi_v; /*a \.{DVI} reader program thinks we are here*/
12874 static scaled @!cur_h, @!cur_v; /*\TeX\ thinks we are here*/
12875 static internal_font_number @!dvi_f; /*the current font*/
12876 static int @!cur_s; /*current depth of output box nesting, initially $-1$*/
12877
12878 @ @<Initialize variables as |ship_out| begins@>=
12879 dvi_h=0;dvi_v=0;cur_h=h_offset;dvi_f=null_font;
12880 ensure_dvi_open;
12881 if (total_pages==0)
12882 {@+dvi_out(pre);dvi_out(id_byte); /*output the preamble*/
12883 @^preamble of \.{DVI} file@>
12884 dvi_four(25400000);dvi_four(473628672); /*conversion ratio for sp*/
12885 prepare_mag();dvi_four(mag); /*magnification factor is frozen*/
12886 old_setting=selector;selector=new_string;
12887 print(" TeX output ");print_int(year);print_char('.');
12888 print_two(month);print_char('.');print_two(day);
12889 print_char(':');print_two(time/60);
12890 print_two(time%60);
12891 selector=old_setting;dvi_out(cur_length);
12892 for (s=str_start[str_ptr]; s<=pool_ptr-1; s++) dvi_out(so(str_pool[s]));
12893 pool_ptr=str_start[str_ptr]; /*flush the current string*/
12894 }
12895
12896 @ When |hlist_out| is called, its duty is to output the box represented
12897 by the |hlist_node| pointed to by |temp_ptr|. The reference point of that
12898 box has coordinates |(cur_h, cur_v)|.
12899
12900 Similarly, when |vlist_out| is called, its duty is to output the box represented
12901 by the |vlist_node| pointed to by |temp_ptr|. The reference point of that
12902 box has coordinates |(cur_h, cur_v)|.
12903 @^recursion@>
12904
12905 @p static void vlist_out(void); /*|hlist_out| and |vlist_out| are mutually
12906 recursive*/
12907
12908 @ The recursive procedures |hlist_out| and |vlist_out| each have local variables
12909 |save_h| and |save_v| to hold the values of |dvi_h| and |dvi_v| just before
12910 entering a new level of recursion. In effect, the values of |save_h| and
12911 |save_v| on \TeX's run-time stack correspond to the values of |h| and |v|
12912 that a \.{DVI}-reading program will push onto its coordinate stack.
12913
12914 @p @t\4@>@<Declare procedures needed in |hlist_out|, |vlist_out|@>@t@>@/
12915 static void hlist_out(void) /*output an |hlist_node| box*/
12916 {@+
12917 scaled base_line; /*the baseline coordinate for this box*/
12918 scaled @!left_edge; /*the left coordinate for this box*/
12919 scaled @!save_h, @!save_v; /*what |dvi_h| and |dvi_v| should pop to*/
12920 pointer @!this_box; /*pointer to containing box*/
12921 glue_ord @!g_order; /*applicable order of infinity for glue*/
12922 int @!g_sign; /*selects type of glue*/
12923 pointer @!p; /*current position in the hlist*/
12924 int @!save_loc; /*\.{DVI} byte location upon entry*/
12925 pointer @!leader_box; /*the leader box being replicated*/
12926 scaled @!leader_wd; /*width of leader box being replicated*/
12927 scaled @!lx; /*extra space between leader boxes*/
12928 bool @!outer_doing_leaders; /*were we doing leaders?*/
12929 scaled @!edge; /*left edge of sub-box, or right edge of leader space*/
12930 double @!glue_temp; /*glue value before rounding*/
12931 double @!cur_glue; /*glue seen so far*/
12932 scaled @!cur_g; /*rounded equivalent of |cur_glue| times the glue ratio*/
12933 cur_g=0;cur_glue=float_constant(0);
12934 this_box=temp_ptr;g_order=glue_order(this_box);
12935 g_sign=glue_sign(this_box);p=list_ptr(this_box);
12936 incr(cur_s);
12937 if (cur_s > 0) dvi_out(push);
12938 if (cur_s > max_push) max_push=cur_s;
12939 save_loc=dvi_offset+dvi_ptr;base_line=cur_v;left_edge=cur_h;
12940 while (p!=null) @<Output node |p| for |hlist_out| and move to the next node,
12941 maintaining the condition |cur_v=base_line|@>;
12942 prune_movements(save_loc);
12943 if (cur_s > 0) dvi_pop(save_loc);
12944 decr(cur_s);
12945 }
12946
12947 @ We ought to give special care to the efficiency of one part of |hlist_out|,
12948 since it belongs to \TeX's inner loop. When a |char_node| is encountered,
12949 we save a little time by processing several nodes in succession until
12950 reaching a non-|char_node|. The program uses the fact that |set_char_0==0|.
12951 @^inner loop@>
12952
12953 @<Output node |p| for |hlist_out|...@>=
12954 reswitch: if (is_char_node(p))
12955 {@+synch_h;synch_v;
12956 @/do@+{f=font(p);c=character(p);
12957 if (f!=dvi_f) @<Change font |dvi_f| to |f|@>;
12958 if (c >= qi(128)) dvi_out(set1);
12959 dvi_out(qo(c));@/
12960 cur_h=cur_h+char_width(f, char_info(f, c));
12961 p=link(p);
12962 }@+ while (!(!is_char_node(p)));
12963 dvi_h=cur_h;
12964 }
12965 else@<Output the non-|char_node| |p| for |hlist_out| and move to the next
12966 node@>@;
12967
12968 @ @<Change font |dvi_f| to |f|@>=
12969 {@+if (!font_used[f])
12970 {@+dvi_font_def(f);font_used[f]=true;
12971 }
12972 if (f <= 64+font_base) dvi_out(f-font_base-1+fnt_num_0)@;
12973 else{@+dvi_out(fnt1);dvi_out(f-font_base-1);
12974 }
12975 dvi_f=f;
12976 }
12977
12978 @ @<Output the non-|char_node| |p| for |hlist_out|...@>=
12979 {@+switch (type(p)) {
12980 case hlist_node: case vlist_node: @<Output a box in an hlist@>@;@+break;
12981 case rule_node: {@+rule_ht=height(p);rule_dp=depth(p);rule_wd=width(p);
12982 goto fin_rule;
12983 }
12984 case whatsit_node: @<Output the whatsit node |p| in an hlist@>;@+break;
12985 case glue_node: @<Move right or output leaders@>@;
12986 case kern_node: case math_node: cur_h=cur_h+width(p);@+break;
12987 case ligature_node: @<Make node |p| look like a |char_node| and |goto reswitch|@>@;
12988 default:do_nothing;
12989 } @/
12990 goto next_p;
12991 fin_rule: @<Output a rule in an hlist@>;
12992 move_past: cur_h=cur_h+rule_wd;
12993 next_p: p=link(p);
12994 }
12995
12996 @ @<Output a box in an hlist@>=
12997 if (list_ptr(p)==null) cur_h=cur_h+width(p);
12998 else{@+save_h=dvi_h;save_v=dvi_v;
12999 cur_v=base_line+shift_amount(p); /*shift the box down*/
13000 temp_ptr=p;edge=cur_h;
13001 if (type(p)==vlist_node) vlist_out();@+else hlist_out();
13002 dvi_h=save_h;dvi_v=save_v;
13003 cur_h=edge+width(p);cur_v=base_line;
13004 }
13005
13006 @ @<Output a rule in an hlist@>=
13007 if (is_running(rule_ht)) rule_ht=height(this_box);
13008 if (is_running(rule_dp)) rule_dp=depth(this_box);
13009 rule_ht=rule_ht+rule_dp; /*this is the rule thickness*/
13010 if ((rule_ht > 0)&&(rule_wd > 0)) /*we don't output empty rules*/
13011 {@+synch_h;cur_v=base_line+rule_dp;synch_v;
13012 dvi_out(set_rule);dvi_four(rule_ht);dvi_four(rule_wd);
13013 cur_v=base_line;dvi_h=dvi_h+rule_wd;
13014 }
13015
13016 @ @d billion float_constant(1000000000)
13017 @d vet_glue(A) glue_temp=A;
13018 if (glue_temp > billion)
13019 glue_temp=billion;
13020 else if (glue_temp < -billion)
13021 glue_temp=-billion
13022
13023 @<Move right or output leaders@>=
13024 {@+g=glue_ptr(p);rule_wd=width(g)-cur_g;
13025 if (g_sign!=normal)
13026 {@+if (g_sign==stretching)
13027 {@+if (stretch_order(g)==g_order)
13028 {@+cur_glue=cur_glue+stretch(g);
13029 vet_glue(unfix(glue_set(this_box))*cur_glue);
13030 @^real multiplication@>
13031 cur_g=round(glue_temp);
13032 }
13033 }
13034 else if (shrink_order(g)==g_order)
13035 {@+cur_glue=cur_glue-shrink(g);
13036 vet_glue(unfix(glue_set(this_box))*cur_glue);
13037 cur_g=round(glue_temp);
13038 }
13039 }
13040 rule_wd=rule_wd+cur_g;
13041 if (subtype(p) >= a_leaders)
13042 @<Output leaders in an hlist, |goto fin_rule| if a rule or to |next_p| if
13043 done@>;
13044 goto move_past;
13045 }
13046
13047 @ @<Output leaders in an hlist...@>=
13048 {@+leader_box=leader_ptr(p);
13049 if (type(leader_box)==rule_node)
13050 {@+rule_ht=height(leader_box);rule_dp=depth(leader_box);
13051 goto fin_rule;
13052 }
13053 leader_wd=width(leader_box);
13054 if ((leader_wd > 0)&&(rule_wd > 0))
13055 {@+rule_wd=rule_wd+10; /*compensate for floating-point rounding*/
13056 edge=cur_h+rule_wd;lx=0;
13057 @<Let |cur_h| be the position of the first box, and set |leader_wd+lx| to
13058 the spacing between corresponding parts of boxes@>;
13059 while (cur_h+leader_wd <= edge)
13060 @<Output a leader box at |cur_h|, then advance |cur_h| by |leader_wd+lx|@>;
13061 cur_h=edge-10;goto next_p;
13062 }
13063 }
13064
13065 @ The calculations related to leaders require a bit of care. First, in the
13066 case of |a_leaders| (aligned leaders), we want to move |cur_h| to
13067 |left_edge| plus the smallest multiple of |leader_wd| for which the result
13068 is not less than the current value of |cur_h|; i.e., |cur_h| should become
13069 $|left_edge|+|leader_wd|\times\lceil
13070 (|cur_h|-|left_edge|)/|leader_wd|\rceil$. The program here should work in
13071 all cases even though some implementations of \PASCAL\ give nonstandard
13072 results for the |/| operation when |cur_h| is less than |left_edge|.
13073
13074 In the case of |c_leaders| (centered leaders), we want to increase |cur_h|
13075 by half of the excess space not occupied by the leaders; and in the
13076 case of |x_leaders| (expanded leaders) we increase |cur_h|
13077 by $1/(q+1)$ of this excess space, where $q$ is the number of times the
13078 leader box will be replicated. Slight inaccuracies in the division might
13079 accumulate; half of this rounding error is placed at each end of the leaders.
13080
13081 @<Let |cur_h| be the position of the first box,...@>=
13082 if (subtype(p)==a_leaders)
13083 {@+save_h=cur_h;
13084 cur_h=left_edge+leader_wd*((cur_h-left_edge)/leader_wd);
13085 if (cur_h < save_h) cur_h=cur_h+leader_wd;
13086 }
13087 else{@+lq=rule_wd/leader_wd; /*the number of box copies*/
13088 lr=rule_wd%leader_wd; /*the remaining space*/
13089 if (subtype(p)==c_leaders) cur_h=cur_h+(lr/2);
13090 else{@+lx=lr/(lq+1);
13091 cur_h=cur_h+((lr-(lq-1)*lx)/2);
13092 }
13093 }
13094
13095 @ The `\\{synch}' operations here are intended to decrease the number of
13096 bytes needed to specify horizontal and vertical motion in the \.{DVI} output.
13097
13098 @<Output a leader box at |cur_h|,...@>=
13099 {@+cur_v=base_line+shift_amount(leader_box);synch_v;save_v=dvi_v;@/
13100 synch_h;save_h=dvi_h;temp_ptr=leader_box;
13101 outer_doing_leaders=doing_leaders;doing_leaders=true;
13102 if (type(leader_box)==vlist_node) vlist_out();@+else hlist_out();
13103 doing_leaders=outer_doing_leaders;
13104 dvi_v=save_v;dvi_h=save_h;cur_v=base_line;
13105 cur_h=save_h+leader_wd+lx;
13106 }
13107
13108 @ The |vlist_out| routine is similar to |hlist_out|, but a bit simpler.
13109
13110 @p static void vlist_out(void) /*output a |vlist_node| box*/
13111 {@+
13112 scaled left_edge; /*the left coordinate for this box*/
13113 scaled @!top_edge; /*the top coordinate for this box*/
13114 scaled @!save_h, @!save_v; /*what |dvi_h| and |dvi_v| should pop to*/
13115 pointer @!this_box; /*pointer to containing box*/
13116 glue_ord @!g_order; /*applicable order of infinity for glue*/
13117 int @!g_sign; /*selects type of glue*/
13118 pointer @!p; /*current position in the vlist*/
13119 int @!save_loc; /*\.{DVI} byte location upon entry*/
13120 pointer @!leader_box; /*the leader box being replicated*/
13121 scaled @!leader_ht; /*height of leader box being replicated*/
13122 scaled @!lx; /*extra space between leader boxes*/
13123 bool @!outer_doing_leaders; /*were we doing leaders?*/
13124 scaled @!edge; /*bottom boundary of leader space*/
13125 double @!glue_temp; /*glue value before rounding*/
13126 double @!cur_glue; /*glue seen so far*/
13127 scaled @!cur_g; /*rounded equivalent of |cur_glue| times the glue ratio*/
13128 cur_g=0;cur_glue=float_constant(0);
13129 this_box=temp_ptr;g_order=glue_order(this_box);
13130 g_sign=glue_sign(this_box);p=list_ptr(this_box);
13131 incr(cur_s);
13132 if (cur_s > 0) dvi_out(push);
13133 if (cur_s > max_push) max_push=cur_s;
13134 save_loc=dvi_offset+dvi_ptr;left_edge=cur_h;cur_v=cur_v-height(this_box);
13135 top_edge=cur_v;
13136 while (p!=null) @<Output node |p| for |vlist_out| and move to the next node,
13137 maintaining the condition |cur_h=left_edge|@>;
13138 prune_movements(save_loc);
13139 if (cur_s > 0) dvi_pop(save_loc);
13140 decr(cur_s);
13141 }
13142
13143 @ @<Output node |p| for |vlist_out|...@>=
13144 {@+if (is_char_node(p)) confusion("vlistout");
13145 @:this can't happen vlistout}{\quad vlistout@>
13146 else@<Output the non-|char_node| |p| for |vlist_out|@>;
13147 next_p: p=link(p);
13148 }
13149
13150 @ @<Output the non-|char_node| |p| for |vlist_out|@>=
13151 {@+switch (type(p)) {
13152 case hlist_node: case vlist_node: @<Output a box in a vlist@>@;@+break;
13153 case rule_node: {@+rule_ht=height(p);rule_dp=depth(p);rule_wd=width(p);
13154 goto fin_rule;
13155 }
13156 case whatsit_node: @<Output the whatsit node |p| in a vlist@>;@+break;
13157 case glue_node: @<Move down or output leaders@>@;
13158 case kern_node: cur_v=cur_v+width(p);@+break;
13159 default:do_nothing;
13160 } @/
13161 goto next_p;
13162 fin_rule: @<Output a rule in a vlist, |goto next_p|@>;
13163 move_past: cur_v=cur_v+rule_ht;
13164 }
13165
13166 @ The |synch_v| here allows the \.{DVI} output to use one-byte commands
13167 for adjusting |v| in most cases, since the baselineskip distance will
13168 usually be constant.
13169
13170 @<Output a box in a vlist@>=
13171 if (list_ptr(p)==null) cur_v=cur_v+height(p)+depth(p);
13172 else{@+cur_v=cur_v+height(p);synch_v;
13173 save_h=dvi_h;save_v=dvi_v;
13174 cur_h=left_edge+shift_amount(p); /*shift the box right*/
13175 temp_ptr=p;
13176 if (type(p)==vlist_node) vlist_out();@+else hlist_out();
13177 dvi_h=save_h;dvi_v=save_v;
13178 cur_v=save_v+depth(p);cur_h=left_edge;
13179 }
13180
13181 @ @<Output a rule in a vlist...@>=
13182 if (is_running(rule_wd)) rule_wd=width(this_box);
13183 rule_ht=rule_ht+rule_dp; /*this is the rule thickness*/
13184 cur_v=cur_v+rule_ht;
13185 if ((rule_ht > 0)&&(rule_wd > 0)) /*we don't output empty rules*/
13186 {@+synch_h;synch_v;
13187 dvi_out(put_rule);dvi_four(rule_ht);dvi_four(rule_wd);
13188 }
13189 goto next_p
13190
13191 @ @<Move down or output leaders@>=
13192 {@+g=glue_ptr(p);rule_ht=width(g)-cur_g;
13193 if (g_sign!=normal)
13194 {@+if (g_sign==stretching)
13195 {@+if (stretch_order(g)==g_order)
13196 {@+cur_glue=cur_glue+stretch(g);
13197 vet_glue(unfix(glue_set(this_box))*cur_glue);
13198 @^real multiplication@>
13199 cur_g=round(glue_temp);
13200 }
13201 }
13202 else if (shrink_order(g)==g_order)
13203 {@+cur_glue=cur_glue-shrink(g);
13204 vet_glue(unfix(glue_set(this_box))*cur_glue);
13205 cur_g=round(glue_temp);
13206 }
13207 }
13208 rule_ht=rule_ht+cur_g;
13209 if (subtype(p) >= a_leaders)
13210 @<Output leaders in a vlist, |goto fin_rule| if a rule or to |next_p| if
13211 done@>;
13212 goto move_past;
13213 }
13214
13215 @ @<Output leaders in a vlist...@>=
13216 {@+leader_box=leader_ptr(p);
13217 if (type(leader_box)==rule_node)
13218 {@+rule_wd=width(leader_box);rule_dp=0;
13219 goto fin_rule;
13220 }
13221 leader_ht=height(leader_box)+depth(leader_box);
13222 if ((leader_ht > 0)&&(rule_ht > 0))
13223 {@+rule_ht=rule_ht+10; /*compensate for floating-point rounding*/
13224 edge=cur_v+rule_ht;lx=0;
13225 @<Let |cur_v| be the position of the first box, and set |leader_ht+lx| to
13226 the spacing between corresponding parts of boxes@>;
13227 while (cur_v+leader_ht <= edge)
13228 @<Output a leader box at |cur_v|, then advance |cur_v| by |leader_ht+lx|@>;
13229 cur_v=edge-10;goto next_p;
13230 }
13231 }
13232
13233 @ @<Let |cur_v| be the position of the first box,...@>=
13234 if (subtype(p)==a_leaders)
13235 {@+save_v=cur_v;
13236 cur_v=top_edge+leader_ht*((cur_v-top_edge)/leader_ht);
13237 if (cur_v < save_v) cur_v=cur_v+leader_ht;
13238 }
13239 else{@+lq=rule_ht/leader_ht; /*the number of box copies*/
13240 lr=rule_ht%leader_ht; /*the remaining space*/
13241 if (subtype(p)==c_leaders) cur_v=cur_v+(lr/2);
13242 else{@+lx=lr/(lq+1);
13243 cur_v=cur_v+((lr-(lq-1)*lx)/2);
13244 }
13245 }
13246
13247 @ When we reach this part of the program, |cur_v| indicates the top of a
13248 leader box, not its baseline.
13249
13250 @<Output a leader box at |cur_v|,...@>=
13251 {@+cur_h=left_edge+shift_amount(leader_box);synch_h;save_h=dvi_h;@/
13252 cur_v=cur_v+height(leader_box);synch_v;save_v=dvi_v;
13253 temp_ptr=leader_box;
13254 outer_doing_leaders=doing_leaders;doing_leaders=true;
13255 if (type(leader_box)==vlist_node) vlist_out();@+else hlist_out();
13256 doing_leaders=outer_doing_leaders;
13257 dvi_v=save_v;dvi_h=save_h;cur_h=left_edge;
13258 cur_v=save_v-height(leader_box)+leader_ht+lx;
13259 }
13260
13261 @ The |hlist_out| and |vlist_out| procedures are now complete, so we are
13262 ready for the |ship_out| routine that gets them started in the first place.
13263
13264 @p static void ship_out(pointer @!p) /*output the box |p|*/
13265 {@+
13266 int page_loc; /*location of the current |bop|*/
13267 int @!j, @!k; /*indices to first ten count registers*/
13268 int @!s; /*index into |str_pool|*/
13269 int @!old_setting; /*saved |selector| setting*/
13270 @<Local variables to save the profiling context@>@;
13271 @<Charge the time used here on |ship_out|@>@;
13272 if (tracing_output > 0)
13273 {@+print_nl("");print_ln();
13274 print("Completed box being shipped out");
13275 @.Completed box...@>
13276 }
13277 if (term_offset > max_print_line-9) print_ln();
13278 else if ((term_offset > 0)||(file_offset > 0)) print_char(' ');
13279 print_char('[');j=9;
13280 while ((count(j)==0)&&(j > 0)) decr(j);
13281 for (k=0; k<=j; k++)
13282 {@+print_int(count(k));
13283 if (k < j) print_char('.');
13284 }
13285 update_terminal;
13286 if (tracing_output > 0)
13287 {@+print_char(']');
13288 begin_diagnostic();show_box(p);end_diagnostic(true);
13289 }
13290 @<Ship box |p| out@>;
13291 if (tracing_output <= 0) print_char(']');
13292 dead_cycles=0;
13293 update_terminal; /*progress report*/
13294 @<Flush the box from memory, showing statistics if requested@>;
13295 @<restore the previous current file, line, and command@>@;
13296 }
13297
13298 @ @<Flush the box from memory, showing statistics if requested@>=
13299 #ifdef @!STAT
13300 if (tracing_stats > 1)
13301 {@+print_nl("Memory usage before: ");
13302 @.Memory usage...@>
13303 print_int(var_used);print_char('&');
13304 print_int(dyn_used);print_char(';');
13305 }
13306 #endif
13307 flush_node_list(p);
13308 #ifdef @!STAT
13309 if (tracing_stats > 1)
13310 {@+print(" after: ");
13311 print_int(var_used);print_char('&');
13312 print_int(dyn_used);print("; still untouched: ");
13313 print_int(hi_mem_min-lo_mem_max-1);print_ln();
13314 }
13315 #endif
13316
13317 @ @<Ship box |p| out@>=
13318 @<Update the values of |max_h| and |max_v|; but if the page is too large,
13319 |goto done|@>;
13320 @<Initialize variables as |ship_out| begins@>;
13321 page_loc=dvi_offset+dvi_ptr;
13322 dvi_out(bop);
13323 for (k=0; k<=9; k++) dvi_four(count(k));
13324 dvi_four(last_bop);last_bop=page_loc;
13325 cur_v=height(p)+v_offset;temp_ptr=p;
13326 if (type(p)==vlist_node) vlist_out();@+else hlist_out();
13327 dvi_out(eop);incr(total_pages);cur_s=-1;
13328 done:
13329
13330 @ Sometimes the user will generate a huge page because other error messages
13331 are being ignored. Such pages are not output to the \.{dvi} file, since they
13332 may confuse the printing software.
13333
13334 @<Update the values of |max_h| and |max_v|; but if the page is too large...@>=
13335 if ((height(p) > max_dimen)||@|(depth(p) > max_dimen)||@|
13336 (height(p)+depth(p)+v_offset > max_dimen)||@|
13337 (width(p)+h_offset > max_dimen))
13338 {@+print_err("Huge page cannot be shipped out");
13339 @.Huge page...@>
13340 help2("The page just created is more than 18 feet tall or",@/
13341 "more than 18 feet wide, so I suspect something went wrong.");
13342 error();
13343 if (tracing_output <= 0)
13344 {@+begin_diagnostic();
13345 print_nl("The following box has been deleted:");
13346 @.The following...deleted@>
13347 show_box(p);
13348 end_diagnostic(true);
13349 }
13350 goto done;
13351 }
13352 if (height(p)+depth(p)+v_offset > max_v) max_v=height(p)+depth(p)+v_offset;
13353 if (width(p)+h_offset > max_h) max_h=width(p)+h_offset
13354
13355 @ At the end of the program, we must finish things off by writing the
13356 post\-amble. If |total_pages==0|, the \.{DVI} file was never opened.
13357 If |total_pages >= 65536|, the \.{DVI} file will lie. And if
13358 |max_push >= 65536|, the user deserves whatever chaos might ensue.
13359
13360 An integer variable |k| will be declared for use by this routine.
13361
13362 @<Finish the \.{DVI} file@>=
13363 while (cur_s > -1)
13364 {@+if (cur_s > 0) dvi_out(pop)@;
13365 else{@+dvi_out(eop);incr(total_pages);
13366 }
13367 decr(cur_s);
13368 }
13369 if (total_pages==0) print_nl("No pages of output.");
13370 @.No pages of output@>
13371 else{@+dvi_out(post); /*beginning of the postamble*/
13372 dvi_four(last_bop);last_bop=dvi_offset+dvi_ptr-5; /*|post| location*/
13373 dvi_four(25400000);dvi_four(473628672); /*conversion ratio for sp*/
13374 prepare_mag();dvi_four(mag); /*magnification factor*/
13375 dvi_four(max_v);dvi_four(max_h);@/
13376 dvi_out(max_push/256);dvi_out(max_push%256);@/
13377 dvi_out((total_pages/256)%256);dvi_out(total_pages%256);@/
13378 @<Output the font definitions for all fonts that were used@>;
13379 dvi_out(post_post);dvi_four(last_bop);dvi_out(id_byte);@/
13380 k=4+((dvi_buf_size-dvi_ptr)%4); /*the number of 223's*/
13381 while (k > 0)
13382 {@+dvi_out(223);decr(k);
13383 }
13384 @<Empty the last bytes out of |dvi_buf|@>;
13385 print_nl("Output written on ");slow_print(output_file_name);
13386 @.Output written on x@>
13387 print(" (");print_int(total_pages);print(" page");
13388 if (total_pages!=1) print_char('s');
13389 print(", ");print_int(dvi_offset+dvi_ptr);print(" bytes).");
13390 b_close(&dvi_file);
13391 }
13392
13393 @ @<Output the font definitions...@>=
13394 while (font_ptr > font_base)
13395 {@+if (font_used[font_ptr]) dvi_font_def(font_ptr);
13396 decr(font_ptr);
13397 }
13398
13399 @* Packaging.
13400 We're essentially done with the parts of \TeX\ that are concerned with
13401 the input (|get_next|) and the output (|ship_out|). So it's time to
13402 get heavily into the remaining part, which does the real work of typesetting.
13403
13404 After lists are constructed, \TeX\ wraps them up and puts them into boxes.
13405 Two major subroutines are given the responsibility for this task: |hpack|
13406 applies to horizontal lists (hlists) and |vpack| applies to vertical lists
13407 (vlists). The main duty of |hpack| and |vpack| is to compute the dimensions
13408 of the resulting boxes, and to adjust the glue if one of those dimensions
13409 is pre-specified. The computed sizes normally enclose all of the material
13410 inside the new box; but some items may stick out if negative glue is used,
13411 if the box is overfull, or if a \.{\\vbox} includes other boxes that have
13412 been shifted left.
13413
13414 The subroutine call |hpack(p, w, m)| returns a pointer to an |hlist_node|
13415 for a box containing the hlist that starts at |p|. Parameter |w| specifies
13416 a width; and parameter |m| is either `|exactly|' or `|additional|'. Thus,
13417 |hpack(p, w, exactly)| produces a box whose width is exactly |w|, while
13418 |hpack(p, w, additional)| yields a box whose width is the natural width plus
13419 |w|. It is convenient to define a macro called `|natural|' to cover the
13420 most common case, so that we can say |hpack(p, natural)| to get a box that
13421 has the natural width of list |p|.
13422
13423 Similarly, |vpack(p, w, m)| returns a pointer to a |vlist_node| for a
13424 box containing the vlist that starts at |p|. In this case |w| represents
13425 a height instead of a width; the parameter |m| is interpreted as in |hpack|.
13426
13427 @d exactly 0 /*a box dimension is pre-specified*/
13428 @d additional 1 /*a box dimension is increased from the natural one*/
13429 @d natural 0, additional /*shorthand for parameters to |hpack| and |vpack|*/
13430
13431 @ The parameters to |hpack| and |vpack| correspond to \TeX's primitives
13432 like `\.{\\hbox} \.{to} \.{300pt}', `\.{\\hbox} \.{spread} \.{10pt}'; note
13433 that `\.{\\hbox}' with no dimension following it is equivalent to
13434 `\.{\\hbox} \.{spread} \.{0pt}'. The |scan_spec| subroutine scans such
13435 constructions in the user's input, including the mandatory left brace that
13436 follows them, and it puts the specification onto |save_stack| so that the
13437 desired box can later be obtained by executing the following code:
13438 $$\vbox{\halign{#\hfil\cr
13439 |save_ptr=save_ptr-2;|\cr
13440 |hpack(p, saved(1), saved(0)).|\cr}}$$
13441 Special care is necessary to ensure that the special |save_stack| codes
13442 are placed just below the new group code, because scanning can change
13443 |save_stack| when \.{\\csname} appears.
13444
13445 @p static void scan_spec(group_code @!c, bool @!three_codes)
13446 /*scans a box specification and left brace*/
13447 {@+
13448 int @!s; /*temporarily saved value*/
13449 int @!spec_code;
13450 if (three_codes) s=saved(0);
13451 if (scan_keyword("to")) spec_code=exactly;
13452 @.to@>
13453 else if (scan_keyword("spread")) spec_code=additional;
13454 @.spread@>
13455 else{@+spec_code=additional;cur_val=0;
13456 goto found;
13457 }
13458 scan_normal_dimen;
13459 found: if (three_codes)
13460 {@+saved(0)=s;incr(save_ptr);
13461 }
13462 saved(0)=spec_code;saved(1)=cur_val;save_ptr=save_ptr+2;
13463 new_save_level(c);scan_left_brace();
13464 }
13465
13466 @ To figure out the glue setting, |hpack| and |vpack| determine how much
13467 stretchability and shrinkability are present, considering all four orders
13468 of infinity. The highest order of infinity that has a nonzero coefficient
13469 is then used as if no other orders were present.
13470
13471 For example, suppose that the given list contains six glue nodes with
13472 the respective stretchabilities 3pt, 8fill, 5fil, 6pt, $-3$fil, $-8$fill.
13473 Then the total is essentially 2fil; and if a total additional space of 6pt
13474 is to be achieved by stretching, the actual amounts of stretch will be
13475 0pt, 0pt, 15pt, 0pt, $-9$pt, and 0pt, since only `fil' glue will be
13476 considered. (The `fill' glue is therefore not really stretching infinitely
13477 with respect to `fil'; nobody would actually want that to happen.)
13478
13479 The arrays |total_stretch| and |total_shrink| are used to determine how much
13480 glue of each kind is present. A global variable |last_badness| is used
13481 to implement \.{\\badness}.
13482
13483 @<Glob...@>=
13484 static scaled @!total_stretch0[filll-normal+1],
13485 *const @!total_stretch = @!total_stretch0-normal,
13486 @!total_shrink0[filll-normal+1], *const @!total_shrink = @!total_shrink0-normal;
13487 /*glue found by |hpack| or |vpack|*/
13488 static int @!last_badness; /*badness of the most recently packaged box*/
13489
13490 @ If the global variable |adjust_tail| is non-null, the |hpack| routine
13491 also removes all occurrences of |ins_node|, |mark_node|, and |adjust_node|
13492 items and appends the resulting material onto the list that ends at
13493 location |adjust_tail|.
13494
13495 @<Glob...@>=
13496 static pointer @!adjust_tail; /*tail of adjustment list*/
13497
13498 @ @<Set init...@>=adjust_tail=null;last_badness=0;
13499
13500 @ Here now is |hpack|, which contains few if any surprises.
13501
13502 @p static pointer hpack(pointer @!p, scaled @!w, small_number @!m)
13503 {@+
13504 pointer r; /*the box node that will be returned*/
13505 pointer @!q; /*trails behind |p|*/
13506 scaled @!h, @!d, @!x; /*height, depth, and natural width*/
13507 scaled @!s; /*shift amount*/
13508 pointer @!g; /*points to a glue specification*/
13509 glue_ord @!o; /*order of infinity*/
13510 internal_font_number @!f; /*the font in a |char_node|*/
13511 four_quarters @!i; /*font information about a |char_node|*/
13512 eight_bits @!hd; /*height and depth indices for a character*/
13513 last_badness=0;r=get_node(box_node_size);type(r)=hlist_node;
13514 subtype(r)=min_quarterword;shift_amount(r)=0;
13515 q=r+list_offset;link(q)=p;@/
13516 h=0;@<Clear dimensions to zero@>;
13517 while (p!=null) @<Examine node |p| in the hlist, taking account of its effect
13518 on the dimensions of the new box, or moving it to the adjustment list; then
13519 advance |p| to the next node@>;
13520 if (adjust_tail!=null) link(adjust_tail)=null;
13521 height(r)=h;depth(r)=d;@/
13522 @<Determine the value of |width(r)| and the appropriate glue setting; then
13523 |return| or |goto common_ending|@>;
13524 common_ending: @<Finish issuing a diagnostic message for an overfull or underfull
13525 hbox@>;
13526 end: return r;
13527 }
13528
13529 @ @<Clear dimensions to zero@>=
13530 d=0;x=0;
13531 total_stretch[normal]=0;total_shrink[normal]=0;
13532 total_stretch[fil]=0;total_shrink[fil]=0;
13533 total_stretch[fill]=0;total_shrink[fill]=0;
13534 total_stretch[filll]=0;total_shrink[filll]=0
13535
13536 @ @<Examine node |p| in the hlist, taking account of its effect...@>=
13537 @^inner loop@>
13538 {@+reswitch: while (is_char_node(p))
13539 @<Incorporate character dimensions into the dimensions of the hbox that
13540 will contain~it, then move to the next node@>;
13541 if (p!=null)
13542 {@+switch (type(p)) {
13543 case hlist_node: case vlist_node: case rule_node:
13544 case unset_node:
13545 @<Incorporate box dimensions into the dimensions of the hbox that will
13546 contain~it@>@;@+break;
13547 case ins_node: case mark_node: case adjust_node: if (adjust_tail!=null)
13548 @<Transfer node |p| to the adjustment list@>@;@+break;
13549 case whatsit_node: @<Incorporate a whatsit node into an hbox@>;@+break;
13550 case glue_node: @<Incorporate glue into the horizontal totals@>@;@+break;
13551 case kern_node: case math_node: x=x+width(p);@+break;
13552 case ligature_node: @<Make node |p| look like a |char_node| and |goto reswitch|@>@;
13553 default:do_nothing;
13554 } @/
13555 p=link(p);
13556 }
13557 }
13558
13559
13560 @ @<Make node |p| look like a |char_node| and |goto reswitch|@>=
13561 {@+mem[lig_trick]=mem[lig_char(p)];link(lig_trick)=link(p);
13562 p=lig_trick;goto reswitch;
13563 }
13564
13565 @ The code here implicitly uses the fact that running dimensions are
13566 indicated by |null_flag|, which will be ignored in the calculations
13567 because it is a highly negative number.
13568
13569 @<Incorporate box dimensions into the dimensions of the hbox...@>=
13570 {@+x=x+width(p);
13571 if (type(p) >= rule_node) s=0;@+else s=shift_amount(p);
13572 if (height(p)-s > h) h=height(p)-s;
13573 if (depth(p)+s > d) d=depth(p)+s;
13574 }
13575
13576 @ The following code is part of \TeX's inner loop; i.e., adding another
13577 character of text to the user's input will cause each of these instructions
13578 to be exercised one more time.
13579 @^inner loop@>
13580
13581 @<Incorporate character dimensions into the dimensions of the hbox...@>=
13582 {@+f=font(p);i=char_info(f, character(p));hd=height_depth(i);
13583 x=x+char_width(f, i);@/
13584 s=char_height(f, hd);@+if (s > h) h=s;
13585 s=char_depth(f, hd);@+if (s > d) d=s;
13586 p=link(p);
13587 }
13588
13589 @ Although node |q| is not necessarily the immediate predecessor of node |p|,
13590 it always points to some node in the list preceding |p|. Thus, we can delete
13591 nodes by moving |q| when necessary. The algorithm takes linear time, and the
13592 extra computation does not intrude on the inner loop unless it is necessary
13593 to make a deletion.
13594 @^inner loop@>
13595
13596 @<Transfer node |p| to the adjustment list@>=
13597 {@+while (link(q)!=p) q=link(q);
13598 if (type(p)==adjust_node)
13599 {@+link(adjust_tail)=adjust_ptr(p);
13600 while (link(adjust_tail)!=null) adjust_tail=link(adjust_tail);
13601 p=link(p);free_node(link(q), small_node_size);
13602 }
13603 else{@+link(adjust_tail)=p;adjust_tail=p;p=link(p);
13604 }
13605 link(q)=p;p=q;
13606 }
13607
13608 @ @<Incorporate glue into the horizontal totals@>=
13609 {@+g=glue_ptr(p);x=x+width(g);@/
13610 o=stretch_order(g);total_stretch[o]=total_stretch[o]+stretch(g);
13611 o=shrink_order(g);total_shrink[o]=total_shrink[o]+shrink(g);
13612 if (subtype(p) >= a_leaders)
13613 {@+g=leader_ptr(p);
13614 if (height(g) > h) h=height(g);
13615 if (depth(g) > d) d=depth(g);
13616 }
13617 }
13618
13619 @ When we get to the present part of the program, |x| is the natural width
13620 of the box being packaged.
13621
13622 @<Determine the value of |width(r)| and the appropriate glue setting...@>=
13623 if (m==additional) w=x+w;
13624 width(r)=w;x=w-x; /*now |x| is the excess to be made up*/
13625 if (x==0)
13626 {@+glue_sign(r)=normal;glue_order(r)=normal;
13627 set_glue_ratio_zero(glue_set(r));
13628 goto end;
13629 }
13630 else if (x > 0) @<Determine horizontal glue stretch setting, then |return|
13631 or \hbox{|goto common_ending|}@>@;
13632 else@<Determine horizontal glue shrink setting, then |return| or \hbox{|goto
13633 common_ending|}@>@;
13634
13635 @ @<Determine horizontal glue stretch setting...@>=
13636 {@+@<Determine the stretch order@>;
13637 glue_order(r)=o;glue_sign(r)=stretching;
13638 if (total_stretch[o]!=0) glue_set(r)=fix(x/(double)total_stretch[o]);
13639 @^real division@>
13640 else{@+glue_sign(r)=normal;
13641 set_glue_ratio_zero(glue_set(r)); /*there's nothing to stretch*/
13642 }
13643 if (o==normal) if (list_ptr(r)!=null)
13644 @<Report an underfull hbox and |goto common_ending|, if this box is sufficiently
13645 bad@>;
13646 goto end;
13647 }
13648
13649 @ @<Determine the stretch order@>=
13650 if (total_stretch[filll]!=0) o=filll;
13651 else if (total_stretch[fill]!=0) o=fill;
13652 else if (total_stretch[fil]!=0) o=fil;
13653 else o=normal
13654
13655 @ @<Report an underfull hbox and |goto common_ending|, if...@>=
13656 {@+last_badness=badness(x, total_stretch[normal]);
13657 if (last_badness > hbadness)
13658 {@+print_ln();
13659 if (last_badness > 100) print_nl("Underfull");@+else print_nl("Loose");
13660 print(" \\hbox (badness ");print_int(last_badness);
13661 @.Underfull \\hbox...@>
13662 @.Loose \\hbox...@>
13663 goto common_ending;
13664 }
13665 }
13666
13667 @ In order to provide a decent indication of where an overfull or underfull
13668 box originated, we use a global variable |pack_begin_line| that is
13669 set nonzero only when |hpack| is being called by the paragraph builder
13670 or the alignment finishing routine.
13671
13672 @<Glob...@>=
13673 static int @!pack_begin_line; /*source file line where the current paragraph
13674 or alignment began; a negative value denotes alignment*/
13675
13676 @ @<Set init...@>=
13677 pack_begin_line=0;
13678
13679 @ @<Finish issuing a diagnostic message for an overfull or underfull hbox@>=
13680 if (output_active) print(") has occurred while \\output is active");
13681 else{@+if (pack_begin_line!=0)
13682 {@+if (pack_begin_line > 0) print(") in paragraph at lines ");
13683 else print(") in alignment at lines ");
13684 print_int(abs(pack_begin_line));
13685 print("--");
13686 }
13687 else print(") detected at line ");
13688 print_int(line);
13689 }
13690 print_ln();@/
13691 font_in_short_display=null_font;short_display(list_ptr(r));print_ln();@/
13692 begin_diagnostic();show_box(r);end_diagnostic(true)
13693
13694 @ @<Determine horizontal glue shrink setting...@>=
13695 {@+@<Determine the shrink order@>;
13696 glue_order(r)=o;glue_sign(r)=shrinking;
13697 if (total_shrink[o]!=0) glue_set(r)=fix((-x)/(double)total_shrink[o]);
13698 @^real division@>
13699 else{@+glue_sign(r)=normal;
13700 set_glue_ratio_zero(glue_set(r)); /*there's nothing to shrink*/
13701 }
13702 if ((total_shrink[o] < -x)&&(o==normal)&&(list_ptr(r)!=null))
13703 {@+last_badness=1000000;
13704 set_glue_ratio_one(glue_set(r)); /*use the maximum shrinkage*/
13705 @<Report an overfull hbox and |goto common_ending|, if this box is sufficiently
13706 bad@>;
13707 }
13708 else if (o==normal) if (list_ptr(r)!=null)
13709 @<Report a tight hbox and |goto common_ending|, if this box is sufficiently
13710 bad@>;
13711 goto end;
13712 }
13713
13714 @ @<Determine the shrink order@>=
13715 if (total_shrink[filll]!=0) o=filll;
13716 else if (total_shrink[fill]!=0) o=fill;
13717 else if (total_shrink[fil]!=0) o=fil;
13718 else o=normal
13719
13720 @ @<Report an overfull hbox and |goto common_ending|, if...@>=
13721 if ((-x-total_shrink[normal] > hfuzz)||(hbadness < 100))
13722 {@+if ((overfull_rule > 0)&&(-x-total_shrink[normal] > hfuzz))
13723 {@+while (link(q)!=null) q=link(q);
13724 link(q)=new_rule();
13725 width(link(q))=overfull_rule;
13726 }
13727 print_ln();print_nl("Overfull \\hbox (");
13728 @.Overfull \\hbox...@>
13729 print_scaled(-x-total_shrink[normal]);print("pt too wide");
13730 goto common_ending;
13731 }
13732
13733 @ @<Report a tight hbox and |goto common_ending|, if...@>=
13734 {@+last_badness=badness(-x, total_shrink[normal]);
13735 if (last_badness > hbadness)
13736 {@+print_ln();print_nl("Tight \\hbox (badness ");print_int(last_badness);
13737 @.Tight \\hbox...@>
13738 goto common_ending;
13739 }
13740 }
13741
13742 @ The |vpack| subroutine is actually a special case of a slightly more
13743 general routine called |vpackage|, which has four parameters. The fourth
13744 parameter, which is |max_dimen| in the case of |vpack|, specifies the
13745 maximum depth of the page box that is constructed. The depth is first
13746 computed by the normal rules; if it exceeds this limit, the reference
13747 point is simply moved down until the limiting depth is attained.
13748
13749
13750 @p
13751 #define vpack(...) @[vpackage(__VA_ARGS__, max_dimen)@] /*special case of unconstrained depth*/
13752 static pointer vpackage(pointer @!p, scaled @!h, small_number @!m, scaled @!l)
13753 {@+
13754 pointer r; /*the box node that will be returned*/
13755 scaled @!w, @!d, @!x; /*width, depth, and natural height*/
13756 scaled @!s; /*shift amount*/
13757 pointer @!g; /*points to a glue specification*/
13758 glue_ord @!o; /*order of infinity*/
13759 last_badness=0;r=get_node(box_node_size);type(r)=vlist_node;
13760 subtype(r)=min_quarterword;shift_amount(r)=0;
13761 list_ptr(r)=p;@/
13762 w=0;@<Clear dimensions to zero@>;
13763 while (p!=null) @<Examine node |p| in the vlist, taking account of its effect
13764 on the dimensions of the new box; then advance |p| to the next node@>;
13765 width(r)=w;
13766 if (d > l)
13767 {@+x=x+d-l;depth(r)=l;
13768 }
13769 else depth(r)=d;
13770 @<Determine the value of |height(r)| and the appropriate glue setting; then
13771 |return| or |goto common_ending|@>;
13772 common_ending: @<Finish issuing a diagnostic message for an overfull or underfull
13773 vbox@>;
13774 end: return r;
13775 }
13776
13777 @ @<Examine node |p| in the vlist, taking account of its effect...@>=
13778 {@+if (is_char_node(p)) confusion("vpack");
13779 @:this can't happen vpack}{\quad vpack@>
13780 else switch (type(p)) {
13781 case hlist_node: case vlist_node: case rule_node:
13782 case unset_node:
13783 @<Incorporate box dimensions into the dimensions of the vbox that will
13784 contain~it@>@;@+break;
13785 case whatsit_node: @<Incorporate a whatsit node into a vbox@>;@+break;
13786 case glue_node: @<Incorporate glue into the vertical totals@>@;@+break;
13787 case kern_node: {@+x=x+d+width(p);d=0;
13788 } @+break;
13789 default:do_nothing;
13790 }
13791 p=link(p);
13792 }
13793
13794 @ @<Incorporate box dimensions into the dimensions of the vbox...@>=
13795 {@+x=x+d+height(p);d=depth(p);
13796 if (type(p) >= rule_node) s=0;@+else s=shift_amount(p);
13797 if (width(p)+s > w) w=width(p)+s;
13798 }
13799
13800 @ @<Incorporate glue into the vertical totals@>=
13801 {@+x=x+d;d=0;@/
13802 g=glue_ptr(p);x=x+width(g);@/
13803 o=stretch_order(g);total_stretch[o]=total_stretch[o]+stretch(g);
13804 o=shrink_order(g);total_shrink[o]=total_shrink[o]+shrink(g);
13805 if (subtype(p) >= a_leaders)
13806 {@+g=leader_ptr(p);
13807 if (width(g) > w) w=width(g);
13808 }
13809 }
13810
13811 @ When we get to the present part of the program, |x| is the natural height
13812 of the box being packaged.
13813
13814 @<Determine the value of |height(r)| and the appropriate glue setting...@>=
13815 if (m==additional) h=x+h;
13816 height(r)=h;x=h-x; /*now |x| is the excess to be made up*/
13817 if (x==0)
13818 {@+glue_sign(r)=normal;glue_order(r)=normal;
13819 set_glue_ratio_zero(glue_set(r));
13820 goto end;
13821 }
13822 else if (x > 0) @<Determine vertical glue stretch setting, then |return| or
13823 \hbox{|goto common_ending|}@>@;
13824 else@<Determine vertical glue shrink setting, then |return| or \hbox{|goto
13825 common_ending|}@>@;
13826
13827 @ @<Determine vertical glue stretch setting...@>=
13828 {@+@<Determine the stretch order@>;
13829 glue_order(r)=o;glue_sign(r)=stretching;
13830 if (total_stretch[o]!=0) glue_set(r)=fix(x/(double)total_stretch[o]);
13831 @^real division@>
13832 else{@+glue_sign(r)=normal;
13833 set_glue_ratio_zero(glue_set(r)); /*there's nothing to stretch*/
13834 }
13835 if (o==normal) if (list_ptr(r)!=null)
13836 @<Report an underfull vbox and |goto common_ending|, if this box is sufficiently
13837 bad@>;
13838 goto end;
13839 }
13840
13841 @ @<Report an underfull vbox and |goto common_ending|, if...@>=
13842 {@+last_badness=badness(x, total_stretch[normal]);
13843 if (last_badness > vbadness)
13844 {@+print_ln();
13845 if (last_badness > 100) print_nl("Underfull");@+else print_nl("Loose");
13846 print(" \\vbox (badness ");print_int(last_badness);
13847 @.Underfull \\vbox...@>
13848 @.Loose \\vbox...@>
13849 goto common_ending;
13850 }
13851 }
13852
13853 @ @<Finish issuing a diagnostic message for an overfull or underfull vbox@>=
13854 if (output_active) print(") has occurred while \\output is active");
13855 else{@+if (pack_begin_line!=0) /*it's actually negative*/
13856 {@+print(") in alignment at lines ");
13857 print_int(abs(pack_begin_line));
13858 print("--");
13859 }
13860 else print(") detected at line ");
13861 print_int(line);
13862 print_ln();@/
13863 }
13864 begin_diagnostic();show_box(r);end_diagnostic(true)
13865
13866 @ @<Determine vertical glue shrink setting...@>=
13867 {@+@<Determine the shrink order@>;
13868 glue_order(r)=o;glue_sign(r)=shrinking;
13869 if (total_shrink[o]!=0) glue_set(r)=fix((-x)/(double)total_shrink[o]);
13870 @^real division@>
13871 else{@+glue_sign(r)=normal;
13872 set_glue_ratio_zero(glue_set(r)); /*there's nothing to shrink*/
13873 }
13874 if ((total_shrink[o] < -x)&&(o==normal)&&(list_ptr(r)!=null))
13875 {@+last_badness=1000000;
13876 set_glue_ratio_one(glue_set(r)); /*use the maximum shrinkage*/
13877 @<Report an overfull vbox and |goto common_ending|, if this box is sufficiently
13878 bad@>;
13879 }
13880 else if (o==normal) if (list_ptr(r)!=null)
13881 @<Report a tight vbox and |goto common_ending|, if this box is sufficiently
13882 bad@>;
13883 goto end;
13884 }
13885
13886 @ @<Report an overfull vbox and |goto common_ending|, if...@>=
13887 if ((-x-total_shrink[normal] > vfuzz)||(vbadness < 100))
13888 {@+print_ln();print_nl("Overfull \\vbox (");
13889 @.Overfull \\vbox...@>
13890 print_scaled(-x-total_shrink[normal]);print("pt too high");
13891 goto common_ending;
13892 }
13893
13894 @ @<Report a tight vbox and |goto common_ending|, if...@>=
13895 {@+last_badness=badness(-x, total_shrink[normal]);
13896 if (last_badness > vbadness)
13897 {@+print_ln();print_nl("Tight \\vbox (badness ");print_int(last_badness);
13898 @.Tight \\vbox...@>
13899 goto common_ending;
13900 }
13901 }
13902
13903 @ When a box is being appended to the current vertical list, the
13904 baselineskip calculation is handled by the |append_to_vlist| routine.
13905
13906 @p static void append_to_vlist(pointer @!b)
13907 {@+scaled d; /*deficiency of space between baselines*/
13908 pointer @!p; /*a new glue node*/
13909 if (prev_depth > ignore_depth)
13910 {@+d=width(baseline_skip)-prev_depth-height(b);
13911 if (d < line_skip_limit) p=new_param_glue(line_skip_code);
13912 else{@+p=new_skip_param(baseline_skip_code);
13913 width(temp_ptr)=d; /*|temp_ptr==glue_ptr(p)|*/
13914 }
13915 link(tail)=p;tail=p;
13916 }
13917 link(tail)=b;tail=b;prev_depth=depth(b);
13918 }
13919
13920 @* Data structures for math mode.
13921 When \TeX\ reads a formula that is enclosed between \.\$'s, it constructs an
13922 {\sl mlist}, which is essentially a tree structure representing that
13923 formula. An mlist is a linear sequence of items, but we can regard it as
13924 a tree structure because mlists can appear within mlists. For example, many
13925 of the entries can be subscripted or superscripted, and such ``scripts''
13926 are mlists in their own right.
13927
13928 An entire formula is parsed into such a tree before any of the actual
13929 typesetting is done, because the current style of type is usually not
13930 known until the formula has been fully scanned. For example, when the
13931 formula `\.{\$a+b \\over c+d\$}' is being read, there is no way to tell
13932 that `\.{a+b}' will be in script size until `\.{\\over}' has appeared.
13933
13934 During the scanning process, each element of the mlist being built is
13935 classified as a relation, a binary operator, an open parenthesis, etc.,
13936 or as a construct like `\.{\\sqrt}' that must be built up. This classification
13937 appears in the mlist data structure.
13938
13939 After a formula has been fully scanned, the mlist is converted to an hlist
13940 so that it can be incorporated into the surrounding text. This conversion is
13941 controlled by a recursive procedure that decides all of the appropriate
13942 styles by a ``top-down'' process starting at the outermost level and working
13943 in towards the subformulas. The formula is ultimately pasted together using
13944 combinations of horizontal and vertical boxes, with glue and penalty nodes
13945 inserted as necessary.
13946
13947 An mlist is represented internally as a linked list consisting chiefly
13948 of ``noads'' (pronounced ``no-adds''), to distinguish them from the somewhat
13949 similar ``nodes'' in hlists and vlists. Certain kinds of ordinary nodes are
13950 allowed to appear in mlists together with the noads; \TeX\ tells the difference
13951 by means of the |type| field, since a noad's |type| is always greater than
13952 that of a node. An mlist does not contain character nodes, hlist nodes, vlist
13953 nodes, math nodes, ligature nodes,
13954 or unset nodes; in particular, each mlist item appears in the
13955 variable-size part of |mem|, so the |type| field is always present.
13956
13957 @ Each noad is four or more words long. The first word contains the |type|
13958 and |subtype| and |link| fields that are already so familiar to us; the
13959 second, third, and fourth words are called the noad's |nucleus|, |subscr|,
13960 and |supscr| fields.
13961
13962 Consider, for example, the simple formula `\.{\$x\^2\$}', which would be
13963 parsed into an mlist containing a single element called an |ord_noad|.
13964 The |nucleus| of this noad is a representation of `\.x', the |subscr| is
13965 empty, and the |supscr| is a representation of `\.2'.
13966
13967 The |nucleus|, |subscr|, and |supscr| fields are further broken into
13968 subfields. If |p| points to a noad, and if |q| is one of its principal
13969 fields (e.g., |q==subscr(p)|), there are several possibilities for the
13970 subfields, depending on the |math_type| of |q|.
13971
13972 \yskip\hang|math_type(q)==math_char| means that |fam(q)| refers to one of
13973 the sixteen font families, and |character(q)| is the number of a character
13974 within a font of that family, as in a character node.
13975
13976 \yskip\hang|math_type(q)==math_text_char| is similar, but the character is
13977 unsubscripted and unsuperscripted and it is followed immediately by another
13978 character from the same font. (This |math_type| setting appears only
13979 briefly during the processing; it is used to suppress unwanted italic
13980 corrections.)
13981
13982 \yskip\hang|math_type(q)==empty| indicates a field with no value (the
13983 corresponding attribute of noad |p| is not present).
13984
13985 \yskip\hang|math_type(q)==sub_box| means that |info(q)| points to a box
13986 node (either an |hlist_node| or a |vlist_node|) that should be used as the
13987 value of the field. The |shift_amount| in the subsidiary box node is the
13988 amount by which that box will be shifted downward.
13989
13990 \yskip\hang|math_type(q)==sub_mlist| means that |info(q)| points to
13991 an mlist; the mlist must be converted to an hlist in order to obtain
13992 the value of this field.
13993
13994 \yskip\noindent In the latter case, we might have |info(q)==null|. This
13995 is not the same as |math_type(q)==empty|; for example, `\.{\$P\_\{\}\$}'
13996 and `\.{\$P\$}' produce different results (the former will not have the
13997 ``italic correction'' added to the width of |P|, but the ``script skip''
13998 will be added).
13999
14000 The definitions of subfields given here are evidently wasteful of space,
14001 since a halfword is being used for the |math_type| although only three
14002 bits would be needed. However, there are hardly ever many noads present at
14003 once, since they are soon converted to nodes that take up even more space,
14004 so we can afford to represent them in whatever way simplifies the
14005 programming.
14006
14007 @d noad_size 4 /*number of words in a normal noad*/
14008 @d nucleus(A) A+1 /*the |nucleus| field of a noad*/
14009 @d supscr(A) A+2 /*the |supscr| field of a noad*/
14010 @d subscr(A) A+3 /*the |subscr| field of a noad*/
14011 @d math_type(A) link(A) /*a |halfword| in |mem|*/
14012 @d fam font /*a |quarterword| in |mem|*/
14013 @d math_char 1 /*|math_type| when the attribute is simple*/
14014 @d sub_box 2 /*|math_type| when the attribute is a box*/
14015 @d sub_mlist 3 /*|math_type| when the attribute is a formula*/
14016 @d math_text_char 4 /*|math_type| when italic correction is dubious*/
14017
14018 @ Each portion of a formula is classified as Ord, Op, Bin, Rel, Open,
14019 Close, Punct, or Inner, for purposes of spacing and line breaking. An
14020 |ord_noad|, |op_noad|, |bin_noad|, |rel_noad|, |open_noad|, |close_noad|,
14021 |punct_noad|, or |inner_noad| is used to represent portions of the various
14022 types. For example, an `\.=' sign in a formula leads to the creation of a
14023 |rel_noad| whose |nucleus| field is a representation of an equals sign
14024 (usually |fam==0|, |character==075|). A formula preceded by \.{\\mathrel}
14025 also results in a |rel_noad|. When a |rel_noad| is followed by an
14026 |op_noad|, say, and possibly separated by one or more ordinary nodes (not
14027 noads), \TeX\ will insert a penalty node (with the current |rel_penalty|)
14028 just after the formula that corresponds to the |rel_noad|, unless there
14029 already was a penalty immediately following; and a ``thick space'' will be
14030 inserted just before the formula that corresponds to the |op_noad|.
14031
14032 A noad of type |ord_noad|, |op_noad|, \dots, |inner_noad| usually
14033 has a |subtype==normal|. The only exception is that an |op_noad| might
14034 have |subtype==limits| or |no_limits|, if the normal positioning of
14035 limits has been overridden for this operator.
14036
14037 @d ord_noad (unset_node+3) /*|type| of a noad classified Ord*/
14038 @d op_noad (ord_noad+1) /*|type| of a noad classified Op*/
14039 @d bin_noad (ord_noad+2) /*|type| of a noad classified Bin*/
14040 @d rel_noad (ord_noad+3) /*|type| of a noad classified Rel*/
14041 @d open_noad (ord_noad+4) /*|type| of a noad classified Open*/
14042 @d close_noad (ord_noad+5) /*|type| of a noad classified Close*/
14043 @d punct_noad (ord_noad+6) /*|type| of a noad classified Punct*/
14044 @d inner_noad (ord_noad+7) /*|type| of a noad classified Inner*/
14045 @d limits 1 /*|subtype| of |op_noad| whose scripts are to be above, below*/
14046 @d no_limits 2 /*|subtype| of |op_noad| whose scripts are to be normal*/
14047
14048 @ A |radical_noad| is five words long; the fifth word is the |left_delimiter|
14049 field, which usually represents a square root sign.
14050
14051 A |fraction_noad| is six words long; it has a |right_delimiter| field
14052 as well as a |left_delimiter|.
14053
14054 Delimiter fields are of type |four_quarters|, and they have four subfields
14055 called |small_fam|, |small_char|, |large_fam|, |large_char|. These subfields
14056 represent variable-size delimiters by giving the ``small'' and ``large''
14057 starting characters, as explained in Chapter~17 of {\sl The \TeX book}.
14058 @:TeXbook}{\sl The \TeX book@>
14059
14060 A |fraction_noad| is actually quite different from all other noads. Not
14061 only does it have six words, it has |thickness|, |denominator|, and
14062 |numerator| fields instead of |nucleus|, |subscr|, and |supscr|. The
14063 |thickness| is a scaled value that tells how thick to make a fraction
14064 rule; however, the special value |default_code| is used to stand for the
14065 |default_rule_thickness| of the current size. The |numerator| and
14066 |denominator| point to mlists that define a fraction; we always have
14067 $$\hbox{|math_type(numerator)==math_type(denominator)==sub_mlist|}.$$ The
14068 |left_delimiter| and |right_delimiter| fields specify delimiters that will
14069 be placed at the left and right of the fraction. In this way, a
14070 |fraction_noad| is able to represent all of \TeX's operators \.{\\over},
14071 \.{\\atop}, \.{\\above}, \.{\\overwithdelims}, \.{\\atopwithdelims}, and
14072 \.{\\abovewithdelims}.
14073
14074 @d left_delimiter(A) A+4 /*first delimiter field of a noad*/
14075 @d right_delimiter(A) A+5 /*second delimiter field of a fraction noad*/
14076 @d radical_noad (inner_noad+1) /*|type| of a noad for square roots*/
14077 @d radical_noad_size 5 /*number of |mem| words in a radical noad*/
14078 @d fraction_noad (radical_noad+1) /*|type| of a noad for generalized fractions*/
14079 @d fraction_noad_size 6 /*number of |mem| words in a fraction noad*/
14080 @d small_fam(A) mem[A].qqqq.b0 /*|fam| for ``small'' delimiter*/
14081 @d small_char(A) mem[A].qqqq.b1 /*|character| for ``small'' delimiter*/
14082 @d large_fam(A) mem[A].qqqq.b2 /*|fam| for ``large'' delimiter*/
14083 @d large_char(A) mem[A].qqqq.b3 /*|character| for ``large'' delimiter*/
14084 @d thickness(A) width(A) /*|thickness| field in a fraction noad*/
14085 @d default_code 010000000000 /*denotes |default_rule_thickness|*/
14086 @d numerator(A) supscr(A) /*|numerator| field in a fraction noad*/
14087 @d denominator(A) subscr(A) /*|denominator| field in a fraction noad*/
14088
14089 @ The global variable |empty_field| is set up for initialization of empty
14090 fields in new noads. Similarly, |null_delimiter| is for the initialization
14091 of delimiter fields.
14092
14093 @<Glob...@>=
14094 static two_halves @!empty_field;
14095 static four_quarters @!null_delimiter;
14096
14097 @ @<Set init...@>=
14098 empty_field.rh=empty;empty_field.lh=null;@/
14099 null_delimiter.b0=0;null_delimiter.b1=min_quarterword;@/
14100 null_delimiter.b2=0;null_delimiter.b3=min_quarterword;
14101
14102 @ The |new_noad| function creates an |ord_noad| that is completely null.
14103
14104 @p static pointer new_noad(void)
14105 {@+pointer p;
14106 p=get_node(noad_size);
14107 type(p)=ord_noad;subtype(p)=normal;
14108 mem[nucleus(p)].hh=empty_field;
14109 mem[subscr(p)].hh=empty_field;
14110 mem[supscr(p)].hh=empty_field;
14111 return p;
14112 }
14113
14114 @ A few more kinds of noads will complete the set: An |under_noad| has its
14115 nucleus underlined; an |over_noad| has it overlined. An |accent_noad| places
14116 an accent over its nucleus; the accent character appears as
14117 |fam(accent_chr(p))| and |character(accent_chr(p))|. A |vcenter_noad|
14118 centers its nucleus vertically with respect to the axis of the formula;
14119 in such noads we always have |math_type(nucleus(p))==sub_box|.
14120
14121 And finally, we have |left_noad| and |right_noad| types, to implement
14122 \TeX's \.{\\left} and \.{\\right} as well as \eTeX's \.{\\middle}.
14123 The |nucleus| of such noads is
14124 replaced by a |delimiter| field; thus, for example, `\.{\\left(}' produces
14125 a |left_noad| such that |delimiter(p)| holds the family and character
14126 codes for all left parentheses. A |left_noad| never appears in an mlist
14127 except as the first element, and a |right_noad| never appears in an mlist
14128 except as the last element; furthermore, we either have both a |left_noad|
14129 and a |right_noad|, or neither one is present. The |subscr| and |supscr|
14130 fields are always |empty| in a |left_noad| and a |right_noad|.
14131
14132 @d under_noad (fraction_noad+1) /*|type| of a noad for underlining*/
14133 @d over_noad (under_noad+1) /*|type| of a noad for overlining*/
14134 @d accent_noad (over_noad+1) /*|type| of a noad for accented subformulas*/
14135 @d accent_noad_size 5 /*number of |mem| words in an accent noad*/
14136 @d accent_chr(A) A+4 /*the |accent_chr| field of an accent noad*/
14137 @d vcenter_noad (accent_noad+1) /*|type| of a noad for \.{\\vcenter}*/
14138 @d left_noad (vcenter_noad+1) /*|type| of a noad for \.{\\left}*/
14139 @d right_noad (left_noad+1) /*|type| of a noad for \.{\\right}*/
14140 @d delimiter(A) nucleus(A) /*|delimiter| field in left and right noads*/
14141 @d middle_noad 1 /*|subtype| of right noad representing \.{\\middle}*/
14142 @d scripts_allowed(A) (type(A) >= ord_noad)&&(type(A) < left_noad)
14143
14144 @ Math formulas can also contain instructions like \.{\\textstyle} that
14145 override \TeX's normal style rules. A |style_node| is inserted into the
14146 data structure to record such instructions; it is three words long, so it
14147 is considered a node instead of a noad. The |subtype| is either |display_style|
14148 or |text_style| or |script_style| or |script_script_style|. The
14149 second and third words of a |style_node| are not used, but they are
14150 present because a |choice_node| is converted to a |style_node|.
14151
14152 \TeX\ uses even numbers 0, 2, 4, 6 to encode the basic styles
14153 |display_style|, \dots, |script_script_style|, and adds~1 to get the
14154 ``cramped'' versions of these styles. This gives a numerical order that
14155 is backwards from the convention of Appendix~G in {\sl The \TeX book\/};
14156 i.e., a smaller style has a larger numerical value.
14157 @:TeXbook}{\sl The \TeX book@>
14158
14159 @d style_node (unset_node+1) /*|type| of a style node*/
14160 @d style_node_size 3 /*number of words in a style node*/
14161 @d display_style 0 /*|subtype| for \.{\\displaystyle}*/
14162 @d text_style 2 /*|subtype| for \.{\\textstyle}*/
14163 @d script_style 4 /*|subtype| for \.{\\scriptstyle}*/
14164 @d script_script_style 6 /*|subtype| for \.{\\scriptscriptstyle}*/
14165 @d cramped 1 /*add this to an uncramped style if you want to cramp it*/
14166
14167 @p static pointer new_style(small_number @!s) /*create a style node*/
14168 {@+pointer p; /*the new node*/
14169 p=get_node(style_node_size);type(p)=style_node;
14170 subtype(p)=s;width(p)=0;depth(p)=0; /*the |width| and |depth| are not used*/
14171 return p;
14172 }
14173
14174 @ Finally, the \.{\\mathchoice} primitive creates a |choice_node|, which
14175 has special subfields |display_mlist|, |text_mlist|, |script_mlist|,
14176 and |script_script_mlist| pointing to the mlists for each style.
14177
14178 @d choice_node (unset_node+2) /*|type| of a choice node*/
14179 @d display_mlist(A) info(A+1) /*mlist to be used in display style*/
14180 @d text_mlist(A) link(A+1) /*mlist to be used in text style*/
14181 @d script_mlist(A) info(A+2) /*mlist to be used in script style*/
14182 @d script_script_mlist(A) link(A+2) /*mlist to be used in scriptscript style*/
14183
14184 @p static pointer new_choice(void) /*create a choice node*/
14185 {@+pointer p; /*the new node*/
14186 p=get_node(style_node_size);type(p)=choice_node;
14187 subtype(p)=0; /*the |subtype| is not used*/
14188 display_mlist(p)=null;text_mlist(p)=null;script_mlist(p)=null;
14189 script_script_mlist(p)=null;
14190 return p;
14191 }
14192
14193 @ Let's consider now the previously unwritten part of |show_node_list|
14194 that displays the things that can only be present in mlists; this
14195 program illustrates how to access the data structures just defined.
14196
14197 In the context of the following program, |p| points to a node or noad that
14198 should be displayed, and the current string contains the ``recursion history''
14199 that leads to this point. The recursion history consists of a dot for each
14200 outer level in which |p| is subsidiary to some node, or in which |p| is
14201 subsidiary to the |nucleus| field of some noad; the dot is replaced by
14202 `\.\_' or `\.\^' or `\./' or `\.\\' if |p| is descended from the |subscr|
14203 or |supscr| or |denominator| or |numerator| fields of noads. For example,
14204 the current string would be `\.{.\^.\_/}' if |p| points to the |ord_noad| for
14205 |x| in the (ridiculous) formula
14206 `\.{\$\\sqrt\{a\^\{\\mathinner\{b\_\{c\\over x+y\}\}\}\}\$}'.
14207
14208 @<Cases of |show_node_list| that arise...@>=
14209 case style_node: print_style(subtype(p));@+break;
14210 case choice_node: @<Display choice node |p|@>@;@+break;
14211 case ord_noad: case op_noad: case bin_noad:
14212 case rel_noad: case open_noad: case close_noad:
14213 case punct_noad: case inner_noad:
14214 case radical_noad: case over_noad: case under_noad:
14215 case vcenter_noad: case accent_noad:
14216 case left_noad: case right_noad: @<Display normal noad |p|@>@;@+break;
14217 case fraction_noad: @<Display fraction noad |p|@>@;@+break;
14218
14219 @ Here are some simple routines used in the display of noads.
14220
14221 @<Declare procedures needed for displaying the elements of mlists@>=
14222 static void print_fam_and_char(pointer @!p) /*prints family and character*/
14223 {@+print_esc("fam");print_int(fam(p));print_char(' ');
14224 print_ASCII(qo(character(p)));
14225 }
14226 @#
14227 static void print_delimiter(pointer @!p) /*prints a delimiter as 24-bit hex value*/
14228 {@+int a; /*accumulator*/
14229 a=small_fam(p)*256+qo(small_char(p));
14230 a=a*0x1000+large_fam(p)*256+qo(large_char(p));
14231 if (a < 0) print_int(a); /*this should never happen*/
14232 else print_hex(a);
14233 }
14234
14235 @ The next subroutine will descend to another level of recursion when a
14236 subsidiary mlist needs to be displayed. The parameter |c| indicates what
14237 character is to become part of the recursion history. An empty mlist is
14238 distinguished from a field with |math_type(p)==empty|, because these are
14239 not equivalent (as explained above).
14240 @^recursion@>
14241
14242 @<Declare procedures needed for displaying...@>=
14243 static void show_info(void); /*|show_node_list(info(temp_ptr))|*/
14244 static void print_subsidiary_data(pointer @!p, ASCII_code @!c)
14245 /*display a noad field*/
14246 {@+if (cur_length >= depth_threshold)
14247 {@+if (math_type(p)!=empty) print(" []");
14248 }
14249 else{@+append_char(c); /*include |c| in the recursion history*/
14250 temp_ptr=p; /*prepare for |show_info| if recursion is needed*/
14251 switch (math_type(p)) {
14252 case math_char: {@+print_ln();print_current_string();print_fam_and_char(p);
14253 } @+break;
14254 case sub_box: show_info();@+break; /*recursive call*/
14255 case sub_mlist: if (info(p)==null)
14256 {@+print_ln();print_current_string();print("{}");
14257 }
14258 else show_info();@+break; /*recursive call*/
14259 default:do_nothing; /*|empty|*/
14260 } @/
14261 flush_char; /*remove |c| from the recursion history*/
14262 }
14263 }
14264
14265 @ The inelegant introduction of |show_info| in the code above seems better
14266 than the alternative of using \PASCAL's strange |forward| declaration for a
14267 procedure with parameters. The \PASCAL\ convention about dropping parameters
14268 from a post-|forward| procedure is, frankly, so intolerable to the author
14269 of \TeX\ that he would rather stoop to communication via a global temporary
14270 variable. (A similar stoopidity occurred with respect to |hlist_out| and
14271 |vlist_out| above, and it will occur with respect to |mlist_to_hlist| below.)
14272 @^Knuth, Donald Ervin@>
14273 @:PASCAL}{\PASCAL@>
14274
14275 @p static void show_info(void) /*the reader will kindly forgive this*/
14276 {@+show_node_list(info(temp_ptr));
14277 }
14278
14279 @ @<Declare procedures needed for displaying...@>=
14280 static void print_style(int @!c)
14281 {@+switch (c/2) {
14282 case 0: print_esc("displaystyle");@+break; /*|display_style==0|*/
14283 case 1: print_esc("textstyle");@+break; /*|text_style==2|*/
14284 case 2: print_esc("scriptstyle");@+break; /*|script_style==4|*/
14285 case 3: print_esc("scriptscriptstyle");@+break; /*|script_script_style==6|*/
14286 default:print("Unknown style!");
14287 }
14288 }
14289
14290 @ @<Display choice node |p|@>=
14291 {@+print_esc("mathchoice");
14292 append_char('D');show_node_list(display_mlist(p));flush_char;
14293 append_char('T');show_node_list(text_mlist(p));flush_char;
14294 append_char('S');show_node_list(script_mlist(p));flush_char;
14295 append_char('s');show_node_list(script_script_mlist(p));flush_char;
14296 }
14297
14298 @ @<Display normal noad |p|@>=
14299 {@+switch (type(p)) {
14300 case ord_noad: print_esc("mathord");@+break;
14301 case op_noad: print_esc("mathop");@+break;
14302 case bin_noad: print_esc("mathbin");@+break;
14303 case rel_noad: print_esc("mathrel");@+break;
14304 case open_noad: print_esc("mathopen");@+break;
14305 case close_noad: print_esc("mathclose");@+break;
14306 case punct_noad: print_esc("mathpunct");@+break;
14307 case inner_noad: print_esc("mathinner");@+break;
14308 case over_noad: print_esc("overline");@+break;
14309 case under_noad: print_esc("underline");@+break;
14310 case vcenter_noad: print_esc("vcenter");@+break;
14311 case radical_noad: {@+print_esc("radical");print_delimiter(left_delimiter(p));
14312 } @+break;
14313 case accent_noad: {@+print_esc("accent");print_fam_and_char(accent_chr(p));
14314 } @+break;
14315 case left_noad: {@+print_esc("left");print_delimiter(delimiter(p));
14316 } @+break;
14317 case right_noad: {@+if (subtype(p)==normal) print_esc("right");
14318 else print_esc("middle");
14319 print_delimiter(delimiter(p));
14320 }
14321 }
14322 if (type(p) < left_noad)
14323 {@+if (subtype(p)!=normal)
14324 if (subtype(p)==limits) print_esc("limits");
14325 else print_esc("nolimits");
14326 print_subsidiary_data(nucleus(p),'.');
14327 }
14328 print_subsidiary_data(supscr(p),'^');
14329 print_subsidiary_data(subscr(p),'_');
14330 }
14331
14332 @ @<Display fraction noad |p|@>=
14333 {@+print_esc("fraction, thickness ");
14334 if (thickness(p)==default_code) print("= default");
14335 else print_scaled(thickness(p));
14336 if ((small_fam(left_delimiter(p))!=0)||@+
14337 (small_char(left_delimiter(p))!=min_quarterword)||@|
14338 (large_fam(left_delimiter(p))!=0)||@|
14339 (large_char(left_delimiter(p))!=min_quarterword))
14340 {@+print(", left-delimiter ");print_delimiter(left_delimiter(p));
14341 }
14342 if ((small_fam(right_delimiter(p))!=0)||@|
14343 (small_char(right_delimiter(p))!=min_quarterword)||@|
14344 (large_fam(right_delimiter(p))!=0)||@|
14345 (large_char(right_delimiter(p))!=min_quarterword))
14346 {@+print(", right-delimiter ");print_delimiter(right_delimiter(p));
14347 }
14348 print_subsidiary_data(numerator(p),'\\');
14349 print_subsidiary_data(denominator(p),'/');
14350 }
14351
14352 @ That which can be displayed can also be destroyed.
14353
14354 @<Cases of |flush_node_list| that arise...@>=
14355 case style_node: {@+free_node(p, style_node_size);goto done;
14356 }
14357 case choice_node: {@+flush_node_list(display_mlist(p));
14358 flush_node_list(text_mlist(p));
14359 flush_node_list(script_mlist(p));
14360 flush_node_list(script_script_mlist(p));
14361 free_node(p, style_node_size);goto done;
14362 }
14363 case ord_noad: case op_noad: case bin_noad:
14364 case rel_noad: case open_noad: case close_noad:
14365 case punct_noad: case inner_noad:
14366 case radical_noad: case over_noad: case under_noad:
14367 case vcenter_noad: case accent_noad: @t@>@;@/
14368 {@+if (math_type(nucleus(p)) >= sub_box)
14369 flush_node_list(info(nucleus(p)));
14370 if (math_type(supscr(p)) >= sub_box)
14371 flush_node_list(info(supscr(p)));
14372 if (math_type(subscr(p)) >= sub_box)
14373 flush_node_list(info(subscr(p)));
14374 if (type(p)==radical_noad) free_node(p, radical_noad_size);
14375 else if (type(p)==accent_noad) free_node(p, accent_noad_size);
14376 else free_node(p, noad_size);
14377 goto done;
14378 }
14379 case left_noad: case right_noad: {@+free_node(p, noad_size);goto done;
14380 }
14381 case fraction_noad: {@+flush_node_list(info(numerator(p)));
14382 flush_node_list(info(denominator(p)));
14383 free_node(p, fraction_noad_size);goto done;
14384 }
14385
14386 @* Subroutines for math mode.
14387 In order to convert mlists to hlists, i.e., noads to nodes, we need several
14388 subroutines that are conveniently dealt with now.
14389
14390 Let us first introduce the macros that make it easy to get at the parameters and
14391 other font information. A size code, which is a multiple of 16, is added to a
14392 family number to get an index into the table of internal font numbers
14393 for each combination of family and size. (Be alert: Size codes get
14394 larger as the type gets smaller.)
14395
14396 @d text_size 0 /*size code for the largest size in a family*/
14397 @d script_size 16 /*size code for the medium size in a family*/
14398 @d script_script_size 32 /*size code for the smallest size in a family*/
14399
14400 @<Basic printing procedures@>=
14401 static void print_size(int @!s)
14402 {@+if (s==text_size) print_esc("textfont");
14403 else if (s==script_size) print_esc("scriptfont");
14404 else print_esc("scriptscriptfont");
14405 }
14406
14407 @ Before an mlist is converted to an hlist, \TeX\ makes sure that
14408 the fonts in family~2 have enough parameters to be math-symbol
14409 fonts, and that the fonts in family~3 have enough parameters to be
14410 math-extension fonts. The math-symbol parameters are referred to by using the
14411 following macros, which take a size code as their parameter; for example,
14412 |num1(cur_size)| gives the value of the |num1| parameter for the current size.
14413 @^parameters for symbols@>
14414 @^font parameters@>
14415
14416 @d mathsy_end(A) fam_fnt(2+A)]].sc
14417 @d mathsy(A) font_info[A+param_base[mathsy_end
14418 @d math_x_height mathsy(5) /*height of `\.x'*/
14419 @d math_quad mathsy(6) /*\.{18mu}*/
14420 @d num1 mathsy(8) /*numerator shift-up in display styles*/
14421 @d num2 mathsy(9) /*numerator shift-up in non-display, non-\.{\\atop}*/
14422 @d num3 mathsy(10) /*numerator shift-up in non-display \.{\\atop}*/
14423 @d denom1 mathsy(11) /*denominator shift-down in display styles*/
14424 @d denom2 mathsy(12) /*denominator shift-down in non-display styles*/
14425 @d sup1 mathsy(13) /*superscript shift-up in uncramped display style*/
14426 @d sup2 mathsy(14) /*superscript shift-up in uncramped non-display*/
14427 @d sup3 mathsy(15) /*superscript shift-up in cramped styles*/
14428 @d sub1 mathsy(16) /*subscript shift-down if superscript is absent*/
14429 @d sub2 mathsy(17) /*subscript shift-down if superscript is present*/
14430 @d sup_drop mathsy(18) /*superscript baseline below top of large box*/
14431 @d sub_drop mathsy(19) /*subscript baseline below bottom of large box*/
14432 @d delim1 mathsy(20) /*size of \.{\\atopwithdelims} delimiters
14433 in display styles*/
14434 @d delim2 mathsy(21) /*size of \.{\\atopwithdelims} delimiters in non-displays*/
14435 @d axis_height mathsy(22) /*height of fraction lines above the baseline*/
14436 @d total_mathsy_params 22
14437
14438 @ The math-extension parameters have similar macros, but the size code is
14439 omitted (since it is always |cur_size| when we refer to such parameters).
14440 @^parameters for symbols@>
14441 @^font parameters@>
14442
14443 @d mathex(A) font_info[A+param_base[fam_fnt(3+cur_size)]].sc
14444 @d default_rule_thickness mathex(8) /*thickness of \.{\\over} bars*/
14445 @d big_op_spacing1 mathex(9) /*minimum clearance above a displayed op*/
14446 @d big_op_spacing2 mathex(10) /*minimum clearance below a displayed op*/
14447 @d big_op_spacing3 mathex(11) /*minimum baselineskip above displayed op*/
14448 @d big_op_spacing4 mathex(12) /*minimum baselineskip below displayed op*/
14449 @d big_op_spacing5 mathex(13) /*padding above and below displayed limits*/
14450 @d total_mathex_params 13
14451
14452 @ We also need to compute the change in style between mlists and their
14453 subsidiaries. The following macros define the subsidiary style for
14454 an overlined nucleus (|cramped_style|), for a subscript or a superscript
14455 (|sub_style| or |sup_style|), or for a numerator or denominator (|num_style|
14456 or |denom_style|).
14457
14458 @d cramped_style(A) 2*(A/2)+cramped /*cramp the style*/
14459 @d sub_style(A) 2*(A/4)+script_style+cramped /*smaller and cramped*/
14460 @d sup_style(A) 2*(A/4)+script_style+(A%2) /*smaller*/
14461 @d num_style(A) A+2-2*(A/6) /*smaller unless already script-script*/
14462 @d denom_style(A) 2*(A/2)+cramped+2-2*(A/6) /*smaller, cramped*/
14463
14464 @ When the style changes, the following piece of program computes associated
14465 information:
14466
14467 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>=
14468 {@+if (cur_style < script_style) cur_size=text_size;
14469 else cur_size=16*((cur_style-text_style)/2);
14470 cur_mu=x_over_n(math_quad(cur_size), 18);
14471 }
14472
14473 @ Here is a function that returns a pointer to a rule node having a given
14474 thickness |t|. The rule will extend horizontally to the boundary of the vlist
14475 that eventually contains it.
14476
14477 @p static pointer fraction_rule(scaled @!t)
14478 /*construct the bar for a fraction*/
14479 {@+pointer p; /*the new node*/
14480 p=new_rule();height(p)=t;depth(p)=0;return p;
14481 }
14482
14483 @ The |overbar| function returns a pointer to a vlist box that consists of
14484 a given box |b|, above which has been placed a kern of height |k| under a
14485 fraction rule of thickness |t| under additional space of height |t|.
14486
14487 @p static pointer overbar(pointer @!b, scaled @!k, scaled @!t)
14488 {@+pointer p, @!q; /*nodes being constructed*/
14489 p=new_kern(k);link(p)=b;q=fraction_rule(t);link(q)=p;
14490 p=new_kern(t);link(p)=q;return vpack(p, natural);
14491 }
14492
14493 @ The |var_delimiter| function, which finds or constructs a sufficiently
14494 large delimiter, is the most interesting of the auxiliary functions that
14495 currently concern us. Given a pointer |d| to a delimiter field in some noad,
14496 together with a size code |s| and a vertical distance |v|, this function
14497 returns a pointer to a box that contains the smallest variant of |d| whose
14498 height plus depth is |v| or more. (And if no variant is large enough, it
14499 returns the largest available variant.) In particular, this routine will
14500 construct arbitrarily large delimiters from extensible components, if
14501 |d| leads to such characters.
14502
14503 The value returned is a box whose |shift_amount| has been set so that
14504 the box is vertically centered with respect to the axis in the given size.
14505 If a built-up symbol is returned, the height of the box before shifting
14506 will be the height of its topmost component.
14507
14508 @p @t\4@>@<Declare subprocedures for |var_delimiter|@>@;
14509 static pointer var_delimiter(pointer @!d, small_number @!s, scaled @!v)
14510 {@+
14511 pointer b; /*the box that will be constructed*/
14512 internal_font_number @!f, @!g; /*best-so-far and tentative font codes*/
14513 quarterword @!c, @!x, @!y; /*best-so-far and tentative character codes*/
14514 int @!m, @!n; /*the number of extensible pieces*/
14515 scaled @!u; /*height-plus-depth of a tentative character*/
14516 scaled @!w; /*largest height-plus-depth so far*/
14517 four_quarters @!q; /*character info*/
14518 eight_bits @!hd; /*height-depth byte*/
14519 four_quarters @!r; /*extensible pieces*/
14520 small_number @!z; /*runs through font family members*/
14521 bool @!large_attempt; /*are we trying the ``large'' variant?*/
14522 f=null_font;w=0;large_attempt=false;
14523 z=small_fam(d);x=small_char(d);
14524 loop@+{@+@<Look at the variants of |(z,x)|; set |f| and |c| whenever a better
14525 character is found; |goto found| as soon as a large enough variant is encountered@>;
14526 if (large_attempt) goto found; /*there were none large enough*/
14527 large_attempt=true;z=large_fam(d);x=large_char(d);
14528 }
14529 found: if (f!=null_font)
14530 @<Make variable |b| point to a box for |(f,c)|@>;
14531 else{@+b=new_null_box();
14532 width(b)=null_delimiter_space; /*use this width if no delimiter was found*/
14533 }
14534 shift_amount(b)=half(height(b)-depth(b))-axis_height(s);
14535 return b;
14536 }
14537
14538 @ The search process is complicated slightly by the facts that some of the
14539 characters might not be present in some of the fonts, and they might not
14540 be probed in increasing order of height.
14541
14542 @<Look at the variants of |(z,x)|; set |f| and |c|...@>=
14543 if ((z!=0)||(x!=min_quarterword))
14544 {@+z=z+s+16;
14545 @/do@+{z=z-16;g=fam_fnt(z);
14546 if (g!=null_font)
14547 @<Look at the list of characters starting with |x| in font |g|; set |f|
14548 and |c| whenever a better character is found; |goto found| as soon as a large
14549 enough variant is encountered@>;
14550 }@+ while (!(z < 16));
14551 }
14552
14553 @ @<Look at the list of characters starting with |x|...@>=
14554 {@+y=x;
14555 if ((qo(y) >= font_bc[g])&&(qo(y) <= font_ec[g]))
14556 {@+resume: q=char_info(g, y);
14557 if (char_exists(q))
14558 {@+if (char_tag(q)==ext_tag)
14559 {@+f=g;c=y;goto found;
14560 }
14561 hd=height_depth(q);
14562 u=char_height(g, hd)+char_depth(g, hd);
14563 if (u > w)
14564 {@+f=g;c=y;w=u;
14565 if (u >= v) goto found;
14566 }
14567 if (char_tag(q)==list_tag)
14568 {@+y=rem_byte(q);goto resume;
14569 }
14570 }
14571 }
14572 }
14573
14574 @ Here is a subroutine that creates a new box, whose list contains a
14575 single character, and whose width includes the italic correction for
14576 that character. The height or depth of the box will be negative, if
14577 the height or depth of the character is negative; thus, this routine
14578 may deliver a slightly different result than |hpack| would produce.
14579
14580 @<Declare subprocedures for |var_delimiter|@>=
14581 static pointer char_box(internal_font_number @!f, quarterword @!c)
14582 {@+four_quarters q;
14583 eight_bits @!hd; /*|height_depth| byte*/
14584 pointer @!b, @!p; /*the new box and its character node*/
14585 q=char_info(f, c);hd=height_depth(q);
14586 b=new_null_box();width(b)=char_width(f, q)+char_italic(f, q);
14587 height(b)=char_height(f, hd);depth(b)=char_depth(f, hd);
14588 p=get_avail();character(p)=c;font(p)=f;list_ptr(b)=p;return b;
14589 }
14590
14591 @ When the following code is executed, |char_tag(q)| will be equal to
14592 |ext_tag| if and only if a built-up symbol is supposed to be returned.
14593
14594 @<Make variable |b| point to a box for |(f,c)|@>=
14595 if (char_tag(q)==ext_tag)
14596 @<Construct an extensible character in a new box |b|, using recipe |rem_byte(q)|
14597 and font |f|@>@;
14598 else b=char_box(f, c)
14599
14600 @ When we build an extensible character, it's handy to have the
14601 following subroutine, which puts a given character on top
14602 of the characters already in box |b|:
14603
14604 @<Declare subprocedures for |var_delimiter|@>=
14605 static void stack_into_box(pointer @!b, internal_font_number @!f,
14606 quarterword @!c)
14607 {@+pointer p; /*new node placed into |b|*/
14608 p=char_box(f, c);link(p)=list_ptr(b);list_ptr(b)=p;
14609 height(b)=height(p);
14610 }
14611
14612 @ Another handy subroutine computes the height plus depth of
14613 a given character:
14614
14615 @<Declare subprocedures for |var_delimiter|@>=
14616 static scaled height_plus_depth(internal_font_number @!f, quarterword @!c)
14617 {@+four_quarters q;
14618 eight_bits @!hd; /*|height_depth| byte*/
14619 q=char_info(f, c);hd=height_depth(q);
14620 return char_height(f, hd)+char_depth(f, hd);
14621 }
14622
14623 @ @<Construct an extensible...@>=
14624 {@+b=new_null_box();
14625 type(b)=vlist_node;
14626 r=font_info[exten_base[f]+rem_byte(q)].qqqq;@/
14627 @<Compute the minimum suitable height, |w|, and the corresponding number of
14628 extension steps, |n|; also set |width(b)|@>;
14629 c=ext_bot(r);
14630 if (c!=min_quarterword) stack_into_box(b, f, c);
14631 c=ext_rep(r);
14632 for (m=1; m<=n; m++) stack_into_box(b, f, c);
14633 c=ext_mid(r);
14634 if (c!=min_quarterword)
14635 {@+stack_into_box(b, f, c);c=ext_rep(r);
14636 for (m=1; m<=n; m++) stack_into_box(b, f, c);
14637 }
14638 c=ext_top(r);
14639 if (c!=min_quarterword) stack_into_box(b, f, c);
14640 depth(b)=w-height(b);
14641 }
14642
14643 @ The width of an extensible character is the width of the repeatable
14644 module. If this module does not have positive height plus depth,
14645 we don't use any copies of it, otherwise we use as few as possible
14646 (in groups of two if there is a middle part).
14647
14648 @<Compute the minimum suitable height, |w|, and...@>=
14649 c=ext_rep(r);u=height_plus_depth(f, c);
14650 w=0;q=char_info(f, c);width(b)=char_width(f, q)+char_italic(f, q);@/
14651 c=ext_bot(r);@+if (c!=min_quarterword) w=w+height_plus_depth(f, c);
14652 c=ext_mid(r);@+if (c!=min_quarterword) w=w+height_plus_depth(f, c);
14653 c=ext_top(r);@+if (c!=min_quarterword) w=w+height_plus_depth(f, c);
14654 n=0;
14655 if (u > 0) while (w < v)
14656 {@+w=w+u;incr(n);
14657 if (ext_mid(r)!=min_quarterword) w=w+u;
14658 }
14659
14660 @ The next subroutine is much simpler; it is used for numerators and
14661 denominators of fractions as well as for displayed operators and
14662 their limits above and below. It takes a given box~|b| and
14663 changes it so that the new box is centered in a box of width~|w|.
14664 The centering is done by putting \.{\\hss} glue at the left and right
14665 of the list inside |b|, then packaging the new box; thus, the
14666 actual box might not really be centered, if it already contains
14667 infinite glue.
14668
14669 The given box might contain a single character whose italic correction
14670 has been added to the width of the box; in this case a compensating
14671 kern is inserted.
14672
14673 @p static pointer rebox(pointer @!b, scaled @!w)
14674 {@+pointer p; /*temporary register for list manipulation*/
14675 internal_font_number @!f; /*font in a one-character box*/
14676 scaled @!v; /*width of a character without italic correction*/
14677 if ((width(b)!=w)&&(list_ptr(b)!=null))
14678 {@+if (type(b)==vlist_node) b=hpack(b, natural);
14679 p=list_ptr(b);
14680 if ((is_char_node(p))&&(link(p)==null))
14681 {@+f=font(p);v=char_width(f, char_info(f, character(p)));
14682 if (v!=width(b)) link(p)=new_kern(width(b)-v);
14683 }
14684 free_node(b, box_node_size);
14685 b=new_glue(ss_glue);link(b)=p;
14686 while (link(p)!=null) p=link(p);
14687 link(p)=new_glue(ss_glue);
14688 return hpack(b, w, exactly);
14689 }
14690 else{@+width(b)=w;return b;
14691 }
14692 }
14693
14694 @ Here is a subroutine that creates a new glue specification from another
14695 one that is expressed in `\.{mu}', given the value of the math unit.
14696
14697 @d mu_mult(A) nx_plus_y(n, A, xn_over_d(A, f, 0200000))
14698
14699 @p static pointer math_glue(pointer @!g, scaled @!m)
14700 {@+pointer p; /*the new glue specification*/
14701 int @!n; /*integer part of |m|*/
14702 scaled @!f; /*fraction part of |m|*/
14703 n=x_over_n(m, 0200000);f=rem;@/
14704 if (f < 0)
14705 {@+decr(n);f=f+0200000;
14706 }
14707 p=get_node(glue_spec_size);
14708 width(p)=mu_mult(width(g)); /*convert \.{mu} to \.{pt}*/
14709 stretch_order(p)=stretch_order(g);
14710 if (stretch_order(p)==normal) stretch(p)=mu_mult(stretch(g));
14711 else stretch(p)=stretch(g);
14712 shrink_order(p)=shrink_order(g);
14713 if (shrink_order(p)==normal) shrink(p)=mu_mult(shrink(g));
14714 else shrink(p)=shrink(g);
14715 return p;
14716 }
14717
14718 @ The |math_kern| subroutine removes |mu_glue| from a kern node, given
14719 the value of the math unit.
14720
14721 @p static void math_kern(pointer @!p, scaled @!m)
14722 {@+int @!n; /*integer part of |m|*/
14723 scaled @!f; /*fraction part of |m|*/
14724 if (subtype(p)==mu_glue)
14725 {@+n=x_over_n(m, 0200000);f=rem;@/
14726 if (f < 0)
14727 {@+decr(n);f=f+0200000;
14728 }
14729 width(p)=mu_mult(width(p));subtype(p)=explicit;
14730 }
14731 }
14732
14733 @ Sometimes it is necessary to destroy an mlist. The following
14734 subroutine empties the current list, assuming that |abs(mode)==mmode|.
14735
14736 @p static void flush_math(void)
14737 {@+flush_node_list(link(head));flush_node_list(incompleat_noad);
14738 link(head)=null;tail=head;incompleat_noad=null;
14739 }
14740
14741 @* Typesetting math formulas.
14742 \TeX's most important routine for dealing with formulas is called
14743 |mlist_to_hlist|. After a formula has been scanned and represented as an
14744 mlist, this routine converts it to an hlist that can be placed into a box
14745 or incorporated into the text of a paragraph. There are three implicit
14746 parameters, passed in global variables: |cur_mlist| points to the first
14747 node or noad in the given mlist (and it might be |null|); |cur_style| is a
14748 style code; and |mlist_penalties| is |true| if penalty nodes for potential
14749 line breaks are to be inserted into the resulting hlist. After
14750 |mlist_to_hlist| has acted, |link(temp_head)| points to the translated hlist.
14751
14752 Since mlists can be inside mlists, the procedure is recursive. And since this
14753 is not part of \TeX's inner loop, the program has been written in a manner
14754 that stresses compactness over efficiency.
14755 @^recursion@>
14756
14757 @<Glob...@>=
14758 static pointer @!cur_mlist; /*beginning of mlist to be translated*/
14759 static small_number @!cur_style; /*style code at current place in the list*/
14760 static small_number @!cur_size; /*size code corresponding to |cur_style|*/
14761 static scaled @!cur_mu; /*the math unit width corresponding to |cur_size|*/
14762 static bool @!mlist_penalties; /*should |mlist_to_hlist| insert penalties?*/
14763
14764 @ The recursion in |mlist_to_hlist| is due primarily to a subroutine
14765 called |clean_box| that puts a given noad field into a box using a given
14766 math style; |mlist_to_hlist| can call |clean_box|, which can call
14767 |mlist_to_hlist|.
14768 @^recursion@>
14769
14770 The box returned by |clean_box| is ``clean'' in the
14771 sense that its |shift_amount| is zero.
14772
14773 @p static void mlist_to_hlist(void);@/
14774 static pointer clean_box(pointer @!p, small_number @!s)
14775 {@+
14776 pointer q; /*beginning of a list to be boxed*/
14777 small_number @!save_style; /*|cur_style| to be restored*/
14778 pointer @!x; /*box to be returned*/
14779 pointer @!r; /*temporary pointer*/
14780 switch (math_type(p)) {
14781 case math_char: {@+cur_mlist=new_noad();mem[nucleus(cur_mlist)]=mem[p];
14782 } @+break;
14783 case sub_box: {@+q=info(p);goto found;
14784 }
14785 case sub_mlist: cur_mlist=info(p);@+break;
14786 default:{@+q=new_null_box();goto found;
14787 }
14788 } @/
14789 save_style=cur_style;cur_style=s;mlist_penalties=false;@/
14790 mlist_to_hlist();q=link(temp_head); /*recursive call*/
14791 cur_style=save_style; /*restore the style*/
14792 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
14793 found: if (is_char_node(q)||(q==null)) x=hpack(q, natural);
14794 else if ((link(q)==null)&&(type(q) <= vlist_node)&&(shift_amount(q)==0))
14795 x=q; /*it's already clean*/
14796 else x=hpack(q, natural);
14797 @<Simplify a trivial box@>;
14798 return x;
14799 }
14800
14801 @ Here we save memory space in a common case.
14802
14803 @<Simplify a trivial box@>=
14804 q=list_ptr(x);
14805 if (is_char_node(q))
14806 {@+r=link(q);
14807 if (r!=null) if (link(r)==null) if (!is_char_node(r))
14808 if (type(r)==kern_node) /*unneeded italic correction*/
14809 {@+free_node(r, small_node_size);link(q)=null;
14810 }
14811 }
14812
14813 @ It is convenient to have a procedure that converts a |math_char|
14814 field to an ``unpacked'' form. The |fetch| routine sets |cur_f|, |cur_c|,
14815 and |cur_i| to the font code, character code, and character information bytes of
14816 a given noad field. It also takes care of issuing error messages for
14817 nonexistent characters; in such cases, |char_exists(cur_i)| will be |false|
14818 after |fetch| has acted, and the field will also have been reset to |empty|.
14819
14820 @p static void fetch(pointer @!a) /*unpack the |math_char| field |a|*/
14821 {@+cur_c=character(a);cur_f=fam_fnt(fam(a)+cur_size);
14822 if (cur_f==null_font)
14823 @<Complain about an undefined family and set |cur_i| null@>@;
14824 else{@+if ((qo(cur_c) >= font_bc[cur_f])&&(qo(cur_c) <= font_ec[cur_f]))
14825 cur_i=char_info(cur_f, cur_c);
14826 else cur_i=null_character;
14827 if (!(char_exists(cur_i)))
14828 {@+char_warning(cur_f, qo(cur_c));
14829 math_type(a)=empty;cur_i=null_character;
14830 }
14831 }
14832 }
14833
14834 @ @<Complain about an undefined family...@>=
14835 {@+print_err("");print_size(cur_size);print_char(' ');
14836 print_int(fam(a));print(" is undefined (character ");
14837 print_ASCII(qo(cur_c));print_char(')');
14838 help4("Somewhere in the math formula just ended, you used the",@/
14839 "stated character from an undefined font family. For example,",@/
14840 "plain TeX doesn't allow \\it or \\sl in subscripts. Proceed,",@/
14841 "and I'll try to forget that I needed that character.");
14842 error();cur_i=null_character;math_type(a)=empty;
14843 }
14844
14845 @ The outputs of |fetch| are placed in global variables.
14846
14847 @<Glob...@>=
14848 static internal_font_number @!cur_f; /*the |font| field of a |math_char|*/
14849 static quarterword @!cur_c; /*the |character| field of a |math_char|*/
14850 static four_quarters @!cur_i; /*the |char_info| of a |math_char|,
14851 or a lig/kern instruction*/
14852
14853 @ We need to do a lot of different things, so |mlist_to_hlist| makes two
14854 passes over the given mlist.
14855
14856 The first pass does most of the processing: It removes ``mu'' spacing from
14857 glue, it recursively evaluates all subsidiary mlists so that only the
14858 top-level mlist remains to be handled, it puts fractions and square roots
14859 and such things into boxes, it attaches subscripts and superscripts, and
14860 it computes the overall height and depth of the top-level mlist so that
14861 the size of delimiters for a |left_noad| and a |right_noad| will be known.
14862 The hlist resulting from each noad is recorded in that noad's |new_hlist|
14863 field, an integer field that replaces the |nucleus| or |thickness|.
14864 @^recursion@>
14865
14866 The second pass eliminates all noads and inserts the correct glue and
14867 penalties between nodes.
14868
14869 @d new_hlist(A) mem[nucleus(A)].i /*the translation of an mlist*/
14870
14871 @ Here is the overall plan of |mlist_to_hlist|, and the list of its
14872 local variables.
14873
14874 @p @t\4@>@<Declare math construction procedures@>@;
14875 static void mlist_to_hlist(void)
14876 {@+
14877
14878 pointer mlist; /*beginning of the given list*/
14879 bool @!penalties; /*should penalty nodes be inserted?*/
14880 small_number @!style; /*the given style*/
14881 small_number @!save_style; /*holds |cur_style| during recursion*/
14882 pointer @!q; /*runs through the mlist*/
14883 pointer @!r; /*the most recent noad preceding |q|*/
14884 small_number @!r_type; /*the |type| of noad |r|, or |op_noad| if |r==null|*/
14885 small_number @!t; /*the effective |type| of noad |q| during the second pass*/
14886 pointer @!p, @!x, @!y, @!z; /*temporary registers for list construction*/
14887 int @!pen; /*a penalty to be inserted*/
14888 small_number @!s; /*the size of a noad to be deleted*/
14889 scaled @!max_h, @!max_d; /*maximum height and depth of the list translated so far*/
14890 scaled @!delta; /*offset between subscript and superscript*/
14891 mlist=cur_mlist;penalties=mlist_penalties;
14892 style=cur_style; /*tuck global parameters away as local variables*/
14893 q=mlist;r=null;r_type=op_noad;max_h=0;max_d=0;
14894 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
14895 while (q!=null) @<Process node-or-noad |q| as much as possible in preparation
14896 for the second pass of |mlist_to_hlist|, then move to the next item in the
14897 mlist@>;
14898 @<Convert \(a)a final |bin_noad| to an |ord_noad|@>;
14899 @<Make a second pass over the mlist, removing all noads and inserting the
14900 proper spacing and penalties@>;
14901 }
14902
14903 @ We use the fact that no character nodes appear in an mlist, hence
14904 the field |type(q)| is always present.
14905
14906 @<Process node-or-noad...@>=
14907 {@+@<Do first-pass processing based on |type(q)|; |goto done_with_noad| if
14908 a noad has been fully processed, |goto check_dimensions| if it has been translated
14909 into |new_hlist(q)|, or |goto done_with_node| if a node has been fully processed@>;
14910 check_dimensions: z=hpack(new_hlist(q), natural);
14911 if (height(z) > max_h) max_h=height(z);
14912 if (depth(z) > max_d) max_d=depth(z);
14913 free_node(z, box_node_size);
14914 done_with_noad: r=q;r_type=type(r);
14915 if (r_type==right_noad)
14916 {@+r_type=left_noad;cur_style=style;@<Set up the values...@>;
14917 }
14918 done_with_node: q=link(q);
14919 }
14920
14921 @ One of the things we must do on the first pass is change a |bin_noad| to
14922 an |ord_noad| if the |bin_noad| is not in the context of a binary operator.
14923 The values of |r| and |r_type| make this fairly easy.
14924
14925 @<Do first-pass processing...@>=
14926 reswitch: delta=0;
14927 switch (type(q)) {
14928 case bin_noad: switch (r_type) {
14929 case bin_noad: case op_noad: case rel_noad:
14930 case open_noad: case punct_noad: case left_noad:
14931 {@+type(q)=ord_noad;goto reswitch;
14932 }
14933 default:do_nothing;
14934 } @+break;
14935 case rel_noad: case close_noad: case punct_noad:
14936 case right_noad: {@+@t@>@;@/
14937 @<Convert \(a)a final |bin_noad| to an |ord_noad|@>;
14938 if (type(q)==right_noad) goto done_with_noad;
14939 } @+break;
14940 @t\4@>@<Cases for noads that can follow a |bin_noad|@>@;
14941 @t\4@>@<Cases for nodes that can appear in an mlist, after which we |goto
14942 done_with_node|@>@;
14943 default:confusion("mlist1");
14944 @:this can't happen mlist1}{\quad mlist1@>
14945 } @/
14946 @<Convert \(n)|nucleus(q)| to an hlist and attach the sub/superscripts@>@;
14947
14948 @ @<Convert \(a)a final |bin_noad| to an |ord_noad|@>=
14949 if (r_type==bin_noad) type(r)=ord_noad
14950
14951 @ @<Cases for nodes that can appear in an mlist...@>=
14952 case style_node: {@+cur_style=subtype(q);
14953 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
14954 goto done_with_node;
14955 }
14956 case choice_node: @<Change this node to a style node followed by the correct
14957 choice, then |goto done_with_node|@>@;
14958 case ins_node: case mark_node: case adjust_node:
14959 case whatsit_node: case penalty_node:
14960 case disc_node: goto done_with_node;
14961 case rule_node: {@+if (height(q) > max_h) max_h=height(q);
14962 if (depth(q) > max_d) max_d=depth(q);goto done_with_node;
14963 }
14964 case glue_node: {@+@<Convert \(m)math glue to ordinary glue@>;
14965 goto done_with_node;
14966 }
14967 case kern_node: {@+math_kern(q, cur_mu);goto done_with_node;
14968 }
14969
14970 @ @d choose_mlist(A) {@+p=A(q);A(q)=null;@+}
14971
14972 @<Change this node to a style node...@>=
14973 {@+switch (cur_style/2) {
14974 case 0: choose_mlist(display_mlist)@;@+break; /*|display_style==0|*/
14975 case 1: choose_mlist(text_mlist)@;@+break; /*|text_style==2|*/
14976 case 2: choose_mlist(script_mlist)@;@+break; /*|script_style==4|*/
14977 case 3: choose_mlist(script_script_mlist); /*|script_script_style==6|*/
14978 } /*there are no other cases*/
14979 flush_node_list(display_mlist(q));
14980 flush_node_list(text_mlist(q));
14981 flush_node_list(script_mlist(q));
14982 flush_node_list(script_script_mlist(q));@/
14983 type(q)=style_node;subtype(q)=cur_style;width(q)=0;depth(q)=0;
14984 if (p!=null)
14985 {@+z=link(q);link(q)=p;
14986 while (link(p)!=null) p=link(p);
14987 link(p)=z;
14988 }
14989 goto done_with_node;
14990 }
14991
14992 @ Conditional math glue (`\.{\\nonscript}') results in a |glue_node|
14993 pointing to |zero_glue|, with |subtype(q)==cond_math_glue|; in such a case
14994 the node following will be eliminated if it is a glue or kern node and if the
14995 current size is different from |text_size|. Unconditional math glue
14996 (`\.{\\muskip}') is converted to normal glue by multiplying the dimensions
14997 by |cur_mu|.
14998 @!@:non\_script\_}{\.{\\nonscript} primitive@>
14999
15000 @<Convert \(m)math glue to ordinary glue@>=
15001 if (subtype(q)==mu_glue)
15002 {@+x=glue_ptr(q);
15003 y=math_glue(x, cur_mu);delete_glue_ref(x);glue_ptr(q)=y;
15004 subtype(q)=normal;
15005 }
15006 else if ((cur_size!=text_size)&&(subtype(q)==cond_math_glue))
15007 {@+p=link(q);
15008 if (p!=null) if ((type(p)==glue_node)||(type(p)==kern_node))
15009 {@+link(q)=link(p);link(p)=null;flush_node_list(p);
15010 }
15011 }
15012
15013 @ @<Cases for noads that can follow a |bin_noad|@>=
15014 case left_noad: goto done_with_noad;
15015 case fraction_noad: {@+make_fraction(q);goto check_dimensions;
15016 }
15017 case op_noad: {@+delta=make_op(q);
15018 if (subtype(q)==limits) goto check_dimensions;
15019 } @+break;
15020 case ord_noad: make_ord(q);@+break;
15021 case open_noad: case inner_noad: do_nothing;@+break;
15022 case radical_noad: make_radical(q);@+break;
15023 case over_noad: make_over(q);@+break;
15024 case under_noad: make_under(q);@+break;
15025 case accent_noad: make_math_accent(q);@+break;
15026 case vcenter_noad: make_vcenter(q);@+break;
15027
15028 @ Most of the actual construction work of |mlist_to_hlist| is done
15029 by procedures with names
15030 like |make_fraction|, |make_radical|, etc. To illustrate
15031 the general setup of such procedures, let's begin with a couple of
15032 simple ones.
15033
15034 @<Declare math...@>=
15035 static void make_over(pointer @!q)
15036 {@+info(nucleus(q))=@|
15037 overbar(clean_box(nucleus(q), cramped_style(cur_style)),@|
15038 3*default_rule_thickness, default_rule_thickness);
15039 math_type(nucleus(q))=sub_box;
15040 }
15041
15042 @ @<Declare math...@>=
15043 static void make_under(pointer @!q)
15044 {@+pointer p, @!x, @!y; /*temporary registers for box construction*/
15045 scaled @!delta; /*overall height plus depth*/
15046 x=clean_box(nucleus(q), cur_style);
15047 p=new_kern(3*default_rule_thickness);link(x)=p;
15048 link(p)=fraction_rule(default_rule_thickness);
15049 y=vpack(x, natural);
15050 delta=height(y)+depth(y)+default_rule_thickness;
15051 height(y)=height(x);depth(y)=delta-height(y);
15052 info(nucleus(q))=y;math_type(nucleus(q))=sub_box;
15053 }
15054
15055 @ @<Declare math...@>=
15056 static void make_vcenter(pointer @!q)
15057 {@+pointer v; /*the box that should be centered vertically*/
15058 scaled @!delta; /*its height plus depth*/
15059 v=info(nucleus(q));
15060 if (type(v)!=vlist_node) confusion("vcenter");
15061 @:this can't happen vcenter}{\quad vcenter@>
15062 delta=height(v)+depth(v);
15063 height(v)=axis_height(cur_size)+half(delta);
15064 depth(v)=delta-height(v);
15065 }
15066
15067 @ According to the rules in the \.{DVI} file specifications, we ensure alignment
15068 @^square roots@>
15069 between a square root sign and the rule above its nucleus by assuming that the
15070 baseline of the square-root symbol is the same as the bottom of the rule. The
15071 height of the square-root symbol will be the thickness of the rule, and the
15072 depth of the square-root symbol should exceed or equal the height-plus-depth
15073 of the nucleus plus a certain minimum clearance~|clr|. The symbol will be
15074 placed so that the actual clearance is |clr| plus half the excess.
15075
15076 @<Declare math...@>=
15077 static void make_radical(pointer @!q)
15078 {@+pointer x, @!y; /*temporary registers for box construction*/
15079 scaled @!delta, @!clr; /*dimensions involved in the calculation*/
15080 x=clean_box(nucleus(q), cramped_style(cur_style));
15081 if (cur_style < text_style) /*display style*/
15082 clr=default_rule_thickness+(abs(math_x_height(cur_size))/4);
15083 else{@+clr=default_rule_thickness;clr=clr+(abs(clr)/4);
15084 }
15085 y=var_delimiter(left_delimiter(q), cur_size, height(x)+depth(x)+clr+
15086 default_rule_thickness);
15087 delta=depth(y)-(height(x)+depth(x)+clr);
15088 if (delta > 0) clr=clr+half(delta); /*increase the actual clearance*/
15089 shift_amount(y)=-(height(x)+clr);
15090 link(y)=overbar(x, clr, height(y));
15091 info(nucleus(q))=hpack(y, natural);math_type(nucleus(q))=sub_box;
15092 }
15093
15094 @ Slants are not considered when placing accents in math mode. The accenter is
15095 centered over the accentee, and the accent width is treated as zero with
15096 respect to the size of the final box.
15097
15098 @<Declare math...@>=
15099 static void make_math_accent(pointer @!q)
15100 {@+
15101 pointer p, @!x, @!y; /*temporary registers for box construction*/
15102 int @!a; /*address of lig/kern instruction*/
15103 quarterword @!c; /*accent character*/
15104 internal_font_number @!f; /*its font*/
15105 four_quarters @!i; /*its |char_info|*/
15106 scaled @!s; /*amount to skew the accent to the right*/
15107 scaled @!h; /*height of character being accented*/
15108 scaled @!delta; /*space to remove between accent and accentee*/
15109 scaled @!w; /*width of the accentee, not including sub/superscripts*/
15110 fetch(accent_chr(q));
15111 if (char_exists(cur_i))
15112 {@+i=cur_i;c=cur_c;f=cur_f;@/
15113 @<Compute the amount of skew@>;
15114 x=clean_box(nucleus(q), cramped_style(cur_style));w=width(x);h=height(x);
15115 @<Switch to a larger accent if available and appropriate@>;
15116 if (h < x_height(f)) delta=h;@+else delta=x_height(f);
15117 if ((math_type(supscr(q))!=empty)||(math_type(subscr(q))!=empty))
15118 if (math_type(nucleus(q))==math_char)
15119 @<Swap the subscript and superscript into box |x|@>;
15120 y=char_box(f, c);
15121 shift_amount(y)=s+half(w-width(y));
15122 width(y)=0;p=new_kern(-delta);link(p)=x;link(y)=p;
15123 y=vpack(y, natural);width(y)=width(x);
15124 if (height(y) < h) @<Make the height of box |y| equal to |h|@>;
15125 info(nucleus(q))=y;
15126 math_type(nucleus(q))=sub_box;
15127 }
15128 }
15129
15130 @ @<Make the height of box |y|...@>=
15131 {@+p=new_kern(h-height(y));link(p)=list_ptr(y);list_ptr(y)=p;
15132 height(y)=h;
15133 }
15134
15135 @ @<Switch to a larger accent if available and appropriate@>=
15136 loop@+{@+if (char_tag(i)!=list_tag) goto done;
15137 y=rem_byte(i);
15138 i=char_info(f, y);
15139 if (!char_exists(i)) goto done;
15140 if (char_width(f, i) > w) goto done;
15141 c=y;
15142 }
15143 done:
15144
15145 @ @<Compute the amount of skew@>=
15146 s=0;
15147 if (math_type(nucleus(q))==math_char)
15148 {@+fetch(nucleus(q));
15149 if (char_tag(cur_i)==lig_tag)
15150 {@+a=lig_kern_start(cur_f, cur_i);
15151 cur_i=font_info[a].qqqq;
15152 if (skip_byte(cur_i) > stop_flag)
15153 {@+a=lig_kern_restart(cur_f, cur_i);
15154 cur_i=font_info[a].qqqq;
15155 }
15156 loop@+{@+if (qo(next_char(cur_i))==skew_char[cur_f])
15157 {@+if (op_byte(cur_i) >= kern_flag)
15158 if (skip_byte(cur_i) <= stop_flag) s=char_kern(cur_f, cur_i);
15159 goto done1;
15160 }
15161 if (skip_byte(cur_i) >= stop_flag) goto done1;
15162 a=a+qo(skip_byte(cur_i))+1;
15163 cur_i=font_info[a].qqqq;
15164 }
15165 }
15166 }
15167 done1:
15168
15169 @ @<Swap the subscript and superscript into box |x|@>=
15170 {@+flush_node_list(x);x=new_noad();
15171 mem[nucleus(x)]=mem[nucleus(q)];
15172 mem[supscr(x)]=mem[supscr(q)];
15173 mem[subscr(x)]=mem[subscr(q)];@/
15174 mem[supscr(q)].hh=empty_field;
15175 mem[subscr(q)].hh=empty_field;@/
15176 math_type(nucleus(q))=sub_mlist;info(nucleus(q))=x;
15177 x=clean_box(nucleus(q), cur_style);delta=delta+height(x)-h;h=height(x);
15178 }
15179
15180 @ The |make_fraction| procedure is a bit different because it sets
15181 |new_hlist(q)| directly rather than making a sub-box.
15182
15183 @<Declare math...@>=
15184 static void make_fraction(pointer @!q)
15185 {@+pointer p, @!v, @!x, @!y, @!z; /*temporary registers for box construction*/
15186 scaled @!delta, @!delta1, @!delta2, @!shift_up, @!shift_down, @!clr;
15187 /*dimensions for box calculations*/
15188 if (thickness(q)==default_code) thickness(q)=default_rule_thickness;
15189 @<Create equal-width boxes |x| and |z| for the numerator and denominator,
15190 and compute the default amounts |shift_up| and |shift_down| by which they
15191 are displaced from the baseline@>;
15192 if (thickness(q)==0) @<Adjust \(s)|shift_up| and |shift_down| for the case
15193 of no fraction line@>@;
15194 else@<Adjust \(s)|shift_up| and |shift_down| for the case of a fraction line@>;
15195 @<Construct a vlist box for the fraction, according to |shift_up| and |shift_down|@>;
15196 @<Put the \(f)fraction into a box with its delimiters, and make |new_hlist(q)|
15197 point to it@>;
15198 }
15199
15200 @ @<Create equal-width boxes |x| and |z| for the numerator and denom...@>=
15201 x=clean_box(numerator(q), num_style(cur_style));
15202 z=clean_box(denominator(q), denom_style(cur_style));
15203 if (width(x) < width(z)) x=rebox(x, width(z));
15204 else z=rebox(z, width(x));
15205 if (cur_style < text_style) /*display style*/
15206 {@+shift_up=num1(cur_size);shift_down=denom1(cur_size);
15207 }
15208 else{@+shift_down=denom2(cur_size);
15209 if (thickness(q)!=0) shift_up=num2(cur_size);
15210 else shift_up=num3(cur_size);
15211 }
15212
15213 @ The numerator and denominator must be separated by a certain minimum
15214 clearance, called |clr| in the following program. The difference between
15215 |clr| and the actual clearance is twice |delta|.
15216
15217 @<Adjust \(s)|shift_up| and |shift_down| for the case of no fraction line@>=
15218 {@+if (cur_style < text_style) clr=7*default_rule_thickness;
15219 else clr=3*default_rule_thickness;
15220 delta=half(clr-((shift_up-depth(x))-(height(z)-shift_down)));
15221 if (delta > 0)
15222 {@+shift_up=shift_up+delta;
15223 shift_down=shift_down+delta;
15224 }
15225 }
15226
15227 @ In the case of a fraction line, the minimum clearance depends on the actual
15228 thickness of the line.
15229
15230 @<Adjust \(s)|shift_up| and |shift_down| for the case of a fraction line@>=
15231 {@+if (cur_style < text_style) clr=3*thickness(q);
15232 else clr=thickness(q);
15233 delta=half(thickness(q));
15234 delta1=clr-((shift_up-depth(x))-(axis_height(cur_size)+delta));
15235 delta2=clr-((axis_height(cur_size)-delta)-(height(z)-shift_down));
15236 if (delta1 > 0) shift_up=shift_up+delta1;
15237 if (delta2 > 0) shift_down=shift_down+delta2;
15238 }
15239
15240 @ @<Construct a vlist box for the fraction...@>=
15241 v=new_null_box();type(v)=vlist_node;
15242 height(v)=shift_up+height(x);depth(v)=depth(z)+shift_down;
15243 width(v)=width(x); /*this also equals |width(z)|*/
15244 if (thickness(q)==0)
15245 {@+p=new_kern((shift_up-depth(x))-(height(z)-shift_down));
15246 link(p)=z;
15247 }
15248 else{@+y=fraction_rule(thickness(q));@/
15249 p=new_kern((axis_height(cur_size)-delta)-@|(height(z)-shift_down));@/
15250 link(y)=p;link(p)=z;@/
15251 p=new_kern((shift_up-depth(x))-(axis_height(cur_size)+delta));
15252 link(p)=y;
15253 }
15254 link(x)=p;list_ptr(v)=x
15255
15256 @ @<Put the \(f)fraction into a box with its delimiters...@>=
15257 if (cur_style < text_style) delta=delim1(cur_size);
15258 else delta=delim2(cur_size);
15259 x=var_delimiter(left_delimiter(q), cur_size, delta);link(x)=v;@/
15260 z=var_delimiter(right_delimiter(q), cur_size, delta);link(v)=z;@/
15261 new_hlist(q)=hpack(x, natural)
15262
15263 @ If the nucleus of an |op_noad| is a single character, it is to be
15264 centered vertically with respect to the axis, after first being enlarged
15265 (via a character list in the font) if we are in display style. The normal
15266 convention for placing displayed limits is to put them above and below the
15267 operator in display style.
15268
15269 The italic correction is removed from the character if there is a subscript
15270 and the limits are not being displayed. The |make_op|
15271 routine returns the value that should be used as an offset between
15272 subscript and superscript.
15273
15274 After |make_op| has acted, |subtype(q)| will be |limits| if and only if
15275 the limits have been set above and below the operator. In that case,
15276 |new_hlist(q)| will already contain the desired final box.
15277
15278 @<Declare math...@>=
15279 static scaled make_op(pointer @!q)
15280 {@+scaled delta; /*offset between subscript and superscript*/
15281 pointer @!p, @!v, @!x, @!y, @!z; /*temporary registers for box construction*/
15282 quarterword @!c;@+four_quarters @!i; /*registers for character examination*/
15283 scaled @!shift_up, @!shift_down; /*dimensions for box calculation*/
15284 if ((subtype(q)==normal)&&(cur_style < text_style))
15285 subtype(q)=limits;
15286 if (math_type(nucleus(q))==math_char)
15287 {@+fetch(nucleus(q));
15288 if ((cur_style < text_style)&&(char_tag(cur_i)==list_tag)) /*make it larger*/
15289 {@+c=rem_byte(cur_i);i=char_info(cur_f, c);
15290 if (char_exists(i))
15291 {@+cur_c=c;cur_i=i;character(nucleus(q))=c;
15292 }
15293 }
15294 delta=char_italic(cur_f, cur_i);x=clean_box(nucleus(q), cur_style);
15295 if ((math_type(subscr(q))!=empty)&&(subtype(q)!=limits))
15296 width(x)=width(x)-delta; /*remove italic correction*/
15297 shift_amount(x)=half(height(x)-depth(x))-axis_height(cur_size);
15298 /*center vertically*/
15299 math_type(nucleus(q))=sub_box;info(nucleus(q))=x;
15300 }
15301 else delta=0;
15302 if (subtype(q)==limits)
15303 @<Construct a box with limits above and below it, skewed by |delta|@>;
15304 return delta;
15305 }
15306
15307 @ The following program builds a vlist box |v| for displayed limits. The
15308 width of the box is not affected by the fact that the limits may be skewed.
15309
15310 @<Construct a box with limits above and below it...@>=
15311 {@+x=clean_box(supscr(q), sup_style(cur_style));
15312 y=clean_box(nucleus(q), cur_style);
15313 z=clean_box(subscr(q), sub_style(cur_style));
15314 v=new_null_box();type(v)=vlist_node;width(v)=width(y);
15315 if (width(x) > width(v)) width(v)=width(x);
15316 if (width(z) > width(v)) width(v)=width(z);
15317 x=rebox(x, width(v));y=rebox(y, width(v));z=rebox(z, width(v));@/
15318 shift_amount(x)=half(delta);shift_amount(z)=-shift_amount(x);
15319 height(v)=height(y);depth(v)=depth(y);
15320 @<Attach the limits to |y| and adjust |height(v)|, |depth(v)| to account for
15321 their presence@>;
15322 new_hlist(q)=v;
15323 }
15324
15325 @ We use |shift_up| and |shift_down| in the following program for the
15326 amount of glue between the displayed operator |y| and its limits |x| and
15327 |z|. The vlist inside box |v| will consist of |x| followed by |y| followed
15328 by |z|, with kern nodes for the spaces between and around them.
15329
15330 @<Attach the limits to |y| and adjust |height(v)|, |depth(v)|...@>=
15331 if (math_type(supscr(q))==empty)
15332 {@+free_node(x, box_node_size);list_ptr(v)=y;
15333 }
15334 else{@+shift_up=big_op_spacing3-depth(x);
15335 if (shift_up < big_op_spacing1) shift_up=big_op_spacing1;
15336 p=new_kern(shift_up);link(p)=y;link(x)=p;@/
15337 p=new_kern(big_op_spacing5);link(p)=x;list_ptr(v)=p;
15338 height(v)=height(v)+big_op_spacing5+height(x)+depth(x)+shift_up;
15339 }
15340 if (math_type(subscr(q))==empty) free_node(z, box_node_size);
15341 else{@+shift_down=big_op_spacing4-height(z);
15342 if (shift_down < big_op_spacing2) shift_down=big_op_spacing2;
15343 p=new_kern(shift_down);link(y)=p;link(p)=z;@/
15344 p=new_kern(big_op_spacing5);link(z)=p;
15345 depth(v)=depth(v)+big_op_spacing5+height(z)+depth(z)+shift_down;
15346 }
15347
15348 @ A ligature found in a math formula does not create a |ligature_node|, because
15349 there is no question of hyphenation afterwards; the ligature will simply be
15350 stored in an ordinary |char_node|, after residing in an |ord_noad|.
15351
15352 The |math_type| is converted to |math_text_char| here if we would not want to
15353 apply an italic correction to the current character unless it belongs
15354 to a math font (i.e., a font with |space==0|).
15355
15356 No boundary characters enter into these ligatures.
15357
15358 @<Declare math...@>=
15359 static void make_ord(pointer @!q)
15360 {@+
15361 int a; /*address of lig/kern instruction*/
15362 pointer @!p, @!r; /*temporary registers for list manipulation*/
15363 restart: @t@>@;@/
15364 if (math_type(subscr(q))==empty) if (math_type(supscr(q))==empty)
15365 if (math_type(nucleus(q))==math_char)
15366 {@+p=link(q);
15367 if (p!=null) if ((type(p) >= ord_noad)&&(type(p) <= punct_noad))
15368 if (math_type(nucleus(p))==math_char)
15369 if (fam(nucleus(p))==fam(nucleus(q)))
15370 {@+math_type(nucleus(q))=math_text_char;
15371 fetch(nucleus(q));
15372 if (char_tag(cur_i)==lig_tag)
15373 {@+a=lig_kern_start(cur_f, cur_i);
15374 cur_c=character(nucleus(p));
15375 cur_i=font_info[a].qqqq;
15376 if (skip_byte(cur_i) > stop_flag)
15377 {@+a=lig_kern_restart(cur_f, cur_i);
15378 cur_i=font_info[a].qqqq;
15379 }
15380 loop@+{@+@<If instruction |cur_i| is a kern with |cur_c|, attach the
15381 kern after~|q|; or if it is a ligature with |cur_c|, combine noads |q| and~|p|
15382 appropriately; then |return| if the cursor has moved past a noad, or |goto
15383 restart|@>;
15384 if (skip_byte(cur_i) >= stop_flag) return;
15385 a=a+qo(skip_byte(cur_i))+1;
15386 cur_i=font_info[a].qqqq;
15387 }
15388 }
15389 }
15390 }
15391 }
15392
15393 @ Note that a ligature between an |ord_noad| and another kind of noad
15394 is replaced by an |ord_noad|, when the two noads collapse into one.
15395 But we could make a parenthesis (say) change shape when it follows
15396 certain letters. Presumably a font designer will define such
15397 ligatures only when this convention makes sense.
15398
15399 \chardef\@@='174 % vertical line to indicate character retention
15400
15401 @<If instruction |cur_i| is a kern with |cur_c|,...@>=
15402 if (next_char(cur_i)==cur_c) if (skip_byte(cur_i) <= stop_flag)
15403 if (op_byte(cur_i) >= kern_flag)
15404 {@+p=new_kern(char_kern(cur_f, cur_i));
15405 link(p)=link(q);link(q)=p;return;
15406 }
15407 else{@+check_interrupt; /*allow a way out of infinite ligature loop*/
15408 switch (op_byte(cur_i)) {
15409 case qi(1): case qi(5): character(nucleus(q))=rem_byte(cur_i);@+break; /*\.{=:\@@}, \.{=:\@@>}*/
15410 case qi(2): case qi(6): character(nucleus(p))=rem_byte(cur_i);@+break; /*\.{\@@=:}, \.{\@@=:>}*/
15411 case qi(3): case qi(7): case qi(11): {@+r=new_noad(); /*\.{\@@=:\@@}, \.{\@@=:\@@>}, \.{\@@=:\@@>>}*/
15412 character(nucleus(r))=rem_byte(cur_i);
15413 fam(nucleus(r))=fam(nucleus(q));@/
15414 link(q)=r;link(r)=p;
15415 if (op_byte(cur_i) < qi(11)) math_type(nucleus(r))=math_char;
15416 else math_type(nucleus(r))=math_text_char; /*prevent combination*/
15417 } @+break;
15418 default:{@+link(q)=link(p);
15419 character(nucleus(q))=rem_byte(cur_i); /*\.{=:}*/
15420 mem[subscr(q)]=mem[subscr(p)];mem[supscr(q)]=mem[supscr(p)];@/
15421 free_node(p, noad_size);
15422 }
15423 }
15424 if (op_byte(cur_i) > qi(3)) return;
15425 math_type(nucleus(q))=math_char;goto restart;
15426 }
15427
15428 @ When we get to the following part of the program, we have ``fallen through''
15429 from cases that did not lead to |check_dimensions| or |done_with_noad| or
15430 |done_with_node|. Thus, |q|~points to a noad whose nucleus may need to be
15431 converted to an hlist, and whose subscripts and superscripts need to be
15432 appended if they are present.
15433
15434 If |nucleus(q)| is not a |math_char|, the variable |delta| is the amount
15435 by which a superscript should be moved right with respect to a subscript
15436 when both are present.
15437 @^subscripts@>
15438 @^superscripts@>
15439
15440 @<Convert \(n)|nucleus(q)| to an hlist and attach the sub/superscripts@>=
15441 switch (math_type(nucleus(q))) {
15442 case math_char: case math_text_char:
15443 @<Create a character node |p| for |nucleus(q)|, possibly followed by a kern
15444 node for the italic correction, and set |delta| to the italic correction if
15445 a subscript is present@>@;@+break;
15446 case empty: p=null;@+break;
15447 case sub_box: p=info(nucleus(q));@+break;
15448 case sub_mlist: {@+cur_mlist=info(nucleus(q));save_style=cur_style;
15449 mlist_penalties=false;mlist_to_hlist(); /*recursive call*/
15450 @^recursion@>
15451 cur_style=save_style;@<Set up the values...@>;
15452 p=hpack(link(temp_head), natural);
15453 } @+break;
15454 default:confusion("mlist2");
15455 @:this can't happen mlist2}{\quad mlist2@>
15456 } @/
15457 new_hlist(q)=p;
15458 if ((math_type(subscr(q))==empty)&&(math_type(supscr(q))==empty))
15459 goto check_dimensions;
15460 make_scripts(q, delta)
15461
15462 @ @<Create a character node |p| for |nucleus(q)|...@>=
15463 {@+fetch(nucleus(q));
15464 if (char_exists(cur_i))
15465 {@+delta=char_italic(cur_f, cur_i);p=new_character(cur_f, qo(cur_c));
15466 if ((math_type(nucleus(q))==math_text_char)&&(space(cur_f)!=0))
15467 delta=0; /*no italic correction in mid-word of text font*/
15468 if ((math_type(subscr(q))==empty)&&(delta!=0))
15469 {@+link(p)=new_kern(delta);delta=0;
15470 }
15471 }
15472 else p=null;
15473 }
15474
15475 @ The purpose of |make_scripts(q, delta)| is to attach the subscript and/or
15476 superscript of noad |q| to the list that starts at |new_hlist(q)|,
15477 given that the subscript and superscript aren't both empty. The superscript
15478 will appear to the right of the subscript by a given distance |delta|.
15479
15480 We set |shift_down| and |shift_up| to the minimum amounts to shift the
15481 baseline of subscripts and superscripts based on the given nucleus.
15482
15483 @<Declare math...@>=
15484 static void make_scripts(pointer @!q, scaled @!delta)
15485 {@+pointer p, @!x, @!y, @!z; /*temporary registers for box construction*/
15486 scaled @!shift_up, @!shift_down, @!clr; /*dimensions in the calculation*/
15487 small_number @!t; /*subsidiary size code*/
15488 p=new_hlist(q);
15489 if (is_char_node(p))
15490 {@+shift_up=0;shift_down=0;
15491 }
15492 else{@+z=hpack(p, natural);
15493 if (cur_style < script_style) t=script_size;@+else t=script_script_size;
15494 shift_up=height(z)-sup_drop(t);
15495 shift_down=depth(z)+sub_drop(t);
15496 free_node(z, box_node_size);
15497 }
15498 if (math_type(supscr(q))==empty)
15499 @<Construct a subscript box |x| when there is no superscript@>@;
15500 else{@+@<Construct a superscript box |x|@>;
15501 if (math_type(subscr(q))==empty) shift_amount(x)=-shift_up;
15502 else@<Construct a sub/superscript combination box |x|, with the superscript
15503 offset by |delta|@>;
15504 }
15505 if (new_hlist(q)==null) new_hlist(q)=x;
15506 else{@+p=new_hlist(q);
15507 while (link(p)!=null) p=link(p);
15508 link(p)=x;
15509 }
15510 }
15511
15512 @ When there is a subscript without a superscript, the top of the subscript
15513 should not exceed the baseline plus four-fifths of the x-height.
15514
15515 @<Construct a subscript box |x| when there is no superscript@>=
15516 {@+x=clean_box(subscr(q), sub_style(cur_style));
15517 width(x)=width(x)+script_space;
15518 if (shift_down < sub1(cur_size)) shift_down=sub1(cur_size);
15519 clr=height(x)-(abs(math_x_height(cur_size)*4)/5);
15520 if (shift_down < clr) shift_down=clr;
15521 shift_amount(x)=shift_down;
15522 }
15523
15524 @ The bottom of a superscript should never descend below the baseline plus
15525 one-fourth of the x-height.
15526
15527 @<Construct a superscript box |x|@>=
15528 {@+x=clean_box(supscr(q), sup_style(cur_style));
15529 width(x)=width(x)+script_space;
15530 if (odd(cur_style)) clr=sup3(cur_size);
15531 else if (cur_style < text_style) clr=sup1(cur_size);
15532 else clr=sup2(cur_size);
15533 if (shift_up < clr) shift_up=clr;
15534 clr=depth(x)+(abs(math_x_height(cur_size))/4);
15535 if (shift_up < clr) shift_up=clr;
15536 }
15537
15538 @ When both subscript and superscript are present, the subscript must be
15539 separated from the superscript by at least four times |default_rule_thickness|.
15540 If this condition would be violated, the subscript moves down, after which
15541 both subscript and superscript move up so that the bottom of the superscript
15542 is at least as high as the baseline plus four-fifths of the x-height.
15543
15544 @<Construct a sub/superscript combination box |x|...@>=
15545 {@+y=clean_box(subscr(q), sub_style(cur_style));
15546 width(y)=width(y)+script_space;
15547 if (shift_down < sub2(cur_size)) shift_down=sub2(cur_size);
15548 clr=4*default_rule_thickness-
15549 ((shift_up-depth(x))-(height(y)-shift_down));
15550 if (clr > 0)
15551 {@+shift_down=shift_down+clr;
15552 clr=(abs(math_x_height(cur_size)*4)/5)-(shift_up-depth(x));
15553 if (clr > 0)
15554 {@+shift_up=shift_up+clr;
15555 shift_down=shift_down-clr;
15556 }
15557 }
15558 shift_amount(x)=delta; /*superscript is |delta| to the right of the subscript*/
15559 p=new_kern((shift_up-depth(x))-(height(y)-shift_down));link(x)=p;link(p)=y;
15560 x=vpack(x, natural);shift_amount(x)=shift_down;
15561 }
15562
15563 @ We have now tied up all the loose ends of the first pass of |mlist_to_hlist|.
15564 The second pass simply goes through and hooks everything together with the
15565 proper glue and penalties. It also handles the |left_noad| and |right_noad| that
15566 might be present, since |max_h| and |max_d| are now known. Variable |p| points
15567 to a node at the current end of the final hlist.
15568
15569 @<Make a second pass over the mlist,...@>=
15570 p=temp_head;link(p)=null;q=mlist;r_type=0;cur_style=style;
15571 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
15572 while (q!=null)
15573 {@+@<If node |q| is a style node, change the style and |goto delete_q|;
15574 otherwise if it is not a noad, put it into the hlist, advance |q|, and |goto
15575 done|; otherwise set |s| to the size of noad |q|, set |t| to the associated
15576 type (|ord_noad.. inner_noad|), and set |pen| to the associated penalty@>;
15577 @<Append inter-element spacing based on |r_type| and |t|@>;
15578 @<Append any |new_hlist| entries for |q|, and any appropriate penalties@>;
15579 if (type(q)==right_noad) t=open_noad;
15580 r_type=t;
15581 delete_q: r=q;q=link(q);free_node(r, s);
15582 done: ;}
15583
15584 @ Just before doing the big |case| switch in the second pass, the program
15585 sets up default values so that most of the branches are short.
15586
15587 @<If node |q| is a style node, change the style...@>=
15588 t=ord_noad;s=noad_size;pen=inf_penalty;
15589 switch (type(q)) {
15590 case op_noad: case open_noad: case close_noad:
15591 case punct_noad: case inner_noad: t=type(q);@+break;
15592 case bin_noad: {@+t=bin_noad;pen=bin_op_penalty;
15593 } @+break;
15594 case rel_noad: {@+t=rel_noad;pen=rel_penalty;
15595 } @+break;
15596 case ord_noad: case vcenter_noad: case over_noad:
15597 case under_noad: do_nothing;@+break;
15598 case radical_noad: s=radical_noad_size;@+break;
15599 case accent_noad: s=accent_noad_size;@+break;
15600 case fraction_noad: s=fraction_noad_size;@+break;
15601 case left_noad: case right_noad: t=make_left_right(q, style, max_d, max_h);@+break;
15602 case style_node: @<Change the current style and |goto delete_q|@>@;
15603 case whatsit_node: case penalty_node:
15604 case rule_node: case disc_node: case adjust_node:
15605 case ins_node: case mark_node:
15606 case glue_node: case kern_node: @t@>@;@/
15607 {@+link(p)=q;p=q;q=link(q);link(p)=null;goto done;
15608 }
15609 default:confusion("mlist3");
15610 @:this can't happen mlist3}{\quad mlist3@>
15611 }
15612
15613 @ The |make_left_right| function constructs a left or right delimiter of
15614 the required size and returns the value |open_noad| or |close_noad|. The
15615 |right_noad| and |left_noad| will both be based on the original |style|,
15616 so they will have consistent sizes.
15617
15618 We use the fact that |right_noad-left_noad==close_noad-open_noad|.
15619
15620 @<Declare math...@>=
15621 static small_number make_left_right(pointer @!q, small_number @!style,
15622 scaled @!max_d, scaled @!max_h)
15623 {@+scaled delta, @!delta1, @!delta2; /*dimensions used in the calculation*/
15624 cur_style=style;@<Set up the values...@>;
15625 delta2=max_d+axis_height(cur_size);
15626 delta1=max_h+max_d-delta2;
15627 if (delta2 > delta1) delta1=delta2; /*|delta1| is max distance from axis*/
15628 delta=(delta1/500)*delimiter_factor;
15629 delta2=delta1+delta1-delimiter_shortfall;
15630 if (delta < delta2) delta=delta2;
15631 new_hlist(q)=var_delimiter(delimiter(q), cur_size, delta);
15632 return type(q)-(left_noad-open_noad); /*|open_noad| or |close_noad|*/
15633 }
15634
15635 @ @<Change the current style and |goto delete_q|@>=
15636 {@+cur_style=subtype(q);s=style_node_size;
15637 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
15638 goto delete_q;
15639 }
15640
15641 @ The inter-element spacing in math formulas depends on an $8\times8$ table that
15642 \TeX\ preloads as a 64-digit string. The elements of this string have the
15643 following significance:
15644 $$\vbox{\halign{#\hfil\cr
15645 \.0 means no space;\cr
15646 \.1 means a conditional thin space (\.{\\nonscript\\mskip\\thinmuskip});\cr
15647 \.2 means a thin space (\.{\\mskip\\thinmuskip});\cr
15648 \.3 means a conditional medium space
15649 (\.{\\nonscript\\mskip\\medmuskip});\cr
15650 \.4 means a conditional thick space
15651 (\.{\\nonscript\\mskip\\thickmuskip});\cr
15652 \.* means an impossible case.\cr}}$$
15653 This is all pretty cryptic, but {\sl The \TeX book\/} explains what is
15654 supposed to happen, and the string makes it happen.
15655 @:TeXbook}{\sl The \TeX book@>
15656
15657 A global variable |magic_offset| is computed so that if |a| and |b| are
15658 in the range |ord_noad dotdot inner_noad|, then |str_pool[a*8+b+magic_offset]|
15659 is the digit for spacing between noad types |a| and |b|.
15660
15661 If \PASCAL\ had provided a good way to preload constant arrays, this part of
15662 the program would not have been so strange.
15663 @:PASCAL}{\PASCAL@>
15664
15665 @d math_spacing @;@/
15666 @t\hskip-35pt@>
15667 "0234000122*4000133**3**344*0400400*000000234000111*1111112341011"
15668 @t$ \hskip-35pt$@>
15669
15670 @ @<Glob...@>=
15671 static const int @!magic_offset=-9*ord_noad; /*used to find inter-element spacing*/
15672
15673 @ @<Append inter-element spacing based on |r_type| and |t|@>=
15674 if (r_type > 0) /*not the first noad*/
15675 {@+switch (so(math_spacing[r_type*8+t+magic_offset])) {
15676 case '0': x=0;@+break;
15677 case '1': if (cur_style < script_style) x=thin_mu_skip_code;@+else x=0;@+break;
15678 case '2': x=thin_mu_skip_code;@+break;
15679 case '3': if (cur_style < script_style) x=med_mu_skip_code;@+else x=0;@+break;
15680 case '4': if (cur_style < script_style) x=thick_mu_skip_code;@+else x=0;@+break;
15681 default:confusion("mlist4");
15682 @:this can't happen mlist4}{\quad mlist4@>
15683 }
15684 if (x!=0)
15685 {@+y=math_glue(glue_par(x), cur_mu);
15686 z=new_glue(y);glue_ref_count(y)=null;link(p)=z;p=z;@/
15687 subtype(z)=x+1; /*store a symbolic subtype*/
15688 }
15689 }
15690
15691 @ We insert a penalty node after the hlist entries of noad |q| if |pen|
15692 is not an ``infinite'' penalty, and if the node immediately following |q|
15693 is not a penalty node or a |rel_noad| or absent entirely.
15694
15695 @<Append any |new_hlist| entries for |q|, and any appropriate penalties@>=
15696 if (new_hlist(q)!=null)
15697 {@+link(p)=new_hlist(q);
15698 @/do@+{p=link(p);
15699 }@+ while (!(link(p)==null));
15700 }
15701 if (penalties) if (link(q)!=null) if (pen < inf_penalty)
15702 {@+r_type=type(link(q));
15703 if (r_type!=penalty_node) if (r_type!=rel_noad)
15704 {@+z=new_penalty(pen);link(p)=z;p=z;
15705 }
15706 }
15707
15708 @* Alignment.
15709 It's sort of a miracle whenever \.{\\halign} and \.{\\valign} work, because
15710 they cut across so many of the control structures of \TeX.
15711
15712 Therefore the
15713 present page is probably not the best place for a beginner to start reading
15714 this program; it is better to master everything else first.
15715
15716 Let us focus our thoughts on an example of what the input might be, in order
15717 to get some idea about how the alignment miracle happens. The example doesn't
15718 do anything useful, but it is sufficiently general to indicate all of the
15719 special cases that must be dealt with; please do not be disturbed by its
15720 apparent complexity and meaninglessness.
15721 $$\vbox{\halign{\.{#}\hfil\cr
15722 {}\\tabskip 2pt plus 3pt\cr
15723 {}\\halign to 300pt\{u1\#v1\&\cr
15724 \hskip 50pt\\tabskip 1pt plus 1fil u2\#v2\&\cr
15725 \hskip 50pt u3\#v3\\cr\cr
15726 \hskip 25pt a1\&\\omit a2\&\\vrule\\cr\cr
15727 \hskip 25pt \\noalign\{\\vskip 3pt\}\cr
15728 \hskip 25pt b1\\span b2\\cr\cr
15729 \hskip 25pt \\omit\&c2\\span\\omit\\cr\}\cr}}$$
15730 Here's what happens:
15731
15732 \yskip
15733 (0) When `\.{\\halign to 300pt\{}' is scanned, the |scan_spec| routine
15734 places the 300pt dimension onto the |save_stack|, and an |align_group|
15735 code is placed above it. This will make it possible to complete the alignment
15736 when the matching `\.\}' is found.
15737
15738 (1) The preamble is scanned next. Macros in the preamble are not expanded,
15739 @^preamble@>
15740 except as part of a tabskip specification. For example, if \.{u2} had been
15741 a macro in the preamble above, it would have been expanded, since \TeX\
15742 must look for `\.{minus...}' as part of the tabskip glue. A ``preamble list''
15743 is constructed based on the user's preamble; in our case it contains the
15744 following seven items:
15745 $$\vbox{\halign{\.{#}\hfil\qquad&(#)\hfil\cr
15746 {}\\glue 2pt plus 3pt&the tabskip preceding column 1\cr
15747 {}\\alignrecord, width $-\infty$&preamble info for column 1\cr
15748 {}\\glue 2pt plus 3pt&the tabskip between columns 1 and 2\cr
15749 {}\\alignrecord, width $-\infty$&preamble info for column 2\cr
15750 {}\\glue 1pt plus 1fil&the tabskip between columns 2 and 3\cr
15751 {}\\alignrecord, width $-\infty$&preamble info for column 3\cr
15752 {}\\glue 1pt plus 1fil&the tabskip following column 3\cr}}$$
15753 These ``alignrecord'' entries have the same size as an |unset_node|,
15754 since they will later be converted into such nodes. However, at the
15755 moment they have no |type| or |subtype| fields; they have |info| fields
15756 instead, and these |info| fields are initially set to the value |end_span|,
15757 for reasons explained below. Furthermore, the alignrecord nodes have no
15758 |height| or |depth| fields; these are renamed |u_part| and |v_part|,
15759 and they point to token lists for the templates of the alignment.
15760 For example, the |u_part| field in the first alignrecord points to the
15761 token list `\.{u1}', i.e., the template preceding the `\.\#' for column~1.
15762
15763 (2) \TeX\ now looks at what follows the \.{\\cr} that ended the preamble.
15764 It is not `\.{\\noalign}' or `\.{\\omit}', so this input is put back to
15765 be read again, and the template `\.{u1}' is fed to the scanner. Just
15766 before reading `\.{u1}', \TeX\ goes into restricted horizontal mode.
15767 Just after reading `\.{u1}', \TeX\ will see `\.{a1}', and then (when the
15768 {\.\&} is sensed) \TeX\ will see `\.{v1}'. Then \TeX\ scans an |endv|
15769 token, indicating the end of a column. At this point an |unset_node| is
15770 created, containing the contents of the current hlist (i.e., `\.{u1a1v1}').
15771 The natural width of this unset node replaces the |width| field of the
15772 alignrecord for column~1; in general, the alignrecords will record the
15773 maximum natural width that has occurred so far in a given column.
15774
15775 (3) Since `\.{\\omit}' follows the `\.\&', the templates for column~2
15776 are now bypassed. Again \TeX\ goes into restricted horizontal mode and
15777 makes an |unset_node| from the resulting hlist; but this time the
15778 hlist contains simply `\.{a2}'. The natural width of the new unset box
15779 is remembered in the |width| field of the alignrecord for column~2.
15780
15781 (4) A third |unset_node| is created for column 3, using essentially the
15782 mechanism that worked for column~1; this unset box contains `\.{u3\\vrule
15783 v3}'. The vertical rule in this case has running dimensions that will later
15784 extend to the height and depth of the whole first row, since each |unset_node|
15785 in a row will eventually inherit the height and depth of its enclosing box.
15786
15787 (5) The first row has now ended; it is made into a single unset box
15788 comprising the following seven items:
15789 $$\vbox{\halign{\hbox to 325pt{\qquad\.{#}\hfil}\cr
15790 {}\\glue 2pt plus 3pt\cr
15791 {}\\unsetbox for 1 column: u1a1v1\cr
15792 {}\\glue 2pt plus 3pt\cr
15793 {}\\unsetbox for 1 column: a2\cr
15794 {}\\glue 1pt plus 1fil\cr
15795 {}\\unsetbox for 1 column: u3\\vrule v3\cr
15796 {}\\glue 1pt plus 1fil\cr}}$$
15797 The width of this unset row is unimportant, but it has the correct height
15798 and depth, so the correct baselineskip glue will be computed as the row
15799 is inserted into a vertical list.
15800
15801 (6) Since `\.{\\noalign}' follows the current \.{\\cr}, \TeX\ appends
15802 additional material (in this case \.{\\vskip 3pt}) to the vertical list.
15803 While processing this material, \TeX\ will be in internal vertical
15804 mode, and |no_align_group| will be on |save_stack|.
15805
15806 (7) The next row produces an unset box that looks like this:
15807 $$\vbox{\halign{\hbox to 325pt{\qquad\.{#}\hfil}\cr
15808 {}\\glue 2pt plus 3pt\cr
15809 {}\\unsetbox for 2 columns: u1b1v1u2b2v2\cr
15810 {}\\glue 1pt plus 1fil\cr
15811 {}\\unsetbox for 1 column: {\rm(empty)}\cr
15812 {}\\glue 1pt plus 1fil\cr}}$$
15813 The natural width of the unset box that spans columns 1~and~2 is stored
15814 in a ``span node,'' which we will explain later; the |info| field of the
15815 alignrecord for column~1 now points to the new span node, and the |info|
15816 of the span node points to |end_span|.
15817
15818 (8) The final row produces the unset box
15819 $$\vbox{\halign{\hbox to 325pt{\qquad\.{#}\hfil}\cr
15820 {}\\glue 2pt plus 3pt\cr
15821 {}\\unsetbox for 1 column: {\rm(empty)}\cr
15822 {}\\glue 2pt plus 3pt\cr
15823 {}\\unsetbox for 2 columns: u2c2v2\cr
15824 {}\\glue 1pt plus 1fil\cr}}$$
15825 A new span node is attached to the alignrecord for column 2.
15826
15827 (9) The last step is to compute the true column widths and to change all the
15828 unset boxes to hboxes, appending the whole works to the vertical list that
15829 encloses the \.{\\halign}. The rules for deciding on the final widths of
15830 each unset column box will be explained below.
15831
15832 \yskip\noindent
15833 Note that as \.{\\halign} is being processed, we fearlessly give up control
15834 to the rest of \TeX. At critical junctures, an alignment routine is
15835 called upon to step in and do some little action, but most of the time
15836 these routines just lurk in the background. It's something like
15837 post-hypnotic suggestion.
15838
15839 @ We have mentioned that alignrecords contain no |height| or |depth| fields.
15840 Their |glue_sign| and |glue_order| are pre-empted as well, since it
15841 is necessary to store information about what to do when a template ends.
15842 This information is called the |extra_info| field.
15843
15844 @d u_part(A) mem[A+height_offset].i /*pointer to \<u_j> token list*/
15845 @d v_part(A) mem[A+depth_offset].i /*pointer to \<v_j> token list*/
15846 @d extra_info(A) info(A+list_offset) /*info to remember during template*/
15847
15848 @ Alignments can occur within alignments, so a small stack is used to access
15849 the alignrecord information. At each level we have a |preamble| pointer,
15850 indicating the beginning of the preamble list; a |cur_align| pointer,
15851 indicating the current position in the preamble list; a |cur_span| pointer,
15852 indicating the value of |cur_align| at the beginning of a sequence of
15853 spanned columns; a |cur_loop| pointer, indicating the tabskip glue before
15854 an alignrecord that should be copied next if the current list is extended;
15855 and the |align_state| variable, which indicates the nesting of braces so
15856 that \.{\\cr} and \.{\\span} and tab marks are properly intercepted.
15857 There also are pointers |cur_head| and |cur_tail| to the head and tail
15858 of a list of adjustments being moved out from horizontal mode to
15859 vertical~mode.
15860
15861 The current values of these seven quantities appear in global variables;
15862 when they have to be pushed down, they are stored in 5-word nodes, and
15863 |align_ptr| points to the topmost such node.
15864
15865 @d preamble link(align_head) /*the current preamble list*/
15866 @d align_stack_node_size 5 /*number of |mem| words to save alignment states*/
15867
15868 @<Glob...@>=
15869 static pointer @!cur_align; /*current position in preamble list*/
15870 static pointer @!cur_span; /*start of currently spanned columns in preamble list*/
15871 static pointer @!cur_loop; /*place to copy when extending a periodic preamble*/
15872 static pointer @!align_ptr; /*most recently pushed-down alignment stack node*/
15873 static pointer @!cur_head, @!cur_tail; /*adjustment list pointers*/
15874
15875 @ The |align_state| and |preamble| variables are initialized elsewhere.
15876
15877 @<Set init...@>=
15878 align_ptr=null;cur_align=null;cur_span=null;cur_loop=null;
15879 cur_head=null;cur_tail=null;
15880
15881 @ Alignment stack maintenance is handled by a pair of trivial routines
15882 called |push_alignment| and |pop_alignment|.
15883
15884 @p static void push_alignment(void)
15885 {@+pointer p; /*the new alignment stack node*/
15886 p=get_node(align_stack_node_size);
15887 link(p)=align_ptr;info(p)=cur_align;
15888 llink(p)=preamble;rlink(p)=cur_span;
15889 mem[p+2].i=cur_loop;mem[p+3].i=align_state;
15890 info(p+4)=cur_head;link(p+4)=cur_tail;
15891 align_ptr=p;
15892 cur_head=get_avail();
15893 }
15894 @#
15895 static void pop_alignment(void)
15896 {@+pointer p; /*the top alignment stack node*/
15897 free_avail(cur_head);
15898 p=align_ptr;
15899 cur_tail=link(p+4);cur_head=info(p+4);
15900 align_state=mem[p+3].i;cur_loop=mem[p+2].i;
15901 cur_span=rlink(p);preamble=llink(p);
15902 cur_align=info(p);align_ptr=link(p);
15903 free_node(p, align_stack_node_size);
15904 }
15905
15906 @ \TeX\ has eight procedures that govern alignments: |init_align| and
15907 |fin_align| are used at the very beginning and the very end; |init_row| and
15908 |fin_row| are used at the beginning and end of individual rows; |init_span|
15909 is used at the beginning of a sequence of spanned columns (possibly involving
15910 only one column); |init_col| and |fin_col| are used at the beginning and
15911 end of individual columns; and |align_peek| is used after \.{\\cr} to see
15912 whether the next item is \.{\\noalign}.
15913
15914 We shall consider these routines in the order they are first used during
15915 the course of a complete \.{\\halign}, namely |init_align|, |align_peek|,
15916 |init_row|, |init_span|, |init_col|, |fin_col|, |fin_row|, |fin_align|.
15917
15918 @ When \.{\\halign} or \.{\\valign} has been scanned in an appropriate
15919 mode, \TeX\ calls |init_align|, whose task is to get everything off to a
15920 good start. This mostly involves scanning the preamble and putting its
15921 information into the preamble list.
15922 @^preamble@>
15923
15924 @p @t\4@>@<Declare the procedure called |get_preamble_token|@>@t@>@/
15925 static void align_peek(void);@/
15926 static void normal_paragraph(void);@/
15927 static void init_align(void)
15928 {@+
15929 pointer save_cs_ptr; /*|warning_index| value for error messages*/
15930 pointer @!p; /*for short-term temporary use*/
15931 save_cs_ptr=cur_cs; /*\.{\\halign} or \.{\\valign}, usually*/
15932 push_alignment();align_state=-1000000; /*enter a new alignment level*/
15933 @<Check for improper alignment in displayed math@>;
15934 push_nest(); /*enter a new semantic level*/
15935 @<Change current mode to |-vmode| for \.{\\halign}, |-hmode| for \.{\\valign}@>;
15936 scan_spec(align_group, false);@/
15937 @<Scan the preamble and record it in the |preamble| list@>;
15938 new_save_level(align_group);
15939 if (every_cr!=null) begin_token_list(every_cr, every_cr_text);
15940 align_peek(); /*look for \.{\\noalign} or \.{\\omit}*/
15941 }
15942
15943 @ In vertical modes, |prev_depth| already has the correct value. But
15944 if we are in |mmode| (displayed formula mode), we reach out to the
15945 enclosing vertical mode for the |prev_depth| value that produces the
15946 correct baseline calculations.
15947
15948 @<Change current mode...@>=
15949 if (mode==mmode)
15950 {@+mode=-vmode;prev_depth=nest[nest_ptr-2].aux_field.sc;
15951 }
15952 else if (mode > 0) negate(mode)
15953
15954 @ When \.{\\halign} is used as a displayed formula, there should be
15955 no other pieces of mlists present.
15956
15957 @<Check for improper alignment in displayed math@>=
15958 if ((mode==mmode)&&((tail!=head)||(incompleat_noad!=null)))
15959 {@+print_err("Improper ");print_esc("halign");print(" inside $$'s");
15960 @.Improper \\halign...@>
15961 help3("Displays can use special alignments (like \\eqalignno)",@/
15962 "only if nothing but the alignment itself is between $$'s.",@/
15963 "So I've deleted the formulas that preceded this alignment.");
15964 error();flush_math();
15965 }
15966
15967 @ @<Scan the preamble and record it in the |preamble| list@>=
15968 preamble=null;cur_align=align_head;cur_loop=null;scanner_status=aligning;
15969 warning_index=save_cs_ptr;align_state=-1000000;
15970 /*at this point, |cur_cmd==left_brace|*/
15971 loop@+{@+@<Append the current tabskip glue to the preamble list@>;
15972 if (cur_cmd==car_ret) goto done; /*\.{\\cr} ends the preamble*/
15973 @<Scan preamble text until |cur_cmd| is |tab_mark| or |car_ret|, looking
15974 for changes in the tabskip glue; append an alignrecord to the preamble list@>;
15975 }
15976 done: scanner_status=normal
15977
15978 @ @<Append the current tabskip glue to the preamble list@>=
15979 link(cur_align)=new_param_glue(tab_skip_code);
15980 cur_align=link(cur_align)
15981
15982 @ @<Scan preamble text until |cur_cmd| is |tab_mark| or |car_ret|...@>=
15983 @<Scan the template \<u_j>, putting the resulting token list in |hold_head|@>;
15984 link(cur_align)=new_null_box();cur_align=link(cur_align); /*a new alignrecord*/
15985 info(cur_align)=end_span;width(cur_align)=null_flag;
15986 u_part(cur_align)=link(hold_head);
15987 @<Scan the template \<v_j>, putting the resulting token list in |hold_head|@>;
15988 v_part(cur_align)=link(hold_head)
15989
15990 @ We enter `\.{\\span}' into |eqtb| with |tab_mark| as its command code,
15991 and with |span_code| as the command modifier. This makes \TeX\ interpret it
15992 essentially the same as an alignment delimiter like `\.\&', yet it is
15993 recognizably different when we need to distinguish it from a normal delimiter.
15994 It also turns out to be useful to give a special |cr_code| to `\.{\\cr}',
15995 and an even larger |cr_cr_code| to `\.{\\crcr}'.
15996
15997 The end of a template is represented by two ``frozen'' control sequences
15998 called \.{\\endtemplate}. The first has the command code |end_template|, which
15999 is | > outer_call|, so it will not easily disappear in the presence of errors.
16000 The |get_x_token| routine converts the first into the second, which has |endv|
16001 as its command code.
16002
16003 @d span_code 256 /*distinct from any character*/
16004 @d cr_code 257 /*distinct from |span_code| and from any character*/
16005 @d cr_cr_code (cr_code+1) /*this distinguishes \.{\\crcr} from \.{\\cr}*/
16006 @d end_template_token cs_token_flag+frozen_end_template
16007
16008 @<Put each of \TeX's primitives into the hash table@>=
16009 primitive("span", tab_mark, span_code);@/
16010 @!@:span\_}{\.{\\span} primitive@>
16011 primitive("cr", car_ret, cr_code);
16012 @!@:cr\_}{\.{\\cr} primitive@>
16013 text(frozen_cr)=text(cur_val);eqtb[frozen_cr]=eqtb[cur_val];@/
16014 primitive("crcr", car_ret, cr_cr_code);
16015 @!@:cr\_cr\_}{\.{\\crcr} primitive@>
16016 text(frozen_end_template)=text(frozen_endv)=s_no("endtemplate");
16017 @.endtemplate@>
16018 eq_type(frozen_endv)=endv;equiv(frozen_endv)=null_list;
16019 eq_level(frozen_endv)=level_one;@/
16020 eqtb[frozen_end_template]=eqtb[frozen_endv];
16021 eq_type(frozen_end_template)=end_template;
16022
16023 @ @<Cases of |print_cmd_chr|...@>=
16024 case tab_mark: if (chr_code==span_code) print_esc("span");
16025 else chr_cmd("alignment tab character ")@;@+break;
16026 case car_ret: if (chr_code==cr_code) print_esc("cr");
16027 else print_esc("crcr");@+break;
16028
16029 @ The preamble is copied directly, except that \.{\\tabskip} causes a change
16030 to the tabskip glue, thereby possibly expanding macros that immediately
16031 follow it. An appearance of \.{\\span} also causes such an expansion.
16032
16033 Note that if the preamble contains `\.{\\global\\tabskip}', the `\.{\\global}'
16034 token survives in the preamble and the `\.{\\tabskip}' defines new
16035 tabskip glue (locally).
16036
16037 @<Declare the procedure called |get_preamble_token|@>=
16038 static void get_preamble_token(void)
16039 {@+
16040 restart: get_token();
16041 while ((cur_chr==span_code)&&(cur_cmd==tab_mark))
16042 {@+get_token(); /*this token will be expanded once*/
16043 if (cur_cmd > max_command)
16044 {@+expand();get_token();
16045 }
16046 }
16047 if (cur_cmd==endv)
16048 fatal_error("(interwoven alignment preambles are not allowed)");
16049 @.interwoven alignment preambles...@>
16050 if ((cur_cmd==assign_glue)&&(cur_chr==glue_base+tab_skip_code))
16051 {@+scan_optional_equals();scan_glue(glue_val);
16052 if (global_defs > 0) geq_define(glue_base+tab_skip_code, glue_ref, cur_val);
16053 else eq_define(glue_base+tab_skip_code, glue_ref, cur_val);
16054 goto restart;
16055 }
16056 }
16057
16058 @ Spaces are eliminated from the beginning of a template.
16059
16060 @<Scan the template \<u_j>...@>=
16061 p=hold_head;link(p)=null;
16062 loop@+{@+get_preamble_token();
16063 if (cur_cmd==mac_param) goto done1;
16064 if ((cur_cmd <= car_ret)&&(cur_cmd >= tab_mark)&&(align_state==-1000000))
16065 if ((p==hold_head)&&(cur_loop==null)&&(cur_cmd==tab_mark)
16066 ) cur_loop=cur_align;
16067 else{@+print_err("Missing # inserted in alignment preamble");
16068 @.Missing \# inserted...@>
16069 help3("There should be exactly one # between &'s, when an",@/
16070 "\\halign or \\valign is being set up. In this case you had",@/
16071 "none, so I've put one in; maybe that will work.");
16072 back_error();goto done1;
16073 }
16074 else if ((cur_cmd!=spacer)||(p!=hold_head))
16075 {@+link(p)=get_avail();p=link(p);info(p)=cur_tok;
16076 }
16077 }
16078 done1:
16079
16080 @ @<Scan the template \<v_j>...@>=
16081 p=hold_head;link(p)=null;
16082 loop@+{@+resume: get_preamble_token();
16083 if ((cur_cmd <= car_ret)&&(cur_cmd >= tab_mark)&&(align_state==-1000000))
16084 goto done2;
16085 if (cur_cmd==mac_param)
16086 {@+print_err("Only one # is allowed per tab");
16087 @.Only one \# is allowed...@>
16088 help3("There should be exactly one # between &'s, when an",@/
16089 "\\halign or \\valign is being set up. In this case you had",@/
16090 "more than one, so I'm ignoring all but the first.");
16091 error();goto resume;
16092 }
16093 link(p)=get_avail();p=link(p);info(p)=cur_tok;
16094 }
16095 done2: link(p)=get_avail();p=link(p);
16096 info(p)=end_template_token /*put \.{\\endtemplate} at the end*/
16097
16098 @ The tricky part about alignments is getting the templates into the
16099 scanner at the right time, and recovering control when a row or column
16100 is finished.
16101
16102 We usually begin a row after each \.{\\cr} has been sensed, unless that
16103 \.{\\cr} is followed by \.{\\noalign} or by the right brace that terminates
16104 the alignment. The |align_peek| routine is used to look ahead and do
16105 the right thing; it either gets a new row started, or gets a \.{\\noalign}
16106 started, or finishes off the alignment.
16107
16108 @<Declare the procedure called |align_peek|@>=
16109 static void align_peek(void)
16110 {@+
16111 restart: align_state=1000000;
16112 @/do@+{get_x_or_protected();
16113 }@+ while (!(cur_cmd!=spacer));
16114 if (cur_cmd==no_align)
16115 {@+scan_left_brace();new_save_level(no_align_group);
16116 if (mode==-vmode) normal_paragraph();
16117 }
16118 else if (cur_cmd==right_brace) fin_align();
16119 else if ((cur_cmd==car_ret)&&(cur_chr==cr_cr_code))
16120 goto restart; /*ignore \.{\\crcr}*/
16121 else{@+init_row(); /*start a new row*/
16122 init_col(); /*start a new column and replace what we peeked at*/
16123 }
16124 }
16125
16126 @ To start a row (i.e., a `row' that rhymes with `dough' but not with `bough'),
16127 we enter a new semantic level, copy the first tabskip glue, and change
16128 from internal vertical mode to restricted horizontal mode or vice versa.
16129 The |space_factor| and |prev_depth| are not used on this semantic level,
16130 but we clear them to zero just to be tidy.
16131
16132 @p @t\4@>@<Declare the procedure called |init_span|@>@t@>@/
16133 static void init_row(void)
16134 {@+push_nest();mode=(-hmode-vmode)-mode;
16135 if (mode==-hmode) space_factor=0;@+else prev_depth=0;
16136 tail_append(new_glue(glue_ptr(preamble)));
16137 subtype(tail)=tab_skip_code+1;@/
16138 cur_align=link(preamble);cur_tail=cur_head;init_span(cur_align);
16139 }
16140
16141 @ The parameter to |init_span| is a pointer to the alignrecord where the
16142 next column or group of columns will begin. A new semantic level is
16143 entered, so that the columns will generate a list for subsequent packaging.
16144
16145 @<Declare the procedure called |init_span|@>=
16146 static void init_span(pointer @!p)
16147 {@+push_nest();
16148 if (mode==-hmode) space_factor=1000;
16149 else{@+prev_depth=ignore_depth;normal_paragraph();
16150 }
16151 cur_span=p;
16152 }
16153
16154 @ When a column begins, we assume that |cur_cmd| is either |omit| or else
16155 the current token should be put back into the input until the \<u_j>
16156 template has been scanned. (Note that |cur_cmd| might be |tab_mark| or
16157 |car_ret|.) We also assume that |align_state| is approximately 1000000 at
16158 this time. We remain in the same mode, and start the template if it is
16159 called for.
16160
16161 @p static void init_col(void)
16162 {@+extra_info(cur_align)=cur_cmd;
16163 if (cur_cmd==omit) align_state=0;
16164 else{@+back_input();begin_token_list(u_part(cur_align), u_template);
16165 } /*now |align_state==1000000|*/
16166 }
16167
16168 @ The scanner sets |align_state| to zero when the \<u_j> template ends. When
16169 a subsequent \.{\\cr} or \.{\\span} or tab mark occurs with |align_state==0|,
16170 the scanner activates the following code, which fires up the \<v_j> template.
16171 We need to remember the |cur_chr|, which is either |cr_cr_code|, |cr_code|,
16172 |span_code|, or a character code, depending on how the column text has ended.
16173
16174 This part of the program had better not be activated when the preamble
16175 to another alignment is being scanned, or when no alignment preamble is active.
16176
16177 @<Insert the \(v)\<v_j>...@>=
16178 {@+if ((scanner_status==aligning)||(cur_align==null))
16179 fatal_error("(interwoven alignment preambles are not allowed)");
16180 @.interwoven alignment preambles...@>
16181 cur_cmd=extra_info(cur_align);extra_info(cur_align)=cur_chr;
16182 if (cur_cmd==omit) begin_token_list(omit_template, v_template);
16183 else begin_token_list(v_part(cur_align), v_template);
16184 align_state=1000000;goto restart;
16185 }
16186
16187 @ The token list |omit_template| just referred to is a constant token
16188 list that contains the special control sequence \.{\\endtemplate} only.
16189
16190 @<Initialize the special...@>=
16191 info(omit_template)=end_template_token; /*|link(omit_template)==null|*/
16192
16193 @ When the |endv| command at the end of a \<v_j> template comes through the
16194 scanner, things really start to happen; and it is the |fin_col| routine
16195 that makes them happen. This routine returns |true| if a row as well as a
16196 column has been finished.
16197
16198 @p static bool fin_col(void)
16199 {@+
16200 pointer p; /*the alignrecord after the current one*/
16201 pointer @!q, @!r; /*temporary pointers for list manipulation*/
16202 pointer @!s; /*a new span node*/
16203 pointer @!u; /*a new unset box*/
16204 scaled @!w; /*natural width*/
16205 glue_ord @!o; /*order of infinity*/
16206 halfword @!n; /*span counter*/
16207 if (cur_align==null) confusion("endv");
16208 q=link(cur_align);@+if (q==null) confusion("endv");
16209 @:this can't happen endv}{\quad endv@>
16210 if (align_state < 500000)
16211 fatal_error("(interwoven alignment preambles are not allowed)");
16212 @.interwoven alignment preambles...@>
16213 p=link(q);
16214 @<If the preamble list has been traversed, check that the row has ended@>;
16215 if (extra_info(cur_align)!=span_code)
16216 {@+unsave();new_save_level(align_group);@/
16217 @<Package an unset box for the current column and record its width@>;
16218 @<Copy the tabskip glue between columns@>;
16219 if (extra_info(cur_align) >= cr_code)
16220 {@+return true;
16221 }
16222 init_span(p);
16223 }
16224 align_state=1000000;
16225 @/do@+{get_x_or_protected();
16226 }@+ while (!(cur_cmd!=spacer));
16227 cur_align=p;
16228 init_col();return false;
16229 }
16230
16231 @ @<If the preamble list has been traversed, check that the row has ended@>=
16232 if ((p==null)&&(extra_info(cur_align) < cr_code))
16233 if (cur_loop!=null) @<Lengthen the preamble periodically@>@;
16234 else{@+print_err("Extra alignment tab has been changed to ");
16235 @.Extra alignment tab...@>
16236 print_esc("cr");
16237 help3("You have given more \\span or & marks than there were",@/
16238 "in the preamble to the \\halign or \\valign now in progress.",@/
16239 "So I'll assume that you meant to type \\cr instead.");
16240 extra_info(cur_align)=cr_code;error();
16241 }
16242
16243 @ @<Lengthen the preamble...@>=
16244 {@+link(q)=new_null_box();p=link(q); /*a new alignrecord*/
16245 info(p)=end_span;width(p)=null_flag;cur_loop=link(cur_loop);
16246 @<Copy the templates from node |cur_loop| into node |p|@>;
16247 cur_loop=link(cur_loop);
16248 link(p)=new_glue(glue_ptr(cur_loop));
16249 subtype(link(p))=tab_skip_code+1;
16250 }
16251
16252 @ @<Copy the templates from node |cur_loop| into node |p|@>=
16253 q=hold_head;r=u_part(cur_loop);
16254 while (r!=null)
16255 {@+link(q)=get_avail();q=link(q);info(q)=info(r);r=link(r);
16256 }
16257 link(q)=null;u_part(p)=link(hold_head);
16258 q=hold_head;r=v_part(cur_loop);
16259 while (r!=null)
16260 {@+link(q)=get_avail();q=link(q);info(q)=info(r);r=link(r);
16261 }
16262 link(q)=null;v_part(p)=link(hold_head)
16263
16264 @ @<Copy the tabskip glue...@>=
16265 tail_append(new_glue(glue_ptr(link(cur_align))));
16266 subtype(tail)=tab_skip_code+1
16267
16268 @ @<Package an unset...@>=
16269 {@+if (mode==-hmode)
16270 {@+adjust_tail=cur_tail;u=hpack(link(head), natural);w=width(u);
16271 cur_tail=adjust_tail;adjust_tail=null;
16272 }
16273 else{@+u=vpackage(link(head), natural, 0);w=height(u);
16274 }
16275 n=min_quarterword; /*this represents a span count of 1*/
16276 if (cur_span!=cur_align) @<Update width entry for spanned columns@>@;
16277 else if (w > width(cur_align)) width(cur_align)=w;
16278 type(u)=unset_node;span_count(u)=n;@/
16279 @<Determine the stretch order@>;
16280 glue_order(u)=o;glue_stretch(u)=total_stretch[o];@/
16281 @<Determine the shrink order@>;
16282 glue_sign(u)=o;glue_shrink(u)=total_shrink[o];@/
16283 pop_nest();link(tail)=u;tail=u;
16284 }
16285
16286 @ A span node is a 2-word record containing |width|, |info|, and |link|
16287 fields. The |link| field is not really a link, it indicates the number of
16288 spanned columns; the |info| field points to a span node for the same
16289 starting column, having a greater extent of spanning, or to |end_span|,
16290 which has the largest possible |link| field; the |width| field holds the
16291 largest natural width corresponding to a particular set of spanned columns.
16292
16293 A list of the maximum widths so far, for spanned columns starting at a
16294 given column, begins with the |info| field of the alignrecord for that
16295 column.
16296
16297 @d span_node_size 2 /*number of |mem| words for a span node*/
16298
16299 @<Initialize the special list heads...@>=
16300 link(end_span)=max_quarterword+1;info(end_span)=null;
16301
16302 @ @<Update width entry for spanned columns@>=
16303 {@+q=cur_span;
16304 @/do@+{incr(n);q=link(link(q));
16305 }@+ while (!(q==cur_align));
16306 if (n > max_quarterword) confusion("256 spans"); /*this can happen, but won't*/
16307 @^system dependencies@>
16308 @:this can't happen 256 spans}{\quad 256 spans@>
16309 q=cur_span;while (link(info(q)) < n) q=info(q);
16310 if (link(info(q)) > n)
16311 {@+s=get_node(span_node_size);info(s)=info(q);link(s)=n;
16312 info(q)=s;width(s)=w;
16313 }
16314 else if (width(info(q)) < w) width(info(q))=w;
16315 }
16316
16317 @ At the end of a row, we append an unset box to the current vlist (for
16318 \.{\\halign}) or the current hlist (for \.{\\valign}). This unset box
16319 contains the unset boxes for the columns, separated by the tabskip glue.
16320 Everything will be set later.
16321
16322 @p static void fin_row(void)
16323 {@+pointer p; /*the new unset box*/
16324 if (mode==-hmode)
16325 {@+p=hpack(link(head), natural);
16326 pop_nest();append_to_vlist(p);
16327 if (cur_head!=cur_tail)
16328 {@+link(tail)=link(cur_head);tail=cur_tail;
16329 }
16330 }
16331 else{@+p=vpack(link(head), natural);pop_nest();
16332 link(tail)=p;tail=p;space_factor=1000;
16333 }
16334 type(p)=unset_node;glue_stretch(p)=0;
16335 if (every_cr!=null) begin_token_list(every_cr, every_cr_text);
16336 align_peek();
16337 } /*note that |glue_shrink(p)==0| since |glue_shrink====shift_amount|*/
16338
16339 @ Finally, we will reach the end of the alignment, and we can breathe a
16340 sigh of relief that memory hasn't overflowed. All the unset boxes will now be
16341 set so that the columns line up, taking due account of spanned columns.
16342
16343 @p static void do_assignments(void);@/
16344 static void resume_after_display(void);@/
16345 static void build_page(void);@/
16346 static void fin_align(void)
16347 {@+pointer @!p, @!q, @!r, @!s, @!u, @!v; /*registers for the list operations*/
16348 scaled @!t, @!w; /*width of column*/
16349 scaled @!o; /*shift offset for unset boxes*/
16350 halfword @!n; /*matching span amount*/
16351 scaled @!rule_save; /*temporary storage for |overfull_rule|*/
16352 memory_word @!aux_save; /*temporary storage for |aux|*/
16353 if (cur_group!=align_group) confusion("align1");
16354 @:this can't happen align}{\quad align@>
16355 unsave(); /*that |align_group| was for individual entries*/
16356 if (cur_group!=align_group) confusion("align0");
16357 unsave(); /*that |align_group| was for the whole alignment*/
16358 if (nest[nest_ptr-1].mode_field==mmode) o=display_indent;
16359 else o=0;
16360 @<Go through the preamble list, determining the column widths and changing
16361 the alignrecords to dummy unset boxes@>;
16362 @<Package the preamble list, to determine the actual tabskip glue amounts,
16363 and let |p| point to this prototype box@>;
16364 @<Set the glue in all the unset boxes of the current list@>;
16365 flush_node_list(p);pop_alignment();
16366 @<Insert the \(c)current list into its environment@>;
16367 } @/
16368 @t\4@>@<Declare the procedure called |align_peek|@>@;
16369
16370 @ It's time now to dismantle the preamble list and to compute the column
16371 widths. Let $w_{ij}$ be the maximum of the natural widths of all entries
16372 that span columns $i$ through $j$, inclusive. The alignrecord for column~$i$
16373 contains $w_{ii}$ in its |width| field, and there is also a linked list of
16374 the nonzero $w_{ij}$ for increasing $j$, accessible via the |info| field;
16375 these span nodes contain the value $j-i+|min_quarterword|$ in their
16376 |link| fields. The values of $w_{ii}$ were initialized to |null_flag|, which
16377 we regard as $-\infty$.
16378
16379 The final column widths are defined by the formula
16380 $$w_j=\max_{1\le i\le j}\biggl( w_{ij}-\sum_{i\le k<j}(t_k+w_k)\biggr),$$
16381 where $t_k$ is the natural width of the tabskip glue between columns
16382 $k$ and~$k+1$. However, if $w_{ij}=-\infty$ for all |i| in the range
16383 |1 <= i <= j| (i.e., if every entry that involved column~|j| also involved
16384 column~|j+1|), we let $w_j=0$, and we zero out the tabskip glue after
16385 column~|j|.
16386
16387 \TeX\ computes these values by using the following scheme: First $w_1=w_{11}$.
16388 Then replace $w_{2j}$ by $\max(w_{2j},w_{1j}-t_1-w_1)$, for all $j>1$.
16389 Then $w_2=w_{22}$. Then replace $w_{3j}$ by $\max(w_{3j},w_{2j}-t_2-w_2)$
16390 for all $j>2$; and so on. If any $w_j$ turns out to be $-\infty$, its
16391 value is changed to zero and so is the next tabskip.
16392
16393 @<Go through the preamble list,...@>=
16394 q=link(preamble);
16395 @/do@+{flush_list(u_part(q));flush_list(v_part(q));
16396 p=link(link(q));
16397 if (width(q)==null_flag)
16398 @<Nullify |width(q)| and the tabskip glue following this column@>;
16399 if (info(q)!=end_span)
16400 @<Merge the widths in the span nodes of |q| with those of |p|, destroying
16401 the span nodes of |q|@>;
16402 type(q)=unset_node;span_count(q)=min_quarterword;height(q)=0;
16403 depth(q)=0;glue_order(q)=normal;glue_sign(q)=normal;
16404 glue_stretch(q)=0;glue_shrink(q)=0;q=p;
16405 }@+ while (!(q==null))
16406
16407 @ @<Nullify |width(q)| and the tabskip glue following this column@>=
16408 {@+width(q)=0;r=link(q);s=glue_ptr(r);
16409 if (s!=zero_glue)
16410 {@+add_glue_ref(zero_glue);delete_glue_ref(s);
16411 glue_ptr(r)=zero_glue;
16412 }
16413 }
16414
16415 @ Merging of two span-node lists is a typical exercise in the manipulation of
16416 linearly linked data structures. The essential invariant in the following
16417 |@/do@+{| loop is that we want to dispense with node |r|, in |q|'s list,
16418 and |u| is its successor; all nodes of |p|'s list up to and including |s|
16419 have been processed, and the successor of |s| matches |r| or precedes |r|
16420 or follows |r|, according as |link(r)==n| or |link(r) > n| or |link(r) < n|.
16421
16422 @<Merge the widths...@>=
16423 {@+t=width(q)+width(glue_ptr(link(q)));
16424 r=info(q);s=end_span;info(s)=p;n=min_quarterword+1;
16425 @/do@+{width(r)=width(r)-t;u=info(r);
16426 while (link(r) > n)
16427 {@+s=info(s);n=link(info(s))+1;
16428 }
16429 if (link(r) < n)
16430 {@+info(r)=info(s);info(s)=r;decr(link(r));s=r;
16431 }
16432 else{@+if (width(r) > width(info(s))) width(info(s))=width(r);
16433 free_node(r, span_node_size);
16434 }
16435 r=u;
16436 }@+ while (!(r==end_span));
16437 }
16438
16439 @ Now the preamble list has been converted to a list of alternating unset
16440 boxes and tabskip glue, where the box widths are equal to the final
16441 column sizes. In case of \.{\\valign}, we change the widths to heights,
16442 so that a correct error message will be produced if the alignment is
16443 overfull or underfull.
16444
16445 @<Package the preamble list...@>=
16446 save_ptr=save_ptr-2;pack_begin_line=-mode_line;
16447 if (mode==-vmode)
16448 {@+rule_save=overfull_rule;
16449 overfull_rule=0; /*prevent rule from being packaged*/
16450 p=hpack(preamble, saved(1), saved(0));overfull_rule=rule_save;
16451 }
16452 else{@+q=link(preamble);
16453 @/do@+{height(q)=width(q);width(q)=0;q=link(link(q));
16454 }@+ while (!(q==null));
16455 p=vpack(preamble, saved(1), saved(0));
16456 q=link(preamble);
16457 @/do@+{width(q)=height(q);height(q)=0;q=link(link(q));
16458 }@+ while (!(q==null));
16459 }
16460 pack_begin_line=0
16461
16462 @ @<Set the glue in all the unset...@>=
16463 q=link(head);s=head;
16464 while (q!=null)
16465 {@+if (!is_char_node(q))
16466 if (type(q)==unset_node)
16467 @<Set the unset box |q| and the unset boxes in it@>@;
16468 else if (type(q)==rule_node)
16469 @<Make the running dimensions in rule |q| extend to the boundaries of
16470 the alignment@>;
16471 s=q;q=link(q);
16472 }
16473
16474 @ @<Make the running dimensions in rule |q| extend...@>=
16475 {@+if (is_running(width(q))) width(q)=width(p);
16476 if (is_running(height(q))) height(q)=height(p);
16477 if (is_running(depth(q))) depth(q)=depth(p);
16478 if (o!=0)
16479 {@+r=link(q);link(q)=null;q=hpack(q, natural);
16480 shift_amount(q)=o;link(q)=r;link(s)=q;
16481 }
16482 }
16483
16484 @ The unset box |q| represents a row that contains one or more unset boxes,
16485 depending on how soon \.{\\cr} occurred in that row.
16486
16487 @<Set the unset box |q| and the unset boxes in it@>=
16488 {@+if (mode==-vmode)
16489 {@+type(q)=hlist_node;width(q)=width(p);
16490 }
16491 else{@+type(q)=vlist_node;height(q)=height(p);
16492 }
16493 glue_order(q)=glue_order(p);glue_sign(q)=glue_sign(p);
16494 glue_set(q)=glue_set(p);shift_amount(q)=o;
16495 r=link(list_ptr(q));s=link(list_ptr(p));
16496 @/do@+{@<Set the glue in node |r| and change it from an unset node@>;
16497 r=link(link(r));s=link(link(s));
16498 }@+ while (!(r==null));
16499 }
16500
16501 @ A box made from spanned columns will be followed by tabskip glue nodes and
16502 by empty boxes as if there were no spanning. This permits perfect alignment
16503 of subsequent entries, and it prevents values that depend on floating point
16504 arithmetic from entering into the dimensions of any boxes.
16505
16506 @<Set the glue in node |r|...@>=
16507 n=span_count(r);t=width(s);w=t;u=hold_head;
16508 while (n > min_quarterword)
16509 {@+decr(n);
16510 @<Append tabskip glue and an empty box to list |u|, and update |s| and |t|
16511 as the prototype nodes are passed@>;
16512 }
16513 if (mode==-vmode)
16514 @<Make the unset node |r| into an |hlist_node| of width |w|, setting the
16515 glue as if the width were |t|@>@;
16516 else@<Make the unset node |r| into a |vlist_node| of height |w|, setting the
16517 glue as if the height were |t|@>;
16518 shift_amount(r)=0;
16519 if (u!=hold_head) /*append blank boxes to account for spanned nodes*/
16520 {@+link(u)=link(r);link(r)=link(hold_head);r=u;
16521 }
16522
16523 @ @<Append tabskip glue and an empty box to list |u|...@>=
16524 s=link(s);v=glue_ptr(s);link(u)=new_glue(v);u=link(u);
16525 subtype(u)=tab_skip_code+1;t=t+width(v);
16526 if (glue_sign(p)==stretching)
16527 {@+if (stretch_order(v)==glue_order(p))
16528 t=t+round(unfix(glue_set(p))*stretch(v));
16529 @^real multiplication@>
16530 }
16531 else if (glue_sign(p)==shrinking)
16532 {@+if (shrink_order(v)==glue_order(p))
16533 t=t-round(unfix(glue_set(p))*shrink(v));
16534 }
16535 s=link(s);link(u)=new_null_box();u=link(u);t=t+width(s);
16536 if (mode==-vmode) width(u)=width(s);@+else
16537 {@+type(u)=vlist_node;height(u)=width(s);
16538 }
16539
16540 @ @<Make the unset node |r| into an |hlist_node| of width |w|...@>=
16541 {@+height(r)=height(q);depth(r)=depth(q);
16542 if (t==width(r))
16543 {@+glue_sign(r)=normal;glue_order(r)=normal;
16544 set_glue_ratio_zero(glue_set(r));
16545 }
16546 else if (t > width(r))
16547 {@+glue_sign(r)=stretching;
16548 if (glue_stretch(r)==0) set_glue_ratio_zero(glue_set(r));
16549 else glue_set(r)=fix((t-width(r))/(double)glue_stretch(r));
16550 @^real division@>
16551 }
16552 else{@+glue_order(r)=glue_sign(r);glue_sign(r)=shrinking;
16553 if (glue_shrink(r)==0) set_glue_ratio_zero(glue_set(r));
16554 else if ((glue_order(r)==normal)&&(width(r)-t > glue_shrink(r)))
16555 set_glue_ratio_one(glue_set(r));
16556 else glue_set(r)=fix((width(r)-t)/(double)glue_shrink(r));
16557 }
16558 width(r)=w;type(r)=hlist_node;
16559 }
16560
16561 @ @<Make the unset node |r| into a |vlist_node| of height |w|...@>=
16562 {@+width(r)=width(q);
16563 if (t==height(r))
16564 {@+glue_sign(r)=normal;glue_order(r)=normal;
16565 set_glue_ratio_zero(glue_set(r));
16566 }
16567 else if (t > height(r))
16568 {@+glue_sign(r)=stretching;
16569 if (glue_stretch(r)==0) set_glue_ratio_zero(glue_set(r));
16570 else glue_set(r)=fix((t-height(r))/(double)glue_stretch(r));
16571 @^real division@>
16572 }
16573 else{@+glue_order(r)=glue_sign(r);glue_sign(r)=shrinking;
16574 if (glue_shrink(r)==0) set_glue_ratio_zero(glue_set(r));
16575 else if ((glue_order(r)==normal)&&(height(r)-t > glue_shrink(r)))
16576 set_glue_ratio_one(glue_set(r));
16577 else glue_set(r)=fix((height(r)-t)/(double)glue_shrink(r));
16578 }
16579 height(r)=w;type(r)=vlist_node;
16580 }
16581
16582 @ We now have a completed alignment, in the list that starts at |head|
16583 and ends at |tail|. This list will be merged with the one that encloses
16584 it. (In case the enclosing mode is |mmode|, for displayed formulas,
16585 we will need to insert glue before and after the display; that part of the
16586 program will be deferred until we're more familiar with such operations.)
16587
16588 In restricted horizontal mode, the |clang| part of |aux| is undefined;
16589 an over-cautious \PASCAL\ runtime system may complain about this.
16590 @^dirty \PASCAL@>
16591
16592 @<Insert the \(c)current list into its environment@>=
16593 aux_save=aux;p=link(head);q=tail;pop_nest();
16594 if (mode==mmode) @<Finish an alignment in a display@>@;
16595 else{@+aux=aux_save;link(tail)=p;
16596 if (p!=null) tail=q;
16597 if (mode==vmode) build_page();
16598 }
16599
16600 @* Breaking paragraphs into lines.
16601 We come now to what is probably the most interesting algorithm of \TeX:
16602 the mechanism for choosing the ``best possible'' breakpoints that yield
16603 the individual lines of a paragraph. \TeX's line-breaking algorithm takes
16604 a given horizontal list and converts it to a sequence of boxes that are
16605 appended to the current vertical list. In the course of doing this, it
16606 creates a special data structure containing three kinds of records that are
16607 not used elsewhere in \TeX. Such nodes are created while a paragraph is
16608 being processed, and they are destroyed afterwards; thus, the other parts
16609 of \TeX\ do not need to know anything about how line-breaking is done.
16610
16611 The method used here is based on an approach devised by Michael F. Plass and
16612 @^Plass, Michael Frederick@>
16613 @^Knuth, Donald Ervin@>
16614 the author in 1977, subsequently generalized and improved by the same two
16615 people in 1980. A detailed discussion appears in {\sl Software---Practice
16616 and Experience \bf11} (1981), 1119--1184, where it is shown that the
16617 line-breaking problem can be regarded as a special case of the problem of
16618 computing the shortest path in an acyclic network. The cited paper includes
16619 numerous examples and describes the history of line breaking as it has been
16620 practiced by printers through the ages. The present implementation adds two
16621 new ideas to the algorithm of 1980: Memory space requirements are considerably
16622 reduced by using smaller records for inactive nodes than for active ones,
16623 and arithmetic overflow is avoided by using ``delta distances'' instead of
16624 keeping track of the total distance from the beginning of the paragraph to the
16625 current point.
16626
16627 @ The |line_break| procedure should be invoked only in horizontal mode; it
16628 leaves that mode and places its output into the current vlist of the
16629 enclosing vertical mode (or internal vertical mode).
16630 There is one explicit parameter: |final_widow_penalty| is the amount of
16631 additional penalty to be inserted before the final line of the paragraph.
16632
16633 There are also a number of implicit parameters: The hlist to be broken
16634 starts at |link(head)|, and it is nonempty. The value of |prev_graf| in the
16635 enclosing semantic level tells where the paragraph should begin in the
16636 sequence of line numbers, in case hanging indentation or \.{\\parshape}
16637 is in use; |prev_graf| is zero unless this paragraph is being continued
16638 after a displayed formula. Other implicit parameters, such as the
16639 |par_shape_ptr| and various penalties to use for hyphenation, etc., appear
16640 in |eqtb|.
16641
16642 After |line_break| has acted, it will have updated the current vlist and the
16643 value of |prev_graf|. Furthermore, the global variable |just_box| will
16644 point to the final box created by |line_break|, so that the width of this
16645 line can be ascertained when it is necessary to decide whether to use
16646 |above_display_skip| or |above_display_short_skip| before a displayed formula.
16647
16648 @<Glob...@>=
16649 static pointer @!just_box; /*the |hlist_node| for the last line of the new paragraph*/
16650
16651 @ Since |line_break| is a rather lengthy procedure---sort of a small world unto
16652 itself---we must build it up little by little, somewhat more cautiously
16653 than we have done with the simpler procedures of \TeX. Here is the
16654 general outline.
16655
16656 @p @t\4@>@<Declare subprocedures for |line_break|@>@;
16657 static void line_break(int @!final_widow_penalty)
16658 {@+
16659 @<Local variables for line breaking@>@;
16660 @<Local variables to save the profiling context@>@;
16661 @<Charge the time used here on |line_break|@>@;
16662 pack_begin_line=mode_line; /*this is for over/underfull box messages*/
16663 @<Get ready to start line breaking@>;
16664 @<Find optimal breakpoints@>;
16665 @<Break the paragraph at the chosen breakpoints, justify the resulting lines
16666 to the correct widths, and append them to the current vertical list@>;
16667 @<Clean up the memory by removing the break nodes@>;
16668 pack_begin_line=0;
16669 @<restore the previous current file, line, and command@>@;
16670 }
16671 @#
16672 @t\4@>@<Declare \eTeX\ procedures for use by |main_control|@>@;
16673
16674 @ The first task is to move the list from |head| to |temp_head| and go
16675 into the enclosing semantic level. We also append the \.{\\parfillskip}
16676 glue to the end of the paragraph, removing a space (or other glue node) if
16677 it was there, since spaces usually precede blank lines and instances of
16678 `\.{\$\$}'. The |par_fill_skip| is preceded by an infinite penalty, so
16679 it will never be considered as a potential breakpoint.
16680
16681 This code assumes that a |glue_node| and a |penalty_node| occupy the
16682 same number of |mem|~words.
16683 @^data structure assumptions@>
16684
16685 @<Get ready to start...@>=
16686 link(temp_head)=link(head);
16687 if (is_char_node(tail)) tail_append(new_penalty(inf_penalty))@;
16688 else if (type(tail)!=glue_node) tail_append(new_penalty(inf_penalty))@;
16689 else{@+type(tail)=penalty_node;delete_glue_ref(glue_ptr(tail));
16690 flush_node_list(leader_ptr(tail));penalty(tail)=inf_penalty;
16691 }
16692 link(tail)=new_param_glue(par_fill_skip_code);
16693 init_cur_lang=prev_graf%0200000;
16694 init_l_hyf=prev_graf/020000000;
16695 init_r_hyf=(prev_graf/0200000)%0100;
16696 pop_nest();
16697
16698 @ When looking for optimal line breaks, \TeX\ creates a ``break node'' for
16699 each break that is {\sl feasible}, in the sense that there is a way to end
16700 a line at the given place without requiring any line to stretch more than
16701 a given tolerance. A break node is characterized by three things: the position
16702 of the break (which is a pointer to a |glue_node|, |math_node|, |penalty_node|,
16703 or |disc_node|); the ordinal number of the line that will follow this
16704 breakpoint; and the fitness classification of the line that has just
16705 ended, i.e., |tight_fit|, |decent_fit|, |loose_fit|, or |very_loose_fit|.
16706
16707 @d tight_fit 3 /*fitness classification for lines shrinking 0.5 to 1.0 of their
16708 shrinkability*/
16709 @d loose_fit 1 /*fitness classification for lines stretching 0.5 to 1.0 of their
16710 stretchability*/
16711 @d very_loose_fit 0 /*fitness classification for lines stretching more than
16712 their stretchability*/
16713 @d decent_fit 2 /*fitness classification for all other lines*/
16714
16715 @ The algorithm essentially determines the best possible way to achieve
16716 each feasible combination of position, line, and fitness. Thus, it answers
16717 questions like, ``What is the best way to break the opening part of the
16718 paragraph so that the fourth line is a tight line ending at such-and-such
16719 a place?'' However, the fact that all lines are to be the same length
16720 after a certain point makes it possible to regard all sufficiently large
16721 line numbers as equivalent, when the looseness parameter is zero, and this
16722 makes it possible for the algorithm to save space and time.
16723
16724 An ``active node'' and a ``passive node'' are created in |mem| for each
16725 feasible breakpoint that needs to be considered. Active nodes are three
16726 words long and passive nodes are two words long. We need active nodes only
16727 for breakpoints near the place in the paragraph that is currently being
16728 examined, so they are recycled within a comparatively short time after
16729 they are created.
16730
16731 @ An active node for a given breakpoint contains six fields:
16732
16733 \yskip\hang|link| points to the next node in the list of active nodes; the
16734 last active node has |link==last_active|.
16735
16736 \yskip\hang|break_node| points to the passive node associated with this
16737 breakpoint.
16738
16739 \yskip\hang|line_number| is the number of the line that follows this
16740 breakpoint.
16741
16742 \yskip\hang|fitness| is the fitness classification of the line ending at this
16743 breakpoint.
16744
16745 \yskip\hang|type| is either |hyphenated| or |unhyphenated|, depending on
16746 whether this breakpoint is a |disc_node|.
16747
16748 \yskip\hang|total_demerits| is the minimum possible sum of demerits over all
16749 lines leading from the beginning of the paragraph to this breakpoint.
16750
16751 \yskip\noindent
16752 The value of |link(active)| points to the first active node on a linked list
16753 of all currently active nodes. This list is in order by |line_number|,
16754 except that nodes with |line_number > easy_line| may be in any order relative
16755 to each other.
16756
16757 @d active_node_size 3 /*number of words in active nodes*/
16758 @d fitness(A) subtype(A) /*|very_loose_fit dotdot tight_fit| on final line for this break*/
16759 @d break_node(A) rlink(A) /*pointer to the corresponding passive node*/
16760 @d line_number(A) llink(A) /*line that begins at this breakpoint*/
16761 @d total_demerits(A) mem[A+2].i /*the quantity that \TeX\ minimizes*/
16762 @d unhyphenated 0 /*the |type| of a normal active break node*/
16763 @d hyphenated 1 /*the |type| of an active node that breaks at a |disc_node|*/
16764 @d last_active active /*the active list ends where it begins*/
16765
16766 @ @<Initialize the special list heads...@>=
16767 type(last_active)=hyphenated;line_number(last_active)=max_halfword;
16768 subtype(last_active)=0; /*the |subtype| is never examined by the algorithm*/
16769
16770 @ The passive node for a given breakpoint contains only four fields:
16771
16772 \yskip\hang|link| points to the passive node created just before this one,
16773 if any, otherwise it is |null|.
16774
16775 \yskip\hang|cur_break| points to the position of this breakpoint in the
16776 horizontal list for the paragraph being broken.
16777
16778 \yskip\hang|prev_break| points to the passive node that should precede this
16779 one in an optimal path to this breakpoint.
16780
16781 \yskip\hang|serial| is equal to |n| if this passive node is the |n|th
16782 one created during the current pass. (This field is used only when
16783 printing out detailed statistics about the line-breaking calculations.)
16784
16785 \yskip\noindent
16786 There is a global variable called |passive| that points to the most
16787 recently created passive node. Another global variable, |printed_node|,
16788 is used to help print out the paragraph when detailed information about
16789 the line-breaking computation is being displayed.
16790
16791 @d passive_node_size 2 /*number of words in passive nodes*/
16792 @d cur_break(A) rlink(A) /*in passive node, points to position of this breakpoint*/
16793 @d prev_break(A) llink(A) /*points to passive node that should precede this one*/
16794 @d serial(A) info(A) /*serial number for symbolic identification*/
16795
16796 @<Glob...@>=
16797 static pointer @!passive; /*most recent node on passive list*/
16798 static pointer @!printed_node; /*most recent node that has been printed*/
16799 static halfword @!pass_number; /*the number of passive nodes allocated on this pass*/
16800
16801 @ The active list also contains ``delta'' nodes that help the algorithm
16802 compute the badness of individual lines. Such nodes appear only between two
16803 active nodes, and they have |type==delta_node|. If |p| and |r| are active nodes
16804 and if |q| is a delta node between them, so that |link(p)==q| and |link(q)==r|,
16805 then |q| tells the space difference between lines in the horizontal list that
16806 start after breakpoint |p| and lines that start after breakpoint |r|. In
16807 other words, if we know the length of the line that starts after |p| and
16808 ends at our current position, then the corresponding length of the line that
16809 starts after |r| is obtained by adding the amounts in node~|q|. A delta node
16810 contains six scaled numbers, since it must record the net change in glue
16811 stretchability with respect to all orders of infinity. The natural width
16812 difference appears in |mem[q+1].sc|; the stretch differences in units of
16813 pt, fil, fill, and filll appear in |mem[q+2 dotdot q+5].sc|; and the shrink difference
16814 appears in |mem[q+6].sc|. The |subtype| field of a delta node is not used.
16815
16816 @d delta_node_size 7 /*number of words in a delta node*/
16817 @d delta_node 2 /*|type| field in a delta node*/
16818
16819 @ As the algorithm runs, it maintains a set of six delta-like registers
16820 for the length of the line following the first active breakpoint to the
16821 current position in the given hlist. When it makes a pass through the
16822 active list, it also maintains a similar set of six registers for the
16823 length following the active breakpoint of current interest. A third set
16824 holds the length of an empty line (namely, the sum of \.{\\leftskip} and
16825 \.{\\rightskip}); and a fourth set is used to create new delta nodes.
16826
16827 When we pass a delta node we want to do operations like
16828 $$\hbox{\ignorespaces|for
16829 k=1 to 6 do cur_active_width[k]=cur_active_width[k]+mem[q+k].sc|};$$ and we
16830 want to do this without the overhead of |for| loops. The |do_all_six|
16831 macro makes such six-tuples convenient.
16832
16833 @d do_all_six(A) A(1);A(2);A(3);A(4);A(5);A(6)
16834
16835 @<Glob...@>=
16836 static scaled @!active_width0[6], *const @!active_width = @!active_width0-1;
16837 /*distance from first active node to~|cur_p|*/
16838 static scaled @!cur_active_width0[6],
16839 *const @!cur_active_width = @!cur_active_width0-1; /*distance from current active node*/
16840 static scaled @!background0[6], *const @!background = @!background0-1; /*length of an ``empty'' line*/
16841 static scaled @!break_width0[6], *const @!break_width = @!break_width0-1; /*length being computed after current break*/
16842
16843 @ Let's state the principles of the delta nodes more precisely and concisely,
16844 so that the following programs will be less obscure. For each legal
16845 breakpoint~|p| in the paragraph, we define two quantities $\alpha(p)$ and
16846 $\beta(p)$ such that the length of material in a line from breakpoint~|p|
16847 to breakpoint~|q| is $\gamma+\beta(q)-\alpha(p)$, for some fixed $\gamma$.
16848 Intuitively, $\alpha(p)$ and $\beta(q)$ are the total length of material from
16849 the beginning of the paragraph to a point ``after'' a break at |p| and to a
16850 point ``before'' a break at |q|; and $\gamma$ is the width of an empty line,
16851 namely the length contributed by \.{\\leftskip} and \.{\\rightskip}.
16852
16853 Suppose, for example, that the paragraph consists entirely of alternating
16854 boxes and glue skips; let the boxes have widths $x_1\ldots x_n$ and
16855 let the skips have widths $y_1\ldots y_n$, so that the paragraph can be
16856 represented by $x_1y_1\ldots x_ny_n$. Let $p_i$ be the legal breakpoint
16857 at $y_i$; then $\alpha(p_i)=x_1+y_1+\cdots+x_i+y_i$, and $\beta(p_i)=
16858 x_1+y_1+\cdots+x_i$. To check this, note that the length of material from
16859 $p_2$ to $p_5$, say, is $\gamma+x_3+y_3+x_4+y_4+x_5=\gamma+\beta(p_5)
16860 -\alpha(p_2)$.
16861
16862 The quantities $\alpha$, $\beta$, $\gamma$ involve glue stretchability and
16863 shrinkability as well as a natural width. If we were to compute $\alpha(p)$
16864 and $\beta(p)$ for each |p|, we would need multiple precision arithmetic, and
16865 the multiprecise numbers would have to be kept in the active nodes.
16866 \TeX\ avoids this problem by working entirely with relative differences
16867 or ``deltas.'' Suppose, for example, that the active list contains
16868 $a_1\,\delta_1\,a_2\,\delta_2\,a_3$, where the |a|'s are active breakpoints
16869 and the $\delta$'s are delta nodes. Then $\delta_1=\alpha(a_1)-\alpha(a_2)$
16870 and $\delta_2=\alpha(a_2)-\alpha(a_3)$. If the line breaking algorithm is
16871 currently positioned at some other breakpoint |p|, the |active_width| array
16872 contains the value $\gamma+\beta(p)-\alpha(a_1)$. If we are scanning through
16873 the list of active nodes and considering a tentative line that runs from
16874 $a_2$ to~|p|, say, the |cur_active_width| array will contain the value
16875 $\gamma+\beta(p)-\alpha(a_2)$. Thus, when we move from $a_2$ to $a_3$,
16876 we want to add $\alpha(a_2)-\alpha(a_3)$ to |cur_active_width|; and this
16877 is just $\delta_2$, which appears in the active list between $a_2$ and
16878 $a_3$. The |background| array contains $\gamma$. The |break_width| array
16879 will be used to calculate values of new delta nodes when the active
16880 list is being updated.
16881
16882 @ Glue nodes in a horizontal list that is being paragraphed are not supposed to
16883 include ``infinite'' shrinkability; that is why the algorithm maintains
16884 four registers for stretching but only one for shrinking. If the user tries to
16885 introduce infinite shrinkability, the shrinkability will be reset to finite
16886 and an error message will be issued. A boolean variable |no_shrink_error_yet|
16887 prevents this error message from appearing more than once per paragraph.
16888
16889 @d check_shrinkage(A) if ((shrink_order(A)!=normal)&&(shrink(A)!=0))
16890 {@+A=finite_shrink(A);
16891 }
16892
16893 @<Glob...@>=
16894 static bool @!no_shrink_error_yet; /*have we complained about infinite shrinkage?*/
16895
16896 @ @<Declare subprocedures for |line_break|@>=
16897 static pointer finite_shrink(pointer @!p) /*recovers from infinite shrinkage*/
16898 {@+pointer q; /*new glue specification*/
16899 if (no_shrink_error_yet)
16900 {@+no_shrink_error_yet=false;
16901 #ifdef @!STAT
16902 if (tracing_paragraphs > 0) end_diagnostic(true);
16903 #endif
16904 @;
16905 print_err("Infinite glue shrinkage found in a paragraph");
16906 @.Infinite glue shrinkage...@>
16907 help5("The paragraph just ended includes some glue that has",@/
16908 "infinite shrinkability, e.g., `\\hskip 0pt minus 1fil'.",@/
16909 "Such glue doesn't belong there---it allows a paragraph",@/
16910 "of any length to fit on one line. But it's safe to proceed,",@/
16911 "since the offensive shrinkability has been made finite.");
16912 error();
16913 #ifdef @!STAT
16914 if (tracing_paragraphs > 0) begin_diagnostic();
16915 #endif
16916 @;
16917 }
16918 q=new_spec(p);shrink_order(q)=normal;
16919 delete_glue_ref(p);return q;
16920 }
16921
16922 @ @<Get ready to start...@>=
16923 no_shrink_error_yet=true;@/
16924 check_shrinkage(left_skip);check_shrinkage(right_skip);@/
16925 q=left_skip;r=right_skip;background[1]=width(q)+width(r);@/
16926 background[2]=0;background[3]=0;background[4]=0;background[5]=0;@/
16927 background[2+stretch_order(q)]=stretch(q);@/
16928 background[2+stretch_order(r)]=@|background[2+stretch_order(r)]+stretch(r);@/
16929 background[6]=shrink(q)+shrink(r);
16930
16931 @ A pointer variable |cur_p| runs through the given horizontal list as we look
16932 for breakpoints. This variable is global, since it is used both by |line_break|
16933 and by its subprocedure |try_break|.
16934
16935 Another global variable called |threshold| is used to determine the feasibility
16936 of individual lines: Breakpoints are feasible if there is a way to reach
16937 them without creating lines whose badness exceeds |threshold|. (The
16938 badness is compared to |threshold| before penalties are added, so that
16939 penalty values do not affect the feasibility of breakpoints, except that
16940 no break is allowed when the penalty is 10000 or more.) If |threshold|
16941 is 10000 or more, all legal breaks are considered feasible, since the
16942 |badness| function specified above never returns a value greater than~10000.
16943
16944 Up to three passes might be made through the paragraph in an attempt to find at
16945 least one set of feasible breakpoints. On the first pass, we have
16946 |threshold==pretolerance| and |second_pass==final_pass==false|.
16947 If this pass fails to find a
16948 feasible solution, |threshold| is set to |tolerance|, |second_pass| is set
16949 |true|, and an attempt is made to hyphenate as many words as possible.
16950 If that fails too, we add |emergency_stretch| to the background
16951 stretchability and set |final_pass==true|.
16952
16953 @<Glob...@>=
16954 static pointer @!cur_p; /*the current breakpoint under consideration*/
16955 static bool @!second_pass; /*is this our second attempt to break this paragraph?*/
16956 static bool @!final_pass; /*is this our final attempt to break this paragraph?*/
16957 static int @!threshold; /*maximum badness on feasible lines*/
16958
16959 @ The heart of the line-breaking procedure is `|try_break|', a subroutine
16960 that tests if the current breakpoint |cur_p| is feasible, by running
16961 through the active list to see what lines of text can be made from active
16962 nodes to~|cur_p|. If feasible breaks are possible, new break nodes are
16963 created. If |cur_p| is too far from an active node, that node is
16964 deactivated.
16965
16966 The parameter |pi| to |try_break| is the penalty associated
16967 with a break at |cur_p|; we have |pi==eject_penalty| if the break is forced,
16968 and |pi==inf_penalty| if the break is illegal.
16969
16970 The other parameter, |break_type|, is set to |hyphenated| or |unhyphenated|,
16971 depending on whether or not the current break is at a |disc_node|. The
16972 end of a paragraph is also regarded as `|hyphenated|'; this case is
16973 distinguishable by the condition |cur_p==null|.
16974
16975 @d copy_to_cur_active(A) cur_active_width[A]=active_width[A]
16976 @<Declare subprocedures for |line_break|@>=
16977 static void try_break(int @!pi, small_number @!break_type)
16978 {@+
16979 pointer r; /*runs through the active list*/
16980 pointer @!prev_r; /*stays a step behind |r|*/
16981 halfword @!old_l; /*maximum line number in current equivalence class of lines*/
16982 bool @!no_break_yet; /*have we found a feasible break at |cur_p|?*/
16983 @<Other local variables for |try_break|@>@;
16984 @<Make sure that |pi| is in the proper range@>;
16985 no_break_yet=true;prev_r=active;old_l=0;
16986 do_all_six(copy_to_cur_active);
16987 loop@+{@+resume: r=link(prev_r);
16988 @<If node |r| is of type |delta_node|, update |cur_active_width|, set |prev_r|
16989 and |prev_prev_r|, then |goto resume|@>;
16990 @<If a line number class has ended, create new active nodes for the best
16991 feasible breaks in that class; then |return| if |r=last_active|, otherwise
16992 compute the new |line_width|@>;
16993 @<Consider the demerits for a line from |r| to |cur_p|; deactivate node
16994 |r| if it should no longer be active; then |goto resume| if a line from
16995 |r| to |cur_p| is infeasible, otherwise record a new feasible break@>;
16996 }
16997 end: ;
16998 #ifdef @!STAT
16999 @<Update the value of |printed_node| for symbolic displays@>;
17000 #endif
17001 @;
17002 }
17003
17004 @ @<Other local variables for |try_break|@>=
17005 pointer @!prev_prev_r; /*a step behind |prev_r|, if |type(prev_r)==delta_node|*/
17006 pointer @!s; /*runs through nodes ahead of |cur_p|*/
17007 pointer @!q; /*points to a new node being created*/
17008 pointer @!v; /*points to a glue specification or a node ahead of |cur_p|*/
17009 int @!t; /*node count, if |cur_p| is a discretionary node*/
17010 internal_font_number @!f; /*used in character width calculation*/
17011 halfword @!l; /*line number of current active node*/
17012 bool @!node_r_stays_active; /*should node |r| remain in the active list?*/
17013 scaled @!line_width; /*the current line will be justified to this width*/
17014 int @!fit_class; /*possible fitness class of test line*/
17015 halfword @!b; /*badness of test line*/
17016 int @!d; /*demerits of test line*/
17017 bool @!artificial_demerits; /*has |d| been forced to zero?*/
17018 #ifdef @!STAT
17019 pointer @!save_link; /*temporarily holds value of |link(cur_p)|*/
17020 #endif
17021 scaled @!shortfall; /*used in badness calculations*/
17022
17023 @ @<Make sure that |pi| is in the proper range@>=
17024 if (abs(pi) >= inf_penalty)
17025 if (pi > 0) goto end; /*this breakpoint is inhibited by infinite penalty*/
17026 else pi=eject_penalty /*this breakpoint will be forced*/
17027
17028 @ The following code uses the fact that |type(last_active)!=delta_node|.
17029
17030 @d update_width(A) @|
17031 cur_active_width[A]=cur_active_width[A]+mem[r+A].sc
17032
17033 @<If node |r|...@>=
17034 @^inner loop@>
17035 if (type(r)==delta_node)
17036 {@+do_all_six(update_width);
17037 prev_prev_r=prev_r;prev_r=r;goto resume;
17038 }
17039
17040 @ As we consider various ways to end a line at |cur_p|, in a given line number
17041 class, we keep track of the best total demerits known, in an array with
17042 one entry for each of the fitness classifications. For example,
17043 |minimal_demerits[tight_fit]| contains the fewest total demerits of feasible
17044 line breaks ending at |cur_p| with a |tight_fit| line; |best_place[tight_fit]|
17045 points to the passive node for the break before~|cur_p| that achieves such
17046 an optimum; and |best_pl_line[tight_fit]| is the |line_number| field in the
17047 active node corresponding to |best_place[tight_fit]|. When no feasible break
17048 sequence is known, the |minimal_demerits| entries will be equal to
17049 |awful_bad|, which is $2^{30}-1$. Another variable, |minimum_demerits|,
17050 keeps track of the smallest value in the |minimal_demerits| array.
17051
17052 @d awful_bad 07777777777 /*more than a billion demerits*/
17053
17054 @<Global...@>=
17055 static int @!minimal_demerits0[tight_fit-very_loose_fit+1],
17056 *const @!minimal_demerits = @!minimal_demerits0-very_loose_fit; /*best total
17057 demerits known for current line class and position, given the fitness*/
17058 static int @!minimum_demerits; /*best total demerits known for current line class
17059 and position*/
17060 static pointer @!best_place0[tight_fit-very_loose_fit+1],
17061 *const @!best_place = @!best_place0-very_loose_fit; /*how to achieve
17062 |minimal_demerits|*/
17063 static halfword @!best_pl_line0[tight_fit-very_loose_fit+1],
17064 *const @!best_pl_line = @!best_pl_line0-very_loose_fit; /*corresponding
17065 line number*/
17066
17067 @ @<Get ready to start...@>=
17068 minimum_demerits=awful_bad;
17069 minimal_demerits[tight_fit]=awful_bad;
17070 minimal_demerits[decent_fit]=awful_bad;
17071 minimal_demerits[loose_fit]=awful_bad;
17072 minimal_demerits[very_loose_fit]=awful_bad;
17073
17074 @ The first part of the following code is part of \TeX's inner loop, so
17075 we don't want to waste any time. The current active node, namely node |r|,
17076 contains the line number that will be considered next. At the end of the
17077 list we have arranged the data structure so that |r==last_active| and
17078 |line_number(last_active) > old_l|.
17079 @^inner loop@>
17080
17081 @<If a line number class...@>=
17082 {@+l=line_number(r);
17083 if (l > old_l)
17084 {@+ /*now we are no longer in the inner loop*/
17085 if ((minimum_demerits < awful_bad)&&@|
17086 ((old_l!=easy_line)||(r==last_active)))
17087 @<Create new active nodes for the best feasible breaks just found@>;
17088 if (r==last_active) goto end;
17089 @<Compute the new line width@>;
17090 }
17091 }
17092
17093 @ It is not necessary to create new active nodes having |minimal_demerits|
17094 greater than
17095 |minimum_demerits+abs(adj_demerits)|, since such active nodes will never
17096 be chosen in the final paragraph breaks. This observation allows us to
17097 omit a substantial number of feasible breakpoints from further consideration.
17098
17099 @<Create new active nodes...@>=
17100 {@+if (no_break_yet) @<Compute the values of |break_width|@>;
17101 @<Insert a delta node to prepare for breaks at |cur_p|@>;
17102 if (abs(adj_demerits) >= awful_bad-minimum_demerits)
17103 minimum_demerits=awful_bad-1;
17104 else minimum_demerits=minimum_demerits+abs(adj_demerits);
17105 for (fit_class=very_loose_fit; fit_class<=tight_fit; fit_class++)
17106 {@+if (minimal_demerits[fit_class] <= minimum_demerits)
17107 @<Insert a new active node from |best_place[fit_class]| to |cur_p|@>;
17108 minimal_demerits[fit_class]=awful_bad;
17109 }
17110 minimum_demerits=awful_bad;
17111 @<Insert a delta node to prepare for the next active node@>;
17112 }
17113
17114 @ When we insert a new active node for a break at |cur_p|, suppose this
17115 new node is to be placed just before active node |a|; then we essentially
17116 want to insert `$\delta\,|cur_p|\,\delta^\prime$' before |a|, where
17117 $\delta=\alpha(a)-\alpha(|cur_p|)$ and $\delta^\prime=\alpha(|cur_p|)-\alpha(a)$
17118 in the notation explained above. The |cur_active_width| array now holds
17119 $\gamma+\beta(|cur_p|)-\alpha(a)$; so $\delta$ can be obtained by
17120 subtracting |cur_active_width| from the quantity $\gamma+\beta(|cur_p|)-
17121 \alpha(|cur_p|)$. The latter quantity can be regarded as the length of a
17122 line ``from |cur_p| to |cur_p|''; we call it the |break_width| at |cur_p|.
17123
17124 The |break_width| is usually negative, since it consists of the background
17125 (which is normally zero) minus the width of nodes following~|cur_p| that are
17126 eliminated after a break. If, for example, node |cur_p| is a glue node, the
17127 width of this glue is subtracted from the background; and we also look
17128 ahead to eliminate all subsequent glue and penalty and kern and math
17129 nodes, subtracting their widths as well.
17130
17131 Kern nodes do not disappear at a line break unless they are |explicit|.
17132
17133 @d set_break_width_to_background(A) break_width[A]=background[A]
17134
17135 @<Compute the values of |break...@>=
17136 {@+no_break_yet=false;do_all_six(set_break_width_to_background);
17137 s=cur_p;
17138 if (break_type > unhyphenated) if (cur_p!=null)
17139 @<Compute the discretionary |break_width| values@>;
17140 while (s!=null)
17141 {@+if (is_char_node(s)) goto done;
17142 switch (type(s)) {
17143 case glue_node: @<Subtract glue from |break_width|@>@;@+break;
17144 case penalty_node: do_nothing;@+break;
17145 case math_node: break_width[1]=break_width[1]-width(s);@+break;
17146 case kern_node: if (subtype(s)!=explicit) goto done;
17147 else break_width[1]=break_width[1]-width(s);@+break;
17148 default:goto done;
17149 } @/
17150 s=link(s);
17151 }
17152 done: ;}
17153
17154 @ @<Subtract glue from |break...@>=
17155 {@+v=glue_ptr(s);break_width[1]=break_width[1]-width(v);
17156 break_width[2+stretch_order(v)]=break_width[2+stretch_order(v)]-stretch(v);
17157 break_width[6]=break_width[6]-shrink(v);
17158 }
17159
17160 @ When |cur_p| is a discretionary break, the length of a line ``from |cur_p| to
17161 |cur_p|'' has to be defined properly so that the other calculations work out.
17162 Suppose that the pre-break text at |cur_p| has length $l_0$, the post-break
17163 text has length $l_1$, and the replacement text has length |l|. Suppose
17164 also that |q| is the node following the replacement text. Then length of a
17165 line from |cur_p| to |q| will be computed as $\gamma+\beta(q)-\alpha(|cur_p|)$,
17166 where $\beta(q)=\beta(|cur_p|)-l_0+l$. The actual length will be the background
17167 plus $l_1$, so the length from |cur_p| to |cur_p| should be $\gamma+l_0+l_1-l$.
17168 If the post-break text of the discretionary is empty, a break may also
17169 discard~|q|; in that unusual case we subtract the length of~|q| and any
17170 other nodes that will be discarded after the discretionary break.
17171
17172 The value of $l_0$ need not be computed, since |line_break| will put
17173 it into the global variable |disc_width| before calling |try_break|.
17174
17175 @<Glob...@>=
17176 static scaled @!disc_width; /*the length of discretionary material preceding a break*/
17177
17178 @ @<Compute the discretionary |break...@>=
17179 {@+t=replace_count(cur_p);v=cur_p;s=post_break(cur_p);
17180 while (t > 0)
17181 {@+decr(t);v=link(v);
17182 @<Subtract the width of node |v| from |break_width|@>;
17183 }
17184 while (s!=null)
17185 {@+@<Add the width of node |s| to |break_width|@>;
17186 s=link(s);
17187 }
17188 break_width[1]=break_width[1]+disc_width;
17189 if (post_break(cur_p)==null) s=link(v);
17190 /*nodes may be discardable after the break*/
17191 }
17192
17193 @ Replacement texts and discretionary texts are supposed to contain
17194 only character nodes, kern nodes, ligature nodes, and box or rule nodes.
17195
17196 @<Subtract the width of node |v|...@>=
17197 if (is_char_node(v))
17198 {@+f=font(v);
17199 break_width[1]=break_width[1]-char_width(f, char_info(f, character(v)));
17200 }
17201 else switch (type(v)) {
17202 case ligature_node: {@+f=font(lig_char(v));@/
17203 break_width[1]=@|break_width[1]-
17204 char_width(f, char_info(f, character(lig_char(v))));
17205 } @+break;
17206 case hlist_node: case vlist_node: case rule_node:
17207 case kern_node:
17208 break_width[1]=break_width[1]-width(v);@+break;
17209 default:confusion("disc1");
17210 @:this can't happen disc1}{\quad disc1@>
17211 }
17212
17213 @ @<Add the width of node |s| to |b...@>=
17214 if (is_char_node(s))
17215 {@+f=font(s);
17216 break_width[1]=@|break_width[1]+char_width(f, char_info(f, character(s)));
17217 }
17218 else switch (type(s)) {
17219 case ligature_node: {@+f=font(lig_char(s));
17220 break_width[1]=break_width[1]+
17221 char_width(f, char_info(f, character(lig_char(s))));
17222 } @+break;
17223 case hlist_node: case vlist_node: case rule_node:
17224 case kern_node:
17225 break_width[1]=break_width[1]+width(s);@+break;
17226 default:confusion("disc2");
17227 @:this can't happen disc2}{\quad disc2@>
17228 }
17229
17230 @ We use the fact that |type(active)!=delta_node|.
17231
17232 @d convert_to_break_width(A) @|
17233 mem[prev_r+A].sc=@|@t\hskip10pt@>mem[prev_r+A].sc
17234 -cur_active_width[A]+break_width[A]
17235 @d store_break_width(A) active_width[A]=break_width[A]
17236 @d new_delta_to_break_width(A) @|
17237 mem[q+A].sc=break_width[A]-cur_active_width[A]
17238
17239 @<Insert a delta node to prepare for breaks at |cur_p|@>=
17240 if (type(prev_r)==delta_node) /*modify an existing delta node*/
17241 {@+do_all_six(convert_to_break_width);
17242 }
17243 else if (prev_r==active) /*no delta node needed at the beginning*/
17244 {@+do_all_six(store_break_width);
17245 }
17246 else{@+q=get_node(delta_node_size);link(q)=r;type(q)=delta_node;@/
17247 subtype(q)=0; /*the |subtype| is not used*/
17248 do_all_six(new_delta_to_break_width);
17249 link(prev_r)=q;prev_prev_r=prev_r;prev_r=q;
17250 }
17251
17252 @ When the following code is performed, we will have just inserted at
17253 least one active node before |r|, so |type(prev_r)!=delta_node|.
17254
17255 @d new_delta_from_break_width(A) @|mem[q+A].sc=
17256 cur_active_width[A]-break_width[A]
17257
17258 @<Insert a delta node to prepare for the next active node@>=
17259 if (r!=last_active)
17260 {@+q=get_node(delta_node_size);link(q)=r;type(q)=delta_node;@/
17261 subtype(q)=0; /*the |subtype| is not used*/
17262 do_all_six(new_delta_from_break_width);
17263 link(prev_r)=q;prev_prev_r=prev_r;prev_r=q;
17264 }
17265
17266 @ When we create an active node, we also create the corresponding
17267 passive node.
17268
17269 @<Insert a new active node from |best_place[fit_class]| to |cur_p|@>=
17270 {@+q=get_node(passive_node_size);
17271 link(q)=passive;passive=q;cur_break(q)=cur_p;
17272 #ifdef @!STAT
17273 incr(pass_number);serial(q)=pass_number;
17274 #endif
17275 @;@/
17276 prev_break(q)=best_place[fit_class];@/
17277 q=get_node(active_node_size);break_node(q)=passive;
17278 line_number(q)=best_pl_line[fit_class]+1;
17279 fitness(q)=fit_class;type(q)=break_type;
17280 total_demerits(q)=minimal_demerits[fit_class];
17281 link(q)=r;link(prev_r)=q;prev_r=q;
17282 #ifdef @!STAT
17283 if (tracing_paragraphs > 0)
17284 @<Print a symbolic description of the new break node@>;
17285 #endif
17286 @;@/
17287 }
17288
17289 @ @<Print a symbolic description of the new break node@>=
17290 {@+print_nl("@@@@");print_int(serial(passive));
17291 @.\AT\AT@>
17292 print(": line ");print_int(line_number(q)-1);
17293 print_char('.');print_int(fit_class);
17294 if (break_type==hyphenated) print_char('-');
17295 print(" t=");print_int(total_demerits(q));
17296 print(" -> @@@@");
17297 if (prev_break(passive)==null) print_char('0');
17298 else print_int(serial(prev_break(passive)));
17299 }
17300
17301 @ The length of lines depends on whether the user has specified
17302 \.{\\parshape} or \.{\\hangindent}. If |par_shape_ptr| is not null, it
17303 points to a $(2n+1)$-word record in |mem|, where the |info| in the first
17304 word contains the value of |n|, and the other $2n$ words contain the left
17305 margins and line lengths for the first |n| lines of the paragraph; the
17306 specifications for line |n| apply to all subsequent lines. If
17307 |par_shape_ptr==null|, the shape of the paragraph depends on the value of
17308 |n==hang_after|; if |n >= 0|, hanging indentation takes place on lines |n+1|,
17309 |n+2|, \dots, otherwise it takes place on lines 1, \dots, $\vert
17310 n\vert$. When hanging indentation is active, the left margin is
17311 |hang_indent|, if |hang_indent >= 0|, else it is 0; the line length is
17312 $|hsize|-\vert|hang_indent|\vert$. The normal setting is
17313 |par_shape_ptr==null|, |hang_after==1|, and |hang_indent==0|.
17314 Note that if |hang_indent==0|, the value of |hang_after| is irrelevant.
17315 @^length of lines@> @^hanging indentation@>
17316
17317 @<Glob...@>=
17318 static halfword @!easy_line; /*line numbers | > easy_line| are equivalent in break nodes*/
17319 static halfword @!last_special_line; /*line numbers | > last_special_line| all have
17320 the same width*/
17321 static scaled @!first_width; /*the width of all lines | <= last_special_line|, if
17322 no \.{\\parshape} has been specified*/
17323 static scaled @!second_width; /*the width of all lines | > last_special_line|*/
17324 static scaled @!first_indent; /*left margin to go with |first_width|*/
17325 static scaled @!second_indent; /*left margin to go with |second_width|*/
17326
17327 @ We compute the values of |easy_line| and the other local variables relating
17328 to line length when the |line_break| procedure is initializing itself.
17329
17330 @<Get ready to start...@>=
17331 if (par_shape_ptr==null)
17332 if (hang_indent==0)
17333 {@+last_special_line=0;second_width=hsize;
17334 second_indent=0;
17335 }
17336 else@<Set line length parameters in preparation for hanging indentation@>@;
17337 else{@+last_special_line=info(par_shape_ptr)-1;
17338 second_width=mem[par_shape_ptr+2*(last_special_line+1)].sc;
17339 second_indent=mem[par_shape_ptr+2*last_special_line+1].sc;
17340 }
17341 if (looseness==0) easy_line=last_special_line;
17342 else easy_line=max_halfword
17343
17344 @ @<Set line length parameters in preparation for hanging indentation@>=
17345 {@+last_special_line=abs(hang_after);
17346 if (hang_after < 0)
17347 {@+first_width=hsize-abs(hang_indent);
17348 if (hang_indent >= 0) first_indent=hang_indent;
17349 else first_indent=0;
17350 second_width=hsize;second_indent=0;
17351 }
17352 else{@+first_width=hsize;first_indent=0;
17353 second_width=hsize-abs(hang_indent);
17354 if (hang_indent >= 0) second_indent=hang_indent;
17355 else second_indent=0;
17356 }
17357 }
17358
17359 @ When we come to the following code, we have just encountered the first
17360 active node~|r| whose |line_number| field contains |l|. Thus we want to
17361 compute the length of the $l\mskip1mu$th line of the current paragraph. Furthermore,
17362 we want to set |old_l| to the last number in the class of line numbers
17363 equivalent to~|l|.
17364
17365 @<Compute the new line width@>=
17366 if (l > easy_line)
17367 {@+line_width=second_width;old_l=max_halfword-1;
17368 }
17369 else{@+old_l=l;
17370 if (l > last_special_line) line_width=second_width;
17371 else if (par_shape_ptr==null) line_width=first_width;
17372 else line_width=mem[par_shape_ptr+2*l@,].sc;
17373 }
17374
17375 @ The remaining part of |try_break| deals with the calculation of
17376 demerits for a break from |r| to |cur_p|.
17377
17378 The first thing to do is calculate the badness, |b|. This value will always
17379 be between zero and |inf_bad+1|; the latter value occurs only in the
17380 case of lines from |r| to |cur_p| that cannot shrink enough to fit the necessary
17381 width. In such cases, node |r| will be deactivated.
17382 We also deactivate node~|r| when a break at~|cur_p| is forced, since future
17383 breaks must go through a forced break.
17384
17385 @<Consider the demerits for a line from |r| to |cur_p|...@>=
17386 {@+artificial_demerits=false;@/
17387 @^inner loop@>
17388 shortfall=line_width-cur_active_width[1]; /*we're this much too short*/
17389 if (shortfall > 0)
17390 @<Set the value of |b| to the badness for stretching the line, and compute
17391 the corresponding |fit_class|@>@;
17392 else@<Set the value of |b| to the badness for shrinking the line, and compute
17393 the corresponding |fit_class|@>;
17394 if ((b > inf_bad)||(pi==eject_penalty))
17395 @<Prepare to deactivate node~|r|, and |goto deactivate| unless there is
17396 a reason to consider lines of text from |r| to |cur_p|@>@;
17397 else{@+prev_r=r;
17398 if (b > threshold) goto resume;
17399 node_r_stays_active=true;
17400 }
17401 @<Record a new feasible break@>;
17402 if (node_r_stays_active) goto resume; /*|prev_r| has been set to |r|*/
17403 deactivate: @<Deactivate node |r|@>;
17404 }
17405
17406 @ When a line must stretch, the available stretchability can be found in the
17407 subarray |cur_active_width[2 dotdot 5]|, in units of points, fil, fill, and filll.
17408
17409 The present section is part of \TeX's inner loop, and it is most often performed
17410 when the badness is infinite; therefore it is worth while to make a quick
17411 test for large width excess and small stretchability, before calling the
17412 |badness| subroutine.
17413 @^inner loop@>
17414
17415 @<Set the value of |b| to the badness for stretching...@>=
17416 if ((cur_active_width[3]!=0)||(cur_active_width[4]!=0)||@|
17417 (cur_active_width[5]!=0))
17418 {@+b=0;fit_class=decent_fit; /*infinite stretch*/
17419 }
17420 else{@+if (shortfall > 7230584) if (cur_active_width[2] < 1663497)
17421 {@+b=inf_bad;fit_class=very_loose_fit;goto done1;
17422 }
17423 b=badness(shortfall, cur_active_width[2]);
17424 if (b > 12)
17425 if (b > 99) fit_class=very_loose_fit;
17426 else fit_class=loose_fit;
17427 else fit_class=decent_fit;
17428 done1: ;
17429 }
17430
17431 @ Shrinkability is never infinite in a paragraph;
17432 we can shrink the line from |r| to |cur_p| by at most |cur_active_width[6]|.
17433
17434 @<Set the value of |b| to the badness for shrinking...@>=
17435 {@+if (-shortfall > cur_active_width[6]) b=inf_bad+1;
17436 else b=badness(-shortfall, cur_active_width[6]);
17437 if (b > 12) fit_class=tight_fit;@+else fit_class=decent_fit;
17438 }
17439
17440 @ During the final pass, we dare not lose all active nodes, lest we lose
17441 touch with the line breaks already found. The code shown here makes sure
17442 that such a catastrophe does not happen, by permitting overfull boxes as
17443 a last resort. This particular part of \TeX\ was a source of several subtle
17444 bugs before the correct program logic was finally discovered; readers
17445 who seek to ``improve'' \TeX\ should therefore think thrice before daring
17446 to make any changes here.
17447 @^overfull boxes@>
17448
17449 @<Prepare to deactivate node~|r|, and |goto deactivate| unless...@>=
17450 {@+if (final_pass&&(minimum_demerits==awful_bad)&&@|
17451 (link(r)==last_active)&&
17452 (prev_r==active))
17453 artificial_demerits=true; /*set demerits zero, this break is forced*/
17454 else if (b > threshold) goto deactivate;
17455 node_r_stays_active=false;
17456 }
17457
17458 @ When we get to this part of the code, the line from |r| to |cur_p| is
17459 feasible, its badness is~|b|, and its fitness classification is |fit_class|.
17460 We don't want to make an active node for this break yet, but we will
17461 compute the total demerits and record them in the |minimal_demerits| array,
17462 if such a break is the current champion among all ways to get to |cur_p|
17463 in a given line-number class and fitness class.
17464
17465 @<Record a new feasible break@>=
17466 if (artificial_demerits) d=0;
17467 else@<Compute the demerits, |d|, from |r| to |cur_p|@>;
17468 #ifdef @!STAT
17469 if (tracing_paragraphs > 0)
17470 @<Print a symbolic description of this feasible break@>;
17471 #endif
17472 @;@/
17473 d=d+total_demerits(r); /*this is the minimum total demerits
17474 from the beginning to |cur_p| via |r|*/
17475 if (d <= minimal_demerits[fit_class])
17476 {@+minimal_demerits[fit_class]=d;
17477 best_place[fit_class]=break_node(r);best_pl_line[fit_class]=l;
17478 if (d < minimum_demerits) minimum_demerits=d;
17479 }
17480
17481 @ @<Print a symbolic description of this feasible break@>=
17482 {@+if (printed_node!=cur_p)
17483 @<Print the list between |printed_node| and |cur_p|, then set |printed_node:=cur_p|@>;
17484 print_nl("@@");
17485 @.\AT@>
17486 if (cur_p==null) print_esc("par");
17487 else if (type(cur_p)!=glue_node)
17488 {@+if (type(cur_p)==penalty_node) print_esc("penalty");
17489 else if (type(cur_p)==disc_node) print_esc("discretionary");
17490 else if (type(cur_p)==kern_node) print_esc("kern");
17491 else print_esc("math");
17492 }
17493 print(" via @@@@");
17494 if (break_node(r)==null) print_char('0');
17495 else print_int(serial(break_node(r)));
17496 print(" b=");
17497 if (b > inf_bad) print_char('*');@+else print_int(b);
17498 @.*\relax@>
17499 print(" p=");print_int(pi);print(" d=");
17500 if (artificial_demerits) print_char('*');@+else print_int(d);
17501 }
17502
17503 @ @<Print the list between |printed_node| and |cur_p|...@>=
17504 {@+print_nl("");
17505 if (cur_p==null) short_display(link(printed_node));
17506 else{@+save_link=link(cur_p);
17507 link(cur_p)=null;print_nl("");short_display(link(printed_node));
17508 link(cur_p)=save_link;
17509 }
17510 printed_node=cur_p;
17511 }
17512
17513 @ When the data for a discretionary break is being displayed, we will have
17514 printed the |pre_break| and |post_break| lists; we want to skip over the
17515 third list, so that the discretionary data will not appear twice. The
17516 following code is performed at the very end of |try_break|.
17517
17518 @<Update the value of |printed_node|...@>=
17519 if (cur_p==printed_node) if (cur_p!=null) if (type(cur_p)==disc_node)
17520 {@+t=replace_count(cur_p);
17521 while (t > 0)
17522 {@+decr(t);printed_node=link(printed_node);
17523 }
17524 }
17525
17526 @ @<Compute the demerits, |d|, from |r| to |cur_p|@>=
17527 {@+d=line_penalty+b;
17528 if (abs(d) >= 10000) d=100000000;@+else d=d*d;
17529 if (pi!=0)
17530 if (pi > 0) d=d+pi*pi;
17531 else if (pi > eject_penalty) d=d-pi*pi;
17532 if ((break_type==hyphenated)&&(type(r)==hyphenated))
17533 if (cur_p!=null) d=d+double_hyphen_demerits;
17534 else d=d+final_hyphen_demerits;
17535 if (abs(fit_class-fitness(r)) > 1) d=d+adj_demerits;
17536 }
17537
17538 @ When an active node disappears, we must delete an adjacent delta node if the
17539 active node was at the beginning or the end of the active list, or if it
17540 was surrounded by delta nodes. We also must preserve the property that
17541 |cur_active_width| represents the length of material from |link(prev_r)|
17542 to~|cur_p|.
17543
17544 @d combine_two_deltas(A) @|mem[prev_r+A].sc=mem[prev_r+A].sc+mem[r+A].sc
17545 @d downdate_width(A) @|cur_active_width[A]=cur_active_width[A]-
17546 mem[prev_r+A].sc
17547
17548 @<Deactivate node |r|@>=
17549 link(prev_r)=link(r);free_node(r, active_node_size);
17550 if (prev_r==active) @<Update the active widths, since the first active node
17551 has been deleted@>@;
17552 else if (type(prev_r)==delta_node)
17553 {@+r=link(prev_r);
17554 if (r==last_active)
17555 {@+do_all_six(downdate_width);
17556 link(prev_prev_r)=last_active;
17557 free_node(prev_r, delta_node_size);prev_r=prev_prev_r;
17558 }
17559 else if (type(r)==delta_node)
17560 {@+do_all_six(update_width);
17561 do_all_six(combine_two_deltas);
17562 link(prev_r)=link(r);free_node(r, delta_node_size);
17563 }
17564 }
17565
17566 @ The following code uses the fact that |type(last_active)!=delta_node|. If the
17567 active list has just become empty, we do not need to update the
17568 |active_width| array, since it will be initialized when an active
17569 node is next inserted.
17570
17571 @d update_active(A) active_width[A]=active_width[A]+mem[r+A].sc
17572
17573 @<Update the active widths,...@>=
17574 {@+r=link(active);
17575 if (type(r)==delta_node)
17576 {@+do_all_six(update_active);
17577 do_all_six(copy_to_cur_active);
17578 link(active)=link(r);free_node(r, delta_node_size);
17579 }
17580 }
17581
17582 @* Breaking paragraphs into lines, continued.
17583 So far we have gotten a little way into the |line_break| routine, having
17584 covered its important |try_break| subroutine. Now let's consider the
17585 rest of the process.
17586
17587 The main loop of |line_break| traverses the given hlist,
17588 starting at |link(temp_head)|, and calls |try_break| at each legal
17589 breakpoint. A variable called |auto_breaking| is set to true except
17590 within math formulas, since glue nodes are not legal breakpoints when
17591 they appear in formulas.
17592
17593 The current node of interest in the hlist is pointed to by |cur_p|. Another
17594 variable, |prev_p|, is usually one step behind |cur_p|, but the real
17595 meaning of |prev_p| is this: If |type(cur_p)==glue_node| then |cur_p| is a legal
17596 breakpoint if and only if |auto_breaking| is true and |prev_p| does not
17597 point to a glue node, penalty node, explicit kern node, or math node.
17598
17599 The following declarations provide for a few other local variables that are
17600 used in special calculations.
17601
17602 @<Local variables for line breaking@>=
17603 bool @!auto_breaking; /*is node |cur_p| outside a formula?*/
17604 pointer @!prev_p; /*helps to determine when glue nodes are breakpoints*/
17605 pointer @!q, @!r, @!s, @!prev_s; /*miscellaneous nodes of temporary interest*/
17606 internal_font_number @!f; /*used when calculating character widths*/
17607
17608 @ The `\ignorespaces|loop|\unskip' in the following code is performed at most
17609 thrice per call of |line_break|, since it is actually a pass over the
17610 entire paragraph.
17611
17612 @<Find optimal breakpoints@>=
17613 threshold=pretolerance;
17614 if (threshold >= 0)
17615 {
17616 #ifdef @!STAT
17617 if (tracing_paragraphs > 0)
17618 {@+begin_diagnostic();print_nl("@@firstpass");@+} @;
17619 #endif
17620 @;@/
17621 second_pass=false;final_pass=false;
17622 }
17623 else{@+threshold=tolerance;second_pass=true;
17624 final_pass=(emergency_stretch <= 0);
17625 #ifdef @!STAT
17626 if (tracing_paragraphs > 0) begin_diagnostic();
17627 #endif
17628 @;
17629 }
17630 loop@+{@+if (threshold > inf_bad) threshold=inf_bad;
17631 if (second_pass) @<Initialize for hyphenating a paragraph@>;
17632 @<Create an active breakpoint representing the beginning of the paragraph@>;
17633 cur_p=link(temp_head);auto_breaking=true;@/
17634 prev_p=cur_p; /*glue at beginning is not a legal breakpoint*/
17635 while ((cur_p!=null)&&(link(active)!=last_active))
17636 @<Call |try_break| if |cur_p| is a legal breakpoint; on the second pass,
17637 also try to hyphenate the next word, if |cur_p| is a glue node; then advance
17638 |cur_p| to the next node of the paragraph that could possibly be a legal breakpoint@>;
17639 if (cur_p==null)
17640 @<Try the final line break at the end of the paragraph, and |goto done|
17641 if the desired breakpoints have been found@>;
17642 @<Clean up the memory by removing the break nodes@>;
17643 if (!second_pass)
17644 {
17645 #ifdef @!STAT
17646 if (tracing_paragraphs > 0) print_nl("@@secondpass");@;
17647 #endif
17648 threshold=tolerance;second_pass=true;final_pass=(emergency_stretch <= 0);
17649 } /*if at first you don't succeed, \dots*/
17650 else{
17651 #ifdef @!STAT
17652 if (tracing_paragraphs > 0)
17653 print_nl("@@emergencypass");@;
17654 #endif
17655 background[2]=background[2]+emergency_stretch;final_pass=true;
17656 }
17657 }
17658 done:
17659 #ifdef @!STAT
17660 if (tracing_paragraphs > 0)
17661 {@+end_diagnostic(true);normalize_selector();
17662 }
17663 #endif
17664
17665 @ The active node that represents the starting point does not need a
17666 corresponding passive node.
17667
17668 @d store_background(A) active_width[A]=background[A]
17669
17670 @<Create an active breakpoint representing the beginning of the paragraph@>=
17671 q=get_node(active_node_size);
17672 type(q)=unhyphenated;fitness(q)=decent_fit;
17673 link(q)=last_active;break_node(q)=null;
17674 line_number(q)=prev_graf+1;total_demerits(q)=0;link(active)=q;
17675 do_all_six(store_background);@/
17676 passive=null;printed_node=temp_head;pass_number=0;
17677 font_in_short_display=null_font
17678
17679 @ @<Clean...@>=
17680 q=link(active);
17681 while (q!=last_active)
17682 {@+cur_p=link(q);
17683 if (type(q)==delta_node) free_node(q, delta_node_size);
17684 else free_node(q, active_node_size);
17685 q=cur_p;
17686 }
17687 q=passive;
17688 while (q!=null)
17689 {@+cur_p=link(q);
17690 free_node(q, passive_node_size);
17691 q=cur_p;
17692 }
17693
17694 @ Here is the main switch in the |line_break| routine, where legal breaks
17695 are determined. As we move through the hlist, we need to keep the |active_width|
17696 array up to date, so that the badness of individual lines is readily calculated
17697 by |try_break|. It is convenient to use the short name |act_width| for
17698 the component of active width that represents real width as opposed to glue.
17699
17700 @d act_width active_width[1] /*length from first active node to current node*/
17701 @d kern_break {@+if (!is_char_node(link(cur_p))&&auto_breaking)
17702 if (type(link(cur_p))==glue_node) try_break(0, unhyphenated);
17703 act_width=act_width+width(cur_p);
17704 }
17705
17706 @<Call |try_break| if |cur_p| is a legal breakpoint...@>=
17707 {@+if (is_char_node(cur_p))
17708 @<Advance \(c)|cur_p| to the node following the present string of characters@>;
17709 switch (type(cur_p)) {
17710 case hlist_node: case vlist_node: case rule_node: act_width=act_width+width(cur_p);@+break;
17711 case whatsit_node: @<Advance \(p)past a whatsit node in the \(l)|line_break|
17712 loop@>@;@+break;
17713 case glue_node: {@+@<If node |cur_p| is a legal breakpoint, call |try_break|;
17714 then update the active widths by including the glue in |glue_ptr(cur_p)|@>;
17715 if (second_pass&&auto_breaking)
17716 @<Try to hyphenate the following word@>;
17717 } @+break;
17718 case kern_node: if (subtype(cur_p)==explicit) kern_break@;
17719 else act_width=act_width+width(cur_p);@+break;
17720 case ligature_node: {@+f=font(lig_char(cur_p));
17721 act_width=act_width+char_width(f, char_info(f, character(lig_char(cur_p))));
17722 } @+break;
17723 case disc_node: @<Try to break after a discretionary fragment, then |goto
17724 done5|@>@;
17725 case math_node: {@+auto_breaking=(subtype(cur_p)==after);kern_break;
17726 } @+break;
17727 case penalty_node: try_break(penalty(cur_p), unhyphenated);@+break;
17728 case mark_node: case ins_node: case adjust_node: do_nothing;@+break;
17729 default:confusion("paragraph");
17730 @:this can't happen paragraph}{\quad paragraph@>
17731 } @/
17732 prev_p=cur_p;cur_p=link(cur_p);
17733 done5: ;}
17734
17735 @ The code that passes over the characters of words in a paragraph is
17736 part of \TeX's inner loop, so it has been streamlined for speed. We use
17737 the fact that `\.{\\parfillskip}' glue appears at the end of each paragraph;
17738 it is therefore unnecessary to check if |link(cur_p)==null| when |cur_p| is a
17739 character node.
17740 @^inner loop@>
17741
17742 @<Advance \(c)|cur_p| to the node following the present string...@>=
17743 {@+prev_p=cur_p;
17744 @/do@+{f=font(cur_p);
17745 act_width=act_width+char_width(f, char_info(f, character(cur_p)));
17746 cur_p=link(cur_p);
17747 }@+ while (!(!is_char_node(cur_p)));
17748 }
17749
17750 @ When node |cur_p| is a glue node, we look at |prev_p| to see whether or not
17751 a breakpoint is legal at |cur_p|, as explained above.
17752
17753 @<If node |cur_p| is a legal breakpoint, call...@>=
17754 if (auto_breaking)
17755 {@+if (is_char_node(prev_p)) try_break(0, unhyphenated);
17756 else if (precedes_break(prev_p)) try_break(0, unhyphenated);
17757 else if ((type(prev_p)==kern_node)&&(subtype(prev_p)!=explicit))
17758 try_break(0, unhyphenated);
17759 }
17760 check_shrinkage(glue_ptr(cur_p));q=glue_ptr(cur_p);
17761 act_width=act_width+width(q);@|
17762 active_width[2+stretch_order(q)]=@|
17763 active_width[2+stretch_order(q)]+stretch(q);@/
17764 active_width[6]=active_width[6]+shrink(q)
17765
17766 @ The following code knows that discretionary texts contain
17767 only character nodes, kern nodes, box nodes, rule nodes, and ligature nodes.
17768
17769 @<Try to break after a discretionary fragment...@>=
17770 {@+s=pre_break(cur_p);disc_width=0;
17771 if (s==null) try_break(ex_hyphen_penalty, hyphenated);
17772 else{@+@/do@+{@<Add the width of node |s| to |disc_width|@>;
17773 s=link(s);
17774 }@+ while (!(s==null));
17775 act_width=act_width+disc_width;
17776 try_break(hyphen_penalty, hyphenated);
17777 act_width=act_width-disc_width;
17778 }
17779 r=replace_count(cur_p);s=link(cur_p);
17780 while (r > 0)
17781 {@+@<Add the width of node |s| to |act_width|@>;
17782 decr(r);s=link(s);
17783 }
17784 prev_p=cur_p;cur_p=s;goto done5;
17785 }
17786
17787 @ @<Add the width of node |s| to |disc_width|@>=
17788 if (is_char_node(s))
17789 {@+f=font(s);
17790 disc_width=disc_width+char_width(f, char_info(f, character(s)));
17791 }
17792 else switch (type(s)) {
17793 case ligature_node: {@+f=font(lig_char(s));
17794 disc_width=disc_width+
17795 char_width(f, char_info(f, character(lig_char(s))));
17796 } @+break;
17797 case hlist_node: case vlist_node: case rule_node:
17798 case kern_node:
17799 disc_width=disc_width+width(s);@+break;
17800 default:confusion("disc3");
17801 @:this can't happen disc3}{\quad disc3@>
17802 }
17803
17804 @ @<Add the width of node |s| to |act_width|@>=
17805 if (is_char_node(s))
17806 {@+f=font(s);
17807 act_width=act_width+char_width(f, char_info(f, character(s)));
17808 }
17809 else switch (type(s)) {
17810 case ligature_node: {@+f=font(lig_char(s));
17811 act_width=act_width+
17812 char_width(f, char_info(f, character(lig_char(s))));
17813 } @+break;
17814 case hlist_node: case vlist_node: case rule_node:
17815 case kern_node:
17816 act_width=act_width+width(s);@+break;
17817 default:confusion("disc4");
17818 @:this can't happen disc4}{\quad disc4@>
17819 }
17820
17821 @ The forced line break at the paragraph's end will reduce the list of
17822 breakpoints so that all active nodes represent breaks at |cur_p==null|.
17823 On the first pass, we insist on finding an active node that has the
17824 correct ``looseness.'' On the final pass, there will be at least one active
17825 node, and we will match the desired looseness as well as we can.
17826
17827 The global variable |best_bet| will be set to the active node for the best
17828 way to break the paragraph, and a few other variables are used to
17829 help determine what is best.
17830
17831 @<Glob...@>=
17832 static pointer @!best_bet; /*use this passive node and its predecessors*/
17833 static int @!fewest_demerits; /*the demerits associated with |best_bet|*/
17834 static halfword @!best_line; /*line number following the last line of the new paragraph*/
17835 static int @!actual_looseness; /*the difference between |line_number(best_bet)|
17836 and the optimum |best_line|*/
17837 static int @!line_diff; /*the difference between the current line number and
17838 the optimum |best_line|*/
17839
17840 @ @<Try the final line break at the end of the paragraph...@>=
17841 {@+try_break(eject_penalty, hyphenated);
17842 if (link(active)!=last_active)
17843 {@+@<Find an active node with fewest demerits@>;
17844 if (looseness==0) goto done;
17845 @<Find the best active node for the desired looseness@>;
17846 if ((actual_looseness==looseness)||final_pass) goto done;
17847 }
17848 }
17849
17850 @ @<Find an active node...@>=
17851 r=link(active);fewest_demerits=awful_bad;
17852 @/do@+{if (type(r)!=delta_node) if (total_demerits(r) < fewest_demerits)
17853 {@+fewest_demerits=total_demerits(r);best_bet=r;
17854 }
17855 r=link(r);
17856 }@+ while (!(r==last_active));
17857 best_line=line_number(best_bet)
17858
17859 @ The adjustment for a desired looseness is a slightly more complicated
17860 version of the loop just considered. Note that if a paragraph is broken
17861 into segments by displayed equations, each segment will be subject to the
17862 looseness calculation, independently of the other segments.
17863
17864 @<Find the best active node...@>=
17865 {@+r=link(active);actual_looseness=0;
17866 @/do@+{if (type(r)!=delta_node)
17867 {@+line_diff=line_number(r)-best_line;
17868 if (((line_diff < actual_looseness)&&(looseness <= line_diff))||@|
17869 ((line_diff > actual_looseness)&&(looseness >= line_diff)))
17870 {@+best_bet=r;actual_looseness=line_diff;
17871 fewest_demerits=total_demerits(r);
17872 }
17873 else if ((line_diff==actual_looseness)&&@|
17874 (total_demerits(r) < fewest_demerits))
17875 {@+best_bet=r;fewest_demerits=total_demerits(r);
17876 }
17877 }
17878 r=link(r);
17879 }@+ while (!(r==last_active));
17880 best_line=line_number(best_bet);
17881 }
17882
17883 @ Once the best sequence of breakpoints has been found (hurray), we call on the
17884 procedure |post_line_break| to finish the remainder of the work.
17885 (By introducing this subprocedure, we are able to keep |line_break|
17886 from getting extremely long.)
17887
17888 @<Break the paragraph at the chosen...@>=
17889 post_line_break(final_widow_penalty)
17890
17891 @ The total number of lines that will be set by |post_line_break|
17892 is |best_line-prev_graf-1|. The last breakpoint is specified by
17893 |break_node(best_bet)|, and this passive node points to the other breakpoints
17894 via the |prev_break| links. The finishing-up phase starts by linking the
17895 relevant passive nodes in forward order, changing |prev_break| to
17896 |next_break|. (The |next_break| fields actually reside in the same memory
17897 space as the |prev_break| fields did, but we give them a new name because
17898 of their new significance.) Then the lines are justified, one by one.
17899
17900 @d next_break prev_break /*new name for |prev_break| after links are reversed*/
17901
17902 @<Declare subprocedures for |line_break|@>=
17903 static void post_line_break(int @!final_widow_penalty)
17904 {@+
17905 pointer q, @!r, @!s; /*temporary registers for list manipulation*/
17906 bool @!disc_break; /*was the current break at a discretionary node?*/
17907 bool @!post_disc_break; /*and did it have a nonempty post-break part?*/
17908 scaled @!cur_width; /*width of line number |cur_line|*/
17909 scaled @!cur_indent; /*left margin of line number |cur_line|*/
17910 quarterword @!t; /*used for replacement counts in discretionary nodes*/
17911 int @!pen; /*use when calculating penalties between lines*/
17912 halfword @!cur_line; /*the current line number being justified*/
17913 @<Reverse the links of the relevant passive nodes, setting |cur_p| to the
17914 first breakpoint@>;
17915 cur_line=prev_graf+1;
17916 @/do@+{@<Justify the line ending at breakpoint |cur_p|, and append it to the
17917 current vertical list, together with associated penalties and other insertions@>;
17918 incr(cur_line);cur_p=next_break(cur_p);
17919 if (cur_p!=null) if (!post_disc_break)
17920 @<Prune unwanted nodes at the beginning of the next line@>;
17921 }@+ while (!(cur_p==null));
17922 if ((cur_line!=best_line)||(link(temp_head)!=null))
17923 confusion("line breaking");
17924 @:this can't happen line breaking}{\quad line breaking@>
17925 prev_graf=best_line-1;
17926 }
17927
17928 @ The job of reversing links in a list is conveniently regarded as the job
17929 of taking items off one stack and putting them on another. In this case we
17930 take them off a stack pointed to by |q| and having |prev_break| fields;
17931 we put them on a stack pointed to by |cur_p| and having |next_break| fields.
17932 Node |r| is the passive node being moved from stack to stack.
17933
17934 @<Reverse the links of the relevant passive nodes...@>=
17935 q=break_node(best_bet);cur_p=null;
17936 @/do@+{r=q;q=prev_break(q);next_break(r)=cur_p;cur_p=r;
17937 }@+ while (!(q==null))
17938
17939 @ Glue and penalty and kern and math nodes are deleted at the beginning of
17940 a line, except in the anomalous case that the node to be deleted is actually
17941 one of the chosen breakpoints. Otherwise
17942 the pruning done here is designed to match
17943 the lookahead computation in |try_break|, where the |break_width| values
17944 are computed for non-discretionary breakpoints.
17945
17946 @<Prune unwanted nodes at the beginning of the next line@>=
17947 {@+r=temp_head;
17948 loop@+{@+q=link(r);
17949 if (q==cur_break(cur_p)) goto done1;
17950 /*|cur_break(cur_p)| is the next breakpoint*/
17951 /*now |q| cannot be |null|*/
17952 if (is_char_node(q)) goto done1;
17953 if (non_discardable(q)) goto done1;
17954 if (type(q)==kern_node) if (subtype(q)!=explicit) goto done1;
17955 r=q; /*now |type(q)==glue_node|, |kern_node|, |math_node|, or |penalty_node|*/
17956 }
17957 done1: if (r!=temp_head)
17958 {@+link(r)=null;flush_node_list(link(temp_head));
17959 link(temp_head)=q;
17960 }
17961 }
17962
17963 @ The current line to be justified appears in a horizontal list starting
17964 at |link(temp_head)| and ending at |cur_break(cur_p)|. If |cur_break(cur_p)| is
17965 a glue node, we reset the glue to equal the |right_skip| glue; otherwise
17966 we append the |right_skip| glue at the right. If |cur_break(cur_p)| is a
17967 discretionary node, we modify the list so that the discretionary break
17968 is compulsory, and we set |disc_break| to |true|. We also append
17969 the |left_skip| glue at the left of the line, unless it is zero.
17970
17971 @<Justify the line ending at breakpoint |cur_p|, and append it...@>=
17972 @<Modify the end of the line to reflect the nature of the break and to include
17973 \.{\\rightskip}; also set the proper value of |disc_break|@>;
17974 @<Put the \(l)\.{\\leftskip} glue at the left and detach this line@>;
17975 @<Call the packaging subroutine, setting |just_box| to the justified box@>;
17976 @<Append the new box to the current vertical list, followed by the list of
17977 special nodes taken out of the box by the packager@>;
17978 @<Append a penalty node, if a nonzero penalty is appropriate@>@;
17979
17980 @ At the end of the following code, |q| will point to the final node on the
17981 list about to be justified.
17982
17983 @<Modify the end of the line...@>=
17984 q=cur_break(cur_p);disc_break=false;post_disc_break=false;
17985 if (q!=null) /*|q| cannot be a |char_node|*/
17986 if (type(q)==glue_node)
17987 {@+delete_glue_ref(glue_ptr(q));
17988 glue_ptr(q)=right_skip;
17989 subtype(q)=right_skip_code+1;add_glue_ref(right_skip);
17990 goto done;
17991 }
17992 else{@+if (type(q)==disc_node)
17993 @<Change discretionary to compulsory and set |disc_break:=true|@>@;
17994 else if ((type(q)==math_node)||(type(q)==kern_node)) width(q)=0;
17995 }
17996 else{@+q=temp_head;
17997 while (link(q)!=null) q=link(q);
17998 }
17999 @<Put the \(r)\.{\\rightskip} glue after node |q|@>;
18000 done:
18001
18002 @ @<Change discretionary to compulsory...@>=
18003 {@+t=replace_count(q);
18004 @<Destroy the |t| nodes following |q|, and make |r| point to the following
18005 node@>;
18006 if (post_break(q)!=null) @<Transplant the post-break list@>;
18007 if (pre_break(q)!=null) @<Transplant the pre-break list@>;
18008 link(q)=r;disc_break=true;
18009 }
18010
18011 @ @<Destroy the |t| nodes following |q|...@>=
18012 if (t==0) r=link(q);
18013 else{@+r=q;
18014 while (t > 1)
18015 {@+r=link(r);decr(t);
18016 }
18017 s=link(r);
18018 r=link(s);link(s)=null;
18019 flush_node_list(link(q));replace_count(q)=0;
18020 }
18021
18022 @ We move the post-break list from inside node |q| to the main list by
18023 re\-attaching it just before the present node |r|, then resetting |r|.
18024
18025 @<Transplant the post-break list@>=
18026 {@+s=post_break(q);
18027 while (link(s)!=null) s=link(s);
18028 link(s)=r;r=post_break(q);post_break(q)=null;post_disc_break=true;
18029 }
18030
18031 @ We move the pre-break list from inside node |q| to the main list by
18032 re\-attaching it just after the present node |q|, then resetting |q|.
18033
18034 @<Transplant the pre-break list@>=
18035 {@+s=pre_break(q);link(q)=s;
18036 while (link(s)!=null) s=link(s);
18037 pre_break(q)=null;q=s;
18038 }
18039
18040 @ @<Put the \(r)\.{\\rightskip} glue after node |q|@>=
18041 r=new_param_glue(right_skip_code);link(r)=link(q);link(q)=r;q=r
18042
18043 @ The following code begins with |q| at the end of the list to be
18044 justified. It ends with |q| at the beginning of that list, and with
18045 |link(temp_head)| pointing to the remainder of the paragraph, if any.
18046
18047 @<Put the \(l)\.{\\leftskip} glue at the left...@>=
18048 r=link(q);link(q)=null;q=link(temp_head);link(temp_head)=r;
18049 if (left_skip!=zero_glue)
18050 {@+r=new_param_glue(left_skip_code);
18051 link(r)=q;q=r;
18052 }
18053
18054 @ @<Append the new box to the current vertical list...@>=
18055 append_to_vlist(just_box);
18056 if (adjust_head!=adjust_tail)
18057 {@+link(tail)=link(adjust_head);tail=adjust_tail;
18058 }
18059 adjust_tail=null
18060
18061 @ Now |q| points to the hlist that represents the current line of the
18062 paragraph. We need to compute the appropriate line width, pack the
18063 line into a box of this size, and shift the box by the appropriate
18064 amount of indentation.
18065
18066 @<Call the packaging subroutine...@>=
18067 if (cur_line > last_special_line)
18068 {@+cur_width=second_width;cur_indent=second_indent;
18069 }
18070 else if (par_shape_ptr==null)
18071 {@+cur_width=first_width;cur_indent=first_indent;
18072 }
18073 else{@+cur_width=mem[par_shape_ptr+2*cur_line].sc;
18074 cur_indent=mem[par_shape_ptr+2*cur_line-1].sc;
18075 }
18076 adjust_tail=adjust_head;just_box=hpack(q, cur_width, exactly);
18077 shift_amount(just_box)=cur_indent
18078
18079 @ Penalties between the lines of a paragraph come from club and widow lines,
18080 from the |inter_line_penalty| parameter, and from lines that end at
18081 discretionary breaks. Breaking between lines of a two-line paragraph gets
18082 both club-line and widow-line penalties. The local variable |pen| will
18083 be set to the sum of all relevant penalties for the current line, except
18084 that the final line is never penalized.
18085
18086 @<Append a penalty node, if a nonzero penalty is appropriate@>=
18087 if (cur_line+1!=best_line)
18088 {@+pen=inter_line_penalty;
18089 if (cur_line==prev_graf+1) pen=pen+club_penalty;
18090 if (cur_line+2==best_line) pen=pen+final_widow_penalty;
18091 if (disc_break) pen=pen+broken_penalty;
18092 if (pen!=0)
18093 {@+r=new_penalty(pen);
18094 link(tail)=r;tail=r;
18095 }
18096 }
18097
18098 @* Pre-hyphenation.
18099 When the line-breaking routine is unable to find a feasible sequence of
18100 breakpoints, it makes a second pass over the paragraph, attempting to
18101 hyphenate the hyphenatable words. The goal of hyphenation is to insert
18102 discretionary material into the paragraph so that there are more
18103 potential places to break.
18104
18105 The general rules for hyphenation are somewhat complex and technical,
18106 because we want to be able to hyphenate words that are preceded or
18107 followed by punctuation marks, and because we want the rules to work
18108 for languages other than English. We also must contend with the fact
18109 that hyphens might radically alter the ligature and kerning structure
18110 of a word.
18111
18112 A sequence of characters will be considered for hyphenation only if it
18113 belongs to a ``potentially hyphenatable part'' of the current paragraph.
18114 This is a sequence of nodes $p_0p_1\ldots p_m$ where $p_0$ is a glue node,
18115 $p_1\ldots p_{m-1}$ are either character or ligature or whatsit or
18116 implicit kern nodes, and $p_m$ is a glue or penalty or insertion or adjust
18117 or mark or whatsit or explicit kern node. (Therefore hyphenation is
18118 disabled by boxes, math formulas, and discretionary nodes already inserted
18119 by the user.) The ligature nodes among $p_1\ldots p_{m-1}$ are effectively
18120 expanded into the original non-ligature characters; the kern nodes and
18121 whatsits are ignored. Each character |c| is now classified as either a
18122 nonletter (if |lc_code(c)==0|), a lowercase letter (if
18123 |lc_code(c)==c|), or an uppercase letter (otherwise); an uppercase letter
18124 is treated as if it were |lc_code(c)| for purposes of hyphenation. The
18125 characters generated by $p_1\ldots p_{m-1}$ may begin with nonletters; let
18126 $c_1$ be the first letter that is not in the middle of a ligature. Whatsit
18127 nodes preceding $c_1$ are ignored; a whatsit found after $c_1$ will be the
18128 terminating node $p_m$. All characters that do not have the same font as
18129 $c_1$ will be treated as nonletters. The |hyphen_char| for that font
18130 must be between 0 and 255, otherwise hyphenation will not be attempted.
18131 \TeX\ looks ahead for as many consecutive letters $c_1\ldots c_n$ as
18132 possible; however, |n| must be less than 64, so a character that would
18133 otherwise be $c_{64}$ is effectively not a letter. Furthermore $c_n$ must
18134 not be in the middle of a ligature. In this way we obtain a string of
18135 letters $c_1\ldots c_n$ that are generated by nodes $p_a\ldots p_b$, where
18136 |1 <= a <= b+1 <= m|. If |n >= l_hyf+r_hyf|, this string qualifies for hyphenation;
18137 however, |uc_hyph| must be positive, if $c_1$ is uppercase.
18138
18139 The hyphenation process takes place in three stages. First, the candidate
18140 sequence $c_1\ldots c_n$ is found; then potential positions for hyphens
18141 are determined by referring to hyphenation tables; and finally, the nodes
18142 $p_a\ldots p_b$ are replaced by a new sequence of nodes that includes the
18143 discretionary breaks found.
18144
18145 Fortunately, we do not have to do all this calculation very often, because
18146 of the way it has been taken out of \TeX's inner loop. For example, when
18147 the second edition of the author's 700-page book {\sl Seminumerical
18148 Algorithms} was typeset by \TeX, only about 1.2 hyphenations needed to be
18149 @^Knuth, Donald Ervin@>
18150 tried per paragraph, since the line breaking algorithm needed to use two
18151 passes on only about 5 per cent of the paragraphs.
18152
18153 @<Initialize for hyphenating...@>=
18154 {
18155 #ifdef @!INIT
18156 if (trie_not_ready) init_trie();
18157 #endif
18158 @;@/
18159 cur_lang=init_cur_lang;l_hyf=init_l_hyf;r_hyf=init_r_hyf;
18160 set_hyph_index;
18161 }
18162
18163 @ The letters $c_1\ldots c_n$ that are candidates for hyphenation are placed
18164 into an array called |hc|; the number |n| is placed into |hn|; pointers to
18165 nodes $p_{a-1}$ and~$p_b$ in the description above are placed into variables
18166 |ha| and |hb|; and the font number is placed into |hf|.
18167
18168 @<Glob...@>=
18169 static int16_t @!hc[66]; /*word to be hyphenated*/
18170 static int @!hn; /*the number of positions occupied in |hc|;
18171 not always a |small_number|*/
18172 static pointer @!ha, @!hb; /*nodes |ha dotdot hb| should be replaced by the hyphenated result*/
18173 static internal_font_number @!hf; /*font number of the letters in |hc|*/
18174 static int16_t @!hu[64]; /*like |hc|, before conversion to lowercase*/
18175 static int @!hyf_char; /*hyphen character of the relevant font*/
18176 static ASCII_code @!cur_lang, @!init_cur_lang; /*current hyphenation table of interest*/
18177 static int @!l_hyf, @!r_hyf, @!init_l_hyf, @!init_r_hyf; /*limits on fragment sizes*/
18178 static halfword @!hyf_bchar; /*boundary character after $c_n$*/
18179
18180 @ Hyphenation routines need a few more local variables.
18181
18182 @<Local variables for line...@>=
18183 small_number @!j; /*an index into |hc| or |hu|*/
18184 int @!c; /*character being considered for hyphenation*/
18185
18186 @ When the following code is activated, the |line_break| procedure is in its
18187 second pass, and |cur_p| points to a glue node.
18188
18189 @<Try to hyphenate...@>=
18190 {@+prev_s=cur_p;s=link(prev_s);
18191 if (s!=null)
18192 {@+@<Skip to node |ha|, or |goto done1| if no hyphenation should be attempted@>;
18193 if (l_hyf+r_hyf > 63) goto done1;
18194 @<Skip to node |hb|, putting letters into |hu| and |hc|@>;
18195 @<Check that the nodes following |hb| permit hyphenation and that at least
18196 |l_hyf+r_hyf| letters have been found, otherwise |goto done1|@>;
18197 hyphenate();
18198 }
18199 done1: ;}
18200
18201 @ @<Declare subprocedures for |line_break|@>=
18202 @t\4@>@<Declare the function called |reconstitute|@>@;
18203 static void hyphenate(void)
18204 {@+
18205 @<Local variables for hyphenation@>@;
18206 @<Find hyphen locations for the word in |hc|, or |return|@>;
18207 @<If no hyphens were found, |return|@>;
18208 @<Replace nodes |ha..hb| by a sequence of nodes that includes the discretionary
18209 hyphens@>;
18210 }
18211
18212 @ The first thing we need to do is find the node |ha| just before the
18213 first letter.
18214
18215 @<Skip to node |ha|, or |goto done1|...@>=
18216 loop@+{@+if (is_char_node(s))
18217 {@+c=qo(character(s));hf=font(s);
18218 }
18219 else if (type(s)==ligature_node)
18220 if (lig_ptr(s)==null) goto resume;
18221 else{@+q=lig_ptr(s);c=qo(character(q));hf=font(q);
18222 }
18223 else if ((type(s)==kern_node)&&(subtype(s)==normal)) goto resume;
18224 else if (type(s)==whatsit_node)
18225 {@+@<Advance \(p)past a whatsit node in the \(p)pre-hyphenation loop@>;
18226 goto resume;
18227 }
18228 else goto done1;
18229 set_lc_code(c);
18230 if (hc[0]!=0)
18231 if ((hc[0]==c)||(uc_hyph > 0)) goto done2;
18232 else goto done1;
18233 resume: prev_s=s;s=link(prev_s);
18234 }
18235 done2: hyf_char=hyphen_char[hf];
18236 if (hyf_char < 0) goto done1;
18237 if (hyf_char > 255) goto done1;
18238 ha=prev_s
18239
18240 @ The word to be hyphenated is now moved to the |hu| and |hc| arrays.
18241
18242 @<Skip to node |hb|, putting letters...@>=
18243 hn=0;
18244 loop@+{@+if (is_char_node(s))
18245 {@+if (font(s)!=hf) goto done3;
18246 hyf_bchar=character(s);c=qo(hyf_bchar);
18247 set_lc_code(c);
18248 if (hc[0]==0) goto done3;
18249 if (hn==63) goto done3;
18250 hb=s;incr(hn);hu[hn]=c;hc[hn]=hc[0];hyf_bchar=non_char;
18251 }
18252 else if (type(s)==ligature_node)
18253 @<Move the characters of a ligature node to |hu| and |hc|; but |goto done3|
18254 if they are not all letters@>@;
18255 else if ((type(s)==kern_node)&&(subtype(s)==normal))
18256 {@+hb=s;
18257 hyf_bchar=font_bchar[hf];
18258 }
18259 else goto done3;
18260 s=link(s);
18261 }
18262 done3:
18263
18264 @ We let |j| be the index of the character being stored when a ligature node
18265 is being expanded, since we do not want to advance |hn| until we are sure
18266 that the entire ligature consists of letters. Note that it is possible
18267 to get to |done3| with |hn==0| and |hb| not set to any value.
18268
18269 @<Move the characters of a ligature node to |hu| and |hc|...@>=
18270 {@+if (font(lig_char(s))!=hf) goto done3;
18271 j=hn;q=lig_ptr(s);@+if (q > null) hyf_bchar=character(q);
18272 while (q > null)
18273 {@+c=qo(character(q));
18274 set_lc_code(c);
18275 if (hc[0]==0) goto done3;
18276 if (j==63) goto done3;
18277 incr(j);hu[j]=c;hc[j]=hc[0];@/
18278 q=link(q);
18279 }
18280 hb=s;hn=j;
18281 if (odd(subtype(s))) hyf_bchar=font_bchar[hf];@+else hyf_bchar=non_char;
18282 }
18283
18284 @ @<Check that the nodes following |hb| permit hyphenation...@>=
18285 if (hn < l_hyf+r_hyf) goto done1; /*|l_hyf| and |r_hyf| are | >= 1|*/
18286 loop@+{@+if (!(is_char_node(s)))
18287 switch (type(s)) {
18288 case ligature_node: do_nothing;@+break;
18289 case kern_node: if (subtype(s)!=normal) goto done4;@+break;
18290 case whatsit_node: case glue_node:
18291 case penalty_node: case ins_node: case adjust_node:
18292 case mark_node:
18293 goto done4;
18294 default:goto done1;
18295 }
18296 s=link(s);
18297 }
18298 done4:
18299
18300 @* Post-hyphenation.
18301 If a hyphen may be inserted between |hc[j]| and |hc[j+1]|, the hyphenation
18302 procedure will set |hyf[j]| to some small odd number. But before we look
18303 at \TeX's hyphenation procedure, which is independent of the rest of the
18304 line-breaking algorithm, let us consider what we will do with the hyphens
18305 it finds, since it is better to work on this part of the program before
18306 forgetting what |ha| and |hb|, etc., are all about.
18307
18308 @<Glob...@>=
18309 static int8_t @!hyf[65]; /*odd values indicate discretionary hyphens*/
18310 static pointer @!init_list; /*list of punctuation characters preceding the word*/
18311 static bool @!init_lig; /*does |init_list| represent a ligature?*/
18312 static bool @!init_lft; /*if so, did the ligature involve a left boundary?*/
18313
18314 @ @<Local variables for hyphenation@>=
18315 int @!i, @!j, @!l; /*indices into |hc| or |hu|*/
18316 pointer @!q, @!r, @!s; /*temporary registers for list manipulation*/
18317 halfword @!bchar; /*boundary character of hyphenated word, or |non_char|*/
18318
18319 @ \TeX\ will never insert a hyphen that has fewer than
18320 \.{\\lefthyphenmin} letters before it or fewer than
18321 \.{\\righthyphenmin} after it; hence, a short word has
18322 comparatively little chance of being hyphenated. If no hyphens have
18323 been found, we can save time by not having to make any changes to the
18324 paragraph.
18325
18326 @<If no hyphens were found, |return|@>=
18327 for (j=l_hyf; j<=hn-r_hyf; j++) if (odd(hyf[j])) goto found1;
18328 return;
18329 found1:
18330
18331 @ If hyphens are in fact going to be inserted, \TeX\ first deletes the
18332 subsequence of nodes between |ha| and~|hb|. An attempt is made to
18333 preserve the effect that implicit boundary characters and punctuation marks
18334 had on ligatures inside the hyphenated word, by storing a left boundary or
18335 preceding character in |hu[0]| and by storing a possible right boundary
18336 in |bchar|. We set |j=0| if |hu[0]| is to be part of the reconstruction;
18337 otherwise |j=1|.
18338 The variable |s| will point to the tail of the current hlist, and
18339 |q| will point to the node following |hb|, so that
18340 things can be hooked up after we reconstitute the hyphenated word.
18341
18342 @<Replace nodes |ha..hb| by a sequence of nodes...@>=
18343 q=link(hb);link(hb)=null;r=link(ha);link(ha)=null;bchar=hyf_bchar;
18344 if (is_char_node(ha))
18345 if (font(ha)!=hf) goto found2;
18346 else{@+init_list=ha;init_lig=false;hu[0]=qo(character(ha));
18347 }
18348 else if (type(ha)==ligature_node)
18349 if (font(lig_char(ha))!=hf) goto found2;
18350 else{@+init_list=lig_ptr(ha);init_lig=true;init_lft=(subtype(ha) > 1);
18351 hu[0]=qo(character(lig_char(ha)));
18352 if (init_list==null) if (init_lft)
18353 {@+hu[0]=256;init_lig=false;
18354 } /*in this case a ligature will be reconstructed from scratch*/
18355 free_node(ha, small_node_size);
18356 }
18357 else{@+ /*no punctuation found; look for left boundary*/
18358 if (!is_char_node(r)) if (type(r)==ligature_node)
18359 if (subtype(r) > 1) goto found2;
18360 j=1;s=ha;init_list=null;goto common_ending;
18361 }
18362 s=cur_p; /*we have |cur_p!=ha| because |type(cur_p)==glue_node|*/
18363 while (link(s)!=ha) s=link(s);
18364 j=0;goto common_ending;
18365 found2: s=ha;j=0;hu[0]=256;init_lig=false;init_list=null;
18366 common_ending: flush_node_list(r);
18367 @<Reconstitute nodes for the hyphenated word, inserting discretionary hyphens@>;
18368 flush_list(init_list)
18369
18370 @ We must now face the fact that the battle is not over, even though the
18371 {\def\!{\kern-1pt}%
18372 hyphens have been found: The process of reconstituting a word can be nontrivial
18373 because ligatures might change when a hyphen is present. {\sl The \TeX book\/}
18374 discusses the difficulties of the word ``difficult'', and
18375 the discretionary material surrounding a
18376 hyphen can be considerably more complex than that. Suppose
18377 \.{abcdef} is a word in a font for which the only ligatures are \.{b\!c},
18378 \.{c\!d}, \.{d\!e}, and \.{e\!f}. If this word permits hyphenation
18379 between \.b and \.c, the two patterns with and without hyphenation are
18380 $\.a\,\.b\,\.-\,\.{c\!d}\,\.{e\!f}$ and $\.a\,\.{b\!c}\,\.{d\!e}\,\.f$.
18381 Thus the insertion of a hyphen might cause effects to ripple arbitrarily
18382 far into the rest of the word. A further complication arises if additional
18383 hyphens appear together with such rippling, e.g., if the word in the
18384 example just given could also be hyphenated between \.c and \.d; \TeX\
18385 avoids this by simply ignoring the additional hyphens in such weird cases.}
18386
18387 Still further complications arise in the presence of ligatures that do not
18388 delete the original characters. When punctuation precedes the word being
18389 hyphenated, \TeX's method is not perfect under all possible scenarios,
18390 because punctuation marks and letters can propagate information back and forth.
18391 For example, suppose the original pre-hyphenation pair
18392 \.{*a} changes to \.{*y} via a \.{\@@=:} ligature, which changes to \.{xy}
18393 via a \.{=:\@@} ligature; if $p_{a-1}=\.x$ and $p_a=\.y$, the reconstitution
18394 procedure isn't smart enough to obtain \.{xy} again. In such cases the
18395 font designer should include a ligature that goes from \.{xa} to \.{xy}.
18396
18397 @ The processing is facilitated by a subroutine called |reconstitute|. Given
18398 a string of characters $x_j\ldots x_n$, there is a smallest index $m\ge j$
18399 such that the ``translation'' of $x_j\ldots x_n$ by ligatures and kerning
18400 has the form $y_1\ldots y_t$ followed by the translation of $x_{m+1}\ldots x_n$,
18401 where $y_1\ldots y_t$ is some nonempty sequence of character, ligature, and
18402 kern nodes. We call $x_j\ldots x_m$ a ``cut prefix'' of $x_j\ldots x_n$.
18403 For example, if $x_1x_2x_3=\.{fly}$, and if the font contains `fl' as a
18404 ligature and a kern between `fl' and `y', then $m=2$, $t=2$, and $y_1$ will
18405 be a ligature node for `fl' followed by an appropriate kern node~$y_2$.
18406 In the most common case, $x_j$~forms no ligature with $x_{j+1}$ and we
18407 simply have $m=j$, $y_1=x_j$. If $m<n$ we can repeat the procedure on
18408 $x_{m+1}\ldots x_n$ until the entire translation has been found.
18409
18410 The |reconstitute| function returns the integer $m$ and puts the nodes
18411 $y_1\ldots y_t$ into a linked list starting at |link(hold_head)|,
18412 getting the input $x_j\ldots x_n$ from the |hu| array. If $x_j=256$,
18413 we consider $x_j$ to be an implicit left boundary character; in this
18414 case |j| must be strictly less than~|n|. There is a
18415 parameter |bchar|, which is either 256 or an implicit right boundary character
18416 assumed to be present just following~$x_n$. (The value |hu[n+1]| is never
18417 explicitly examined, but the algorithm imagines that |bchar| is there.)
18418
18419 If there exists an index |k| in the range $j\le k\le m$ such that |hyf[k]|
18420 is odd and such that the result of |reconstitute| would have been different
18421 if $x_{k+1}$ had been |hchar|, then |reconstitute| sets |hyphen_passed|
18422 to the smallest such~|k|. Otherwise it sets |hyphen_passed| to zero.
18423
18424 A special convention is used in the case |j==0|: Then we assume that the
18425 translation of |hu[0]| appears in a special list of charnodes starting at
18426 |init_list|; moreover, if |init_lig| is |true|, then |hu[0]| will be
18427 a ligature character, involving a left boundary if |init_lft| is |true|.
18428 This facility is provided for cases when a hyphenated
18429 word is preceded by punctuation (like single or double quotes) that might
18430 affect the translation of the beginning of the word.
18431
18432 @<Glob...@>=
18433 static small_number @!hyphen_passed; /*first hyphen in a ligature, if any*/
18434
18435 @ @<Declare the function called |reconstitute|@>=
18436 static
18437 small_number reconstitute(small_number @!j, small_number @!n, halfword @!bchar, halfword @!hchar)
18438 {@+
18439 pointer @!p; /*temporary register for list manipulation*/
18440 pointer @!t; /*a node being appended to*/
18441 four_quarters @!q; /*character information or a lig/kern instruction*/
18442 halfword @!cur_rh; /*hyphen character for ligature testing*/
18443 halfword @!test_char; /*hyphen or other character for ligature testing*/
18444 scaled @!w; /*amount of kerning*/
18445 font_index @!k; /*position of current lig/kern instruction*/
18446 hyphen_passed=0;t=hold_head;w=0;link(hold_head)=null;
18447 /*at this point |ligature_present==lft_hit==rt_hit==false|*/
18448 @<Set up data structures with the cursor following position |j|@>;
18449 resume: @<If there's a ligature or kern at the cursor position, update the
18450 data structures, possibly advancing~|j|; continue until the cursor moves@>;
18451 @<Append a ligature and/or kern to the translation; |goto resume| if the
18452 stack of inserted ligatures is nonempty@>;
18453 return j;
18454 }
18455
18456 @ The reconstitution procedure shares many of the global data structures
18457 by which \TeX\ has processed the words before they were hyphenated.
18458 There is an implied ``cursor'' between characters |cur_l| and |cur_r|;
18459 these characters will be tested for possible ligature activity. If
18460 |ligature_present| then |cur_l| is a ligature character formed from the
18461 original characters following |cur_q| in the current translation list.
18462 There is a ``ligature stack'' between the cursor and character |j+1|,
18463 consisting of pseudo-ligature nodes linked together by their |link| fields.
18464 This stack is normally empty unless a ligature command has created a new
18465 character that will need to be processed later. A pseudo-ligature is
18466 a special node having a |character| field that represents a potential
18467 ligature and a |lig_ptr| field that points to a |char_node| or is |null|.
18468 We have
18469 $$|cur_r|=\cases{|character(lig_stack)|,&if |lig_stack > null|;\cr
18470 \hbox{|qi(hu[j+1])|},&if |lig_stack==null| and |j < n|;\cr
18471 bchar,&if |lig_stack==null| and |j==n|.\cr}$$
18472
18473 @<Glob...@>=
18474 static halfword @!cur_l, @!cur_r; /*characters before and after the cursor*/
18475 static pointer @!cur_q; /*where a ligature should be detached*/
18476 static pointer @!lig_stack; /*unfinished business to the right of the cursor*/
18477 static bool @!ligature_present; /*should a ligature node be made for |cur_l|?*/
18478 static bool @!lft_hit, @!rt_hit; /*did we hit a ligature with a boundary character?*/
18479
18480 @ @d append_charnode_to_t(A) {@+link(t)=get_avail();t=link(t);
18481 font(t)=hf;character(t)=A;
18482 }
18483 @d set_cur_r {@+if (j < n) cur_r=qi(hu[j+1]);@+else cur_r=bchar;
18484 if (odd(hyf[j])) cur_rh=hchar;@+else cur_rh=non_char;
18485 }
18486
18487 @<Set up data structures with the cursor following position |j|@>=
18488 cur_l=qi(hu[j]);cur_q=t;
18489 if (j==0)
18490 {@+ligature_present=init_lig;p=init_list;
18491 if (ligature_present) lft_hit=init_lft;
18492 while (p > null)
18493 {@+append_charnode_to_t(character(p));p=link(p);
18494 }
18495 }
18496 else if (cur_l < non_char) append_charnode_to_t(cur_l);
18497 lig_stack=null;set_cur_r
18498
18499 @ We may want to look at the lig/kern program twice, once for a hyphen
18500 and once for a normal letter. (The hyphen might appear after the letter
18501 in the program, so we'd better not try to look for both at once.)
18502
18503 @<If there's a ligature or kern at the cursor position, update...@>=
18504 if (cur_l==non_char)
18505 {@+k=bchar_label[hf];
18506 if (k==non_address) goto done;@+else q=font_info[k].qqqq;
18507 }
18508 else{@+q=char_info(hf, cur_l);
18509 if (char_tag(q)!=lig_tag) goto done;
18510 k=lig_kern_start(hf, q);q=font_info[k].qqqq;
18511 if (skip_byte(q) > stop_flag)
18512 {@+k=lig_kern_restart(hf, q);q=font_info[k].qqqq;
18513 }
18514 } /*now |k| is the starting address of the lig/kern program*/
18515 if (cur_rh < non_char) test_char=cur_rh;@+else test_char=cur_r;
18516 loop@+{@+if (next_char(q)==test_char) if (skip_byte(q) <= stop_flag)
18517 if (cur_rh < non_char)
18518 {@+hyphen_passed=j;hchar=non_char;cur_rh=non_char;
18519 goto resume;
18520 }
18521 else{@+if (hchar < non_char) if (odd(hyf[j]))
18522 {@+hyphen_passed=j;hchar=non_char;
18523 }
18524 if (op_byte(q) < kern_flag)
18525 @<Carry out a ligature replacement, updating the cursor structure and
18526 possibly advancing~|j|; |goto resume| if the cursor doesn't advance, otherwise
18527 |goto done|@>;
18528 w=char_kern(hf, q);goto done; /*this kern will be inserted below*/
18529 }
18530 if (skip_byte(q) >= stop_flag)
18531 if (cur_rh==non_char) goto done;
18532 else{@+cur_rh=non_char;goto resume;
18533 }
18534 k=k+qo(skip_byte(q))+1;q=font_info[k].qqqq;
18535 }
18536 done:
18537
18538 @ @d wrap_lig(A) if (ligature_present)
18539 {@+p=new_ligature(hf, cur_l, link(cur_q));
18540 if (lft_hit)
18541 {@+subtype(p)=2;lft_hit=false;
18542 }
18543 if (A) if (lig_stack==null)
18544 {@+incr(subtype(p));rt_hit=false;
18545 }
18546 link(cur_q)=p;t=p;ligature_present=false;
18547 }
18548 @d pop_lig_stack {@+if (lig_ptr(lig_stack) > null)
18549 {@+link(t)=lig_ptr(lig_stack); /*this is a charnode for |hu[j+1]|*/
18550 t=link(t);incr(j);
18551 }
18552 p=lig_stack;lig_stack=link(p);free_node(p, small_node_size);
18553 if (lig_stack==null) set_cur_r@;@+else cur_r=character(lig_stack);
18554 } /*if |lig_stack| isn't |null| we have |cur_rh==non_char|*/
18555
18556 @<Append a ligature and/or kern to the translation...@>=
18557 wrap_lig(rt_hit);
18558 if (w!=0)
18559 {@+link(t)=new_kern(w);t=link(t);w=0;
18560 }
18561 if (lig_stack > null)
18562 {@+cur_q=t;cur_l=character(lig_stack);ligature_present=true;
18563 pop_lig_stack;goto resume;
18564 }
18565
18566 @ @<Carry out a ligature replacement, updating the cursor structure...@>=
18567 {@+if (cur_l==non_char) lft_hit=true;
18568 if (j==n) if (lig_stack==null) rt_hit=true;
18569 check_interrupt; /*allow a way out in case there's an infinite ligature loop*/
18570 switch (op_byte(q)) {
18571 case qi(1): case qi(5): {@+cur_l=rem_byte(q); /*\.{=:\@@}, \.{=:\@@>}*/
18572 ligature_present=true;
18573 } @+break;
18574 case qi(2): case qi(6): {@+cur_r=rem_byte(q); /*\.{\@@=:}, \.{\@@=:>}*/
18575 if (lig_stack > null) character(lig_stack)=cur_r;
18576 else{@+lig_stack=new_lig_item(cur_r);
18577 if (j==n) bchar=non_char;
18578 else{@+p=get_avail();lig_ptr(lig_stack)=p;
18579 character(p)=qi(hu[j+1]);font(p)=hf;
18580 }
18581 }
18582 } @+break;
18583 case qi(3): {@+cur_r=rem_byte(q); /*\.{\@@=:\@@}*/
18584 p=lig_stack;lig_stack=new_lig_item(cur_r);link(lig_stack)=p;
18585 } @+break;
18586 case qi(7): case qi(11): {@+wrap_lig(false); /*\.{\@@=:\@@>}, \.{\@@=:\@@>>}*/
18587 cur_q=t;cur_l=rem_byte(q);ligature_present=true;
18588 } @+break;
18589 default:{@+cur_l=rem_byte(q);ligature_present=true; /*\.{=:}*/
18590 if (lig_stack > null) pop_lig_stack@;
18591 else if (j==n) goto done;
18592 else{@+append_charnode_to_t(cur_r);incr(j);set_cur_r;
18593 }
18594 }
18595 }
18596 if (op_byte(q) > qi(4)) if (op_byte(q)!=qi(7)) goto done;
18597 goto resume;
18598 }
18599
18600 @ Okay, we're ready to insert the potential hyphenations that were found.
18601 When the following program is executed, we want to append the word
18602 |hu[1 dotdot hn]| after node |ha|, and node |q| should be appended to the result.
18603 During this process, the variable |i| will be a temporary
18604 index into |hu|; the variable |j| will be an index to our current position
18605 in |hu|; the variable |l| will be the counterpart of |j|, in a discretionary
18606 branch; the variable |r| will point to new nodes being created; and
18607 we need a few new local variables:
18608
18609 @<Local variables for hyph...@>=
18610 pointer @!major_tail, @!minor_tail; /*the end of lists in the main and
18611 discretionary branches being reconstructed*/
18612 ASCII_code @!c; /*character temporarily replaced by a hyphen*/
18613 int @!c_loc; /*where that character came from*/
18614 int @!r_count; /*replacement count for discretionary*/
18615 pointer @!hyf_node; /*the hyphen, if it exists*/
18616
18617 @ When the following code is performed, |hyf[0]| and |hyf[hn]| will be zero.
18618
18619 @<Reconstitute nodes for the hyphenated word...@>=
18620 @/do@+{l=j;j=reconstitute(j, hn, bchar, qi(hyf_char))+1;
18621 if (hyphen_passed==0)
18622 {@+link(s)=link(hold_head);
18623 while (link(s) > null) s=link(s);
18624 if (odd(hyf[j-1]))
18625 {@+l=j;hyphen_passed=j-1;link(hold_head)=null;
18626 }
18627 }
18628 if (hyphen_passed > 0)
18629 @<Create and append a discretionary node as an alternative to the unhyphenated
18630 word, and continue to develop both branches until they become equivalent@>;
18631 }@+ while (!(j > hn));
18632 link(s)=q
18633
18634 @ In this repeat loop we will insert another discretionary if |hyf[j-1]| is
18635 odd, when both branches of the previous discretionary end at position |j-1|.
18636 Strictly speaking, we aren't justified in doing this, because we don't know
18637 that a hyphen after |j-1| is truly independent of those branches. But in almost
18638 all applications we would rather not lose a potentially valuable hyphenation
18639 point. (Consider the word `difficult', where the letter `c' is in position |j|.)
18640
18641 @d advance_major_tail {@+major_tail=link(major_tail);incr(r_count);
18642 }
18643
18644 @<Create and append a discretionary node as an alternative...@>=
18645 @/do@+{r=get_node(small_node_size);
18646 link(r)=link(hold_head);type(r)=disc_node;
18647 major_tail=r;r_count=0;
18648 while (link(major_tail) > null) advance_major_tail;
18649 i=hyphen_passed;hyf[i]=0;
18650 @<Put the \(c)characters |hu[l..i]| and a hyphen into |pre_break(r)|@>;
18651 @<Put the \(c)characters |hu[i+1..]| into |post_break(r)|, appending to this
18652 list and to |major_tail| until synchronization has been achieved@>;
18653 @<Move pointer |s| to the end of the current list, and set |replace_count(r)|
18654 appropriately@>;
18655 hyphen_passed=j-1;link(hold_head)=null;
18656 }@+ while (!(!odd(hyf[j-1])))
18657
18658 @ The new hyphen might combine with the previous character via ligature
18659 or kern. At this point we have |l-1 <= i < j| and |i < hn|.
18660
18661 @<Put the \(c)characters |hu[l..i]| and a hyphen into |pre_break(r)|@>=
18662 minor_tail=null;pre_break(r)=null;hyf_node=new_character(hf, hyf_char);
18663 if (hyf_node!=null)
18664 {@+incr(i);c=hu[i];hu[i]=hyf_char;free_avail(hyf_node);
18665 }
18666 while (l <= i)
18667 {@+l=reconstitute(l, i, font_bchar[hf], non_char)+1;
18668 if (link(hold_head) > null)
18669 {@+if (minor_tail==null) pre_break(r)=link(hold_head);
18670 else link(minor_tail)=link(hold_head);
18671 minor_tail=link(hold_head);
18672 while (link(minor_tail) > null) minor_tail=link(minor_tail);
18673 }
18674 }
18675 if (hyf_node!=null)
18676 {@+hu[i]=c; /*restore the character in the hyphen position*/
18677 l=i;decr(i);
18678 }
18679
18680 @ The synchronization algorithm begins with |l==i+1 <= j|.
18681
18682 @<Put the \(c)characters |hu[i+1..]| into |post_break(r)|...@>=
18683 minor_tail=null;post_break(r)=null;c_loc=0;
18684 if (bchar_label[hf]!=non_address) /*put left boundary at beginning of new line*/
18685 {@+decr(l);c=hu[l];c_loc=l;hu[l]=256;
18686 }
18687 while (l < j)
18688 {@+@/do@+{l=reconstitute(l, hn, bchar, non_char)+1;
18689 if (c_loc > 0)
18690 {@+hu[c_loc]=c;c_loc=0;
18691 }
18692 if (link(hold_head) > null)
18693 {@+if (minor_tail==null) post_break(r)=link(hold_head);
18694 else link(minor_tail)=link(hold_head);
18695 minor_tail=link(hold_head);
18696 while (link(minor_tail) > null) minor_tail=link(minor_tail);
18697 }
18698 }@+ while (!(l >= j));
18699 while (l > j)
18700 @<Append characters of |hu[j..]| to |major_tail|, advancing~|j|@>;
18701 }
18702
18703 @ @<Append characters of |hu[j..]|...@>=
18704 {@+j=reconstitute(j, hn, bchar, non_char)+1;
18705 link(major_tail)=link(hold_head);
18706 while (link(major_tail) > null) advance_major_tail;
18707 }
18708
18709 @ Ligature insertion can cause a word to grow exponentially in size. Therefore
18710 we must test the size of |r_count| here, even though the hyphenated text
18711 was at most 63 characters long.
18712
18713 @<Move pointer |s| to the end of the current list...@>=
18714 if (r_count > 127) /*we have to forget the discretionary hyphen*/
18715 {@+link(s)=link(r);link(r)=null;flush_node_list(r);
18716 }
18717 else{@+link(s)=r;replace_count(r)=r_count;
18718 }
18719 s=major_tail
18720
18721 @* Hyphenation.
18722 When a word |hc[1 dotdot hn]| has been set up to contain a candidate for hyphenation,
18723 \TeX\ first looks to see if it is in the user's exception dictionary. If not,
18724 hyphens are inserted based on patterns that appear within the given word,
18725 using an algorithm due to Frank~M. Liang.
18726 @^Liang, Franklin Mark@>
18727
18728 Let's consider Liang's method first, since it is much more interesting than the
18729 exception-lookup routine. The algorithm begins by setting |hyf[j]| to zero
18730 for all |j|, and invalid characters are inserted into |hc[0]|
18731 and |hc[hn+1]| to serve as delimiters. Then a reasonably fast method is
18732 used to see which of a given set of patterns occurs in the word
18733 |hc[0 dotdot(hn+1)]|. Each pattern $p_1\ldots p_k$ of length |k| has an associated
18734 sequence of |k+1| numbers $n_0\ldots n_k$; and if the pattern occurs in
18735 |hc[(j+1)dotdot(j+k)]|, \TeX\ will set |hyf[j+i]=@tmax@>(hyf[j+i],@t$n\_i$@>)| for
18736 |0 <= i <= k|. After this has been done for each pattern that occurs, a
18737 discretionary hyphen will be inserted between |hc[j]| and |hc[j+1]| when
18738 |hyf[j]| is odd, as we have already seen.
18739
18740 The set of patterns $p_1\ldots p_k$ and associated numbers $n_0\ldots n_k$
18741 depends, of course, on the language whose words are being hyphenated, and
18742 on the degree of hyphenation that is desired. A method for finding
18743 appropriate |p|'s and |n|'s, from a given dictionary of words and acceptable
18744 hyphenations, is discussed in Liang's Ph.D. thesis (Stanford University,
18745 1983); \TeX\ simply starts with the patterns and works from there.
18746
18747 @ The patterns are stored in a compact table that is also efficient for
18748 retrieval, using a variant of ``trie memory'' [cf.\ {\sl The Art of
18749 Computer Programming \bf3} (1973), 481--505]. We can find each pattern
18750 $p_1\ldots p_k$ by letting $z_0$ be one greater than the relevant language
18751 index and then, for |1 <= i <= k|,
18752 setting |@t$z\_i$@>=trie_link@t$(z\_{i-1})+p\_i$@>|; the pattern will be
18753 identified by the number $z_k$. Since all the pattern information is
18754 packed together into a single |trie_link| array, it is necessary to
18755 prevent confusion between the data from inequivalent patterns, so another
18756 table is provided such that |trie_char@t$(z\_i)=p\_i$@>| for all |i|. There
18757 is also a table |trie_op|$(z_k)$ to identify the numbers $n_0\ldots n_k$
18758 associated with $p_1\ldots p_k$.
18759
18760 Comparatively few different number sequences $n_0\ldots n_k$ actually occur,
18761 since most of the |n|'s are generally zero. Therefore the number sequences
18762 are encoded in such a way that |trie_op|$(z_k)$ is only one byte long.
18763 If |trie_op(@t$z\_k$@>)!=min_quarterword|, when $p_1\ldots p_k$ has matched
18764 the letters in |hc[(l-k+1)dotdot l@,]| of language |t|,
18765 we perform all of the required operations
18766 for this pattern by carrying out the following little program: Set
18767 |v=trie_op(@t$z\_k$@>)|. Then set |v=v+op_start[t]|,
18768 |hyf[l-hyf_distance[v]]=@tmax@>(hyf[l-hyf_distance[v]], hyf_num[v])|,
18769 and |v=hyf_next[v]|; repeat, if necessary, until |v==min_quarterword|.
18770
18771 @<Types...@>=
18772 typedef int32_t trie_pointer; /*an index into |trie|*/
18773
18774 @ @d trie_link(A) trie[A].rh /*``downward'' link in a trie*/
18775 @d trie_char(A) trie[A].b1 /*character matched at this trie location*/
18776 @d trie_op(A) trie[A].b0 /*program for hyphenation at this trie location*/
18777
18778 @<Glob...@>=
18779 static two_halves @!trie[trie_size+1]; /*|trie_link|, |trie_char|, |trie_op|*/
18780 static small_number @!hyf_distance0[trie_op_size],
18781 *const @!hyf_distance = @!hyf_distance0-1; /*position |k-j| of $n_j$*/
18782 static small_number @!hyf_num0[trie_op_size],
18783 *const @!hyf_num = @!hyf_num0-1; /*value of $n_j$*/
18784 static quarterword @!hyf_next0[trie_op_size],
18785 *const @!hyf_next = @!hyf_next0-1; /*continuation code*/
18786 static uint16_t @!op_start[256]; /*offset for current language*/
18787
18788 @ @<Local variables for hyph...@>=
18789 trie_pointer @!z; /*an index into |trie|*/
18790 int @!v; /*an index into |hyf_distance|, etc.*/
18791
18792 @ Assuming that these auxiliary tables have been set up properly, the
18793 hyphenation algorithm is quite short. In the following code we set |hc[hn+2]|
18794 to the impossible value 256, in order to guarantee that |hc[hn+3]| will
18795 never be fetched.
18796
18797 @<Find hyphen locations for the word in |hc|...@>=
18798 for (j=0; j<=hn; j++) hyf[j]=0;
18799 @<Look for the word |hc[1..hn]| in the exception table, and |goto found| (with
18800 |hyf| containing the hyphens) if an entry is found@>;
18801 if (trie_char(cur_lang+1)!=qi(cur_lang)) return; /*no patterns for |cur_lang|*/
18802 hc[0]=0;hc[hn+1]=0;hc[hn+2]=256; /*insert delimiters*/
18803 for (j=0; j<=hn-r_hyf+1; j++)
18804 {@+z=trie_link(cur_lang+1)+hc[j];l=j;
18805 while (hc[l]==qo(trie_char(z)))
18806 {@+if (trie_op(z)!=min_quarterword)
18807 @<Store \(m)maximum values in the |hyf| table@>;
18808 incr(l);z=trie_link(z)+hc[l];
18809 }
18810 }
18811 found: for (j=0; j<=l_hyf-1; j++) hyf[j]=0;
18812 for (j=0; j<=r_hyf-1; j++) hyf[hn-j]=0
18813
18814 @ @<Store \(m)maximum values in the |hyf| table@>=
18815 {@+v=trie_op(z);
18816 @/do@+{v=v+op_start[cur_lang];i=l-hyf_distance[v];
18817 if (hyf_num[v] > hyf[i]) hyf[i]=hyf_num[v];
18818 v=hyf_next[v];
18819 }@+ while (!(v==min_quarterword));
18820 }
18821
18822 @ The exception table that is built by \TeX's \.{\\hyphenation} primitive is
18823 organized as an ordered hash table [cf.\ Amble and Knuth, {\sl The Computer
18824 @^Amble, Ole@> @^Knuth, Donald Ervin@>
18825 Journal\/ \bf17} (1974), 135--142] using linear probing. If $\alpha$ and
18826 $\beta$ are words, we will say that $\alpha<\beta$ if $\vert\alpha\vert<
18827 \vert\beta\vert$ or if $\vert\alpha\vert=\vert\beta\vert$ and
18828 $\alpha$ is lexicographically smaller than $\beta$. (The notation $\vert
18829 \alpha\vert$ stands for the length of $\alpha$.) The idea of ordered hashing
18830 is to arrange the table so that a given word $\alpha$ can be sought by computing
18831 a hash address $h=h(\alpha)$ and then looking in table positions |h|, |h-1|,
18832 \dots, until encountering the first word $\le\alpha$. If this word is
18833 different from $\alpha$, we can conclude that $\alpha$ is not in the table.
18834
18835 The words in the table point to lists in |mem| that specify hyphen positions
18836 in their |info| fields. The list for $c_1\ldots c_n$ contains the number |k| if
18837 the word $c_1\ldots c_n$ has a discretionary hyphen between $c_k$ and
18838 $c_{k+1}$.
18839
18840 @<Types...@>=
18841 typedef int16_t hyph_pointer; /*an index into the ordered hash table*/
18842
18843 @ @<Glob...@>=
18844 static str_number @!hyph_word[hyph_size+1]; /*exception words*/
18845 static pointer @!hyph_list[hyph_size+1]; /*lists of hyphen positions*/
18846 static hyph_pointer @!hyph_count; /*the number of words in the exception dictionary*/
18847
18848 @ @<Local variables for init...@>=
18849 int @!z; /*runs through the exception dictionary*/
18850
18851 @ @<Set init...@>=
18852 for (z=0; z<=hyph_size; z++)
18853 {@+hyph_word[z]=0;hyph_list[z]=null;
18854 }
18855 hyph_count=0;
18856
18857 @ The algorithm for exception lookup is quite simple, as soon as we have
18858 a few more local variables to work with.
18859
18860 @<Local variables for hyph...@>=
18861 hyph_pointer @!h; /*an index into |hyph_word| and |hyph_list|*/
18862 str_number @!k; /*an index into |str_start|*/
18863 pool_pointer @!u; /*an index into |str_pool|*/
18864
18865 @ First we compute the hash code |h|, then we search until we either
18866 find the word or we don't. Words from different languages are kept
18867 separate by appending the language code to the string.
18868
18869 @<Look for the word |hc[1...@>=
18870 h=hc[1];incr(hn);hc[hn]=cur_lang;
18871 for (j=2; j<=hn; j++) h=(h+h+hc[j])%hyph_size;
18872 loop@+{@+@<If the string |hyph_word[h]| is less than \(hc)|hc[1..hn]|, |goto
18873 not_found|; but if the two strings are equal, set |hyf| to the hyphen positions
18874 and |goto found|@>;
18875 if (h > 0) decr(h);@+else h=hyph_size;
18876 }
18877 not_found: decr(hn)
18878
18879 @ @<If the string |hyph_word[h]| is less than \(hc)...@>=
18880 k=hyph_word[h];if (k==0) goto not_found;
18881 if (length(k) < hn) goto not_found;
18882 if (length(k)==hn)
18883 {@+j=1;u=str_start[k];
18884 @/do@+{if (so(str_pool[u]) < hc[j]) goto not_found;
18885 if (so(str_pool[u]) > hc[j]) goto done;
18886 incr(j);incr(u);
18887 }@+ while (!(j > hn));
18888 @<Insert hyphens as specified in |hyph_list[h]|@>;
18889 decr(hn);goto found;
18890 }
18891 done:
18892
18893 @ @<Insert hyphens as specified...@>=
18894 s=hyph_list[h];
18895 while (s!=null)
18896 {@+hyf[info(s)]=1;s=link(s);
18897 }
18898
18899 @ @<Search |hyph_list| for pointers to |p|@>=
18900 for (q=0; q<=hyph_size; q++)
18901 {@+if (hyph_list[q]==p)
18902 {@+print_nl("HYPH(");print_int(q);print_char(')');
18903 }
18904 }
18905
18906 @ We have now completed the hyphenation routine, so the |line_break| procedure
18907 is finished at last. Since the hyphenation exception table is fresh in our
18908 minds, it's a good time to deal with the routine that adds new entries to it.
18909
18910 When \TeX\ has scanned `\.{\\hyphenation}', it calls on a procedure named
18911 |new_hyph_exceptions| to do the right thing.
18912
18913 @d set_cur_lang if (language <= 0) cur_lang=0;
18914 else if (language > 255) cur_lang=0;
18915 else cur_lang=language
18916
18917 @p static void new_hyph_exceptions(void) /*enters new exceptions*/
18918 {@+
18919 int n; /*length of current word; not always a |small_number|*/
18920 int @!j; /*an index into |hc|*/
18921 hyph_pointer @!h; /*an index into |hyph_word| and |hyph_list|*/
18922 str_number @!k; /*an index into |str_start|*/
18923 pointer @!p; /*head of a list of hyphen positions*/
18924 pointer @!q; /*used when creating a new node for list |p|*/
18925 str_number @!s, @!t; /*strings being compared or stored*/
18926 pool_pointer @!u, @!v; /*indices into |str_pool|*/
18927 scan_left_brace(); /*a left brace must follow \.{\\hyphenation}*/
18928 set_cur_lang;
18929 #ifdef @!INIT
18930 if (trie_not_ready)
18931 {@+hyph_index=0;goto not_found1;
18932 }
18933 #endif
18934 set_hyph_index;
18935 not_found1:
18936 @<Enter as many hyphenation exceptions as are listed, until coming to a right
18937 brace; then |return|@>;
18938 }
18939
18940 @ @<Enter as many...@>=
18941 n=0;p=null;
18942 loop@+{@+get_x_token();
18943 reswitch: switch (cur_cmd) {
18944 case letter: case other_char: case char_given: @<Append a new letter or
18945 hyphen@>@;@+break;
18946 case char_num: {@+scan_char_num();cur_chr=cur_val;cur_cmd=char_given;
18947 goto reswitch;
18948 }
18949 case spacer: case right_brace: {@+if (n > 1) @<Enter a hyphenation exception@>;
18950 if (cur_cmd==right_brace) return;
18951 n=0;p=null;
18952 } @+break;
18953 default:@<Give improper \.{\\hyphenation} error@>@;
18954 }
18955 }
18956
18957 @ @<Give improper \.{\\hyph...@>=
18958 {@+print_err("Improper ");print_esc("hyphenation");
18959 @.Improper \\hyphenation...@>
18960 print(" will be flushed");
18961 help2("Hyphenation exceptions must contain only letters",@/
18962 "and hyphens. But continue; I'll forgive and forget.");
18963 error();
18964 }
18965
18966 @ @<Append a new letter or hyphen@>=
18967 if (cur_chr=='-') @<Append the value |n| to list |p|@>@;
18968 else{@+set_lc_code(cur_chr);
18969 if (hc[0]==0)
18970 {@+print_err("Not a letter");
18971 @.Not a letter@>
18972 help2("Letters in \\hyphenation words must have \\lccode>0.",@/
18973 "Proceed; I'll ignore the character I just read.");
18974 error();
18975 }
18976 else if (n < 63)
18977 {@+incr(n);hc[n]=hc[0];
18978 }
18979 }
18980
18981 @ @<Append the value |n| to list |p|@>=
18982 {@+if (n < 63)
18983 {@+q=get_avail();link(q)=p;info(q)=n;p=q;
18984 }
18985 }
18986
18987 @ @<Enter a hyphenation exception@>=
18988 {@+incr(n);hc[n]=cur_lang;str_room(n);h=0;
18989 for (j=1; j<=n; j++)
18990 {@+h=(h+h+hc[j])%hyph_size;
18991 append_char(hc[j]);
18992 }
18993 s=make_string();
18994 @<Insert the \(p)pair |(s,p)| into the exception table@>;
18995 }
18996
18997 @ @<Insert the \(p)pair |(s,p)|...@>=
18998 if (hyph_count==hyph_size) overflow("exception dictionary", hyph_size);
18999 @:TeX capacity exceeded exception dictionary}{\quad exception dictionary@>
19000 incr(hyph_count);
19001 while (hyph_word[h]!=0)
19002 {@+@<If the string |hyph_word[h]| is less than \(or)or equal to |s|, interchange
19003 |(hyph_word[h],hyph_list[h])| with |(s,p)|@>;
19004 if (h > 0) decr(h);@+else h=hyph_size;
19005 }
19006 hyph_word[h]=s;hyph_list[h]=p
19007
19008 @ @<If the string |hyph_word[h]| is less than \(or)...@>=
19009 k=hyph_word[h];
19010 if (length(k) < length(s)) goto found;
19011 if (length(k) > length(s)) goto not_found;
19012 u=str_start[k];v=str_start[s];
19013 @/do@+{if (str_pool[u] < str_pool[v]) goto found;
19014 if (str_pool[u] > str_pool[v]) goto not_found;
19015 incr(u);incr(v);
19016 }@+ while (!(u==str_start[k+1]));
19017 found: q=hyph_list[h];hyph_list[h]=p;p=q;@/
19018 t=hyph_word[h];hyph_word[h]=s;s=t;
19019 not_found:
19020
19021 @* Initializing the hyphenation tables.
19022 The trie for \TeX's hyphenation algorithm is built from a sequence of
19023 patterns following a \.{\\patterns} specification. Such a specification
19024 is allowed only in \.{INITEX}, since the extra memory for auxiliary tables
19025 and for the initialization program itself would only clutter up the
19026 production version of \TeX\ with a lot of deadwood.
19027
19028 The first step is to build a trie that is linked, instead of packed
19029 into sequential storage, so that insertions are readily made.
19030 After all patterns have been processed, \.{INITEX}
19031 compresses the linked trie by identifying common subtries. Finally the
19032 trie is packed into the efficient sequential form that the hyphenation
19033 algorithm actually uses.
19034
19035 @<Declare subprocedures for |line_break|@>=
19036 #ifdef @!INIT
19037 @<Declare procedures for preprocessing hyphenation patterns@>@;
19038 #endif
19039
19040 @ Before we discuss trie building in detail, let's consider the simpler
19041 problem of creating the |hyf_distance|, |hyf_num|, and |hyf_next| arrays.
19042
19043 Suppose, for example, that \TeX\ reads the pattern `\.{ab2cde1}'. This is
19044 a pattern of length 5, with $n_0\ldots n_5=0\,0\,2\,0\,0\,1$ in the
19045 notation above. We want the corresponding |trie_op| code |v| to have
19046 |hyf_distance[v]==3|, |hyf_num[v]==2|, and |hyf_next[v]==@t$v^\prime$@>|,
19047 where the auxiliary |trie_op| code $v^\prime$ has
19048 |hyf_distance[@t$v^\prime$@>]==0|, |hyf_num[@t$v^\prime$@>]==1|, and
19049 |hyf_next[@t$v^\prime$@>]==min_quarterword|.
19050
19051 \TeX\ computes an appropriate value |v| with the |new_trie_op| subroutine
19052 below, by setting
19053 $$\hbox{|@t$v^\prime$@>=new_trie_op(0, 1, min_quarterword)|,\qquad
19054 |v=new_trie_op(3, 2,@t$v^\prime$@>)|.}$$
19055 This subroutine looks up its three
19056 parameters in a special hash table, assigning a new value only if these
19057 three have not appeared before for the current language.
19058
19059 The hash table is called |trie_op_hash|, and the number of entries it contains
19060 is |trie_op_ptr|.
19061
19062 @<Glob...@>=
19063 #ifdef @!INIT
19064 static uint16_t @!trie_op_hash0[trie_op_size+trie_op_size+1],
19065 *const @!trie_op_hash = @!trie_op_hash0+trie_op_size;
19066 /*trie op codes for quadruples*/
19067 static quarterword @!trie_used[256];
19068 /*largest opcode used so far for this language*/
19069 static ASCII_code @!trie_op_lang0[trie_op_size],
19070 *const @!trie_op_lang = @!trie_op_lang0-1;
19071 /*language part of a hashed quadruple*/
19072 static quarterword @!trie_op_val0[trie_op_size],
19073 *const @!trie_op_val = @!trie_op_val0-1;
19074 /*opcode corresponding to a hashed quadruple*/
19075 static int @!trie_op_ptr; /*number of stored ops so far*/
19076 #endif
19077
19078 @ It's tempting to remove the |overflow| stops in the following procedure;
19079 |new_trie_op| could return |min_quarterword| (thereby simply ignoring
19080 part of a hyphenation pattern) instead of aborting the job. However, that would
19081 lead to different hyphenation results on different installations of \TeX\
19082 using the same patterns. The |overflow| stops are necessary for portability
19083 of patterns.
19084
19085 @<Declare procedures for preprocessing hyph...@>=
19086 static quarterword new_trie_op(small_number @!d, small_number @!n, quarterword @!v)
19087 {@+
19088 int h; /*trial hash location*/
19089 quarterword @!u; /*trial op code*/
19090 int @!l; /*pointer to stored data*/
19091 h=abs(n+313*d+361*v+1009*cur_lang)%(trie_op_size+trie_op_size)
19092 -trie_op_size;
19093 loop@+{@+l=trie_op_hash[h];
19094 if (l==0) /*empty position found for a new op*/
19095 {@+if (trie_op_ptr==trie_op_size)
19096 overflow("pattern memory ops", trie_op_size);
19097 u=trie_used[cur_lang];
19098 if (u==max_quarterword)
19099 overflow("pattern memory ops per language",
19100 max_quarterword-min_quarterword);
19101 incr(trie_op_ptr);incr(u);trie_used[cur_lang]=u;
19102 hyf_distance[trie_op_ptr]=d;
19103 hyf_num[trie_op_ptr]=n;hyf_next[trie_op_ptr]=v;
19104 trie_op_lang[trie_op_ptr]=cur_lang;trie_op_hash[h]=trie_op_ptr;
19105 trie_op_val[trie_op_ptr]=u;return u;
19106 }
19107 if ((hyf_distance[l]==d)&&(hyf_num[l]==n)&&(hyf_next[l]==v)
19108 &&(trie_op_lang[l]==cur_lang))
19109 {@+return trie_op_val[l];
19110 }
19111 if (h > -trie_op_size) decr(h);@+else h=trie_op_size;
19112 }
19113 }
19114
19115 @ After |new_trie_op| has compressed the necessary opcode information,
19116 plenty of information is available to unscramble the data into the
19117 final form needed by our hyphenation algorithm.
19118
19119 @<Sort \(t)the hyphenation op tables into proper order@>=
19120 op_start[0]=-min_quarterword;
19121 for (j=1; j<=255; j++) op_start[j]=op_start[j-1]+qo(trie_used[j-1]);
19122 for (j=1; j<=trie_op_ptr; j++)
19123 trie_op_hash[j]=op_start[trie_op_lang[j]]+trie_op_val[j]; /*destination*/
19124 for (j=1; j<=trie_op_ptr; j++) while (trie_op_hash[j] > j)
19125 {@+k=trie_op_hash[j];@/
19126 t=hyf_distance[k];hyf_distance[k]=hyf_distance[j];hyf_distance[j]=t;@/
19127 t=hyf_num[k];hyf_num[k]=hyf_num[j];hyf_num[j]=t;@/
19128 t=hyf_next[k];hyf_next[k]=hyf_next[j];hyf_next[j]=t;@/
19129 trie_op_hash[j]=trie_op_hash[k];trie_op_hash[k]=k;
19130 }
19131
19132 @ Before we forget how to initialize the data structures that have been
19133 mentioned so far, let's write down the code that gets them started.
19134
19135 @<Initialize table entries...@>=
19136 for (k=-trie_op_size; k<=trie_op_size; k++) trie_op_hash[k]=0;
19137 for (k=0; k<=255; k++) trie_used[k]=min_quarterword;
19138 trie_op_ptr=0;
19139
19140 @ The linked trie that is used to preprocess hyphenation patterns appears
19141 in several global arrays. Each node represents an instruction of the form
19142 ``if you see character |c|, then perform operation |o|, move to the
19143 next character, and go to node |l|; otherwise go to node |r|.''
19144 The four quantities |c|, |o|, |l|, and |r| are stored in four arrays
19145 |trie_c|, |trie_o|, |trie_l|, and |trie_r|. The root of the trie
19146 is |trie_l[0]|, and the number of nodes is |trie_ptr|. Null trie
19147 pointers are represented by zero. To initialize the trie, we simply
19148 set |trie_l[0]| and |trie_ptr| to zero. We also set |trie_c[0]| to some
19149 arbitrary value, since the algorithm may access it.
19150
19151 The algorithms maintain the condition
19152 $$\hbox{|trie_c[trie_r[z]] > trie_c[z]|\qquad
19153 whenever |z!=0| and |trie_r[z]!=0|};$$ in other words, sibling nodes are
19154 ordered by their |c| fields.
19155
19156 @d trie_root trie_l[0] /*root of the linked trie*/
19157
19158 @<Glob...@>=
19159 #ifdef @!INIT
19160 static packed_ASCII_code @!trie_c[trie_size+1];
19161 /*characters to match*/
19162 @t\hskip10pt@>static quarterword @!trie_o[trie_size+1];
19163 /*operations to perform*/
19164 @t\hskip10pt@>static trie_pointer @!trie_l[trie_size+1];
19165 /*left subtrie links*/
19166 @t\hskip10pt@>static trie_pointer @!trie_r[trie_size+1];
19167 /*right subtrie links*/
19168 @t\hskip10pt@>static trie_pointer @!trie_ptr; /*the number of nodes in the trie*/
19169 @t\hskip10pt@>static trie_pointer @!trie_hash[trie_size+1];
19170 /*used to identify equivalent subtries*/
19171 #endif
19172
19173 @ Let us suppose that a linked trie has already been constructed.
19174 Experience shows that we can often reduce its size by recognizing common
19175 subtries; therefore another hash table is introduced for this purpose,
19176 somewhat similar to |trie_op_hash|. The new hash table will be
19177 initialized to zero.
19178
19179 The function |trie_node(p)| returns |p| if |p| is distinct from other nodes
19180 that it has seen, otherwise it returns the number of the first equivalent
19181 node that it has seen.
19182
19183 Notice that we might make subtries equivalent even if they correspond to
19184 patterns for different languages, in which the trie ops might mean quite
19185 different things. That's perfectly all right.
19186
19187 @<Declare procedures for preprocessing hyph...@>=
19188 static trie_pointer trie_node(trie_pointer @!p) /*converts
19189 to a canonical form*/
19190 {@+
19191 trie_pointer h; /*trial hash location*/
19192 trie_pointer @!q; /*trial trie node*/
19193 h=abs(trie_c[p]+1009*trie_o[p]+@|
19194 2718*trie_l[p]+3142*trie_r[p])%trie_size;
19195 loop@+{@+q=trie_hash[h];
19196 if (q==0)
19197 {@+trie_hash[h]=p;return p;
19198 }
19199 if ((trie_c[q]==trie_c[p])&&(trie_o[q]==trie_o[p])&&@|
19200 (trie_l[q]==trie_l[p])&&(trie_r[q]==trie_r[p]))
19201 {@+return q;
19202 }
19203 if (h > 0) decr(h);@+else h=trie_size;
19204 }
19205 }
19206
19207 @ A neat recursive procedure is now able to compress a trie by
19208 traversing it and applying |trie_node| to its nodes in ``bottom up''
19209 fashion. We will compress the entire trie by clearing |trie_hash| to
19210 zero and then saying `|trie_root=compress_trie(trie_root)|'.
19211 @^recursion@>
19212
19213 @<Declare procedures for preprocessing hyph...@>=
19214 static trie_pointer compress_trie(trie_pointer @!p)
19215 {@+if (p==0) return 0;
19216 else{@+trie_l[p]=compress_trie(trie_l[p]);
19217 trie_r[p]=compress_trie(trie_r[p]);
19218 return trie_node(p);
19219 }
19220 }
19221
19222 @ The compressed trie will be packed into the |trie| array using a
19223 ``top-down first-fit'' procedure. This is a little tricky, so the reader
19224 should pay close attention: The |trie_hash| array is cleared to zero
19225 again and renamed |trie_ref| for this phase of the operation; later on,
19226 |trie_ref[p]| will be nonzero only if the linked trie node |p| is the
19227 smallest character
19228 in a family and if the characters |c| of that family have been allocated to
19229 locations |trie_ref[p]+c| in the |trie| array. Locations of |trie| that
19230 are in use will have |trie_link==0|, while the unused holes in |trie|
19231 will be doubly linked with |trie_link| pointing to the next larger vacant
19232 location and |trie_back| pointing to the next smaller one. This double
19233 linking will have been carried out only as far as |trie_max|, where
19234 |trie_max| is the largest index of |trie| that will be needed.
19235 To save time at the low end of the trie, we maintain array entries
19236 |trie_min[c]| pointing to the smallest hole that is greater than~|c|.
19237 Another array |trie_taken| tells whether or not a given location is
19238 equal to |trie_ref[p]| for some |p|; this array is used to ensure that
19239 distinct nodes in the compressed trie will have distinct |trie_ref|
19240 entries.
19241
19242 @d trie_ref trie_hash /*where linked trie families go into |trie|*/
19243 @d trie_back(A) trie[A].lh /*backward links in |trie| holes*/
19244
19245 @<Glob...@>=
19246 #ifdef @!INIT
19247 static bool @!trie_taken0[trie_size],
19248 *const @!trie_taken = @!trie_taken0-1;
19249 /*does a family start here?*/
19250 @t\hskip10pt@>static trie_pointer @!trie_min[256];
19251 /*the first possible slot for each character*/
19252 @t\hskip10pt@>static trie_pointer @!trie_max; /*largest location used in |trie|*/
19253 @t\hskip10pt@>static bool @!trie_not_ready; /*is the trie still in linked form?*/
19254 #endif
19255
19256 @ Each time \.{\\patterns} appears, it contributes further patterns to
19257 the future trie, which will be built only when hyphenation is attempted or
19258 when a format file is dumped. The boolean variable |trie_not_ready|
19259 will change to |false| when the trie is compressed; this will disable
19260 further patterns.
19261
19262 @<Initialize table entries...@>=
19263 trie_not_ready=true;trie_root=0;trie_c[0]=si(0);trie_ptr=0;
19264
19265 @ Here is how the trie-compression data structures are initialized.
19266 If storage is tight, it would be possible to overlap |trie_op_hash|,
19267 |trie_op_lang|, and |trie_op_val| with |trie|, |trie_hash|, and |trie_taken|,
19268 because we finish with the former just before we need the latter.
19269
19270 @<Get ready to compress the trie@>=
19271 @<Sort \(t)the hyphenation...@>;
19272 for (p=0; p<=trie_size; p++) trie_hash[p]=0;
19273 hyph_root=compress_trie(hyph_root);
19274 trie_root=compress_trie(trie_root); /*identify equivalent subtries*/
19275 for (p=0; p<=trie_ptr; p++) trie_ref[p]=0;
19276 for (p=0; p<=255; p++) trie_min[p]=p+1;
19277 trie_link(0)=1;trie_max=0
19278
19279 @ The |first_fit| procedure finds the smallest hole |z| in |trie| such that
19280 a trie family starting at a given node |p| will fit into vacant positions
19281 starting at |z|. If |c==trie_c[p]|, this means that location |z-c| must
19282 not already be taken by some other family, and that |z-c+@t$c^\prime$@>|
19283 must be vacant for all characters $c^\prime$ in the family. The procedure
19284 sets |trie_ref[p]| to |z-c| when the first fit has been found.
19285
19286 @<Declare procedures for preprocessing hyph...@>=
19287 static void first_fit(trie_pointer @!p) /*packs a family into |trie|*/
19288 {@+
19289 trie_pointer h; /*candidate for |trie_ref[p]|*/
19290 trie_pointer @!z; /*runs through holes*/
19291 trie_pointer @!q; /*runs through the family starting at |p|*/
19292 ASCII_code @!c; /*smallest character in the family*/
19293 trie_pointer @!l, @!r; /*left and right neighbors*/
19294 int @!ll; /*upper limit of |trie_min| updating*/
19295 c=so(trie_c[p]);
19296 z=trie_min[c]; /*get the first conceivably good hole*/
19297 loop@+{@+h=z-c;@/
19298 @<Ensure that |trie_max>=h+256|@>;
19299 if (trie_taken[h]) goto not_found;
19300 @<If all characters of the family fit relative to |h|, then |goto found|,\30\
19301 otherwise |goto not_found|@>;
19302 not_found: z=trie_link(z); /*move to the next hole*/
19303 }
19304 found: @<Pack the family into |trie| relative to |h|@>;
19305 }
19306
19307 @ By making sure that |trie_max| is at least |h+256|, we can be sure that
19308 |trie_max > z|, since |h==z-c|. It follows that location |trie_max| will
19309 never be occupied in |trie|, and we will have |trie_max >= trie_link(z)|.
19310
19311 @<Ensure that |trie_max>=h+256|@>=
19312 if (trie_max < h+256)
19313 {@+if (trie_size <= h+256) overflow("pattern memory", trie_size);
19314 @:TeX capacity exceeded pattern memory}{\quad pattern memory@>
19315 @/do@+{incr(trie_max);trie_taken[trie_max]=false;
19316 trie_link(trie_max)=trie_max+1;trie_back(trie_max)=trie_max-1;
19317 }@+ while (!(trie_max==h+256));
19318 }
19319
19320 @ @<If all characters of the family fit relative to |h|...@>=
19321 q=trie_r[p];
19322 while (q > 0)
19323 {@+if (trie_link(h+so(trie_c[q]))==0) goto not_found;
19324 q=trie_r[q];
19325 }
19326 goto found
19327
19328 @ @<Pack the family into |trie| relative to |h|@>=
19329 trie_taken[h]=true;trie_ref[p]=h;q=p;
19330 @/do@+{z=h+so(trie_c[q]);l=trie_back(z);r=trie_link(z);
19331 trie_back(r)=l;trie_link(l)=r;trie_link(z)=0;
19332 if (l < 256)
19333 {@+if (z < 256) ll=z;@+else ll=256;
19334 @/do@+{trie_min[l]=r;incr(l);
19335 }@+ while (!(l==ll));
19336 }
19337 q=trie_r[q];
19338 }@+ while (!(q==0))
19339
19340 @ To pack the entire linked trie, we use the following recursive procedure.
19341 @^recursion@>
19342
19343 @<Declare procedures for preprocessing hyph...@>=
19344 static void trie_pack(trie_pointer @!p) /*pack subtries of a family*/
19345 {@+trie_pointer q; /*a local variable that need not be saved on recursive calls*/
19346 @/do@+{q=trie_l[p];
19347 if ((q > 0)&&(trie_ref[q]==0))
19348 {@+first_fit(q);trie_pack(q);
19349 }
19350 p=trie_r[p];
19351 }@+ while (!(p==0));
19352 }
19353
19354 @ When the whole trie has been allocated into the sequential table, we
19355 must go through it once again so that |trie| contains the correct
19356 information. Null pointers in the linked trie will be represented by the
19357 value~0, which properly implements an ``empty'' family.
19358
19359 @<Move the data into |trie|@>=
19360 h.rh=0;h.b0=min_quarterword;h.b1=min_quarterword; /*|trie_link=0|,
19361 |trie_op=min_quarterword|, |trie_char=qi(0)|*/
19362 if (trie_max==0) /*no patterns were given*/
19363 {@+for (r=0; r<=256; r++) trie[r]=h;
19364 trie_max=256;
19365 }
19366 else{@+if (hyph_root > 0) trie_fix(hyph_root);
19367 if (trie_root > 0) trie_fix(trie_root); /*this fixes the non-holes in |trie|*/
19368 r=0; /*now we will zero out all the holes*/
19369 @/do@+{s=trie_link(r);trie[r]=h;r=s;
19370 }@+ while (!(r > trie_max));
19371 }
19372 trie_char(0)=qi('?'); /*make |trie_char(c)!=c| for all |c|*/
19373
19374 @ The fixing-up procedure is, of course, recursive. Since the linked trie
19375 usually has overlapping subtries, the same data may be moved several
19376 times; but that causes no harm, and at most as much work is done as it
19377 took to build the uncompressed trie.
19378 @^recursion@>
19379
19380 @<Declare procedures for preprocessing hyph...@>=
19381 static void trie_fix(trie_pointer @!p) /*moves |p| and its siblings into |trie|*/
19382 {@+trie_pointer q; /*a local variable that need not be saved on recursive calls*/
19383 ASCII_code @!c; /*another one that need not be saved*/
19384 trie_pointer @!z; /*|trie| reference; this local variable must be saved*/
19385 z=trie_ref[p];
19386 @/do@+{q=trie_l[p];c=so(trie_c[p]);
19387 trie_link(z+c)=trie_ref[q];trie_char(z+c)=qi(c);trie_op(z+c)=trie_o[p];
19388 if (q > 0) trie_fix(q);
19389 p=trie_r[p];
19390 }@+ while (!(p==0));
19391 }
19392
19393 @ Now let's go back to the easier problem, of building the linked
19394 trie. When \.{INITEX} has scanned the `\.{\\patterns}' control
19395 sequence, it calls on |new_patterns| to do the right thing.
19396
19397 @<Declare procedures for preprocessing hyph...@>=
19398 static void new_patterns(void) /*initializes the hyphenation pattern data*/
19399 {@+
19400 int k, @!l; /*indices into |hc| and |hyf|;
19401 not always in |small_number| range*/
19402 bool @!digit_sensed; /*should the next digit be treated as a letter?*/
19403 quarterword @!v; /*trie op code*/
19404 trie_pointer @!p, @!q; /*nodes of trie traversed during insertion*/
19405 bool @!first_child; /*is |p==trie_l[q]|?*/
19406 int @!c; /*character being inserted*/
19407 if (trie_not_ready)
19408 {@+set_cur_lang;scan_left_brace(); /*a left brace must follow \.{\\patterns}*/
19409 @<Enter all of the patterns into a linked trie, until coming to a right
19410 brace@>;
19411 if (saving_hyph_codes > 0)
19412 @<Store hyphenation codes for current language@>;
19413 }
19414 else{@+print_err("Too late for ");print_esc("patterns");
19415 help1("All patterns must be given before typesetting begins.");
19416 error();link(garbage)=scan_toks(false, false);flush_list(def_ref);
19417 }
19418 }
19419
19420 @ Novices are not supposed to be using \.{\\patterns}, so the error
19421 messages are terse. (Note that all error messages appear in \TeX's string
19422 pool, even if they are used only by \.{INITEX}.)
19423
19424 @<Enter all of the patterns into a linked trie...@>=
19425 k=0;hyf[0]=0;digit_sensed=false;
19426 loop@+{@+get_x_token();
19427 switch (cur_cmd) {
19428 case letter: case other_char: @<Append a new letter or a hyphen level@>@;@+break;
19429 case spacer: case right_brace: {@+if (k > 0)
19430 @<Insert a new pattern into the linked trie@>;
19431 if (cur_cmd==right_brace) goto done;
19432 k=0;hyf[0]=0;digit_sensed=false;
19433 } @+break;
19434 default:{@+print_err("Bad ");print_esc("patterns");
19435 @.Bad \\patterns@>
19436 help1("(See Appendix H.)");error();
19437 }
19438 }
19439 }
19440 done:
19441
19442 @ @<Append a new letter or a hyphen level@>=
19443 if (digit_sensed||(cur_chr < '0')||(cur_chr > '9'))
19444 {@+if (cur_chr=='.') cur_chr=0; /*edge-of-word delimiter*/
19445 else{@+cur_chr=lc_code(cur_chr);
19446 if (cur_chr==0)
19447 {@+print_err("Nonletter");
19448 @.Nonletter@>
19449 help1("(See Appendix H.)");error();
19450 }
19451 }
19452 if (k < 63)
19453 {@+incr(k);hc[k]=cur_chr;hyf[k]=0;digit_sensed=false;
19454 }
19455 }
19456 else if (k < 63)
19457 {@+hyf[k]=cur_chr-'0';digit_sensed=true;
19458 }
19459
19460 @ When the following code comes into play, the pattern $p_1\ldots p_k$
19461 appears in |hc[1 dotdot k]|, and the corresponding sequence of numbers $n_0\ldots
19462 n_k$ appears in |hyf[0 dotdot k]|.
19463
19464 @<Insert a new pattern into the linked trie@>=
19465 {@+@<Compute the trie op code, |v|, and set |l:=0|@>;
19466 q=0;hc[0]=cur_lang;
19467 while (l <= k)
19468 {@+c=hc[l];incr(l);p=trie_l[q];first_child=true;
19469 while ((p > 0)&&(c > so(trie_c[p])))
19470 {@+q=p;p=trie_r[q];first_child=false;
19471 }
19472 if ((p==0)||(c < so(trie_c[p])))
19473 @<Insert a new trie node between |q| and |p|, and make |p| point to it@>;
19474 q=p; /*now node |q| represents $p_1\ldots p_{l-1}$*/
19475 }
19476 if (trie_o[q]!=min_quarterword)
19477 {@+print_err("Duplicate pattern");
19478 @.Duplicate pattern@>
19479 help1("(See Appendix H.)");error();
19480 }
19481 trie_o[q]=v;
19482 }
19483
19484 @ @<Insert a new trie node between |q| and |p|...@>=
19485 {@+if (trie_ptr==trie_size) overflow("pattern memory", trie_size);
19486 @:TeX capacity exceeded pattern memory}{\quad pattern memory@>
19487 incr(trie_ptr);trie_r[trie_ptr]=p;p=trie_ptr;trie_l[p]=0;
19488 if (first_child) trie_l[q]=p;@+else trie_r[q]=p;
19489 trie_c[p]=si(c);trie_o[p]=min_quarterword;
19490 }
19491
19492 @ @<Compute the trie op code, |v|...@>=
19493 if (hc[1]==0) hyf[0]=0;
19494 if (hc[k]==0) hyf[k]=0;
19495 l=k;v=min_quarterword;
19496 loop@+{@+if (hyf[l]!=0) v=new_trie_op(k-l, hyf[l], v);
19497 if (l > 0) decr(l);@+else goto done1;
19498 }
19499 done1:
19500
19501 @ Finally we put everything together: Here is how the trie gets to its
19502 final, efficient form.
19503 The following packing routine is rigged so that the root of the linked
19504 tree gets mapped into location 1 of |trie|, as required by the hyphenation
19505 algorithm. This happens because the first call of |first_fit| will
19506 ``take'' location~1.
19507
19508 @<Declare procedures for preprocessing hyphenation patterns@>=
19509 static void init_trie(void)
19510 {@+int @!p; /*pointer for initialization*/
19511 int @!j, @!k, @!t; /*all-purpose registers for initialization*/
19512 int @!r, @!s; /*used to clean up the packed |trie|*/
19513 two_halves @!h; /*template used to zero out |trie|'s holes*/
19514 @<Local variables to save the profiling context@>@;
19515 @<Charge the time used here on |init_trie|@>@;
19516 @<Get ready to compress the trie@>;
19517 if (trie_root!=0)
19518 {@+first_fit(trie_root);trie_pack(trie_root);
19519 }
19520 if (hyph_root!=0) @<Pack all stored |hyph_codes|@>;
19521 @<Move the data into |trie|@>;
19522 trie_not_ready=false;
19523 @<restore the previous current file, line, and command@>@;
19524 }
19525
19526 @* Breaking vertical lists into pages.
19527 The |vsplit| procedure, which implements \TeX's \.{\\vsplit} operation,
19528 is considerably simpler than |line_break| because it doesn't have to
19529 worry about hyphenation, and because its mission is to discover a single
19530 break instead of an optimum sequence of breakpoints. But before we get
19531 into the details of |vsplit|, we need to consider a few more basic things.
19532
19533 @ A subroutine called |prune_page_top| takes a pointer to a vlist and
19534 returns a pointer to a modified vlist in which all glue, kern, and penalty nodes
19535 have been deleted before the first box or rule node. However, the first
19536 box or rule is actually preceded by a newly created glue node designed so that
19537 the topmost baseline will be at distance |split_top_skip| from the top,
19538 whenever this is possible without backspacing.
19539
19540 When the second argument |s| is |false| the deleted nodes are destroyed,
19541 otherwise they are collected in a list starting at |split_disc|.
19542
19543 In this routine and those that follow, we make use of the fact that a
19544 vertical list contains no character nodes, hence the |type| field exists
19545 for each node in the list.
19546 @^data structure assumptions@>
19547
19548 @p static pointer prune_page_top(pointer @!p, bool @!s)
19549 /*adjust top after page break*/
19550 {@+pointer prev_p; /*lags one step behind |p|*/
19551 pointer @!q, @!r; /*temporary variables for list manipulation*/
19552 prev_p=temp_head;link(temp_head)=p;
19553 while (p!=null)
19554 switch (type(p)) {
19555 case hlist_node: case vlist_node: case rule_node: @<Insert glue for |split_top_skip|
19556 and set~|p:=null|@>@;@+break;
19557 case whatsit_node: case mark_node: case ins_node: {@+prev_p=p;p=link(prev_p);
19558 } @+break;
19559 case glue_node: case kern_node: case penalty_node: {@+q=p;p=link(q);link(q)=null;
19560 link(prev_p)=p;
19561 if (s)
19562 {@+if (split_disc==null) split_disc=q;@+else link(r)=q;
19563 r=q;
19564 }
19565 else flush_node_list(q);
19566 } @+break;
19567 default:confusion("pruning");
19568 @:this can't happen pruning}{\quad pruning@>
19569 }
19570 return link(temp_head);
19571 }
19572
19573 @ @<Insert glue for |split_top_skip|...@>=
19574 {@+q=new_skip_param(split_top_skip_code);link(prev_p)=q;link(q)=p;
19575 /*now |temp_ptr==glue_ptr(q)|*/
19576 if (width(temp_ptr) > height(p)) width(temp_ptr)=width(temp_ptr)-height(p);
19577 else width(temp_ptr)=0;
19578 p=null;
19579 }
19580
19581 @ The next subroutine finds the best place to break a given vertical list
19582 so as to obtain a box of height~|h|, with maximum depth~|d|.
19583 A pointer to the beginning of the vertical list is given,
19584 and a pointer to the optimum breakpoint is returned. The list is effectively
19585 followed by a forced break, i.e., a penalty node with the |eject_penalty|;
19586 if the best break occurs at this artificial node, the value |null| is returned.
19587
19588 An array of six |scaled| distances is used to keep track of the height
19589 from the beginning of the list to the current place, just as in |line_break|.
19590 In fact, we use one of the same arrays, only changing its name to reflect
19591 its new significance.
19592
19593 @d active_height active_width /*new name for the six distance variables*/
19594 @d cur_height active_height[1] /*the natural height*/
19595 @d set_height_zero(A) active_height[A]=0 /*initialize the height to zero*/
19596 @#
19597 @p static pointer vert_break(pointer @!p, scaled @!h, scaled @!d)
19598 /*finds optimum page break*/
19599 {@+
19600 pointer prev_p; /*if |p| is a glue node, |type(prev_p)| determines
19601 whether |p| is a legal breakpoint*/
19602 pointer @!q, @!r; /*glue specifications*/
19603 int @!pi; /*penalty value*/
19604 int @!b; /*badness at a trial breakpoint*/
19605 int @!least_cost; /*the smallest badness plus penalties found so far*/
19606 pointer @!best_place; /*the most recent break that leads to |least_cost|*/
19607 scaled @!prev_dp; /*depth of previous box in the list*/
19608 small_number @!t; /*|type| of the node following a kern*/
19609 prev_p=p; /*an initial glue node is not a legal breakpoint*/
19610 least_cost=awful_bad;do_all_six(set_height_zero);prev_dp=0;
19611 loop@+{@+@<If node |p| is a legal breakpoint, check if this break is the best
19612 known, and |goto done| if |p| is null or if the page-so-far is already too
19613 full to accept more stuff@>;
19614 prev_p=p;p=link(prev_p);
19615 }
19616 done: return best_place;
19617 }
19618
19619 @ A global variable |best_height_plus_depth| will be set to the natural size
19620 of the box that corresponds to the optimum breakpoint found by |vert_break|.
19621 (This value is used by the insertion-splitting algorithm of the page builder.)
19622
19623 @<Glob...@>=
19624 static scaled @!best_height_plus_depth; /*height of the best box, without stretching or
19625 shrinking*/
19626
19627 @ A subtle point to be noted here is that the maximum depth~|d| might be
19628 negative, so |cur_height| and |prev_dp| might need to be corrected even
19629 after a glue or kern node.
19630
19631 @<If node |p| is a legal breakpoint, check...@>=
19632 if (p==null) pi=eject_penalty;
19633 else@<Use node |p| to update the current height and depth measurements; if
19634 this node is not a legal breakpoint, |goto not_found| or |update_heights|,
19635 otherwise set |pi| to the associated penalty at the break@>;
19636 @<Check if node |p| is a new champion breakpoint; then \(go)|goto done| if
19637 |p| is a forced break or if the page-so-far is already too full@>;
19638 if ((type(p) < glue_node)||(type(p) > kern_node)) goto not_found;
19639 update_heights: @<Update the current height and depth measurements with respect
19640 to a glue or kern node~|p|@>;
19641 not_found: if (prev_dp > d)
19642 {@+cur_height=cur_height+prev_dp-d;
19643 prev_dp=d;
19644 }
19645
19646 @ @<Use node |p| to update the current height and depth measurements...@>=
19647 switch (type(p)) {
19648 case hlist_node: case vlist_node: case rule_node: {@+@t@>@;@/
19649 cur_height=cur_height+prev_dp+height(p);prev_dp=depth(p);
19650 goto not_found;
19651 }
19652 case whatsit_node: @<Process whatsit |p| in |vert_break| loop, |goto not_found|@>;
19653 case glue_node: if (precedes_break(prev_p)) pi=0;
19654 else goto update_heights;@+break;
19655 case kern_node: {@+if (link(p)==null) t=penalty_node;
19656 else t=type(link(p));
19657 if (t==glue_node) pi=0;@+else goto update_heights;
19658 } @+break;
19659 case penalty_node: pi=penalty(p);@+break;
19660 case mark_node: case ins_node: goto not_found;
19661 default:confusion("vertbreak");
19662 @:this can't happen vertbreak}{\quad vertbreak@>
19663 }
19664
19665 @ @d deplorable 100000 /*more than |inf_bad|, but less than |awful_bad|*/
19666
19667 @<Check if node |p| is a new champion breakpoint; then \(go)...@>=
19668 if (pi < inf_penalty)
19669 {@+@<Compute the badness, |b|, using |awful_bad| if the box is too full@>;
19670 if (b < awful_bad)
19671 if (pi <= eject_penalty) b=pi;
19672 else if (b < inf_bad) b=b+pi;
19673 else b=deplorable;
19674 if (b <= least_cost)
19675 {@+best_place=p;least_cost=b;
19676 best_height_plus_depth=cur_height+prev_dp;
19677 }
19678 if ((b==awful_bad)||(pi <= eject_penalty)) goto done;
19679 }
19680
19681 @ @<Compute the badness, |b|, using |awful_bad| if the box is too full@>=
19682 if (cur_height < h)
19683 if ((active_height[3]!=0)||(active_height[4]!=0)||
19684 (active_height[5]!=0)) b=0;
19685 else b=badness(h-cur_height, active_height[2]);
19686 else if (cur_height-h > active_height[6]) b=awful_bad;
19687 else b=badness(cur_height-h, active_height[6])
19688
19689 @ Vertical lists that are subject to the |vert_break| procedure should not
19690 contain infinite shrinkability, since that would permit any amount of
19691 information to ``fit'' on one page.
19692
19693 @<Update the current height and depth measurements with...@>=
19694 if (type(p)==kern_node) q=p;
19695 else{@+q=glue_ptr(p);
19696 active_height[2+stretch_order(q)]=@|
19697 active_height[2+stretch_order(q)]+stretch(q);@/
19698 active_height[6]=active_height[6]+shrink(q);
19699 if ((shrink_order(q)!=normal)&&(shrink(q)!=0))
19700 {@+@t@>@;@/
19701 print_err("Infinite glue shrinkage found in box being split");@/
19702 @.Infinite glue shrinkage...@>
19703 help4("The box you are \\vsplitting contains some infinitely",@/
19704 "shrinkable glue, e.g., `\\vss' or `\\vskip 0pt minus 1fil'.",@/
19705 "Such glue doesn't belong there; but you can safely proceed,",@/
19706 "since the offensive shrinkability has been made finite.");
19707 error();r=new_spec(q);shrink_order(r)=normal;delete_glue_ref(q);
19708 glue_ptr(p)=r;q=r;
19709 }
19710 }
19711 cur_height=cur_height+prev_dp+width(q);prev_dp=0
19712
19713 @ Now we are ready to consider |vsplit| itself. Most of
19714 its work is accomplished by the two subroutines that we have just considered.
19715
19716 Given the number of a vlist box |n|, and given a desired page height |h|,
19717 the |vsplit| function finds the best initial segment of the vlist and
19718 returns a box for a page of height~|h|. The remainder of the vlist, if
19719 any, replaces the original box, after removing glue and penalties and
19720 adjusting for |split_top_skip|. Mark nodes in the split-off box are used to
19721 set the values of |split_first_mark| and |split_bot_mark|; we use the
19722 fact that |split_first_mark==null| if and only if |split_bot_mark==null|.
19723
19724 The original box becomes ``void'' if and only if it has been entirely
19725 extracted. The extracted box is ``void'' if and only if the original
19726 box was void (or if it was, erroneously, an hlist box).
19727
19728 @p @t\4@>@<Declare the function called |do_marks|@>@;
19729 static pointer vsplit(halfword @!n, scaled @!h)
19730 /*extracts a page of height |h| from box |n|*/
19731 {@+
19732 pointer v; /*the box to be split*/
19733 pointer p; /*runs through the vlist*/
19734 pointer q; /*points to where the break occurs*/
19735 cur_val=n;fetch_box(v);
19736 flush_node_list(split_disc);split_disc=null;
19737 if (sa_mark!=null)
19738 if (do_marks(vsplit_init, 0, sa_mark)) sa_mark=null;
19739 if (split_first_mark!=null)
19740 {@+delete_token_ref(split_first_mark);split_first_mark=null;
19741 delete_token_ref(split_bot_mark);split_bot_mark=null;
19742 }
19743 @<Dispense with trivial cases of void or bad boxes@>;
19744 q=vert_break(list_ptr(v), h, split_max_depth);
19745 @<Look at all the marks in nodes before the break, and set the final link
19746 to |null| at the break@>;
19747 q=prune_page_top(q, saving_vdiscards > 0);
19748 p=list_ptr(v);free_node(v, box_node_size);
19749 if (q!=null) q=vpack(q, natural);
19750 change_box(q); /*the |eq_level| of the box stays the same*/
19751 return vpackage(p, h, exactly, split_max_depth);
19752 }
19753
19754 @ @<Dispense with trivial cases of void or bad boxes@>=
19755 if (v==null)
19756 {@+return null;
19757 }
19758 if (type(v)!=vlist_node)
19759 {@+print_err("");print_esc("vsplit");print(" needs a ");
19760 print_esc("vbox");
19761 @:vsplit\_}{\.{\\vsplit needs a \\vbox}@>
19762 help2("The box you are trying to split is an \\hbox.",@/
19763 "I can't split such a box, so I'll leave it alone.");
19764 error();return null;
19765 }
19766
19767 @ It's possible that the box begins with a penalty node that is the
19768 ``best'' break, so we must be careful to handle this special case correctly.
19769
19770 @<Look at all the marks...@>=
19771 p=list_ptr(v);
19772 if (p==q) list_ptr(v)=null;
19773 else loop@+{@+if (type(p)==mark_node)
19774 if (mark_class(p)!=0) @<Update the current marks for |vsplit|@>@;
19775 else if (split_first_mark==null)
19776 {@+split_first_mark=mark_ptr(p);
19777 split_bot_mark=split_first_mark;
19778 token_ref_count(split_first_mark)=@|
19779 token_ref_count(split_first_mark)+2;
19780 }
19781 else{@+delete_token_ref(split_bot_mark);
19782 split_bot_mark=mark_ptr(p);
19783 add_token_ref(split_bot_mark);
19784 }
19785 if (link(p)==q)
19786 {@+link(p)=null;goto done;
19787 }
19788 p=link(p);
19789 }
19790 done:
19791
19792 @* The page builder.
19793 When \TeX\ appends new material to its main vlist in vertical mode, it uses
19794 a method something like |vsplit| to decide where a page ends, except that
19795 the calculations are done ``on line'' as new items come in.
19796 The main complication in this process is that insertions must be put
19797 into their boxes and removed from the vlist, in a more-or-less optimum manner.
19798
19799 We shall use the term ``current page'' for that part of the main vlist that
19800 is being considered as a candidate for being broken off and sent to the
19801 user's output routine. The current page starts at |link(page_head)|, and
19802 it ends at |page_tail|. We have |page_head==page_tail| if this list is empty.
19803 @^current page@>
19804
19805 Utter chaos would reign if the user kept changing page specifications
19806 while a page is being constructed, so the page builder keeps the pertinent
19807 specifications frozen as soon as the page receives its first box or
19808 insertion. The global variable |page_contents| is |empty| when the
19809 current page contains only mark nodes and content-less whatsit nodes; it
19810 is |inserts_only| if the page contains only insertion nodes in addition to
19811 marks and whatsits. Glue nodes, kern nodes, and penalty nodes are
19812 discarded until a box or rule node appears, at which time |page_contents|
19813 changes to |box_there|. As soon as |page_contents| becomes non-|empty|,
19814 the current |vsize| and |max_depth| are squirreled away into |page_goal|
19815 and |page_max_depth|; the latter values will be used until the page has
19816 been forwarded to the user's output routine. The \.{\\topskip} adjustment
19817 is made when |page_contents| changes to |box_there|.
19818
19819 Although |page_goal| starts out equal to |vsize|, it is decreased by the
19820 scaled natural height-plus-depth of the insertions considered so far, and by
19821 the \.{\\skip} corrections for those insertions. Therefore it represents
19822 the size into which the non-inserted material should fit, assuming that
19823 all insertions in the current page have been made.
19824
19825 The global variables |best_page_break| and |least_page_cost| correspond
19826 respectively to the local variables |best_place| and |least_cost| in the
19827 |vert_break| routine that we have already studied; i.e., they record the
19828 location and value of the best place currently known for breaking the
19829 current page. The value of |page_goal| at the time of the best break is
19830 stored in |best_size|.
19831
19832 @d inserts_only 1
19833 /*|page_contents| when an insert node has been contributed, but no boxes*/
19834 @d box_there 2 /*|page_contents| when a box or rule has been contributed*/
19835
19836 @<Glob...@>=
19837 static pointer @!page_tail; /*the final node on the current page*/
19838 static int @!page_contents; /*what is on the current page so far?*/
19839 static scaled @!page_max_depth; /*maximum box depth on page being built*/
19840 static pointer @!best_page_break; /*break here to get the best page known so far*/
19841 static int @!least_page_cost; /*the score for this currently best page*/
19842 static scaled @!best_size; /*its |page_goal|*/
19843
19844 @ The page builder has another data structure to keep track of insertions.
19845 This is a list of four-word nodes, starting and ending at |page_ins_head|.
19846 That is, the first element of the list is node |r@t$\_1$@>==link(page_ins_head)|;
19847 node $r_j$ is followed by |r@t$\_{j+1}$@>==link(r@t$\_j$@>)|; and if there are
19848 |n| items we have |r@t$\_{n+1}$@>==page_ins_head|. The |subtype| field of
19849 each node in this list refers to an insertion number; for example, `\.{\\insert
19850 250}' would correspond to a node whose |subtype| is |qi(250)|
19851 (the same as the |subtype| field of the relevant |ins_node|). These |subtype|
19852 fields are in increasing order, and |subtype(page_ins_head)==
19853 qi(255)|, so |page_ins_head| serves as a convenient sentinel
19854 at the end of the list. A record is present for each insertion number that
19855 appears in the current page.
19856
19857 The |type| field in these nodes distinguishes two possibilities that
19858 might occur as we look ahead before deciding on the optimum page break.
19859 If |type(r)==inserting|, then |height(r)| contains the total of the
19860 height-plus-depth dimensions of the box and all its inserts seen so far.
19861 If |type(r)==split_up|, then no more insertions will be made into this box,
19862 because at least one previous insertion was too big to fit on the current
19863 page; |broken_ptr(r)| points to the node where that insertion will be
19864 split, if \TeX\ decides to split it, |broken_ins(r)| points to the
19865 insertion node that was tentatively split, and |height(r)| includes also the
19866 natural height plus depth of the part that would be split off.
19867
19868 In both cases, |last_ins_ptr(r)| points to the last |ins_node|
19869 encountered for box |qo(subtype(r))| that would be at least partially
19870 inserted on the next page; and |best_ins_ptr(r)| points to the last
19871 such |ins_node| that should actually be inserted, to get the page with
19872 minimum badness among all page breaks considered so far. We have
19873 |best_ins_ptr(r)==null| if and only if no insertion for this box should
19874 be made to produce this optimum page.
19875
19876 The data structure definitions here use the fact that the |@!height| field
19877 appears in the fourth word of a box node.
19878 @^data structure assumptions@>
19879
19880 @d page_ins_node_size 4 /*number of words for a page insertion node*/
19881 @d inserting 0 /*an insertion class that has not yet overflowed*/
19882 @d split_up 1 /*an overflowed insertion class*/
19883 @d broken_ptr(A) link(A+1)
19884 /*an insertion for this class will break here if anywhere*/
19885 @d broken_ins(A) info(A+1) /*this insertion might break at |broken_ptr|*/
19886 @d last_ins_ptr(A) link(A+2) /*the most recent insertion for this |subtype|*/
19887 @d best_ins_ptr(A) info(A+2) /*the optimum most recent insertion*/
19888
19889 @<Initialize the special list heads...@>=
19890 subtype(page_ins_head)=qi(255);
19891 type(page_ins_head)=split_up;link(page_ins_head)=page_ins_head;
19892
19893 @ An array |page_so_far| records the heights and depths of everything
19894 on the current page. This array contains six |scaled| numbers, like the
19895 similar arrays already considered in |line_break| and |vert_break|; and it
19896 also contains |page_goal| and |page_depth|, since these values are
19897 all accessible to the user via |set_page_dimen| commands. The
19898 value of |page_so_far[1]| is also called |page_total|. The stretch
19899 and shrink components of the \.{\\skip} corrections for each insertion are
19900 included in |page_so_far|, but the natural space components of these
19901 corrections are not, since they have been subtracted from |page_goal|.
19902
19903 The variable |page_depth| records the depth of the current page; it has been
19904 adjusted so that it is at most |page_max_depth|. The variable
19905 |last_glue| points to the glue specification of the most recent node
19906 contributed from the contribution list, if this was a glue node; otherwise
19907 |last_glue==max_halfword|. (If the contribution list is nonempty,
19908 however, the value of |last_glue| is not necessarily accurate.)
19909 The variables |last_penalty|, |last_kern|, and |last_node_type|
19910 are similar. And
19911 finally, |insert_penalties| holds the sum of the penalties associated with
19912 all split and floating insertions.
19913
19914 @d page_goal page_so_far[0] /*desired height of information on page being built*/
19915 @d page_total page_so_far[1] /*height of the current page*/
19916 @d page_shrink page_so_far[6] /*shrinkability of the current page*/
19917 @d page_depth page_so_far[7] /*depth of the current page*/
19918
19919 @<Glob...@>=
19920 static scaled @!page_so_far[8]; /*height and glue of the current page*/
19921 static pointer @!last_glue; /*used to implement \.{\\lastskip}*/
19922 static int @!last_penalty; /*used to implement \.{\\lastpenalty}*/
19923 static scaled @!last_kern; /*used to implement \.{\\lastkern}*/
19924 static int @!last_node_type; /*used to implement \.{\\lastnodetype}*/
19925 static int @!insert_penalties; /*sum of the penalties for insertions
19926 that were held over*/
19927
19928 @ @<Put each...@>=
19929 primitive("pagegoal", set_page_dimen, 0);
19930 @!@:page\_goal\_}{\.{\\pagegoal} primitive@>
19931 primitive("pagetotal", set_page_dimen, 1);
19932 @!@:page\_total\_}{\.{\\pagetotal} primitive@>
19933 primitive("pagestretch", set_page_dimen, 2);
19934 @!@:page\_stretch\_}{\.{\\pagestretch} primitive@>
19935 primitive("pagefilstretch", set_page_dimen, 3);
19936 @!@:page\_fil\_stretch\_}{\.{\\pagefilstretch} primitive@>
19937 primitive("pagefillstretch", set_page_dimen, 4);
19938 @!@:page\_fill\_stretch\_}{\.{\\pagefillstretch} primitive@>
19939 primitive("pagefilllstretch", set_page_dimen, 5);
19940 @!@:page\_filll\_stretch\_}{\.{\\pagefilllstretch} primitive@>
19941 primitive("pageshrink", set_page_dimen, 6);
19942 @!@:page\_shrink\_}{\.{\\pageshrink} primitive@>
19943 primitive("pagedepth", set_page_dimen, 7);
19944 @!@:page\_depth\_}{\.{\\pagedepth} primitive@>
19945
19946 @ @<Cases of |print_cmd_chr|...@>=
19947 case set_page_dimen: switch (chr_code) {
19948 case 0: print_esc("pagegoal");@+break;
19949 case 1: print_esc("pagetotal");@+break;
19950 case 2: print_esc("pagestretch");@+break;
19951 case 3: print_esc("pagefilstretch");@+break;
19952 case 4: print_esc("pagefillstretch");@+break;
19953 case 5: print_esc("pagefilllstretch");@+break;
19954 case 6: print_esc("pageshrink");@+break;
19955 default:print_esc("pagedepth");
19956 } @+break;
19957
19958 @ @d print_plus(A, B) if (page_so_far[A]!=0)
19959 {@+print(" plus ");print_scaled(page_so_far[A]);print(B);@+}
19960
19961 @p static void print_totals(void)
19962 {@+print_scaled(page_total);
19963 print_plus(2,"");
19964 print_plus(3,"fil");
19965 print_plus(4,"fill");
19966 print_plus(5,"filll");
19967 if (page_shrink!=0)
19968 {@+print(" minus ");print_scaled(page_shrink);
19969 }
19970 }
19971
19972 @ @<Show the status of the current page@>=
19973 if (page_head!=page_tail)
19974 {@+print_nl("### current page:");
19975 if (output_active) print(" (held over for next output)");
19976 @.held over for next output@>
19977 show_box(link(page_head));
19978 if (page_contents > empty)
19979 {@+print_nl("total height ");print_totals();
19980 @:total\_height}{\.{total height}@>
19981 print_nl(" goal height ");print_scaled(page_goal);
19982 @.goal height@>
19983 r=link(page_ins_head);
19984 while (r!=page_ins_head)
19985 {@+print_ln();print_esc("insert");t=qo(subtype(r));
19986 print_int(t);print(" adds ");
19987 if (count(t)==1000) t=height(r);
19988 else t=x_over_n(height(r), 1000)*count(t);
19989 print_scaled(t);
19990 if (type(r)==split_up)
19991 {@+q=page_head;t=0;
19992 @/do@+{q=link(q);
19993 if ((type(q)==ins_node)&&(subtype(q)==subtype(r))) incr(t);
19994 }@+ while (!(q==broken_ins(r)));
19995 print(", #");print_int(t);print(" might split");
19996 }
19997 r=link(r);
19998 }
19999 }
20000 }
20001
20002 @ Here is a procedure that is called when the |page_contents| is changing
20003 from |empty| to |inserts_only| or |box_there|.
20004
20005 @d set_page_so_far_zero(A) page_so_far[A]=0
20006
20007 @p static void freeze_page_specs(small_number @!s)
20008 {@+page_contents=s;
20009 page_goal=vsize;page_max_depth=max_depth;
20010 page_depth=0;do_all_six(set_page_so_far_zero);
20011 least_page_cost=awful_bad;
20012 #ifdef @!STAT
20013 if (tracing_pages > 0)
20014 {@+begin_diagnostic();
20015 print_nl("%% goal height=");print_scaled(page_goal);
20016 @.goal height@>
20017 print(", max depth=");print_scaled(page_max_depth);
20018 end_diagnostic(false);
20019 } @;
20020 #endif
20021 @;@/
20022 }
20023
20024 @ Pages are built by appending nodes to the current list in \TeX's
20025 vertical mode, which is at the outermost level of the semantic nest. This
20026 vlist is split into two parts; the ``current page'' that we have been
20027 talking so much about already, and the ``contribution list'' that receives
20028 new nodes as they are created. The current page contains everything that
20029 the page builder has accounted for in its data structures, as described
20030 above, while the contribution list contains other things that have been
20031 generated by other parts of \TeX\ but have not yet been
20032 seen by the page builder.
20033 The contribution list starts at |link(contrib_head)|, and it ends at the
20034 current node in \TeX's vertical mode.
20035
20036 When \TeX\ has appended new material in vertical mode, it calls the procedure
20037 |build_page|, which tries to catch up by moving nodes from the contribution
20038 list to the current page. This procedure will succeed in its goal of
20039 emptying the contribution list, unless a page break is discovered, i.e.,
20040 unless the current page has grown to the point where the optimum next
20041 page break has been determined. In the latter case, the nodes after the
20042 optimum break will go back onto the contribution list, and control will
20043 effectively pass to the user's output routine.
20044
20045 We make |type(page_head)==glue_node|, so that an initial glue node on
20046 the current page will not be considered a valid breakpoint.
20047
20048 @<Initialize the special list...@>=
20049 type(page_head)=glue_node;subtype(page_head)=normal;
20050
20051 @ The global variable |output_active| is true during the time the
20052 user's output routine is driving \TeX.
20053
20054 @<Glob...@>=
20055 static bool @!output_active; /*are we in the midst of an output routine?*/
20056
20057 @ @<Set init...@>=
20058 output_active=false;insert_penalties=0;
20059
20060 @ The page builder is ready to start a fresh page if we initialize
20061 the following state variables. (However, the page insertion list is initialized
20062 elsewhere.)
20063
20064 @<Start a new current page@>=
20065 page_contents=empty;page_tail=page_head;link(page_head)=null;@/
20066 last_glue=max_halfword;last_penalty=0;last_kern=0;
20067 last_node_type=-1;
20068 page_depth=0;page_max_depth=0
20069
20070 @ At certain times box 255 is supposed to be void (i.e., |null|),
20071 or an insertion box is supposed to be ready to accept a vertical list.
20072 If not, an error message is printed, and the following subroutine
20073 flushes the unwanted contents, reporting them to the user.
20074
20075 @p static void box_error(eight_bits @!n)
20076 {@+error();begin_diagnostic();
20077 print_nl("The following box has been deleted:");
20078 @.The following...deleted@>
20079 show_box(box(n));end_diagnostic(true);
20080 flush_node_list(box(n));box(n)=null;
20081 }
20082
20083 @ The following procedure guarantees that a given box register
20084 does not contain an \.{\\hbox}.
20085
20086 @p static void ensure_vbox(eight_bits @!n)
20087 {@+pointer p; /*the box register contents*/
20088 p=box(n);
20089 if (p!=null) if (type(p)==hlist_node)
20090 {@+print_err("Insertions can only be added to a vbox");
20091 @.Insertions can only...@>
20092 help3("Tut tut: You're trying to \\insert into a",@/
20093 "\\box register that now contains an \\hbox.",@/
20094 "Proceed, and I'll discard its present contents.");
20095 box_error(n);
20096 }
20097 }
20098
20099 @ \TeX\ is not always in vertical mode at the time |build_page|
20100 is called; the current mode reflects what \TeX\ should return to, after
20101 the contribution list has been emptied. A call on |build_page| should
20102 be immediately followed by `|goto big_switch|', which is \TeX's central
20103 control point.
20104
20105 @p @t\4@>@<Declare the procedure called |fire_up|@>@;@/
20106 static void build_page(void) /*append contributions to the current page*/
20107 {@+
20108 pointer p; /*the node being appended*/
20109 pointer @!q, @!r; /*nodes being examined*/
20110 int @!b, @!c; /*badness and cost of current page*/
20111 int @!pi; /*penalty to be added to the badness*/
20112 int @!n; /*insertion box number*/
20113 scaled @!delta, @!h, @!w; /*sizes used for insertion calculations*/
20114 @<Local variables to save the profiling context@>@;
20115 if ((link(contrib_head)==null)||output_active) return;
20116 @<Charge the time used here on |build_page|@>@;
20117 @/do@+{resume: p=link(contrib_head);@/
20118 @<Update the values of |last_glue|, |last_penalty|, and |last_kern|@>;
20119 @<Move node |p| to the current page; if it is time for a page break, put the
20120 nodes following the break back onto the contribution list, and |return| to
20121 the user's output routine if there is one@>;
20122 }@+ while (!(link(contrib_head)==null));
20123 @<Make the contribution list empty by setting its tail to |contrib_head|@>;
20124 @<restore the previous current file, line, and command@>@;
20125 }
20126
20127 @ @d contrib_tail nest[0].tail_field /*tail of the contribution list*/
20128
20129 @<Make the contribution list empty...@>=
20130 if (nest_ptr==0) tail=contrib_head; /*vertical mode*/
20131 else contrib_tail=contrib_head /*other modes*/
20132
20133 @ @<Update the values of |last_glue|...@>=
20134 if (last_glue!=max_halfword) delete_glue_ref(last_glue);
20135 last_penalty=0;last_kern=0;
20136 last_node_type=type(p)+1;
20137 if (type(p)==glue_node)
20138 {@+last_glue=glue_ptr(p);add_glue_ref(last_glue);
20139 }
20140 else{@+last_glue=max_halfword;
20141 if (type(p)==penalty_node) last_penalty=penalty(p);
20142 else if (type(p)==kern_node) last_kern=width(p);
20143 }
20144
20145 @ The code here is an example of a many-way switch into routines that
20146 merge together in different places. Some people call this unstructured
20147 programming, but the author doesn't see much wrong with it, as long as
20148 @^Knuth, Donald Ervin@>
20149 the various labels have a well-understood meaning.
20150
20151 @<Move node |p| to the current page;...@>=
20152 @<If the current page is empty and node |p| is to be deleted, |goto done1|;
20153 otherwise use node |p| to update the state of the current page; if this node
20154 is an insertion, |goto contribute|; otherwise if this node is not a legal
20155 breakpoint, |goto contribute| or |update_heights|; otherwise set |pi| to the
20156 penalty associated with this breakpoint@>;
20157 @<Check if node |p| is a new champion breakpoint; then \(if)if it is time
20158 for a page break, prepare for output, and either fire up the user's output
20159 routine and |return| or ship out the page and |goto done|@>;
20160 if ((type(p) < glue_node)||(type(p) > kern_node)) goto contribute;
20161 update_heights: @<Update the current page measurements with respect to the
20162 glue or kern specified by node~|p|@>;
20163 contribute: @<Make sure that |page_max_depth| is not exceeded@>;
20164 @<Link node |p| into the current page and |goto done|@>;
20165 done1: @<Recycle node |p|@>;
20166 done:
20167
20168 @ @<Link node |p| into the current page and |goto done|@>=
20169 link(page_tail)=p;page_tail=p;
20170 link(contrib_head)=link(p);link(p)=null;goto done
20171
20172 @ @<Recycle node |p|@>=
20173 link(contrib_head)=link(p);link(p)=null;
20174 if (saving_vdiscards > 0)
20175 {@+if (page_disc==null) page_disc=p;@+else link(tail_page_disc)=p;
20176 tail_page_disc=p;
20177 }
20178 else flush_node_list(p)
20179
20180 @ The title of this section is already so long, it seems best to avoid
20181 making it more accurate but still longer, by mentioning the fact that a
20182 kern node at the end of the contribution list will not be contributed until
20183 we know its successor.
20184
20185 @<If the current page is empty...@>=
20186 switch (type(p)) {
20187 case hlist_node: case vlist_node: case rule_node: if (page_contents < box_there)
20188 @<Initialize the current page, insert the \.{\\topskip} glue ahead of
20189 |p|, and |goto resume|@>@;
20190 else@<Prepare to move a box or rule node to the current page, then |goto
20191 contribute|@>@;@+break;
20192 case whatsit_node: @<Prepare to move whatsit |p| to the current page, then
20193 |goto contribute|@>;
20194 case glue_node: if (page_contents < box_there) goto done1;
20195 else if (precedes_break(page_tail)) pi=0;
20196 else goto update_heights;@+break;
20197 case kern_node: if (page_contents < box_there) goto done1;
20198 else if (link(p)==null) return;
20199 else if (type(link(p))==glue_node) pi=0;
20200 else goto update_heights;@+break;
20201 case penalty_node: if (page_contents < box_there) goto done1;@+else pi=penalty(p);@+break;
20202 case mark_node: goto contribute;
20203 case ins_node: @<Append an insertion to the current page and |goto contribute|@>@;
20204 default:confusion("page");
20205 @:this can't happen page}{\quad page@>
20206 }
20207
20208 @ @<Initialize the current page, insert the \.{\\topskip} glue...@>=
20209 {@+if (page_contents==empty) freeze_page_specs(box_there);
20210 else page_contents=box_there;
20211 q=new_skip_param(top_skip_code); /*now |temp_ptr==glue_ptr(q)|*/
20212 if (width(temp_ptr) > height(p)) width(temp_ptr)=width(temp_ptr)-height(p);
20213 else width(temp_ptr)=0;
20214 link(q)=p;link(contrib_head)=q;goto resume;
20215 }
20216
20217 @ @<Prepare to move a box or rule node to the current page...@>=
20218 {@+page_total=page_total+page_depth+height(p);
20219 page_depth=depth(p);
20220 goto contribute;
20221 }
20222
20223 @ @<Make sure that |page_max_depth| is not exceeded@>=
20224 if (page_depth > page_max_depth)
20225 {@+page_total=@|
20226 page_total+page_depth-page_max_depth;@/
20227 page_depth=page_max_depth;
20228 }
20229
20230 @ @<Update the current page measurements with respect to the glue...@>=
20231 if (type(p)==kern_node) q=p;
20232 else{@+q=glue_ptr(p);
20233 page_so_far[2+stretch_order(q)]=@|
20234 page_so_far[2+stretch_order(q)]+stretch(q);@/
20235 page_shrink=page_shrink+shrink(q);
20236 if ((shrink_order(q)!=normal)&&(shrink(q)!=0))
20237 {@+@t@>@;@/
20238 print_err("Infinite glue shrinkage found on current page");@/
20239 @.Infinite glue shrinkage...@>
20240 help4("The page about to be output contains some infinitely",@/
20241 "shrinkable glue, e.g., `\\vss' or `\\vskip 0pt minus 1fil'.",@/
20242 "Such glue doesn't belong there; but you can safely proceed,",@/
20243 "since the offensive shrinkability has been made finite.");
20244 error();
20245 r=new_spec(q);shrink_order(r)=normal;delete_glue_ref(q);
20246 glue_ptr(p)=r;q=r;
20247 }
20248 }
20249 page_total=page_total+page_depth+width(q);page_depth=0
20250
20251 @ @<Check if node |p| is a new champion breakpoint; then \(if)...@>=
20252 if (pi < inf_penalty)
20253 {@+@<Compute the badness, |b|, of the current page, using |awful_bad| if
20254 the box is too full@>;
20255 if (b < awful_bad)
20256 if (pi <= eject_penalty) c=pi;
20257 else if (b < inf_bad) c=b+pi+insert_penalties;
20258 else c=deplorable;
20259 else c=b;
20260 if (insert_penalties >= 10000) c=awful_bad;
20261 #ifdef @!STAT
20262 if (tracing_pages > 0) @<Display the page break cost@>;
20263 #endif
20264 @;@/
20265 if (c <= least_page_cost)
20266 {@+best_page_break=p;best_size=page_goal;
20267 least_page_cost=c;
20268 r=link(page_ins_head);
20269 while (r!=page_ins_head)
20270 {@+best_ins_ptr(r)=last_ins_ptr(r);
20271 r=link(r);
20272 }
20273 }
20274 if ((c==awful_bad)||(pi <= eject_penalty))
20275 {@+fire_up(p); /*output the current page at the best place*/
20276 if (output_active)
20277 { @<restore the previous current file, line, and command@>@;
20278 return; /*user's output routine will act*/
20279 }
20280 goto done; /*the page has been shipped out by default output routine*/
20281 }
20282 }
20283
20284 @ @<Display the page break cost@>=
20285 {@+begin_diagnostic();print_nl("%");
20286 print(" t=");print_totals();@/
20287 print(" g=");print_scaled(page_goal);@/
20288 print(" b=");
20289 if (b==awful_bad) print_char('*');@+else print_int(b);
20290 @.*\relax@>
20291 print(" p=");print_int(pi);
20292 print(" c=");
20293 if (c==awful_bad) print_char('*');@+else print_int(c);
20294 if (c <= least_page_cost) print_char('#');
20295 end_diagnostic(false);
20296 }
20297
20298 @ @<Compute the badness, |b|, of the current page...@>=
20299 if (page_total < page_goal)
20300 if ((page_so_far[3]!=0)||(page_so_far[4]!=0)||@|
20301 (page_so_far[5]!=0)) b=0;
20302 else b=badness(page_goal-page_total, page_so_far[2]);
20303 else if (page_total-page_goal > page_shrink) b=awful_bad;
20304 else b=badness(page_total-page_goal, page_shrink)
20305
20306 @ @<Append an insertion to the current page and |goto contribute|@>=
20307 {@+if (page_contents==empty) freeze_page_specs(inserts_only);
20308 n=subtype(p);r=page_ins_head;
20309 while (n >= subtype(link(r))) r=link(r);
20310 n=qo(n);
20311 if (subtype(r)!=qi(n))
20312 @<Create a page insertion node with |subtype(r)=qi(n)|, and include the
20313 glue correction for box |n| in the current page state@>;
20314 if (type(r)==split_up) insert_penalties=insert_penalties+float_cost(p);
20315 else{@+last_ins_ptr(r)=p;
20316 delta=page_goal-page_total-page_depth+page_shrink;
20317 /*this much room is left if we shrink the maximum*/
20318 if (count(n)==1000) h=height(p);
20319 else h=x_over_n(height(p), 1000)*count(n); /*this much room is needed*/
20320 if (((h <= 0)||(h <= delta))&&(height(p)+height(r) <= dimen(n)))
20321 {@+page_goal=page_goal-h;height(r)=height(r)+height(p);
20322 }
20323 else@<Find the best way to split the insertion, and change |type(r)| to
20324 |split_up|@>;
20325 }
20326 goto contribute;
20327 }
20328
20329 @ We take note of the value of \.{\\skip} |n| and the height plus depth
20330 of \.{\\box}~|n| only when the first \.{\\insert}~|n| node is
20331 encountered for a new page. A user who changes the contents of \.{\\box}~|n|
20332 after that first \.{\\insert}~|n| had better be either extremely careful
20333 or extremely lucky, or both.
20334
20335 @<Create a page insertion node...@>=
20336 {@+q=get_node(page_ins_node_size);link(q)=link(r);link(r)=q;r=q;
20337 subtype(r)=qi(n);type(r)=inserting;ensure_vbox(n);
20338 if (box(n)==null) height(r)=0;
20339 else height(r)=height(box(n))+depth(box(n));
20340 best_ins_ptr(r)=null;@/
20341 q=skip(n);
20342 if (count(n)==1000) h=height(r);
20343 else h=x_over_n(height(r), 1000)*count(n);
20344 page_goal=page_goal-h-width(q);@/
20345 page_so_far[2+stretch_order(q)]=@|page_so_far[2+stretch_order(q)]+stretch(q);@/
20346 page_shrink=page_shrink+shrink(q);
20347 if ((shrink_order(q)!=normal)&&(shrink(q)!=0))
20348 {@+print_err("Infinite glue shrinkage inserted from ");print_esc("skip");
20349 @.Infinite glue shrinkage...@>
20350 print_int(n);
20351 help3("The correction glue for page breaking with insertions",@/
20352 "must have finite shrinkability. But you may proceed,",@/
20353 "since the offensive shrinkability has been made finite.");
20354 error();
20355 }
20356 }
20357
20358 @ Here is the code that will split a long footnote between pages, in an
20359 emergency. The current situation deserves to be recapitulated: Node |p|
20360 is an insertion into box |n|; the insertion will not fit, in its entirety,
20361 either because it would make the total contents of box |n| greater than
20362 \.{\\dimen} |n|, or because it would make the incremental amount of growth
20363 |h| greater than the available space |delta|, or both. (This amount |h| has
20364 been weighted by the insertion scaling factor, i.e., by \.{\\count} |n|
20365 over 1000.) Now we will choose the best way to break the vlist of the
20366 insertion, using the same criteria as in the \.{\\vsplit} operation.
20367
20368 @<Find the best way to split the insertion...@>=
20369 {@+if (count(n) <= 0) w=max_dimen;
20370 else{@+w=page_goal-page_total-page_depth;
20371 if (count(n)!=1000) w=x_over_n(w, count(n))*1000;
20372 }
20373 if (w > dimen(n)-height(r)) w=dimen(n)-height(r);
20374 q=vert_break(ins_ptr(p), w, depth(p));
20375 height(r)=height(r)+best_height_plus_depth;
20376 #ifdef @!STAT
20377 if (tracing_pages > 0) @<Display the insertion split cost@>;
20378 #endif
20379 @;@/
20380 if (count(n)!=1000)
20381 best_height_plus_depth=x_over_n(best_height_plus_depth, 1000)*count(n);
20382 page_goal=page_goal-best_height_plus_depth;
20383 type(r)=split_up;broken_ptr(r)=q;broken_ins(r)=p;
20384 if (q==null) insert_penalties=insert_penalties+eject_penalty;
20385 else if (type(q)==penalty_node) insert_penalties=insert_penalties+penalty(q);
20386 }
20387
20388 @ @<Display the insertion split cost@>=
20389 {@+begin_diagnostic();print_nl("% split");print_int(n);
20390 @.split@>
20391 print(" to ");print_scaled(w);
20392 print_char(',');print_scaled(best_height_plus_depth);@/
20393 print(" p=");
20394 if (q==null) print_int(eject_penalty);
20395 else if (type(q)==penalty_node) print_int(penalty(q));
20396 else print_char('0');
20397 end_diagnostic(false);
20398 }
20399
20400 @ When the page builder has looked at as much material as could appear before
20401 the next page break, it makes its decision. The break that gave minimum
20402 badness will be used to put a completed ``page'' into box 255, with insertions
20403 appended to their other boxes.
20404
20405 We also set the values of |top_mark|, |first_mark|, and |bot_mark|. The
20406 program uses the fact that |bot_mark!=null| implies |first_mark!=null|;
20407 it also knows that |bot_mark==null| implies |top_mark==first_mark==null|.
20408
20409 The |fire_up| subroutine prepares to output the current page at the best
20410 place; then it fires up the user's output routine, if there is one,
20411 or it simply ships out the page. There is one parameter, |c|, which represents
20412 the node that was being contributed to the page when the decision to
20413 force an output was made.
20414
20415 @<Declare the procedure called |fire_up|@>=
20416 static void fire_up(pointer @!c)
20417 {@+
20418 pointer p, @!q, @!r, @!s; /*nodes being examined and/or changed*/
20419 pointer @!prev_p; /*predecessor of |p|*/
20420 int @!n; /*insertion box number*/
20421 bool @!wait; /*should the present insertion be held over?*/
20422 int @!save_vbadness; /*saved value of |vbadness|*/
20423 scaled @!save_vfuzz; /*saved value of |vfuzz|*/
20424 pointer @!save_split_top_skip; /*saved value of |split_top_skip|*/
20425 @<Set the value of |output_penalty|@>;
20426 if (sa_mark!=null)
20427 if (do_marks(fire_up_init, 0, sa_mark)) sa_mark=null;
20428 if (bot_mark!=null)
20429 {@+if (top_mark!=null) delete_token_ref(top_mark);
20430 top_mark=bot_mark;add_token_ref(top_mark);
20431 delete_token_ref(first_mark);first_mark=null;
20432 }
20433 @<Put the \(o)optimal current page into box 255, update |first_mark| and |bot_mark|,
20434 append insertions to their boxes, and put the remaining nodes back on the
20435 contribution list@>;
20436 if (sa_mark!=null)
20437 if (do_marks(fire_up_done, 0, sa_mark)) sa_mark=null;
20438 if ((top_mark!=null)&&(first_mark==null))
20439 {@+first_mark=top_mark;add_token_ref(top_mark);
20440 }
20441 if (output_routine!=null)
20442 if (dead_cycles >= max_dead_cycles)
20443 @<Explain that too many dead cycles have occurred in a row@>@;
20444 else@<Fire up the user's output routine and |return|@>;
20445 @<Perform the default output routine@>;
20446 }
20447
20448 @ @<Set the value of |output_penalty|@>=
20449 if (type(best_page_break)==penalty_node)
20450 {@+geq_word_define(int_base+output_penalty_code, penalty(best_page_break));
20451 penalty(best_page_break)=inf_penalty;
20452 }
20453 else geq_word_define(int_base+output_penalty_code, inf_penalty)
20454
20455 @ As the page is finally being prepared for output,
20456 pointer |p| runs through the vlist, with |prev_p| trailing behind;
20457 pointer |q| is the tail of a list of insertions that
20458 are being held over for a subsequent page.
20459
20460 @<Put the \(o)optimal current page into box 255...@>=
20461 if (c==best_page_break) best_page_break=null; /*|c| not yet linked in*/
20462 @<Ensure that box 255 is empty before output@>;
20463 insert_penalties=0; /*this will count the number of insertions held over*/
20464 save_split_top_skip=split_top_skip;
20465 if (holding_inserts <= 0)
20466 @<Prepare all the boxes involved in insertions to act as queues@>;
20467 q=hold_head;link(q)=null;prev_p=page_head;p=link(prev_p);
20468 while (p!=best_page_break)
20469 {@+if (type(p)==ins_node)
20470 {@+if (holding_inserts <= 0)
20471 @<Either insert the material specified by node |p| into the appropriate
20472 box, or hold it for the next page; also delete node |p| from the current page@>;
20473 }
20474 else if (type(p)==mark_node)
20475 if (mark_class(p)!=0) @<Update the current marks for |fire_up|@>@;
20476 else@<Update the values of |first_mark| and |bot_mark|@>;
20477 prev_p=p;p=link(prev_p);
20478 }
20479 split_top_skip=save_split_top_skip;
20480 @<Break the current page at node |p|, put it in box~255, and put the remaining
20481 nodes on the contribution list@>;
20482 @<Delete \(t)the page-insertion nodes@>@;
20483
20484 @ @<Ensure that box 255 is empty before output@>=
20485 if (box(255)!=null)
20486 {@+print_err("");print_esc("box");print("255 is not void");
20487 @:box255}{\.{\\box255 is not void}@>
20488 help2("You shouldn't use \\box255 except in \\output routines.",@/
20489 "Proceed, and I'll discard its present contents.");
20490 box_error(255);
20491 }
20492
20493 @ @<Update the values of |first_mark| and |bot_mark|@>=
20494 {@+if (first_mark==null)
20495 {@+first_mark=mark_ptr(p);
20496 add_token_ref(first_mark);
20497 }
20498 if (bot_mark!=null) delete_token_ref(bot_mark);
20499 bot_mark=mark_ptr(p);add_token_ref(bot_mark);
20500 }
20501
20502 @ When the following code is executed, the current page runs from node
20503 |link(page_head)| to node |prev_p|, and the nodes from |p| to |page_tail|
20504 are to be placed back at the front of the contribution list. Furthermore
20505 the heldover insertions appear in a list from |link(hold_head)| to |q|; we
20506 will put them into the current page list for safekeeping while the user's
20507 output routine is active. We might have |q==hold_head|; and |p==null| if
20508 and only if |prev_p==page_tail|. Error messages are suppressed within
20509 |vpackage|, since the box might appear to be overfull or underfull simply
20510 because the stretch and shrink from the \.{\\skip} registers for inserts
20511 are not actually present in the box.
20512
20513 @<Break the current page at node |p|, put it...@>=
20514 if (p!=null)
20515 {@+if (link(contrib_head)==null)
20516 if (nest_ptr==0) tail=page_tail;
20517 else contrib_tail=page_tail;
20518 link(page_tail)=link(contrib_head);
20519 link(contrib_head)=p;
20520 link(prev_p)=null;
20521 }
20522 save_vbadness=vbadness;vbadness=inf_bad;
20523 save_vfuzz=vfuzz;vfuzz=max_dimen; /*inhibit error messages*/
20524 box(255)=vpackage(link(page_head), best_size, exactly, page_max_depth);
20525 vbadness=save_vbadness;vfuzz=save_vfuzz;
20526 if (last_glue!=max_halfword) delete_glue_ref(last_glue);
20527 @<Start a new current page@>; /*this sets |last_glue=max_halfword|*/
20528 if (q!=hold_head)
20529 {@+link(page_head)=link(hold_head);page_tail=q;
20530 }
20531
20532 @ If many insertions are supposed to go into the same box, we want to know
20533 the position of the last node in that box, so that we don't need to waste time
20534 when linking further information into it. The |last_ins_ptr| fields of the
20535 page insertion nodes are therefore used for this purpose during the
20536 packaging phase.
20537
20538 @<Prepare all the boxes involved in insertions to act as queues@>=
20539 {@+r=link(page_ins_head);
20540 while (r!=page_ins_head)
20541 {@+if (best_ins_ptr(r)!=null)
20542 {@+n=qo(subtype(r));ensure_vbox(n);
20543 if (box(n)==null) box(n)=new_null_box();
20544 p=box(n)+list_offset;
20545 while (link(p)!=null) p=link(p);
20546 last_ins_ptr(r)=p;
20547 }
20548 r=link(r);
20549 }
20550 }
20551
20552 @ @<Delete \(t)the page-insertion nodes@>=
20553 r=link(page_ins_head);
20554 while (r!=page_ins_head)
20555 {@+q=link(r);free_node(r, page_ins_node_size);r=q;
20556 }
20557 link(page_ins_head)=page_ins_head
20558
20559 @ We will set |best_ins_ptr=null| and package the box corresponding to
20560 insertion node~|r|, just after making the final insertion into that box.
20561 If this final insertion is `|split_up|', the remainder after splitting
20562 and pruning (if any) will be carried over to the next page.
20563
20564 @<Either insert the material specified by node |p| into...@>=
20565 {@+r=link(page_ins_head);
20566 while (subtype(r)!=subtype(p)) r=link(r);
20567 if (best_ins_ptr(r)==null) wait=true;
20568 else{@+wait=false;s=last_ins_ptr(r);link(s)=ins_ptr(p);
20569 if (best_ins_ptr(r)==p)
20570 @<Wrap up the box specified by node |r|, splitting node |p| if called
20571 for; set |wait:=true| if node |p| holds a remainder after splitting@>@;
20572 else{@+while (link(s)!=null) s=link(s);
20573 last_ins_ptr(r)=s;
20574 }
20575 }
20576 @<Either append the insertion node |p| after node |q|, and remove it from
20577 the current page, or delete |node(p)|@>;
20578 }
20579
20580 @ @<Wrap up the box specified by node |r|, splitting node |p| if...@>=
20581 {@+if (type(r)==split_up)
20582 if ((broken_ins(r)==p)&&(broken_ptr(r)!=null))
20583 {@+while (link(s)!=broken_ptr(r)) s=link(s);
20584 link(s)=null;
20585 split_top_skip=split_top_ptr(p);
20586 ins_ptr(p)=prune_page_top(broken_ptr(r), false);
20587 if (ins_ptr(p)!=null)
20588 {@+temp_ptr=vpack(ins_ptr(p), natural);
20589 height(p)=height(temp_ptr)+depth(temp_ptr);
20590 free_node(temp_ptr, box_node_size);wait=true;
20591 }
20592 }
20593 best_ins_ptr(r)=null;
20594 n=qo(subtype(r));
20595 temp_ptr=list_ptr(box(n));
20596 free_node(box(n), box_node_size);
20597 box(n)=vpack(temp_ptr, natural);
20598 }
20599
20600 @ @<Either append the insertion node |p|...@>=
20601 link(prev_p)=link(p);link(p)=null;
20602 if (wait)
20603 {@+link(q)=p;q=p;incr(insert_penalties);
20604 }
20605 else{@+delete_glue_ref(split_top_ptr(p));
20606 free_node(p, ins_node_size);
20607 }
20608 p=prev_p
20609
20610 @ The list of heldover insertions, running from |link(page_head)| to
20611 |page_tail|, must be moved to the contribution list when the user has
20612 specified no output routine.
20613
20614 @<Perform the default output routine@>=
20615 {@+if (link(page_head)!=null)
20616 {@+if (link(contrib_head)==null)
20617 if (nest_ptr==0) tail=page_tail;@+else contrib_tail=page_tail;
20618 else link(page_tail)=link(contrib_head);
20619 link(contrib_head)=link(page_head);
20620 link(page_head)=null;page_tail=page_head;
20621 }
20622 flush_node_list(page_disc);page_disc=null;
20623 ship_out(box(255));box(255)=null;
20624 }
20625
20626 @ @<Explain that too many dead cycles have occurred in a row@>=
20627 {@+print_err("Output loop---");print_int(dead_cycles);
20628 @.Output loop...@>
20629 print(" consecutive dead cycles");
20630 help3("I've concluded that your \\output is awry; it never does a",@/
20631 "\\shipout, so I'm shipping \\box255 out myself. Next time",@/
20632 "increase \\maxdeadcycles if you want me to be more patient!");error();
20633 }
20634
20635 @ @<Fire up the user's output routine and |return|@>=
20636 {@+output_active=true;
20637 incr(dead_cycles);
20638 push_nest();mode=-vmode;prev_depth=ignore_depth;mode_line=-line;
20639 begin_token_list(output_routine, output_text);
20640 new_save_level(output_group);normal_paragraph();
20641 scan_left_brace();
20642 return;
20643 }
20644
20645 @ When the user's output routine finishes, it has constructed a vlist
20646 in internal vertical mode, and \TeX\ will do the following:
20647
20648 @<Resume the page builder after an output routine has come to an end@>=
20649 {@+if ((loc!=null)||
20650 ((token_type!=output_text)&&(token_type!=backed_up)))
20651 @<Recover from an unbalanced output routine@>;
20652 end_token_list(); /*conserve stack space in case more outputs are triggered*/
20653 end_graf();unsave();output_active=false;insert_penalties=0;@/
20654 @<Ensure that box 255 is empty after output@>;
20655 if (tail!=head) /*current list goes after heldover insertions*/
20656 {@+link(page_tail)=link(head);
20657 page_tail=tail;
20658 }
20659 if (link(page_head)!=null) /*and both go before heldover contributions*/
20660 {@+if (link(contrib_head)==null) contrib_tail=page_tail;
20661 link(page_tail)=link(contrib_head);
20662 link(contrib_head)=link(page_head);
20663 link(page_head)=null;page_tail=page_head;
20664 }
20665 flush_node_list(page_disc);page_disc=null;
20666 pop_nest();build_page();
20667 }
20668
20669 @ @<Recover from an unbalanced output routine@>=
20670 {@+print_err("Unbalanced output routine");
20671 @.Unbalanced output routine@>
20672 help2("Your sneaky output routine has problematic {'s and/or }'s.",@/
20673 "I can't handle that very well; good luck.");error();
20674 @/do@+{get_token();
20675 }@+ while (!(loc==null));
20676 } /*loops forever if reading from a file, since |null==min_halfword <= 0|*/
20677
20678 @ @<Ensure that box 255 is empty after output@>=
20679 if (box(255)!=null)
20680 {@+print_err("Output routine didn't use all of ");
20681 print_esc("box");print_int(255);
20682 @.Output routine didn't use...@>
20683 help3("Your \\output commands should empty \\box255,",@/
20684 "e.g., by saying `\\shipout\\box255'.",@/
20685 "Proceed; I'll discard its present contents.");
20686 box_error(255);
20687 }
20688
20689 @* The chief executive.
20690 We come now to the |main_control| routine, which contains the master
20691 switch that causes all the various pieces of \TeX\ to do their things,
20692 in the right order.
20693
20694 In a sense, this is the grand climax of the program: It applies all the
20695 tools that we have worked so hard to construct. In another sense, this is
20696 the messiest part of the program: It necessarily refers to other pieces
20697 of code all over the place, so that a person can't fully understand what is
20698 going on without paging back and forth to be reminded of conventions that
20699 are defined elsewhere. We are now at the hub of the web, the central nervous
20700 system that touches most of the other parts and ties them together.
20701 @^brain@>
20702
20703 The structure of |main_control| itself is quite simple. There's a label
20704 called |big_switch|, at which point the next token of input is fetched
20705 using |get_x_token|. Then the program branches at high speed into one of
20706 about 100 possible directions, based on the value of the current
20707 mode and the newly fetched command code; the sum |abs(mode)+cur_cmd|
20708 indicates what to do next. For example, the case `|vmode+letter|' arises
20709 when a letter occurs in vertical mode (or internal vertical mode); this
20710 case leads to instructions that initialize a new paragraph and enter
20711 horizontal mode.
20712
20713 The big |case| statement that contains this multiway switch has been labeled
20714 |reswitch|, so that the program can |goto reswitch| when the next token
20715 has already been fetched. Most of the cases are quite short; they call
20716 an ``action procedure'' that does the work for that case, and then they
20717 either |goto reswitch| or they ``fall through'' to the end of the |case|
20718 statement, which returns control back to |big_switch|. Thus, |main_control|
20719 is not an extremely large procedure, in spite of the multiplicity of things
20720 it must do; it is small enough to be handled by \PASCAL\ compilers that put
20721 severe restrictions on procedure size.
20722 @!@^action procedure@>
20723
20724 One case is singled out for special treatment, because it accounts for most
20725 of \TeX's activities in typical applications. The process of reading simple
20726 text and converting it into |char_node| records, while looking for ligatures
20727 and kerns, is part of \TeX's ``inner loop''; the whole program runs
20728 efficiently when its inner loop is fast, so this part has been written
20729 with particular care.
20730
20731 @ We shall concentrate first on the inner loop of |main_control|, deferring
20732 consideration of the other cases until later.
20733 @^inner loop@>
20734
20735 @p @t\4@>@<Declare action procedures for use by |main_control|@>@;
20736 @t\4@>@<Declare the procedure called |handle_right_brace|@>@;
20737 static void main_control(void) /*governs \TeX's activities*/
20738 {@+
20739 int @!t; /*general-purpose temporary variable*/
20740 @<Initialize profiling@>@;
20741 if (every_job!=null) begin_token_list(every_job, every_job_text);
20742 big_switch:
20743 @<record timing information@>@;
20744 get_x_token();@/
20745 big_reswitch:
20746 @<set current file, line, and command for the current time slot@>@;
20747 @<Give diagnostic information, if requested@>;
20748 switch (abs(mode)+cur_cmd) {
20749 case hmode+letter: case hmode+other_char:
20750 case hmode+char_given: goto main_loop;
20751 case hmode+char_num: {@+scan_char_num();cur_chr=cur_val;goto main_loop;@+}
20752 case hmode+no_boundary: {@+get_x_token();
20753 if ((cur_cmd==letter)||(cur_cmd==other_char)||(cur_cmd==char_given)||
20754 (cur_cmd==char_num)) cancel_boundary=true;
20755 goto big_reswitch;
20756 }
20757 case hmode+spacer: if (space_factor==1000) goto append_normal_space;
20758 else app_space();@+break;
20759 case hmode+ex_space: case mmode+ex_space: goto append_normal_space;
20760 @t\4@>@<Cases of |main_control| that are not part of the inner loop@>@;
20761 } /*of the big |case| statement*/
20762 goto big_switch;
20763 main_loop:
20764 @<record timing information@>@;
20765 @<set current file, line, and command for the current time slot@>@;
20766 @<Append character |cur_chr| and the following characters (if~any)
20767 to the current hlist in the current font; |goto big_reswitch| when a non-character
20768 has been fetched@>;
20769 append_normal_space: @<Append a normal inter-word space to the current list,
20770 then |goto big_switch|@>;
20771 }
20772
20773 @ When a new token has just been fetched at |big_switch|, we have an
20774 ideal place to monitor \TeX's activity.
20775 @^debugging@>
20776
20777 @<Give diagnostic information, if requested@>=
20778 if (interrupt!=0) if (OK_to_interrupt)
20779 {@+back_input();check_interrupt;goto big_switch;
20780 }
20781 #ifdef @!DEBUG
20782 if (panicking) check_mem(false);@;
20783 #endif
20784 if (tracing_commands > 0) show_cur_cmd_chr()
20785
20786 @ The following part of the program was first written in a structured
20787 manner, according to the philosophy that ``premature optimization is
20788 the root of all evil.'' Then it was rearranged into pieces of
20789 spaghetti so that the most common actions could proceed with little or
20790 no redundancy.
20791
20792 The original unoptimized form of this algorithm resembles the
20793 |reconstitute| procedure, which was described earlier in connection with
20794 hyphenation. Again we have an implied ``cursor'' between characters
20795 |cur_l| and |cur_r|. The main difference is that the |lig_stack| can now
20796 contain a charnode as well as pseudo-ligatures; that stack is now
20797 usually nonempty, because the next character of input (if any) has been
20798 appended to it. In |main_control| we have
20799 $$|cur_r|=\cases{|character(lig_stack)|,&if |lig_stack > null|;\cr
20800 |font_bchar[cur_font]|,&otherwise;\cr}$$
20801 except when |character(lig_stack)==font_false_bchar[cur_font]|.
20802 Several additional global variables are needed.
20803
20804 @<Glob...@>=
20805 static internal_font_number @!main_f; /*the current font*/
20806 static four_quarters @!main_i; /*character information bytes for |cur_l|*/
20807 static four_quarters @!main_j; /*ligature/kern command*/
20808 static font_index @!main_k; /*index into |font_info|*/
20809 static pointer @!main_p; /*temporary register for list manipulation*/
20810 static int @!main_s; /*space factor value*/
20811 static halfword @!bchar; /*boundary character of current font, or |non_char|*/
20812 static halfword @!false_bchar; /*nonexistent character matching |bchar|, or |non_char|*/
20813 static bool @!cancel_boundary; /*should the left boundary be ignored?*/
20814 static bool @!ins_disc; /*should we insert a discretionary node?*/
20815
20816 @ The boolean variables of the main loop are normally false, and always reset
20817 to false before the loop is left. That saves us the extra work of initializing
20818 each time.
20819
20820 @<Set init...@>=
20821 ligature_present=false;cancel_boundary=false;lft_hit=false;rt_hit=false;
20822 ins_disc=false;
20823
20824 @ We leave the |space_factor| unchanged if |sf_code(cur_chr)==0|; otherwise we
20825 set it equal to |sf_code(cur_chr)|, except that it should never change
20826 from a value less than 1000 to a value exceeding 1000. The most common
20827 case is |sf_code(cur_chr)==1000|, so we want that case to be fast.
20828
20829 The overall structure of the main loop is presented here. Some program labels
20830 are inside the individual sections.
20831 @^inner loop@>
20832
20833 @d adjust_space_factor @t@>@;@/
20834 main_s=sf_code(cur_chr);
20835 if (main_s==1000) space_factor=1000;
20836 else if (main_s < 1000)
20837 {@+if (main_s > 0) space_factor=main_s;
20838 }
20839 else if (space_factor < 1000) space_factor=1000;
20840 else space_factor=main_s
20841
20842 @<Append character |cur_chr|...@>=
20843 adjust_space_factor;@/
20844 main_f=cur_font;
20845 bchar=font_bchar[main_f];false_bchar=font_false_bchar[main_f];
20846 if (mode > 0) if (language!=clang) fix_language();
20847 fast_get_avail(lig_stack);font(lig_stack)=main_f;cur_l=qi(cur_chr);
20848 character(lig_stack)=cur_l;@/
20849 cur_q=tail;
20850 if (cancel_boundary)
20851 {@+cancel_boundary=false;main_k=non_address;
20852 }
20853 else main_k=bchar_label[main_f];
20854 if (main_k==non_address) goto main_loop_move2; /*no left boundary processing*/
20855 cur_r=cur_l;cur_l=non_char;
20856 goto main_lig_loop1; /*begin with cursor after left boundary*/
20857 @#
20858 main_loop_wrapup: @<Make a ligature node, if |ligature_present|; insert a
20859 null discretionary, if appropriate@>;
20860 main_loop_move: @<If the cursor is immediately followed by the right boundary,
20861 |goto big_reswitch|; if it's followed by an invalid character, |goto big_switch|;
20862 otherwise move the cursor one step to the right and |goto main_lig_loop|@>;
20863 main_loop_lookahead: @<Look ahead for another character, or leave |lig_stack|
20864 empty if there's none there@>;
20865 main_lig_loop: @<If there's a ligature/kern command relevant to |cur_l| and
20866 |cur_r|, adjust the text appropriately; exit to |main_loop_wrapup|@>;
20867 main_loop_move_lig: @<Move the cursor past a pseudo-ligature, then |goto main_loop_lookahead|
20868 or |main_lig_loop|@>@;
20869
20870 @ If |link(cur_q)| is nonnull when |wrapup| is invoked, |cur_q| points to
20871 the list of characters that were consumed while building the ligature
20872 character~|cur_l|.
20873
20874 A discretionary break is not inserted for an explicit hyphen when we are in
20875 restricted horizontal mode. In particular, this avoids putting discretionary
20876 nodes inside of other discretionaries.
20877 @^inner loop@>
20878
20879 @d pack_lig(X) /*the parameter is either |rt_hit| or |false|*/
20880 {@+main_p=new_ligature(main_f, cur_l, link(cur_q));
20881 if (lft_hit)
20882 {@+subtype(main_p)=2;lft_hit=false;
20883 }
20884 if (X) if (lig_stack==null)
20885 {@+incr(subtype(main_p));rt_hit=false;
20886 }
20887 link(cur_q)=main_p;tail=main_p;ligature_present=false;
20888 }
20889
20890 @d wrapup(A) if (cur_l < non_char)
20891 {@+if (link(cur_q) > null)
20892 if (character(tail)==qi(hyphen_char[main_f])) ins_disc=true;
20893 if (ligature_present) pack_lig(A);
20894 if (ins_disc)
20895 {@+ins_disc=false;
20896 if (mode > 0) tail_append(new_disc());
20897 }
20898 }
20899
20900 @<Make a ligature node, if |ligature_present|;...@>=
20901 wrapup(rt_hit)
20902
20903 @ @<If the cursor is immediately followed by the right boundary...@>=
20904 @^inner loop@>
20905 if (lig_stack==null) goto big_reswitch;
20906 cur_q=tail;cur_l=character(lig_stack);
20907 main_loop_move1: if (!is_char_node(lig_stack)) goto main_loop_move_lig;
20908 main_loop_move2: if ((cur_chr < font_bc[main_f])||(cur_chr > font_ec[main_f]))
20909 {@+char_warning(main_f, cur_chr);free_avail(lig_stack);goto big_switch;
20910 }
20911 main_i=char_info(main_f, cur_l);
20912 if (!char_exists(main_i))
20913 {@+char_warning(main_f, cur_chr);free_avail(lig_stack);goto big_switch;
20914 }
20915 link(tail)=lig_stack;tail=lig_stack /*|main_loop_lookahead| is next*/
20916
20917 @ Here we are at |main_loop_move_lig|.
20918 When we begin this code we have |cur_q==tail| and |cur_l==character(lig_stack)|.
20919
20920 @<Move the cursor past a pseudo-ligature...@>=
20921 main_p=lig_ptr(lig_stack);
20922 if (main_p > null) tail_append(main_p); /*append a single character*/
20923 temp_ptr=lig_stack;lig_stack=link(temp_ptr);
20924 free_node(temp_ptr, small_node_size);
20925 main_i=char_info(main_f, cur_l);ligature_present=true;
20926 if (lig_stack==null)
20927 if (main_p > null) goto main_loop_lookahead;
20928 else cur_r=bchar;
20929 else cur_r=character(lig_stack);
20930 goto main_lig_loop
20931
20932 @ The result of \.{\\char} can participate in a ligature or kern, so we must
20933 look ahead for it.
20934
20935 @<Look ahead for another character...@>=
20936 get_next(); /*set only |cur_cmd| and |cur_chr|, for speed*/
20937 if (cur_cmd==letter) goto main_loop_lookahead1;
20938 if (cur_cmd==other_char) goto main_loop_lookahead1;
20939 if (cur_cmd==char_given) goto main_loop_lookahead1;
20940 x_token(); /*now expand and set |cur_cmd|, |cur_chr|, |cur_tok|*/
20941 if (cur_cmd==letter) goto main_loop_lookahead1;
20942 if (cur_cmd==other_char) goto main_loop_lookahead1;
20943 if (cur_cmd==char_given) goto main_loop_lookahead1;
20944 if (cur_cmd==char_num)
20945 {@+scan_char_num();cur_chr=cur_val;goto main_loop_lookahead1;
20946 }
20947 if (cur_cmd==no_boundary) bchar=non_char;
20948 cur_r=bchar;lig_stack=null;goto main_lig_loop;
20949 main_loop_lookahead1: adjust_space_factor;
20950 fast_get_avail(lig_stack);font(lig_stack)=main_f;
20951 cur_r=qi(cur_chr);character(lig_stack)=cur_r;
20952 if (cur_r==false_bchar) cur_r=non_char /*this prevents spurious ligatures*/
20953
20954 @ Even though comparatively few characters have a lig/kern program, several
20955 of the instructions here count as part of \TeX's inner loop, since a
20956 @^inner loop@>
20957 potentially long sequential search must be performed. For example, tests with
20958 Computer Modern Roman showed that about 40 per cent of all characters
20959 actually encountered in practice had a lig/kern program, and that about four
20960 lig/kern commands were investigated for every such character.
20961
20962 At the beginning of this code we have |main_i==char_info(main_f, cur_l)|.
20963
20964 @<If there's a ligature/kern command...@>=
20965 if (char_tag(main_i)!=lig_tag) goto main_loop_wrapup;
20966 if (cur_r==non_char) goto main_loop_wrapup;
20967 main_k=lig_kern_start(main_f, main_i);main_j=font_info[main_k].qqqq;
20968 if (skip_byte(main_j) <= stop_flag) goto main_lig_loop2;
20969 main_k=lig_kern_restart(main_f, main_j);
20970 main_lig_loop1: main_j=font_info[main_k].qqqq;
20971 main_lig_loop2: if (next_char(main_j)==cur_r)
20972 if (skip_byte(main_j) <= stop_flag)
20973 @<Do ligature or kern command, returning to |main_lig_loop| or |main_loop_wrapup|
20974 or |main_loop_move|@>;
20975 if (skip_byte(main_j)==qi(0)) incr(main_k);
20976 else{@+if (skip_byte(main_j) >= stop_flag) goto main_loop_wrapup;
20977 main_k=main_k+qo(skip_byte(main_j))+1;
20978 }
20979 goto main_lig_loop1
20980
20981 @ When a ligature or kern instruction matches a character, we know from
20982 |read_font_info| that the character exists in the font, even though we
20983 haven't verified its existence in the normal way.
20984
20985 This section could be made into a subroutine, if the code inside
20986 |main_control| needs to be shortened.
20987
20988 \chardef\@@='174 % vertical line to indicate character retention
20989
20990 @<Do ligature or kern command...@>=
20991 {@+if (op_byte(main_j) >= kern_flag)
20992 {@+wrapup(rt_hit);
20993 tail_append(new_kern(char_kern(main_f, main_j)));goto main_loop_move;
20994 }
20995 if (cur_l==non_char) lft_hit=true;
20996 else if (lig_stack==null) rt_hit=true;
20997 check_interrupt; /*allow a way out in case there's an infinite ligature loop*/
20998 switch (op_byte(main_j)) {
20999 case qi(1): case qi(5): {@+cur_l=rem_byte(main_j); /*\.{=:\@@}, \.{=:\@@>}*/
21000 main_i=char_info(main_f, cur_l);ligature_present=true;
21001 } @+break;
21002 case qi(2): case qi(6): {@+cur_r=rem_byte(main_j); /*\.{\@@=:}, \.{\@@=:>}*/
21003 if (lig_stack==null) /*right boundary character is being consumed*/
21004 {@+lig_stack=new_lig_item(cur_r);bchar=non_char;
21005 }
21006 else if (is_char_node(lig_stack)) /*|link(lig_stack)==null|*/
21007 {@+main_p=lig_stack;lig_stack=new_lig_item(cur_r);
21008 lig_ptr(lig_stack)=main_p;
21009 }
21010 else character(lig_stack)=cur_r;
21011 } @+break;
21012 case qi(3): {@+cur_r=rem_byte(main_j); /*\.{\@@=:\@@}*/
21013 main_p=lig_stack;lig_stack=new_lig_item(cur_r);
21014 link(lig_stack)=main_p;
21015 } @+break;
21016 case qi(7): case qi(11): {@+wrapup(false); /*\.{\@@=:\@@>}, \.{\@@=:\@@>>}*/
21017 cur_q=tail;cur_l=rem_byte(main_j);
21018 main_i=char_info(main_f, cur_l);ligature_present=true;
21019 } @+break;
21020 default:{@+cur_l=rem_byte(main_j);ligature_present=true; /*\.{=:}*/
21021 if (lig_stack==null) goto main_loop_wrapup;
21022 else goto main_loop_move1;
21023 }
21024 }
21025 if (op_byte(main_j) > qi(4))
21026 if (op_byte(main_j)!=qi(7)) goto main_loop_wrapup;
21027 if (cur_l < non_char) goto main_lig_loop;
21028 main_k=bchar_label[main_f];goto main_lig_loop1;
21029 }
21030
21031 @ The occurrence of blank spaces is almost part of \TeX's inner loop,
21032 @^inner loop@>
21033 since we usually encounter about one space for every five non-blank characters.
21034 Therefore |main_control| gives second-highest priority to ordinary spaces.
21035
21036 When a glue parameter like \.{\\spaceskip} is set to `\.{0pt}', we will
21037 see to it later that the corresponding glue specification is precisely
21038 |zero_glue|, not merely a pointer to some specification that happens
21039 to be full of zeroes. Therefore it is simple to test whether a glue parameter
21040 is zero or~not.
21041
21042 @<Append a normal inter-word space...@>=
21043 if (space_skip==zero_glue)
21044 {@+@<Find the glue specification, |main_p|, for text spaces in the current
21045 font@>;
21046 temp_ptr=new_glue(main_p);
21047 }
21048 else temp_ptr=new_param_glue(space_skip_code);
21049 link(tail)=temp_ptr;tail=temp_ptr;
21050 goto big_switch
21051
21052 @ Having |font_glue| allocated for each text font saves both time and memory.
21053 If any of the three spacing parameters are subsequently changed by the
21054 use of \.{\\fontdimen}, the |find_font_dimen| procedure deallocates the
21055 |font_glue| specification allocated here.
21056
21057 @<Find the glue specification...@>=
21058 {@+main_p=font_glue[cur_font];
21059 if (main_p==null)
21060 {@+main_p=new_spec(zero_glue);main_k=param_base[cur_font]+space_code;
21061 width(main_p)=font_info[main_k].sc; /*that's |space(cur_font)|*/
21062 stretch(main_p)=font_info[main_k+1].sc; /*and |space_stretch(cur_font)|*/
21063 shrink(main_p)=font_info[main_k+2].sc; /*and |space_shrink(cur_font)|*/
21064 font_glue[cur_font]=main_p;
21065 }
21066 }
21067
21068 @ @<Declare act...@>=
21069 static void app_space(void) /*handle spaces when |space_factor!=1000|*/
21070 {@+pointer @!q; /*glue node*/
21071 if ((space_factor >= 2000)&&(xspace_skip!=zero_glue))
21072 q=new_param_glue(xspace_skip_code);
21073 else{@+if (space_skip!=zero_glue) main_p=space_skip;
21074 else@<Find the glue specification...@>;
21075 main_p=new_spec(main_p);
21076 @<Modify the glue specification in |main_p| according to the space factor@>;
21077 q=new_glue(main_p);glue_ref_count(main_p)=null;
21078 }
21079 link(tail)=q;tail=q;
21080 }
21081
21082 @ @<Modify the glue specification in |main_p| according to the space factor@>=
21083 if (space_factor >= 2000) width(main_p)=width(main_p)+extra_space(cur_font);
21084 stretch(main_p)=xn_over_d(stretch(main_p), space_factor, 1000);
21085 shrink(main_p)=xn_over_d(shrink(main_p), 1000, space_factor)
21086
21087 @ Whew---that covers the main loop. We can now proceed at a leisurely
21088 pace through the other combinations of possibilities.
21089
21090 @d any_mode(A) case vmode+A: case hmode+A:
21091 case mmode+A /*for mode-independent commands*/
21092
21093 @<Cases of |main_control| that are not part of the inner loop@>=
21094 any_mode(relax): case vmode+spacer: case mmode+spacer:
21095 case mmode+no_boundary: do_nothing;@+break;
21096 any_mode(ignore_spaces): {@+@<Get the next non-blank non-call...@>;
21097 goto big_reswitch;
21098 }
21099 case vmode+stop:
21100 if (its_all_over())
21101 { @<record the end of \TeX@>@;
21102 return; /*this is the only way out*/
21103 }
21104 @+break;
21105 @t\4@>@<Forbidden cases detected in |main_control|@>@+@, any_mode(mac_param):
21106 report_illegal_case();@+break;
21107 @<Math-only cases in non-math modes, or vice versa@>: insert_dollar_sign();@+break;
21108 @t\4@>@<Cases of |main_control| that build boxes and lists@>@;
21109 @t\4@>@<Cases of |main_control| that don't depend on |mode|@>@;
21110 @t\4@>@<Cases of |main_control| that are for extensions to \TeX@>@;
21111
21112 @ Here is a list of cases where the user has probably gotten into or out of math
21113 mode by mistake. \TeX\ will insert a dollar sign and rescan the current token.
21114
21115 @d non_math(A) case vmode+A: case hmode+A
21116
21117 @<Math-only cases in non-math modes...@>=
21118 non_math(sup_mark): non_math(sub_mark): non_math(math_char_num):
21119 non_math(math_given): non_math(math_comp): non_math(delim_num):
21120 non_math(left_right): non_math(above): non_math(radical):
21121 non_math(math_style): non_math(math_choice): non_math(vcenter):
21122 non_math(non_script): non_math(mkern): non_math(limit_switch):
21123 non_math(mskip): non_math(math_accent):
21124 case mmode+endv: case mmode+par_end: case mmode+stop:
21125 case mmode+vskip: case mmode+un_vbox:
21126 case mmode+valign: case mmode+hrule
21127
21128 @ @<Declare action...@>=
21129 static void insert_dollar_sign(void)
21130 {@+back_input();cur_tok=math_shift_token+'$';
21131 print_err("Missing $ inserted");
21132 @.Missing \$ inserted@>
21133 help2("I've inserted a begin-math/end-math symbol since I think",@/
21134 "you left one out. Proceed, with fingers crossed.");ins_error();
21135 }
21136
21137 @ When erroneous situations arise, \TeX\ usually issues an error message
21138 specific to the particular error. For example, `\.{\\noalign}' should
21139 not appear in any mode, since it is recognized by the |align_peek| routine
21140 in all of its legitimate appearances; a special error message is given
21141 when `\.{\\noalign}' occurs elsewhere. But sometimes the most appropriate
21142 error message is simply that the user is not allowed to do what he or she
21143 has attempted. For example, `\.{\\moveleft}' is allowed only in vertical mode,
21144 and `\.{\\lower}' only in non-vertical modes. Such cases are enumerated
21145 here and in the other sections referred to under `See also \dots.'
21146
21147 @<Forbidden cases...@>=
21148 case vmode+vmove: case hmode+hmove: case mmode+hmove: any_mode(last_item):
21149
21150 @ The `|you_cant|' procedure prints a line saying that the current command
21151 is illegal in the current mode; it identifies these things symbolically.
21152
21153 @<Declare action...@>=
21154 static void you_cant(void)
21155 {@+print_err("You can't use `");
21156 @.You can't use x in y mode@>
21157 print_cmd_chr(cur_cmd, cur_chr);
21158 print("' in ");print_mode(mode);
21159 }
21160
21161 @ @<Declare act...@>=
21162 static void report_illegal_case(void)
21163 {@+you_cant();
21164 help4("Sorry, but I'm not programmed to handle this case;",@/
21165 "I'll just pretend that you didn't ask for it.",@/
21166 "If you're in the wrong mode, you might be able to",@/
21167 "return to the right one by typing `I}' or `I$' or `I\\par'.");@/
21168 error();
21169 }
21170
21171 @ Some operations are allowed only in privileged modes, i.e., in cases
21172 that |mode > 0|. The |privileged| function is used to detect violations
21173 of this rule; it issues an error message and returns |false| if the
21174 current |mode| is negative.
21175
21176 @<Declare act...@>=
21177 static bool privileged(void)
21178 {@+if (mode > 0) return true;
21179 else{@+report_illegal_case();return false;
21180 }
21181 }
21182
21183 @ Either \.{\\dump} or \.{\\end} will cause |main_control| to enter the
21184 endgame, since both of them have `|stop|' as their command code.
21185
21186 @<Put each...@>=
21187 primitive("end", stop, 0);@/
21188 @!@:end\_}{\.{\\end} primitive@>
21189 primitive("dump", stop, 1);@/
21190 @!@:dump\_}{\.{\\dump} primitive@>
21191
21192 @ @<Cases of |print_cmd_chr|...@>=
21193 case stop: if (chr_code==1) print_esc("dump");@+else print_esc("end");@+break;
21194
21195 @ We don't want to leave |main_control| immediately when a |stop| command
21196 is sensed, because it may be necessary to invoke an \.{\\output} routine
21197 several times before things really grind to a halt. (The output routine
21198 might even say `\.{\\gdef\\end\{...\}}', to prolong the life of the job.)
21199 Therefore |its_all_over| is |true| only when the current page
21200 and contribution list are empty, and when the last output was not a
21201 ``dead cycle.''
21202
21203 @<Declare act...@>=
21204 static bool its_all_over(void) /*do this when \.{\\end} or \.{\\dump} occurs*/
21205 {@+
21206 if (privileged())
21207 {@+if ((page_head==page_tail)&&(head==tail)&&(dead_cycles==0))
21208 {@+return true;
21209 }
21210 back_input(); /*we will try to end again after ejecting residual material*/
21211 tail_append(new_null_box());
21212 width(tail)=hsize;
21213 tail_append(new_glue(fill_glue));
21214 tail_append(new_penalty(-010000000000));@/
21215 build_page(); /*append \.{\\hbox to \\hsize\{\}\\vfill\\penalty-'10000000000}*/
21216 }
21217 return false;
21218 }
21219
21220 @* Building boxes and lists.
21221 The most important parts of |main_control| are concerned with \TeX's
21222 chief mission of box-making. We need to control the activities that put
21223 entries on vlists and hlists, as well as the activities that convert
21224 those lists into boxes. All of the necessary machinery has already been
21225 developed; it remains for us to ``push the buttons'' at the right times.
21226
21227 @ As an introduction to these routines, let's consider one of the simplest
21228 cases: What happens when `\.{\\hrule}' occurs in vertical mode, or
21229 `\.{\\vrule}' in horizontal mode or math mode? The code in |main_control|
21230 is short, since the |scan_rule_spec| routine already does most of what is
21231 required; thus, there is no need for a special action procedure.
21232
21233 Note that baselineskip calculations are disabled after a rule in vertical
21234 mode, by setting |prev_depth=ignore_depth|.
21235
21236 @<Cases of |main_control| that build...@>=
21237 case vmode+hrule: case hmode+vrule: case mmode+vrule: {@+tail_append(scan_rule_spec());
21238 if (abs(mode)==vmode) prev_depth=ignore_depth;
21239 else if (abs(mode)==hmode) space_factor=1000;
21240 } @+break;
21241
21242 @ The processing of things like \.{\\hskip} and \.{\\vskip} is slightly
21243 more complicated. But the code in |main_control| is very short, since
21244 it simply calls on the action routine |append_glue|. Similarly, \.{\\kern}
21245 activates |append_kern|.
21246
21247 @<Cases of |main_control| that build...@>=
21248 case vmode+vskip: case hmode+hskip: case mmode+hskip:
21249 case mmode+mskip: append_glue();@+break;
21250 any_mode(kern): case mmode+mkern: append_kern();@+break;
21251
21252 @ The |hskip| and |vskip| command codes are used for control sequences
21253 like \.{\\hss} and \.{\\vfil} as well as for \.{\\hskip} and \.{\\vskip}.
21254 The difference is in the value of |cur_chr|.
21255
21256 @d fil_code 0 /*identifies \.{\\hfil} and \.{\\vfil}*/
21257 @d fill_code 1 /*identifies \.{\\hfill} and \.{\\vfill}*/
21258 @d ss_code 2 /*identifies \.{\\hss} and \.{\\vss}*/
21259 @d fil_neg_code 3 /*identifies \.{\\hfilneg} and \.{\\vfilneg}*/
21260 @d skip_code 4 /*identifies \.{\\hskip} and \.{\\vskip}*/
21261 @d mskip_code 5 /*identifies \.{\\mskip}*/
21262
21263 @<Put each...@>=
21264 primitive("hskip", hskip, skip_code);@/
21265 @!@:hskip\_}{\.{\\hskip} primitive@>
21266 primitive("hfil", hskip, fil_code);
21267 @!@:hfil\_}{\.{\\hfil} primitive@>
21268 primitive("hfill", hskip, fill_code);@/
21269 @!@:hfill\_}{\.{\\hfill} primitive@>
21270 primitive("hss", hskip, ss_code);
21271 @!@:hss\_}{\.{\\hss} primitive@>
21272 primitive("hfilneg", hskip, fil_neg_code);@/
21273 @!@:hfil\_neg\_}{\.{\\hfilneg} primitive@>
21274 primitive("vskip", vskip, skip_code);@/
21275 @!@:vskip\_}{\.{\\vskip} primitive@>
21276 primitive("vfil", vskip, fil_code);
21277 @!@:vfil\_}{\.{\\vfil} primitive@>
21278 primitive("vfill", vskip, fill_code);@/
21279 @!@:vfill\_}{\.{\\vfill} primitive@>
21280 primitive("vss", vskip, ss_code);
21281 @!@:vss\_}{\.{\\vss} primitive@>
21282 primitive("vfilneg", vskip, fil_neg_code);@/
21283 @!@:vfil\_neg\_}{\.{\\vfilneg} primitive@>
21284 primitive("mskip", mskip, mskip_code);@/
21285 @!@:mskip\_}{\.{\\mskip} primitive@>
21286 primitive("kern", kern, explicit);
21287 @!@:kern\_}{\.{\\kern} primitive@>
21288 primitive("mkern", mkern, mu_glue);@/
21289 @!@:mkern\_}{\.{\\mkern} primitive@>
21290
21291 @ @<Cases of |print_cmd_chr|...@>=
21292 case hskip: switch (chr_code) {
21293 case skip_code: print_esc("hskip");@+break;
21294 case fil_code: print_esc("hfil");@+break;
21295 case fill_code: print_esc("hfill");@+break;
21296 case ss_code: print_esc("hss");@+break;
21297 default:print_esc("hfilneg");
21298 } @+break;
21299 case vskip: switch (chr_code) {
21300 case skip_code: print_esc("vskip");@+break;
21301 case fil_code: print_esc("vfil");@+break;
21302 case fill_code: print_esc("vfill");@+break;
21303 case ss_code: print_esc("vss");@+break;
21304 default:print_esc("vfilneg");
21305 } @+break;
21306 case mskip: print_esc("mskip");@+break;
21307 case kern: print_esc("kern");@+break;
21308 case mkern: print_esc("mkern");@+break;
21309
21310 @ All the work relating to glue creation has been relegated to the
21311 following subroutine. It does not call |build_page|, because it is
21312 used in at least one place where that would be a mistake.
21313
21314 @<Declare action...@>=
21315 static void append_glue(void)
21316 {@+small_number s; /*modifier of skip command*/
21317 s=cur_chr;
21318 switch (s) {
21319 case fil_code: cur_val=fil_glue;@+break;
21320 case fill_code: cur_val=fill_glue;@+break;
21321 case ss_code: cur_val=ss_glue;@+break;
21322 case fil_neg_code: cur_val=fil_neg_glue;@+break;
21323 case skip_code: scan_glue(glue_val);@+break;
21324 case mskip_code: scan_glue(mu_val);
21325 } /*now |cur_val| points to the glue specification*/
21326 tail_append(new_glue(cur_val));
21327 if (s >= skip_code)
21328 {@+decr(glue_ref_count(cur_val));
21329 if (s > skip_code) subtype(tail)=mu_glue;
21330 }
21331 }
21332
21333 @ @<Declare act...@>=
21334 static void append_kern(void)
21335 {@+quarterword s; /*|subtype| of the kern node*/
21336 s=cur_chr;scan_dimen(s==mu_glue, false, false);
21337 tail_append(new_kern(cur_val));subtype(tail)=s;
21338 }
21339
21340 @ Many of the actions related to box-making are triggered by the appearance
21341 of braces in the input. For example, when the user says `\.{\\hbox}
21342 \.{to} \.{100pt\{$\langle\,\hbox{\rm hlist}\,\rangle$\}}' in vertical mode,
21343 the information about the box size (100pt, |exactly|) is put onto |save_stack|
21344 with a level boundary word just above it, and |cur_group=adjusted_hbox_group|;
21345 \TeX\ enters restricted horizontal mode to process the hlist. The right
21346 brace eventually causes |save_stack| to be restored to its former state,
21347 at which time the information about the box size (100pt, |exactly|) is
21348 available once again; a box is packaged and we leave restricted horizontal
21349 mode, appending the new box to the current list of the enclosing mode
21350 (in this case to the current list of vertical mode), followed by any
21351 vertical adjustments that were removed from the box by |hpack|.
21352
21353 The next few sections of the program are therefore concerned with the
21354 treatment of left and right curly braces.
21355
21356 @ If a left brace occurs in the middle of a page or paragraph, it simply
21357 introduces a new level of grouping, and the matching right brace will not have
21358 such a drastic effect. Such grouping affects neither the mode nor the
21359 current list.
21360
21361 @<Cases of |main_control| that build...@>=
21362 non_math(left_brace): new_save_level(simple_group);@+break;
21363 any_mode(begin_group): new_save_level(semi_simple_group);@+break;
21364 any_mode(end_group): if (cur_group==semi_simple_group) unsave();
21365 else off_save();@+break;
21366
21367 @ We have to deal with errors in which braces and such things are not
21368 properly nested. Sometimes the user makes an error of commission by
21369 inserting an extra symbol, but sometimes the user makes an error of omission.
21370 \TeX\ can't always tell one from the other, so it makes a guess and tries
21371 to avoid getting into a loop.
21372
21373 The |off_save| routine is called when the current group code is wrong. It tries
21374 to insert something into the user's input that will help clean off
21375 the top level.
21376
21377 @<Declare act...@>=
21378 static void off_save(void)
21379 {@+pointer p; /*inserted token*/
21380 if (cur_group==bottom_level)
21381 @<Drop current token and complain that it was unmatched@>@;
21382 else{@+back_input();p=get_avail();link(temp_head)=p;
21383 print_err("Missing ");
21384 @<Prepare to insert a token that matches |cur_group|, and print what it
21385 is@>;
21386 print(" inserted");ins_list(link(temp_head));
21387 help5("I've inserted something that you may have forgotten.",@/
21388 "(See the <inserted text> above.)",@/
21389 "With luck, this will get me unwedged. But if you",@/
21390 "really didn't forget anything, try typing `2' now; then",@/
21391 "my insertion and my current dilemma will both disappear.");
21392 error();
21393 }
21394 }
21395
21396 @ At this point, |link(temp_head)==p|, a pointer to an empty one-word node.
21397
21398 @<Prepare to insert a token that matches |cur_group|...@>=
21399 switch (cur_group) {
21400 case semi_simple_group: {@+info(p)=cs_token_flag+frozen_end_group;
21401 print_esc("endgroup");
21402 @.Missing \\endgroup inserted@>
21403 } @+break;
21404 case math_shift_group: {@+info(p)=math_shift_token+'$';print_char('$');
21405 @.Missing \$ inserted@>
21406 } @+break;
21407 case math_left_group: {@+info(p)=cs_token_flag+frozen_right;link(p)=get_avail();
21408 p=link(p);info(p)=other_token+'.';print_esc("right.");
21409 @.Missing \\right\hbox{.} inserted@>
21410 @^null delimiter@>
21411 } @+break;
21412 default:{@+info(p)=right_brace_token+'}';print_char('}');
21413 @.Missing \} inserted@>
21414 }
21415 }
21416
21417 @ @<Drop current token and complain that it was unmatched@>=
21418 {@+print_err("Extra ");print_cmd_chr(cur_cmd, cur_chr);
21419 @.Extra x@>
21420 help1("Things are pretty mixed up, but I think the worst is over.");@/
21421 error();
21422 }
21423
21424 @ The routine for a |right_brace| character branches into many subcases,
21425 since a variety of things may happen, depending on |cur_group|. Some
21426 types of groups are not supposed to be ended by a right brace; error
21427 messages are given in hopes of pinpointing the problem. Most branches
21428 of this routine will be filled in later, when we are ready to understand
21429 them; meanwhile, we must prepare ourselves to deal with such errors.
21430
21431 @<Cases of |main_control| that build...@>=
21432 any_mode(right_brace): handle_right_brace();@+break;
21433
21434 @ @<Declare the procedure called |handle_right_brace|@>=
21435 static void handle_right_brace(void)
21436 {@+pointer p, @!q; /*for short-term use*/
21437 scaled @!d; /*holds |split_max_depth| in |insert_group|*/
21438 int @!f; /*holds |floating_penalty| in |insert_group|*/
21439 switch (cur_group) {
21440 case simple_group: unsave();@+break;
21441 case bottom_level: {@+print_err("Too many }'s");
21442 @.Too many \}'s@>
21443 help2("You've closed more groups than you opened.",@/
21444 "Such booboos are generally harmless, so keep going.");error();
21445 } @+break;
21446 case semi_simple_group: case math_shift_group:
21447 case math_left_group: extra_right_brace();@+break;
21448 @t\4@>@<Cases of |handle_right_brace| where a |right_brace| triggers a delayed
21449 action@>@;
21450 default:confusion("rightbrace");
21451 @:this can't happen rightbrace}{\quad rightbrace@>
21452 }
21453 }
21454
21455 @ @<Declare act...@>=
21456 static void extra_right_brace(void)
21457 {@+print_err("Extra }, or forgotten ");
21458 @.Extra \}, or forgotten x@>
21459 switch (cur_group) {
21460 case semi_simple_group: print_esc("endgroup");@+break;
21461 case math_shift_group: print_char('$');@+break;
21462 case math_left_group: print_esc("right");
21463 } @/
21464 help5("I've deleted a group-closing symbol because it seems to be",@/
21465 "spurious, as in `$x}$'. But perhaps the } is legitimate and",@/
21466 "you forgot something else, as in `\\hbox{$x}'. In such cases",@/
21467 "the way to recover is to insert both the forgotten and the",@/
21468 "deleted material, e.g., by typing `I$}'.");error();
21469 incr(align_state);
21470 }
21471
21472 @ Here is where we clear the parameters that are supposed to revert to their
21473 default values after every paragraph and when internal vertical mode is entered.
21474
21475 @<Declare act...@>=
21476 static void normal_paragraph(void)
21477 {@+if (looseness!=0) eq_word_define(int_base+looseness_code, 0);
21478 if (hang_indent!=0) eq_word_define(dimen_base+hang_indent_code, 0);
21479 if (hang_after!=1) eq_word_define(int_base+hang_after_code, 1);
21480 if (par_shape_ptr!=null) eq_define(par_shape_loc, shape_ref, null);
21481 if (inter_line_penalties_ptr!=null)
21482 eq_define(inter_line_penalties_loc, shape_ref, null);
21483 }
21484
21485 @ Now let's turn to the question of how \.{\\hbox} is treated. We actually
21486 need to consider also a slightly larger context, since constructions like
21487 `\.{\\setbox3=}\penalty0\.{\\hbox...}' and
21488 `\.{\\leaders}\penalty0\.{\\hbox...}' and
21489 `\.{\\lower3.8pt\\hbox...}'
21490 are supposed to invoke quite
21491 different actions after the box has been packaged. Conversely,
21492 constructions like `\.{\\setbox3=}' can be followed by a variety of
21493 different kinds of boxes, and we would like to encode such things in an
21494 efficient way.
21495
21496 In other words, there are two problems: to represent the context of a box,
21497 and to represent its type.
21498
21499 The first problem is solved by putting a ``context code'' on the |save_stack|,
21500 just below the two entries that give the dimensions produced by |scan_spec|.
21501 The context code is either a (signed) shift amount, or it is a large
21502 integer | >= box_flag|, where |box_flag==@t$2^{30}$@>|. Codes |box_flag| through
21503 |global_box_flag-1| represent `\.{\\setbox0}' through `\.{\\setbox32767}';
21504 codes |global_box_flag| through |ship_out_flag-1| represent
21505 `\.{\\global\\setbox0}' through `\.{\\global\\setbox32767}';
21506 code |ship_out_flag| represents `\.{\\shipout}'; and codes |leader_flag|
21507 through |leader_flag+2| represent `\.{\\leaders}', `\.{\\cleaders}',
21508 and `\.{\\xleaders}'.
21509
21510 The second problem is solved by giving the command code |make_box| to all
21511 control sequences that produce a box, and by using the following |chr_code|
21512 values to distinguish between them: |box_code|, |copy_code|, |last_box_code|,
21513 |vsplit_code|, |vtop_code|, |vtop_code+vmode|, and |vtop_code+hmode|, where
21514 the latter two are used to denote \.{\\vbox} and \.{\\hbox}, respectively.
21515
21516 @d box_flag 010000000000 /*context code for `\.{\\setbox0}'*/
21517 @d global_box_flag 010000100000 /*context code for `\.{\\global\\setbox0}'*/
21518 @d ship_out_flag 010000200000 /*context code for `\.{\\shipout}'*/
21519 @d leader_flag 010000200001 /*context code for `\.{\\leaders}'*/
21520 @d box_code 0 /*|chr_code| for `\.{\\box}'*/
21521 @d copy_code 1 /*|chr_code| for `\.{\\copy}'*/
21522 @d last_box_code 2 /*|chr_code| for `\.{\\lastbox}'*/
21523 @d vsplit_code 3 /*|chr_code| for `\.{\\vsplit}'*/
21524 @d vtop_code 4 /*|chr_code| for `\.{\\vtop}'*/
21525
21526 @<Put each...@>=
21527 primitive("moveleft", hmove, 1);
21528 @!@:move\_left\_}{\.{\\moveleft} primitive@>
21529 primitive("moveright", hmove, 0);@/
21530 @!@:move\_right\_}{\.{\\moveright} primitive@>
21531 primitive("raise", vmove, 1);
21532 @!@:raise\_}{\.{\\raise} primitive@>
21533 primitive("lower", vmove, 0);
21534 @!@:lower\_}{\.{\\lower} primitive@>
21535 @#
21536 primitive("box", make_box, box_code);
21537 @!@:box\_}{\.{\\box} primitive@>
21538 primitive("copy", make_box, copy_code);
21539 @!@:copy\_}{\.{\\copy} primitive@>
21540 primitive("lastbox", make_box, last_box_code);
21541 @!@:last\_box\_}{\.{\\lastbox} primitive@>
21542 primitive("vsplit", make_box, vsplit_code);
21543 @!@:vsplit\_}{\.{\\vsplit} primitive@>
21544 primitive("vtop", make_box, vtop_code);@/
21545 @!@:vtop\_}{\.{\\vtop} primitive@>
21546 primitive("vbox", make_box, vtop_code+vmode);
21547 @!@:vbox\_}{\.{\\vbox} primitive@>
21548 primitive("hbox", make_box, vtop_code+hmode);@/
21549 @!@:hbox\_}{\.{\\hbox} primitive@>
21550 primitive("shipout", leader_ship, a_leaders-1); /*|ship_out_flag==leader_flag-1|*/
21551 @!@:ship\_out\_}{\.{\\shipout} primitive@>
21552 primitive("leaders", leader_ship, a_leaders);
21553 @!@:leaders\_}{\.{\\leaders} primitive@>
21554 primitive("cleaders", leader_ship, c_leaders);
21555 @!@:c\_leaders\_}{\.{\\cleaders} primitive@>
21556 primitive("xleaders", leader_ship, x_leaders);
21557 @!@:x\_leaders\_}{\.{\\xleaders} primitive@>
21558
21559 @ @<Cases of |print_cmd_chr|...@>=
21560 case hmove: if (chr_code==1) print_esc("moveleft");@+else print_esc("moveright");@+break;
21561 case vmove: if (chr_code==1) print_esc("raise");@+else print_esc("lower");@+break;
21562 case make_box: switch (chr_code) {
21563 case box_code: print_esc("box");@+break;
21564 case copy_code: print_esc("copy");@+break;
21565 case last_box_code: print_esc("lastbox");@+break;
21566 case vsplit_code: print_esc("vsplit");@+break;
21567 case vtop_code: print_esc("vtop");@+break;
21568 case vtop_code+vmode: print_esc("vbox");@+break;
21569 default:print_esc("hbox");
21570 } @+break;
21571 case leader_ship: if (chr_code==a_leaders) print_esc("leaders");
21572 else if (chr_code==c_leaders) print_esc("cleaders");
21573 else if (chr_code==x_leaders) print_esc("xleaders");
21574 else print_esc("shipout");@+break;
21575
21576 @ Constructions that require a box are started by calling |scan_box| with
21577 a specified context code. The |scan_box| routine verifies
21578 that a |make_box| command comes next and then it calls |begin_box|.
21579
21580 @<Cases of |main_control| that build...@>=
21581 case vmode+hmove: case hmode+vmove: case mmode+vmove: {@+t=cur_chr;
21582 scan_normal_dimen;
21583 if (t==0) scan_box(cur_val);@+else scan_box(-cur_val);
21584 } @+break;
21585 any_mode(leader_ship): scan_box(leader_flag-a_leaders+cur_chr);@+break;
21586 any_mode(make_box): begin_box(0);@+break;
21587
21588 @ The global variable |cur_box| will point to a newly made box. If the box
21589 is void, we will have |cur_box==null|. Otherwise we will have
21590 |type(cur_box)==hlist_node| or |vlist_node| or |rule_node|; the |rule_node|
21591 case can occur only with leaders.
21592
21593 @<Glob...@>=
21594 static pointer @!cur_box; /*box to be placed into its context*/
21595
21596 @ The |box_end| procedure does the right thing with |cur_box|, if
21597 |box_context| represents the context as explained above.
21598
21599 @<Declare act...@>=
21600 static void box_end(int @!box_context)
21601 {@+pointer p; /*|ord_noad| for new box in math mode*/
21602 small_number @!a; /*global prefix*/
21603 if (box_context < box_flag) @<Append box |cur_box| to the current list, shifted
21604 by |box_context|@>@;
21605 else if (box_context < ship_out_flag) @<Store \(c)|cur_box| in a box register@>@;
21606 else if (cur_box!=null)
21607 if (box_context > ship_out_flag) @<Append a new leader node that uses |cur_box|@>@;
21608 else ship_out(cur_box);
21609 }
21610
21611 @ The global variable |adjust_tail| will be non-null if and only if the
21612 current box might include adjustments that should be appended to the
21613 current vertical list.
21614
21615 @<Append box |cur_box| to the current...@>=
21616 {@+if (cur_box!=null)
21617 {@+shift_amount(cur_box)=box_context;
21618 if (abs(mode)==vmode)
21619 {@+append_to_vlist(cur_box);
21620 if (adjust_tail!=null)
21621 {@+if (adjust_head!=adjust_tail)
21622 {@+link(tail)=link(adjust_head);tail=adjust_tail;
21623 }
21624 adjust_tail=null;
21625 }
21626 if (mode > 0) build_page();
21627 }
21628 else{@+if (abs(mode)==hmode) space_factor=1000;
21629 else{@+p=new_noad();
21630 math_type(nucleus(p))=sub_box;
21631 info(nucleus(p))=cur_box;cur_box=p;
21632 }
21633 link(tail)=cur_box;tail=cur_box;
21634 }
21635 }
21636 }
21637
21638 @ @<Store \(c)|cur_box| in a box register@>=
21639 {@+if (box_context < global_box_flag)
21640 {@+cur_val=box_context-box_flag;a=0;
21641 }
21642 else{@+cur_val=box_context-global_box_flag;a=4;
21643 }
21644 if (cur_val < 256) define(box_base+cur_val, box_ref, cur_box);
21645 else sa_def_box;
21646 }
21647
21648 @ @<Append a new leader node...@>=
21649 {@+@<Get the next non-blank non-relax...@>;
21650 if (((cur_cmd==hskip)&&(abs(mode)!=vmode))||@|
21651 ((cur_cmd==vskip)&&(abs(mode)==vmode)))
21652 {@+append_glue();subtype(tail)=box_context-(leader_flag-a_leaders);
21653 leader_ptr(tail)=cur_box;
21654 }
21655 else{@+print_err("Leaders not followed by proper glue");
21656 @.Leaders not followed by...@>
21657 help3("You should say `\\leaders <box or rule><hskip or vskip>'.",@/
21658 "I found the <box or rule>, but there's no suitable",@/
21659 "<hskip or vskip>, so I'm ignoring these leaders.");back_error();
21660 flush_node_list(cur_box);
21661 }
21662 }
21663
21664 @ Now that we can see what eventually happens to boxes, we can consider
21665 the first steps in their creation. The |begin_box| routine is called when
21666 |box_context| is a context specification, |cur_chr| specifies the type of
21667 box desired, and |cur_cmd==make_box|.
21668
21669 @<Declare act...@>=
21670 static void begin_box(int @!box_context)
21671 {@+
21672 pointer @!p, @!q; /*run through the current list*/
21673 int @!m; /*the length of a replacement list*/
21674 halfword @!k; /*0 or |vmode| or |hmode|*/
21675 halfword @!n; /*a box number*/
21676 switch (cur_chr) {
21677 case box_code: {@+scan_register_num();fetch_box(cur_box);
21678 change_box(null); /*the box becomes void, at the same level*/
21679 } @+break;
21680 case copy_code: {@+scan_register_num();fetch_box(q);cur_box=copy_node_list(q);
21681 } @+break;
21682 case last_box_code: @<If the current list ends with a box node, delete it
21683 from the list and make |cur_box| point to it; otherwise set |cur_box:=null|@>@;@+break;
21684 case vsplit_code: @<Split off part of a vertical box, make |cur_box| point
21685 to it@>@;@+break;
21686 default:@<Initiate the construction of an hbox or vbox, then |return|@>@;
21687 } @/
21688 box_end(box_context); /*in simple cases, we use the box immediately*/
21689 }
21690
21691 @ Note that the condition |!is_char_node(tail)| implies that |head!=tail|,
21692 since |head| is a one-word node.
21693
21694 @<If the current list ends with a box node, delete it...@>=
21695 {@+cur_box=null;
21696 if (abs(mode)==mmode)
21697 {@+you_cant();help1("Sorry; this \\lastbox will be void.");error();
21698 }
21699 else if ((mode==vmode)&&(head==tail))
21700 {@+you_cant();
21701 help2("Sorry...I usually can't take things from the current page.",@/
21702 "This \\lastbox will therefore be void.");error();
21703 }
21704 else{@+if (!is_char_node(tail))
21705 if ((type(tail)==hlist_node)||(type(tail)==vlist_node))
21706 @<Remove the last box, unless it's part of a discretionary@>;
21707 }
21708 }
21709
21710 @ @<Remove the last box...@>=
21711 {@+q=head;
21712 @/do@+{p=q;
21713 if (!is_char_node(q)) if (type(q)==disc_node)
21714 {@+for (m=1; m<=replace_count(q); m++) p=link(p);
21715 if (p==tail) goto done;
21716 }
21717 q=link(p);
21718 }@+ while (!(q==tail));
21719 cur_box=tail;shift_amount(cur_box)=0;
21720 tail=p;link(p)=null;
21721 done: ;}
21722
21723 @ Here we deal with things like `\.{\\vsplit 13 to 100pt}'.
21724
21725 @<Split off part of a vertical box, make |cur_box| point to it@>=
21726 {@+scan_register_num();n=cur_val;
21727 if (!scan_keyword("to"))
21728 @.to@>
21729 {@+print_err("Missing `to' inserted");
21730 @.Missing `to' inserted@>
21731 help2("I'm working on `\\vsplit<box number> to <dimen>';",@/
21732 "will look for the <dimen> next.");error();
21733 }
21734 scan_normal_dimen;
21735 cur_box=vsplit(n, cur_val);
21736 }
21737
21738 @ Here is where we enter restricted horizontal mode or internal vertical
21739 mode, in order to make a box.
21740
21741 @<Initiate the construction of an hbox or vbox, then |return|@>=
21742 {@+k=cur_chr-vtop_code;saved(0)=box_context;
21743 if (k==hmode)
21744 if ((box_context < box_flag)&&(abs(mode)==vmode))
21745 scan_spec(adjusted_hbox_group, true);
21746 else scan_spec(hbox_group, true);
21747 else{@+if (k==vmode) scan_spec(vbox_group, true);
21748 else{@+scan_spec(vtop_group, true);k=vmode;
21749 }
21750 normal_paragraph();
21751 }
21752 push_nest();mode=-k;
21753 if (k==vmode)
21754 {@+prev_depth=ignore_depth;
21755 if (every_vbox!=null) begin_token_list(every_vbox, every_vbox_text);
21756 }
21757 else{@+space_factor=1000;
21758 if (every_hbox!=null) begin_token_list(every_hbox, every_hbox_text);
21759 }
21760 return;
21761 }
21762
21763 @ @<Declare act...@>=
21764 static void scan_box(int @!box_context)
21765 /*the next input should specify a box or perhaps a rule*/
21766 {@+@<Get the next non-blank non-relax...@>;
21767 if (cur_cmd==make_box) begin_box(box_context);
21768 else if ((box_context >= leader_flag)&&((cur_cmd==hrule)||(cur_cmd==vrule)))
21769 {@+cur_box=scan_rule_spec();box_end(box_context);
21770 }
21771 else{@+@t@>@;@/
21772 print_err("A <box> was supposed to be here");@/
21773 @.A <box> was supposed to...@>
21774 help3("I was expecting to see \\hbox or \\vbox or \\copy or \\box or",@/
21775 "something like that. So you might find something missing in",@/
21776 "your output. But keep trying; you can fix this later.");back_error();
21777 }
21778 }
21779
21780 @ When the right brace occurs at the end of an \.{\\hbox} or \.{\\vbox} or
21781 \.{\\vtop} construction, the |package| routine comes into action. We might
21782 also have to finish a paragraph that hasn't ended.
21783
21784 @<Cases of |handle...@>=
21785 case hbox_group: package(0);@+break;
21786 case adjusted_hbox_group: {@+adjust_tail=adjust_head;package(0);
21787 } @+break;
21788 case vbox_group: {@+end_graf();package(0);
21789 } @+break;
21790 case vtop_group: {@+end_graf();package(vtop_code);
21791 } @+break;
21792
21793 @ @<Declare action...@>=
21794 static void package(small_number @!c)
21795 {@+scaled h; /*height of box*/
21796 pointer @!p; /*first node in a box*/
21797 scaled @!d; /*max depth*/
21798 d=box_max_depth;unsave();save_ptr=save_ptr-3;
21799 if (mode==-hmode) cur_box=hpack(link(head), saved(2), saved(1));
21800 else{@+cur_box=vpackage(link(head), saved(2), saved(1), d);
21801 if (c==vtop_code) @<Readjust the height and depth of |cur_box|, for \.{\\vtop}@>;
21802 }
21803 pop_nest();box_end(saved(0));
21804 }
21805
21806 @ The height of a `\.{\\vtop}' box is inherited from the first item on its list,
21807 if that item is an |hlist_node|, |vlist_node|, or |rule_node|; otherwise
21808 the \.{\\vtop} height is zero.
21809
21810
21811 @<Readjust the height...@>=
21812 {@+h=0;p=list_ptr(cur_box);
21813 if (p!=null) if (type(p) <= rule_node) h=height(p);
21814 depth(cur_box)=depth(cur_box)-h+height(cur_box);height(cur_box)=h;
21815 }
21816
21817 @ A paragraph begins when horizontal-mode material occurs in vertical mode,
21818 or when the paragraph is explicitly started by `\.{\\indent}' or
21819 `\.{\\noindent}'.
21820
21821 @<Put each...@>=
21822 primitive("indent", start_par, 1);
21823 @!@:indent\_}{\.{\\indent} primitive@>
21824 primitive("noindent", start_par, 0);
21825 @!@:no\_indent\_}{\.{\\noindent} primitive@>
21826
21827 @ @<Cases of |print_cmd_chr|...@>=
21828 case start_par: if (chr_code==0) print_esc("noindent");@+else print_esc("indent");@+break;
21829
21830 @ @<Cases of |main_control| that build...@>=
21831 case vmode+start_par: new_graf(cur_chr > 0);@+break;
21832 case vmode+letter: case vmode+other_char:
21833 case vmode+char_num: case vmode+char_given:
21834 case vmode+math_shift: case vmode+un_hbox:
21835 case vmode+vrule:
21836 case vmode+accent: case vmode+discretionary:
21837 case vmode+hskip: case vmode+valign:
21838 case vmode+ex_space: case vmode+no_boundary: @t@>@;@/
21839 {@+back_input();new_graf(true);
21840 } @+break;
21841
21842 @ @<Declare act...@>=
21843 static small_number norm_min(int @!h)
21844 {@+if (h <= 0) return 1;@+else if (h >= 63) return 63;@+
21845 else return h;
21846 }
21847 @#
21848 static void new_graf(bool @!indented)
21849 {@+prev_graf=0;
21850 if ((mode==vmode)||(head!=tail))
21851 tail_append(new_param_glue(par_skip_code));
21852 push_nest();mode=hmode;space_factor=1000;set_cur_lang;clang=cur_lang;
21853 prev_graf=(norm_min(left_hyphen_min)*0100+norm_min(right_hyphen_min))
21854 *0200000+cur_lang;
21855 if (indented)
21856 {@+tail=new_null_box();link(head)=tail;width(tail)=par_indent;@+
21857 }
21858 if (every_par!=null) begin_token_list(every_par, every_par_text);
21859 if (nest_ptr==1) build_page(); /*put |par_skip| glue on current page*/
21860 }
21861
21862 @ @<Cases of |main_control| that build...@>=
21863 case hmode+start_par: case mmode+start_par: indent_in_hmode();@+break;
21864
21865 @ @<Declare act...@>=
21866 static void indent_in_hmode(void)
21867 {@+pointer p, @!q;
21868 if (cur_chr > 0) /*\.{\\indent}*/
21869 {@+p=new_null_box();width(p)=par_indent;
21870 if (abs(mode)==hmode) space_factor=1000;
21871 else{@+q=new_noad();math_type(nucleus(q))=sub_box;
21872 info(nucleus(q))=p;p=q;
21873 }
21874 tail_append(p);
21875 }
21876 }
21877
21878 @ A paragraph ends when a |par_end| command is sensed, or when we are in
21879 horizontal mode when reaching the right brace of vertical-mode routines
21880 like \.{\\vbox}, \.{\\insert}, or \.{\\output}.
21881
21882 @<Cases of |main_control| that build...@>=
21883 case vmode+par_end: {@+normal_paragraph();
21884 if (mode > 0) build_page();
21885 } @+break;
21886 case hmode+par_end: {@+if (align_state < 0) off_save(); /*this tries to
21887 recover from an alignment that didn't end properly*/
21888 end_graf(); /*this takes us to the enclosing mode, if |mode > 0|*/
21889 if (mode==vmode) build_page();
21890 } @+break;
21891 case hmode+stop: case hmode+vskip: case hmode+hrule:
21892 case hmode+un_vbox: case hmode+halign: head_for_vmode();@+break;
21893
21894 @ @<Declare act...@>=
21895 static void head_for_vmode(void)
21896 {@+if (mode < 0)
21897 if (cur_cmd!=hrule) off_save();
21898 else{@+print_err("You can't use `");
21899 print_esc("hrule");print("' here except with leaders");
21900 @.You can't use \\hrule...@>
21901 help2("To put a horizontal rule in an hbox or an alignment,",@/
21902 "you should use \\leaders or \\hrulefill (see The TeXbook).");
21903 error();
21904 }
21905 else{@+back_input();cur_tok=par_token;back_input();token_type=inserted;
21906 }
21907 }
21908
21909 @ @<Declare act...@>=
21910 static void end_graf(void)
21911 {@+if (mode==hmode)
21912 {@+if (head==tail) pop_nest(); /*null paragraphs are ignored*/
21913 else line_break(widow_penalty);
21914 normal_paragraph();
21915 error_count=0;
21916 }
21917 }
21918
21919 @ Insertion and adjustment and mark nodes are constructed by the following
21920 pieces of the program.
21921
21922 @<Cases of |main_control| that build...@>=
21923 any_mode(insert): case hmode+vadjust:
21924 case mmode+vadjust: begin_insert_or_adjust();@+break;
21925 any_mode(mark): make_mark();@+break;
21926
21927 @ @<Forbidden...@>=
21928 case vmode+vadjust:
21929
21930 @ @<Declare act...@>=
21931 static void begin_insert_or_adjust(void)
21932 {@+if (cur_cmd==vadjust) cur_val=255;
21933 else{@+scan_eight_bit_int();
21934 if (cur_val==255)
21935 {@+print_err("You can't ");print_esc("insert");print_int(255);
21936 @.You can't \\insert255@>
21937 help1("I'm changing to \\insert0; box 255 is special.");
21938 error();cur_val=0;
21939 }
21940 }
21941 saved(0)=cur_val;incr(save_ptr);
21942 new_save_level(insert_group);scan_left_brace();normal_paragraph();
21943 push_nest();mode=-vmode;prev_depth=ignore_depth;
21944 }
21945
21946 @ @<Cases of |handle...@>=
21947 case insert_group: {@+end_graf();q=split_top_skip;add_glue_ref(q);
21948 d=split_max_depth;f=floating_penalty;unsave();decr(save_ptr);
21949 /*now |saved(0)| is the insertion number, or 255 for |vadjust|*/
21950 p=vpack(link(head), natural);pop_nest();
21951 if (saved(0) < 255)
21952 {@+tail_append(get_node(ins_node_size));
21953 type(tail)=ins_node;subtype(tail)=qi(saved(0));
21954 height(tail)=height(p)+depth(p);ins_ptr(tail)=list_ptr(p);
21955 split_top_ptr(tail)=q;depth(tail)=d;float_cost(tail)=f;
21956 }
21957 else{@+tail_append(get_node(small_node_size));
21958 type(tail)=adjust_node;@/
21959 subtype(tail)=0; /*the |subtype| is not used*/
21960 adjust_ptr(tail)=list_ptr(p);delete_glue_ref(q);
21961 }
21962 free_node(p, box_node_size);
21963 if (nest_ptr==0) build_page();
21964 } @+break;
21965 case output_group: @<Resume the page builder...@>@;@+break;
21966
21967 @ @<Declare act...@>=
21968 static void make_mark(void)
21969 {@+pointer p; /*new node*/
21970 halfword @!c; /*the mark class*/
21971 if (cur_chr==0) c=0;
21972 else{@+scan_register_num();c=cur_val;
21973 }
21974 p=scan_toks(false, true);p=get_node(small_node_size);
21975 mark_class(p)=c;
21976 type(p)=mark_node;subtype(p)=0; /*the |subtype| is not used*/
21977 mark_ptr(p)=def_ref;link(tail)=p;tail=p;
21978 }
21979
21980 @ Penalty nodes get into a list via the |break_penalty| command.
21981 @^penalties@>
21982
21983 @<Cases of |main_control| that build...@>=
21984 any_mode(break_penalty): append_penalty();@+break;
21985
21986 @ @<Declare action...@>=
21987 static void append_penalty(void)
21988 {@+scan_int();tail_append(new_penalty(cur_val));
21989 if (mode==vmode) build_page();
21990 }
21991
21992 @ The |remove_item| command removes a penalty, kern, or glue node if it
21993 appears at the tail of the current list, using a brute-force linear scan.
21994 Like \.{\\lastbox}, this command is not allowed in vertical mode (except
21995 internal vertical mode), since the current list in vertical mode is sent
21996 to the page builder. But if we happen to be able to implement it in
21997 vertical mode, we do.
21998
21999 @<Cases of |main_control| that build...@>=
22000 any_mode(remove_item): delete_last();@+break;
22001
22002 @ When |delete_last| is called, |cur_chr| is the |type| of node that
22003 will be deleted, if present.
22004
22005 @<Declare action...@>=
22006 static void delete_last(void)
22007 {@+
22008 pointer @!p, @!q; /*run through the current list*/
22009 int @!m; /*the length of a replacement list*/
22010 if ((mode==vmode)&&(tail==head))
22011 @<Apologize for inability to do the operation now, unless \.{\\unskip} follows
22012 non-glue@>@;
22013 else{@+if (!is_char_node(tail)) if (type(tail)==cur_chr)
22014 {@+q=head;
22015 @/do@+{p=q;
22016 if (!is_char_node(q)) if (type(q)==disc_node)
22017 {@+for (m=1; m<=replace_count(q); m++) p=link(p);
22018 if (p==tail) return;
22019 }
22020 q=link(p);
22021 }@+ while (!(q==tail));
22022 link(p)=null;flush_node_list(tail);tail=p;
22023 }
22024 }
22025 }
22026
22027 @ @<Apologize for inability to do the operation...@>=
22028 {@+if ((cur_chr!=glue_node)||(last_glue!=max_halfword))
22029 {@+you_cant();
22030 help2("Sorry...I usually can't take things from the current page.",@/
22031 "Try `I\\vskip-\\lastskip' instead.");
22032 if (cur_chr==kern_node) help_line[0]=
22033 ("Try `I\\kern-\\lastkern' instead.");
22034 else if (cur_chr!=glue_node) help_line[0]=@|
22035 ("Perhaps you can make the output routine do it.");
22036 error();
22037 }
22038 }
22039
22040 @ @<Put each...@>=
22041 primitive("unpenalty", remove_item, penalty_node);@/
22042 @!@:un\_penalty\_}{\.{\\unpenalty} primitive@>
22043 primitive("unkern", remove_item, kern_node);@/
22044 @!@:un\_kern\_}{\.{\\unkern} primitive@>
22045 primitive("unskip", remove_item, glue_node);@/
22046 @!@:un\_skip\_}{\.{\\unskip} primitive@>
22047 primitive("unhbox", un_hbox, box_code);@/
22048 @!@:un\_hbox\_}{\.{\\unhbox} primitive@>
22049 primitive("unhcopy", un_hbox, copy_code);@/
22050 @!@:un\_hcopy\_}{\.{\\unhcopy} primitive@>
22051 primitive("unvbox", un_vbox, box_code);@/
22052 @!@:un\_vbox\_}{\.{\\unvbox} primitive@>
22053 primitive("unvcopy", un_vbox, copy_code);@/
22054 @!@:un\_vcopy\_}{\.{\\unvcopy} primitive@>
22055
22056 @ @<Cases of |print_cmd_chr|...@>=
22057 case remove_item: if (chr_code==glue_node) print_esc("unskip");
22058 else if (chr_code==kern_node) print_esc("unkern");
22059 else print_esc("unpenalty");@+break;
22060 case un_hbox: if (chr_code==copy_code) print_esc("unhcopy");
22061 else print_esc("unhbox");@+break;
22062 case un_vbox: if (chr_code==copy_code) print_esc("unvcopy")
22063 @<Cases of |un_vbox| for |print_cmd_chr|@>;@/
22064 else print_esc("unvbox");@+break;
22065
22066 @ The |un_hbox| and |un_vbox| commands unwrap one of the 256 current boxes.
22067
22068 @<Cases of |main_control| that build...@>=
22069 case vmode+un_vbox: case hmode+un_hbox:
22070 case mmode+un_hbox: unpackage();@+break;
22071
22072 @ @<Declare act...@>=
22073 static void unpackage(void)
22074 {@+
22075 pointer p; /*the box*/
22076 int @!c; /*should we copy?*/
22077 if (cur_chr > copy_code) @<Handle saved items and |goto done|@>;
22078 c=cur_chr;scan_register_num();fetch_box(p);
22079 if (p==null) return;
22080 if ((abs(mode)==mmode)||((abs(mode)==vmode)&&(type(p)!=vlist_node))||@|
22081 ((abs(mode)==hmode)&&(type(p)!=hlist_node)))
22082 {@+print_err("Incompatible list can't be unboxed");
22083 @.Incompatible list...@>
22084 help3("Sorry, Pandora. (You sneaky devil.)",@/
22085 "I refuse to unbox an \\hbox in vertical mode or vice versa.",@/
22086 "And I can't open any boxes in math mode.");@/
22087 error();return;
22088 }
22089 if (c==copy_code) link(tail)=copy_node_list(list_ptr(p));
22090 else{@+link(tail)=list_ptr(p);change_box(null);
22091 free_node(p, box_node_size);
22092 }
22093 done:
22094 while (link(tail)!=null) tail=link(tail);
22095 }
22096
22097 @ @<Forbidden...@>=case vmode+ital_corr:
22098
22099 @ Italic corrections are converted to kern nodes when the |ital_corr| command
22100 follows a character. In math mode the same effect is achieved by appending
22101 a kern of zero here, since italic corrections are supplied later.
22102
22103 @<Cases of |main_control| that build...@>=
22104 case hmode+ital_corr: append_italic_correction();@+break;
22105 case mmode+ital_corr: tail_append(new_kern(0))@;@+break;
22106
22107 @ @<Declare act...@>=
22108 static void append_italic_correction(void)
22109 {@+
22110 pointer p; /*|char_node| at the tail of the current list*/
22111 internal_font_number @!f; /*the font in the |char_node|*/
22112 if (tail!=head)
22113 {@+if (is_char_node(tail)) p=tail;
22114 else if (type(tail)==ligature_node) p=lig_char(tail);
22115 else return;
22116 f=font(p);
22117 tail_append(new_kern(char_italic(f, char_info(f, character(p)))));
22118 subtype(tail)=explicit;
22119 }
22120 }
22121
22122 @ Discretionary nodes are easy in the common case `\.{\\-}', but in the
22123 general case we must process three braces full of items.
22124
22125 @<Put each...@>=
22126 primitive("-", discretionary, 1);
22127 @!@:Single-character primitives -}{\quad\.{\\-}@>
22128 primitive("discretionary", discretionary, 0);
22129 @!@:discretionary\_}{\.{\\discretionary} primitive@>
22130
22131 @ @<Cases of |print_cmd_chr|...@>=
22132 case discretionary: if (chr_code==1)
22133 print_esc("-");@+else print_esc("discretionary");@+break;
22134
22135 @ @<Cases of |main_control| that build...@>=
22136 case hmode+discretionary: case mmode+discretionary: append_discretionary();@+break;
22137
22138 @ The space factor does not change when we append a discretionary node,
22139 but it starts out as 1000 in the subsidiary lists.
22140
22141 @<Declare act...@>=
22142 static void append_discretionary(void)
22143 {@+int c; /*hyphen character*/
22144 tail_append(new_disc());
22145 if (cur_chr==1)
22146 {@+c=hyphen_char[cur_font];
22147 if (c >= 0) if (c < 256) pre_break(tail)=new_character(cur_font, c);
22148 }
22149 else{@+incr(save_ptr);saved(-1)=0;new_save_level(disc_group);
22150 scan_left_brace();push_nest();mode=-hmode;space_factor=1000;
22151 }
22152 }
22153
22154 @ The three discretionary lists are constructed somewhat as if they were
22155 hboxes. A~subroutine called |build_discretionary| handles the transitions.
22156 (This is sort of fun.)
22157
22158 @<Cases of |handle...@>=
22159 case disc_group: build_discretionary();@+break;
22160
22161 @ @<Declare act...@>=
22162 static void build_discretionary(void)
22163 {@+
22164 pointer p, @!q; /*for link manipulation*/
22165 int @!n; /*length of discretionary list*/
22166 unsave();
22167 @<Prune the current list, if necessary, until it contains only |char_node|,
22168 |kern_node|, |hlist_node|, |vlist_node|, |rule_node|, and |ligature_node|
22169 items; set |n| to the length of the list, and set |q| to the list's tail@>;
22170 p=link(head);pop_nest();
22171 switch (saved(-1)) {
22172 case 0: pre_break(tail)=p;@+break;
22173 case 1: post_break(tail)=p;@+break;
22174 case 2: @<Attach list |p| to the current list, and record its length; then
22175 finish up and |return|@>;
22176 } /*there are no other cases*/
22177 incr(saved(-1));new_save_level(disc_group);scan_left_brace();
22178 push_nest();mode=-hmode;space_factor=1000;
22179 }
22180
22181 @ @<Attach list |p| to the current...@>=
22182 {@+if ((n > 0)&&(abs(mode)==mmode))
22183 {@+print_err("Illegal math ");print_esc("discretionary");
22184 @.Illegal math \\disc...@>
22185 help2("Sorry: The third part of a discretionary break must be",@/
22186 "empty, in math formulas. I had to delete your third part.");
22187 flush_node_list(p);n=0;error();
22188 }
22189 else link(tail)=p;
22190 if (n <= max_quarterword) replace_count(tail)=n;
22191 else{@+print_err("Discretionary list is too long");
22192 @.Discretionary list is too long@>
22193 help2("Wow---I never thought anybody would tweak me here.",@/
22194 "You can't seriously need such a huge discretionary list?");
22195 error();
22196 }
22197 if (n > 0) tail=q;
22198 decr(save_ptr);return;
22199 }
22200
22201 @ During this loop, |p==link(q)| and there are |n| items preceding |p|.
22202
22203 @<Prune the current list, if necessary...@>=
22204 q=head;p=link(q);n=0;
22205 while (p!=null)
22206 {@+if (!is_char_node(p)) if (type(p) > rule_node)
22207 if (type(p)!=kern_node) if (type(p)!=ligature_node)
22208 {@+print_err("Improper discretionary list");
22209 @.Improper discretionary list@>
22210 help1("Discretionary lists must contain only boxes and kerns.");@/
22211 error();
22212 begin_diagnostic();
22213 print_nl("The following discretionary sublist has been deleted:");
22214 @.The following...deleted@>
22215 show_box(p);
22216 end_diagnostic(true);
22217 flush_node_list(p);link(q)=null;goto done;
22218 }
22219 q=p;p=link(q);incr(n);
22220 }
22221 done:
22222
22223 @ We need only one more thing to complete the horizontal mode routines, namely
22224 the \.{\\accent} primitive.
22225
22226 @<Cases of |main_control| that build...@>=
22227 case hmode+accent: make_accent();@+break;
22228
22229 @ The positioning of accents is straightforward but tedious. Given an accent
22230 of width |a|, designed for characters of height |x| and slant |s|;
22231 and given a character of width |w|, height |h|, and slant |t|: We will shift
22232 the accent down by |x-h|, and we will insert kern nodes that have the effect of
22233 centering the accent over the character and shifting the accent to the
22234 right by $\delta={1\over2}(w-a)+h\cdot t-x\cdot s$. If either character is
22235 absent from the font, we will simply use the other, without shifting.
22236
22237 @<Declare act...@>=
22238 static void make_accent(void)
22239 {@+double s, @!t; /*amount of slant*/
22240 pointer @!p, @!q, @!r; /*character, box, and kern nodes*/
22241 internal_font_number @!f; /*relevant font*/
22242 scaled @!a, @!h, @!x, @!w, @!delta; /*heights and widths, as explained above*/
22243 four_quarters @!i; /*character information*/
22244 scan_char_num();f=cur_font;p=new_character(f, cur_val);
22245 if (p!=null)
22246 {@+x=x_height(f);s=slant(f)/float_constant(65536);
22247 @^real division@>
22248 a=char_width(f, char_info(f, character(p)));@/
22249 do_assignments();@/
22250 @<Create a character node |q| for the next character, but set |q:=null|
22251 if problems arise@>;
22252 if (q!=null) @<Append the accent with appropriate kerns, then set |p:=q|@>;
22253 link(tail)=p;tail=p;space_factor=1000;
22254 }
22255 }
22256
22257 @ @<Create a character node |q| for the next...@>=
22258 q=null;f=cur_font;
22259 if ((cur_cmd==letter)||(cur_cmd==other_char)||(cur_cmd==char_given))
22260 q=new_character(f, cur_chr);
22261 else if (cur_cmd==char_num)
22262 {@+scan_char_num();q=new_character(f, cur_val);
22263 }
22264 else back_input()
22265
22266 @ The kern nodes appended here must be distinguished from other kerns, lest
22267 they be wiped away by the hyphenation algorithm or by a previous line break.
22268
22269 The two kerns are computed with (machine-dependent) |double| arithmetic, but
22270 their sum is machine-independent; the net effect is machine-independent,
22271 because the user cannot remove these nodes nor access them via \.{\\lastkern}.
22272
22273 @<Append the accent with appropriate kerns...@>=
22274 {@+t=slant(f)/float_constant(65536);
22275 @^real division@>
22276 i=char_info(f, character(q));
22277 w=char_width(f, i);h=char_height(f, height_depth(i));
22278 if (h!=x) /*the accent must be shifted up or down*/
22279 {@+p=hpack(p, natural);shift_amount(p)=x-h;
22280 }
22281 delta=round((w-a)/float_constant(2)+h*t-x*s);
22282 @^real multiplication@>
22283 @^real addition@>
22284 r=new_kern(delta);subtype(r)=acc_kern;link(tail)=r;link(r)=p;
22285 tail=new_kern(-a-delta);subtype(tail)=acc_kern;link(p)=tail;p=q;
22286 }
22287
22288 @ When `\.{\\cr}' or `\.{\\span}' or a tab mark comes through the scanner
22289 into |main_control|, it might be that the user has foolishly inserted
22290 one of them into something that has nothing to do with alignment. But it is
22291 far more likely that a left brace or right brace has been omitted, since
22292 |get_next| takes actions appropriate to alignment only when `\.{\\cr}'
22293 or `\.{\\span}' or tab marks occur with |align_state==0|. The following
22294 program attempts to make an appropriate recovery.
22295
22296 @<Cases of |main_control| that build...@>=
22297 any_mode(car_ret): any_mode(tab_mark): align_error();@+break;
22298 any_mode(no_align): no_align_error();@+break;
22299 any_mode(omit): omit_error();@+break;
22300
22301 @ @<Declare act...@>=
22302 static void align_error(void)
22303 {@+if (abs(align_state) > 2)
22304 @<Express consternation over the fact that no alignment is in progress@>@;
22305 else{@+back_input();
22306 if (align_state < 0)
22307 {@+print_err("Missing { inserted");
22308 @.Missing \{ inserted@>
22309 incr(align_state);cur_tok=left_brace_token+'{';
22310 }
22311 else{@+print_err("Missing } inserted");
22312 @.Missing \} inserted@>
22313 decr(align_state);cur_tok=right_brace_token+'}';
22314 }
22315 help3("I've put in what seems to be necessary to fix",@/
22316 "the current column of the current alignment.",@/
22317 "Try to go on, since this might almost work.");ins_error();
22318 }
22319 }
22320
22321 @ @<Express consternation...@>=
22322 {@+print_err("Misplaced ");print_cmd_chr(cur_cmd, cur_chr);
22323 @.Misplaced \&@>
22324 @.Misplaced \\span@>
22325 @.Misplaced \\cr@>
22326 if (cur_tok==tab_token+'&')
22327 {@+help6("I can't figure out why you would want to use a tab mark",@/
22328 "here. If you just want an ampersand, the remedy is",@/
22329 "simple: Just type `I\\&' now. But if some right brace",@/
22330 "up above has ended a previous alignment prematurely,",@/
22331 "you're probably due for more error messages, and you",@/
22332 "might try typing `S' now just to see what is salvageable.");
22333 }
22334 else{@+help5("I can't figure out why you would want to use a tab mark",@/
22335 "or \\cr or \\span just now. If something like a right brace",@/
22336 "up above has ended a previous alignment prematurely,",@/
22337 "you're probably due for more error messages, and you",@/
22338 "might try typing `S' now just to see what is salvageable.");
22339 }
22340 error();
22341 }
22342
22343 @ The help messages here contain a little white lie, since \.{\\noalign}
22344 and \.{\\omit} are allowed also after `\.{\\noalign\{...\}}'.
22345
22346 @<Declare act...@>=
22347 static void no_align_error(void)
22348 {@+print_err("Misplaced ");print_esc("noalign");
22349 @.Misplaced \\noalign@>
22350 help2("I expect to see \\noalign only after the \\cr of",@/
22351 "an alignment. Proceed, and I'll ignore this case.");error();
22352 }
22353 static void omit_error(void)
22354 {@+print_err("Misplaced ");print_esc("omit");
22355 @.Misplaced \\omit@>
22356 help2("I expect to see \\omit only after tab marks or the \\cr of",@/
22357 "an alignment. Proceed, and I'll ignore this case.");error();
22358 }
22359
22360 @ We've now covered most of the abuses of \.{\\halign} and \.{\\valign}.
22361 Let's take a look at what happens when they are used correctly.
22362
22363 @<Cases of |main_control| that build...@>=
22364 case vmode+halign: case hmode+valign: init_align();@+break;
22365 case mmode+halign: if (privileged())
22366 if (cur_group==math_shift_group) init_align();
22367 else off_save();@+break;
22368 case vmode+endv: case hmode+endv: do_endv();@+break;
22369
22370 @ An |align_group| code is supposed to remain on the |save_stack|
22371 during an entire alignment, until |fin_align| removes it.
22372
22373 A devious user might force an |endv| command to occur just about anywhere;
22374 we must defeat such hacks.
22375
22376 @<Declare act...@>=
22377 static void do_endv(void)
22378 {@+base_ptr=input_ptr;input_stack[base_ptr]=cur_input;
22379 while ((input_stack[base_ptr].index_field!=v_template)&&
22380 (input_stack[base_ptr].loc_field==null)&&
22381 (input_stack[base_ptr].state_field==token_list)) decr(base_ptr);
22382 if ((input_stack[base_ptr].index_field!=v_template)||
22383 (input_stack[base_ptr].loc_field!=null)||
22384 (input_stack[base_ptr].state_field!=token_list))
22385 fatal_error("(interwoven alignment preambles are not allowed)");
22386 @.interwoven alignment preambles...@>
22387 if (cur_group==align_group)
22388 {@+end_graf();
22389 if (fin_col()) fin_row();
22390 }
22391 else off_save();
22392 }
22393
22394 @ @<Cases of |handle_right_brace|...@>=
22395 case align_group: {@+back_input();cur_tok=cs_token_flag+frozen_cr;
22396 print_err("Missing ");print_esc("cr");print(" inserted");
22397 @.Missing \\cr inserted@>
22398 help1("I'm guessing that you meant to end an alignment here.");
22399 ins_error();
22400 } @+break;
22401
22402 @ @<Cases of |handle_right_brace|...@>=
22403 case no_align_group: {@+end_graf();unsave();align_peek();
22404 } @+break;
22405
22406 @ Finally, \.{\\endcsname} is not supposed to get through to |main_control|.
22407
22408 @<Cases of |main_control| that build...@>=
22409 any_mode(end_cs_name): cs_error();@+break;
22410
22411 @ @<Declare act...@>=
22412 static void cs_error(void)
22413 {@+print_err("Extra ");print_esc("endcsname");
22414 @.Extra \\endcsname@>
22415 help1("I'm ignoring this, since I wasn't doing a \\csname.");
22416 error();
22417 }
22418
22419 @* Building math lists.
22420 The routines that \TeX\ uses to create mlists are similar to those we have
22421 just seen for the generation of hlists and vlists. But it is necessary to
22422 make ``noads'' as well as nodes, so the reader should review the
22423 discussion of math mode data structures before trying to make sense out of
22424 the following program.
22425
22426 Here is a little routine that needs to be done whenever a subformula
22427 is about to be processed. The parameter is a code like |math_group|.
22428
22429 @<Declare act...@>=
22430 static void push_math(group_code @!c)
22431 {@+push_nest();mode=-mmode;incompleat_noad=null;new_save_level(c);
22432 }
22433
22434 @ We get into math mode from horizontal mode when a `\.\$' (i.e., a
22435 |math_shift| character) is scanned. We must check to see whether this
22436 `\.\$' is immediately followed by another, in case display math mode is
22437 called for.
22438
22439 @<Cases of |main_control| that build...@>=
22440 case hmode+math_shift: init_math();@+break;
22441
22442 @ @<Declare act...@>=
22443 static void init_math(void)
22444 {@+
22445 scaled w; /*new or partial |pre_display_size|*/
22446 scaled @!l; /*new |display_width|*/
22447 scaled @!s; /*new |display_indent|*/
22448 pointer @!p; /*current node when calculating |pre_display_size|*/
22449 pointer @!q; /*glue specification when calculating |pre_display_size|*/
22450 internal_font_number @!f; /*font in current |char_node|*/
22451 int @!n; /*scope of paragraph shape specification*/
22452 scaled @!v; /*|w| plus possible glue amount*/
22453 scaled @!d; /*increment to |v|*/
22454 get_token(); /*|get_x_token| would fail on \.{\\ifmmode}\thinspace!*/
22455 if ((cur_cmd==math_shift)&&(mode > 0)) @<Go into display math mode@>@;
22456 else{@+back_input();@<Go into ordinary math mode@>;
22457 }
22458 }
22459
22460 @ @<Go into ordinary math mode@>=
22461 {@+push_math(math_shift_group);eq_word_define(int_base+cur_fam_code,-1);
22462 if (every_math!=null) begin_token_list(every_math, every_math_text);
22463 }
22464
22465 @ We get into ordinary math mode from display math mode when `\.{\\eqno}' or
22466 `\.{\\leqno}' appears. In such cases |cur_chr| will be 0 or~1, respectively;
22467 the value of |cur_chr| is placed onto |save_stack| for safe keeping.
22468
22469 @<Cases of |main_control| that build...@>=
22470 case mmode+eq_no: if (privileged())
22471 if (cur_group==math_shift_group) start_eq_no();
22472 else off_save();@+break;
22473
22474 @ @<Put each...@>=
22475 primitive("eqno", eq_no, 0);
22476 @!@:eq\_no\_}{\.{\\eqno} primitive@>
22477 primitive("leqno", eq_no, 1);
22478 @!@:leq\_no\_}{\.{\\leqno} primitive@>
22479
22480 @ When \TeX\ is in display math mode, |cur_group==math_shift_group|,
22481 so it is not necessary for the |start_eq_no| procedure to test for
22482 this condition.
22483
22484 @<Declare act...@>=
22485 static void start_eq_no(void)
22486 {@+saved(0)=cur_chr;incr(save_ptr);
22487 @<Go into ordinary math mode@>;
22488 }
22489
22490 @ @<Cases of |print_cmd_chr|...@>=
22491 case eq_no: if (chr_code==1) print_esc("leqno");@+else print_esc("eqno");@+break;
22492
22493 @ @<Forbidden...@>=non_math(eq_no):
22494
22495 @ When we enter display math mode, we need to call |line_break| to
22496 process the partial paragraph that has just been interrupted by the
22497 display. Then we can set the proper values of |display_width| and
22498 |display_indent| and |pre_display_size|.
22499
22500 @<Go into display math mode@>=
22501 {@+if (head==tail) /*`\.{\\noindent\$\$}' or `\.{\$\${ }\$\$}'*/
22502 {@+pop_nest();w=-max_dimen;
22503 }
22504 else{@+line_break(display_widow_penalty);@/
22505 @<Calculate the natural width, |w|, by which the characters of the final
22506 line extend to the right of the reference point, plus two ems; or set |w:=max_dimen|
22507 if the non-blank information on that line is affected by stretching or shrinking@>;
22508 }
22509 /*now we are in vertical mode, working on the list that will contain the display*/
22510 @<Calculate the length, |l|, and the shift amount, |s|, of the display lines@>;
22511 push_math(math_shift_group);mode=mmode;
22512 eq_word_define(int_base+cur_fam_code,-1);@/
22513 eq_word_define(dimen_base+pre_display_size_code, w);
22514 eq_word_define(dimen_base+display_width_code, l);
22515 eq_word_define(dimen_base+display_indent_code, s);
22516 if (every_display!=null) begin_token_list(every_display, every_display_text);
22517 if (nest_ptr==1) build_page();
22518 }
22519
22520 @ @<Calculate the natural width, |w|, by which...@>=
22521 v=shift_amount(just_box)+2*quad(cur_font);w=-max_dimen;
22522 p=list_ptr(just_box);
22523 while (p!=null)
22524 {@+@<Let |d| be the natural width of node |p|; if the node is ``visible,''
22525 |goto found|; if the node is glue that stretches or shrinks, set |v:=max_dimen|@>;
22526 if (v < max_dimen) v=v+d;
22527 goto not_found;
22528 found: if (v < max_dimen)
22529 {@+v=v+d;w=v;
22530 }
22531 else{@+w=max_dimen;goto done;
22532 }
22533 not_found: p=link(p);
22534 }
22535 done:
22536
22537 @ @<Let |d| be the natural width of node |p|...@>=
22538 reswitch: if (is_char_node(p))
22539 {@+f=font(p);d=char_width(f, char_info(f, character(p)));
22540 goto found;
22541 }
22542 switch (type(p)) {
22543 case hlist_node: case vlist_node: case rule_node: {@+d=width(p);goto found;
22544 }
22545 case ligature_node: @<Make node |p| look like a |char_node|...@>@;
22546 case kern_node: case math_node: d=width(p);@+break;
22547 case glue_node: @<Let |d| be the natural width of this glue; if stretching
22548 or shrinking, set |v:=max_dimen|; |goto found| in the case of leaders@>@;@+break;
22549 case whatsit_node: @<Let |d| be the width of the whatsit |p|@>;@+break;
22550 default:d=0;
22551 }
22552
22553 @ We need to be careful that |w|, |v|, and |d| do not depend on any |glue_set|
22554 values, since such values are subject to system-dependent rounding.
22555 System-dependent numbers are not allowed to infiltrate parameters like
22556 |pre_display_size|, since \TeX82 is supposed to make the same decisions on all
22557 machines.
22558
22559 @<Let |d| be the natural width of this glue...@>=
22560 {@+q=glue_ptr(p);d=width(q);
22561 if (glue_sign(just_box)==stretching)
22562 {@+if ((glue_order(just_box)==stretch_order(q))&&@|
22563 (stretch(q)!=0))
22564 v=max_dimen;
22565 }
22566 else if (glue_sign(just_box)==shrinking)
22567 {@+if ((glue_order(just_box)==shrink_order(q))&&@|
22568 (shrink(q)!=0))
22569 v=max_dimen;
22570 }
22571 if (subtype(p) >= a_leaders) goto found;
22572 }
22573
22574 @ A displayed equation is considered to be three lines long, so we
22575 calculate the length and offset of line number |prev_graf+2|.
22576
22577 @<Calculate the length, |l|,...@>=
22578 if (par_shape_ptr==null)
22579 if ((hang_indent!=0)&&@|
22580 (((hang_after >= 0)&&(prev_graf+2 > hang_after))||@|
22581 (prev_graf+1 < -hang_after)))
22582 {@+l=hsize-abs(hang_indent);
22583 if (hang_indent > 0) s=hang_indent;@+else s=0;
22584 }
22585 else{@+l=hsize;s=0;
22586 }
22587 else{@+n=info(par_shape_ptr);
22588 if (prev_graf+2 >= n) p=par_shape_ptr+2*n;
22589 else p=par_shape_ptr+2*(prev_graf+2);
22590 s=mem[p-1].sc;l=mem[p].sc;
22591 }
22592
22593 @ Subformulas of math formulas cause a new level of math mode to be entered,
22594 on the semantic nest as well as the save stack. These subformulas arise in
22595 several ways: (1)~A left brace by itself indicates the beginning of a
22596 subformula that will be put into a box, thereby freezing its glue and
22597 preventing line breaks. (2)~A subscript or superscript is treated as a
22598 subformula if it is not a single character; the same applies to
22599 the nucleus of things like \.{\\underline}. (3)~The \.{\\left} primitive
22600 initiates a subformula that will be terminated by a matching \.{\\right}.
22601 The group codes placed on |save_stack| in these three cases are
22602 |math_group|, |math_group|, and |math_left_group|, respectively.
22603
22604 Here is the code that handles case (1); the other cases are not quite as
22605 trivial, so we shall consider them later.
22606
22607 @<Cases of |main_control| that build...@>=
22608 case mmode+left_brace: {@+tail_append(new_noad());
22609 back_input();scan_math(nucleus(tail));
22610 } @+break;
22611
22612 @ Recall that the |nucleus|, |subscr|, and |supscr| fields in a noad are
22613 broken down into subfields called |math_type| and either |info| or
22614 |(fam, character)|. The job of |scan_math| is to figure out what to place
22615 in one of these principal fields; it looks at the subformula that
22616 comes next in the input, and places an encoding of that subformula
22617 into a given word of |mem|.
22618
22619 @d fam_in_range ((cur_fam >= 0)&&(cur_fam < 16))
22620
22621 @<Declare act...@>=
22622 static void scan_math(pointer @!p)
22623 {@+
22624 int c; /*math character code*/
22625 restart: @<Get the next non-blank non-relax...@>;
22626 reswitch: switch (cur_cmd) {
22627 case letter: case other_char: case char_given: {@+c=ho(math_code(cur_chr));
22628 if (c==0100000)
22629 {@+@<Treat |cur_chr| as an active character@>;
22630 goto restart;
22631 }
22632 } @+break;
22633 case char_num: {@+scan_char_num();cur_chr=cur_val;cur_cmd=char_given;
22634 goto reswitch;
22635 }
22636 case math_char_num: {@+scan_fifteen_bit_int();c=cur_val;
22637 } @+break;
22638 case math_given: c=cur_chr;@+break;
22639 case delim_num: {@+scan_twenty_seven_bit_int();c=cur_val/010000;
22640 } @+break;
22641 default:@<Scan a subformula enclosed in braces and |return|@>@;
22642 } @/
22643 math_type(p)=math_char;character(p)=qi(c%256);
22644 if ((c >= var_code)&&fam_in_range) fam(p)=cur_fam;
22645 else fam(p)=(c/256)%16;
22646 }
22647
22648 @ An active character that is an |outer_call| is allowed here.
22649
22650 @<Treat |cur_chr|...@>=
22651 {@+cur_cs=cur_chr+active_base;
22652 cur_cmd=eq_type(cur_cs);cur_chr=equiv(cur_cs);
22653 x_token();back_input();
22654 }
22655
22656 @ The pointer |p| is placed on |save_stack| while a complex subformula
22657 is being scanned.
22658
22659 @<Scan a subformula...@>=
22660 {@+back_input();scan_left_brace();@/
22661 saved(0)=p;incr(save_ptr);push_math(math_group);return;
22662 }
22663
22664 @ The simplest math formula is, of course, `\.{\${ }\$}', when no noads are
22665 generated. The next simplest cases involve a single character, e.g.,
22666 `\.{\$x\$}'. Even though such cases may not seem to be very interesting,
22667 the reader can perhaps understand how happy the author was when `\.{\$x\$}'
22668 was first properly typeset by \TeX. The code in this section was used.
22669 @^Knuth, Donald Ervin@>
22670
22671 @<Cases of |main_control| that build...@>=
22672 case mmode+letter: case mmode+other_char:
22673 case mmode+char_given:
22674 set_math_char(ho(math_code(cur_chr)));@+break;
22675 case mmode+char_num: {@+scan_char_num();cur_chr=cur_val;
22676 set_math_char(ho(math_code(cur_chr)));
22677 } @+break;
22678 case mmode+math_char_num: {@+scan_fifteen_bit_int();set_math_char(cur_val);
22679 } @+break;
22680 case mmode+math_given: set_math_char(cur_chr);@+break;
22681 case mmode+delim_num: {@+scan_twenty_seven_bit_int();
22682 set_math_char(cur_val/010000);
22683 } @+break;
22684
22685 @ The |set_math_char| procedure creates a new noad appropriate to a given
22686 math code, and appends it to the current mlist. However, if the math code
22687 is sufficiently large, the |cur_chr| is treated as an active character and
22688 nothing is appended.
22689
22690 @<Declare act...@>=
22691 static void set_math_char(int @!c)
22692 {@+pointer p; /*the new noad*/
22693 if (c >= 0100000)
22694 @<Treat |cur_chr|...@>@;
22695 else{@+p=new_noad();math_type(nucleus(p))=math_char;
22696 character(nucleus(p))=qi(c%256);
22697 fam(nucleus(p))=(c/256)%16;
22698 if (c >= var_code)
22699 {@+if (fam_in_range) fam(nucleus(p))=cur_fam;
22700 type(p)=ord_noad;
22701 }
22702 else type(p)=ord_noad+(c/010000);
22703 link(tail)=p;tail=p;
22704 }
22705 }
22706
22707 @ Primitive math operators like \.{\\mathop} and \.{\\underline} are given
22708 the command code |math_comp|, supplemented by the noad type that they
22709 generate.
22710
22711 @<Put each...@>=
22712 primitive("mathord", math_comp, ord_noad);
22713 @!@:math\_ord\_}{\.{\\mathord} primitive@>
22714 primitive("mathop", math_comp, op_noad);
22715 @!@:math\_op\_}{\.{\\mathop} primitive@>
22716 primitive("mathbin", math_comp, bin_noad);
22717 @!@:math\_bin\_}{\.{\\mathbin} primitive@>
22718 primitive("mathrel", math_comp, rel_noad);
22719 @!@:math\_rel\_}{\.{\\mathrel} primitive@>
22720 primitive("mathopen", math_comp, open_noad);
22721 @!@:math\_open\_}{\.{\\mathopen} primitive@>
22722 primitive("mathclose", math_comp, close_noad);
22723 @!@:math\_close\_}{\.{\\mathclose} primitive@>
22724 primitive("mathpunct", math_comp, punct_noad);
22725 @!@:math\_punct\_}{\.{\\mathpunct} primitive@>
22726 primitive("mathinner", math_comp, inner_noad);
22727 @!@:math\_inner\_}{\.{\\mathinner} primitive@>
22728 primitive("underline", math_comp, under_noad);
22729 @!@:underline\_}{\.{\\underline} primitive@>
22730 primitive("overline", math_comp, over_noad);@/
22731 @!@:overline\_}{\.{\\overline} primitive@>
22732 primitive("displaylimits", limit_switch, normal);
22733 @!@:display\_limits\_}{\.{\\displaylimits} primitive@>
22734 primitive("limits", limit_switch, limits);
22735 @!@:limits\_}{\.{\\limits} primitive@>
22736 primitive("nolimits", limit_switch, no_limits);
22737 @!@:no\_limits\_}{\.{\\nolimits} primitive@>
22738
22739 @ @<Cases of |print_cmd_chr|...@>=
22740 case math_comp: switch (chr_code) {
22741 case ord_noad: print_esc("mathord");@+break;
22742 case op_noad: print_esc("mathop");@+break;
22743 case bin_noad: print_esc("mathbin");@+break;
22744 case rel_noad: print_esc("mathrel");@+break;
22745 case open_noad: print_esc("mathopen");@+break;
22746 case close_noad: print_esc("mathclose");@+break;
22747 case punct_noad: print_esc("mathpunct");@+break;
22748 case inner_noad: print_esc("mathinner");@+break;
22749 case under_noad: print_esc("underline");@+break;
22750 default:print_esc("overline");
22751 } @+break;
22752 case limit_switch: if (chr_code==limits) print_esc("limits");
22753 else if (chr_code==no_limits) print_esc("nolimits");
22754 else print_esc("displaylimits");@+break;
22755
22756 @ @<Cases of |main_control| that build...@>=
22757 case mmode+math_comp: {@+tail_append(new_noad());
22758 type(tail)=cur_chr;scan_math(nucleus(tail));
22759 } @+break;
22760 case mmode+limit_switch: math_limit_switch();@+break;
22761
22762 @ @<Declare act...@>=
22763 static void math_limit_switch(void)
22764 {@+
22765 if (head!=tail) if (type(tail)==op_noad)
22766 {@+subtype(tail)=cur_chr;return;
22767 }
22768 print_err("Limit controls must follow a math operator");
22769 @.Limit controls must follow...@>
22770 help1("I'm ignoring this misplaced \\limits or \\nolimits command.");error();
22771 }
22772
22773 @ Delimiter fields of noads are filled in by the |scan_delimiter| routine.
22774 The first parameter of this procedure is the |mem| address where the
22775 delimiter is to be placed; the second tells if this delimiter follows
22776 \.{\\radical} or not.
22777
22778 @<Declare act...@>=
22779 static void scan_delimiter(pointer @!p, bool @!r)
22780 {@+if (r) scan_twenty_seven_bit_int();
22781 else{@+@<Get the next non-blank non-relax...@>;
22782 switch (cur_cmd) {
22783 case letter: case other_char: cur_val=del_code(cur_chr);@+break;
22784 case delim_num: scan_twenty_seven_bit_int();@+break;
22785 default:cur_val=-1;
22786 }
22787 }
22788 if (cur_val < 0) @<Report that an invalid delimiter code is being changed
22789 to null; set~|cur_val:=0|@>;
22790 small_fam(p)=(cur_val/04000000)%16;
22791 small_char(p)=qi((cur_val/010000)%256);
22792 large_fam(p)=(cur_val/256)%16;
22793 large_char(p)=qi(cur_val%256);
22794 }
22795
22796 @ @<Report that an invalid delimiter...@>=
22797 {@+print_err("Missing delimiter (. inserted)");
22798 @.Missing delimiter...@>
22799 help6("I was expecting to see something like `(' or `\\{' or",@/
22800 "`\\}' here. If you typed, e.g., `{' instead of `\\{', you",@/
22801 "should probably delete the `{' by typing `1' now, so that",@/
22802 "braces don't get unbalanced. Otherwise just proceed.",@/
22803 "Acceptable delimiters are characters whose \\delcode is",@/
22804 "nonnegative, or you can use `\\delimiter <delimiter code>'.");
22805 back_error();cur_val=0;
22806 }
22807
22808 @ @<Cases of |main_control| that build...@>=
22809 case mmode+radical: math_radical();@+break;
22810
22811 @ @<Declare act...@>=
22812 static void math_radical(void)
22813 {@+tail_append(get_node(radical_noad_size));
22814 type(tail)=radical_noad;subtype(tail)=normal;
22815 mem[nucleus(tail)].hh=empty_field;
22816 mem[subscr(tail)].hh=empty_field;
22817 mem[supscr(tail)].hh=empty_field;
22818 scan_delimiter(left_delimiter(tail), true);scan_math(nucleus(tail));
22819 }
22820
22821 @ @<Cases of |main_control| that build...@>=
22822 case mmode+accent: case mmode+math_accent: math_ac();@+break;
22823
22824 @ @<Declare act...@>=
22825 static void math_ac(void)
22826 {@+if (cur_cmd==accent)
22827 @<Complain that the user should have said \.{\\mathaccent}@>;
22828 tail_append(get_node(accent_noad_size));
22829 type(tail)=accent_noad;subtype(tail)=normal;
22830 mem[nucleus(tail)].hh=empty_field;
22831 mem[subscr(tail)].hh=empty_field;
22832 mem[supscr(tail)].hh=empty_field;
22833 math_type(accent_chr(tail))=math_char;
22834 scan_fifteen_bit_int();
22835 character(accent_chr(tail))=qi(cur_val%256);
22836 if ((cur_val >= var_code)&&fam_in_range) fam(accent_chr(tail))=cur_fam;
22837 else fam(accent_chr(tail))=(cur_val/256)%16;
22838 scan_math(nucleus(tail));
22839 }
22840
22841 @ @<Complain that the user should have said \.{\\mathaccent}@>=
22842 {@+print_err("Please use ");print_esc("mathaccent");
22843 print(" for accents in math mode");
22844 @.Please use \\mathaccent...@>
22845 help2("I'm changing \\accent to \\mathaccent here; wish me luck.",@/
22846 "(Accents are not the same in formulas as they are in text.)");
22847 error();
22848 }
22849
22850 @ @<Cases of |main_control| that build...@>=
22851 case mmode+vcenter: {@+scan_spec(vcenter_group, false);normal_paragraph();
22852 push_nest();mode=-vmode;prev_depth=ignore_depth;
22853 if (every_vbox!=null) begin_token_list(every_vbox, every_vbox_text);
22854 } @+break;
22855
22856 @ @<Cases of |handle...@>=
22857 case vcenter_group: {@+end_graf();unsave();save_ptr=save_ptr-2;
22858 p=vpack(link(head), saved(1), saved(0));pop_nest();
22859 tail_append(new_noad());type(tail)=vcenter_noad;
22860 math_type(nucleus(tail))=sub_box;info(nucleus(tail))=p;
22861 } @+break;
22862
22863 @ The routine that inserts a |style_node| holds no surprises.
22864
22865 @<Put each...@>=
22866 primitive("displaystyle", math_style, display_style);
22867 @!@:display\_style\_}{\.{\\displaystyle} primitive@>
22868 primitive("textstyle", math_style, text_style);
22869 @!@:text\_style\_}{\.{\\textstyle} primitive@>
22870 primitive("scriptstyle", math_style, script_style);
22871 @!@:script\_style\_}{\.{\\scriptstyle} primitive@>
22872 primitive("scriptscriptstyle", math_style, script_script_style);
22873 @!@:script\_script\_style\_}{\.{\\scriptscriptstyle} primitive@>
22874
22875 @ @<Cases of |print_cmd_chr|...@>=
22876 case math_style: print_style(chr_code);@+break;
22877
22878 @ @<Cases of |main_control| that build...@>=
22879 case mmode+math_style: tail_append(new_style(cur_chr))@;@+break;
22880 case mmode+non_script: {@+tail_append(new_glue(zero_glue));
22881 subtype(tail)=cond_math_glue;
22882 } @+break;
22883 case mmode+math_choice: append_choices();@+break;
22884
22885 @ The routine that scans the four mlists of a \.{\\mathchoice} is very
22886 much like the routine that builds discretionary nodes.
22887
22888 @<Declare act...@>=
22889 static void append_choices(void)
22890 {@+tail_append(new_choice());incr(save_ptr);saved(-1)=0;
22891 push_math(math_choice_group);scan_left_brace();
22892 }
22893
22894 @ @<Cases of |handle_right_brace|...@>=
22895 case math_choice_group: build_choices();@+break;
22896
22897 @ @<Declare act...@>=
22898 @t\4@>@<Declare the function called |fin_mlist|@>@t@>@;@/
22899 static void build_choices(void)
22900 {@+
22901 pointer p; /*the current mlist*/
22902 unsave();p=fin_mlist(null);
22903 switch (saved(-1)) {
22904 case 0: display_mlist(tail)=p;@+break;
22905 case 1: text_mlist(tail)=p;@+break;
22906 case 2: script_mlist(tail)=p;@+break;
22907 case 3: {@+script_script_mlist(tail)=p;decr(save_ptr);return;
22908 }
22909 } /*there are no other cases*/
22910 incr(saved(-1));push_math(math_choice_group);scan_left_brace();
22911 }
22912
22913 @ Subscripts and superscripts are attached to the previous nucleus by the
22914 @^superscripts@>@^subscripts@>
22915 action procedure called |sub_sup|. We use the facts that |sub_mark==sup_mark+1|
22916 and |subscr(p)==supscr(p)+1|.
22917
22918 @<Cases of |main_control| that build...@>=
22919 case mmode+sub_mark: case mmode+sup_mark: sub_sup();@+break;
22920
22921 @ @<Declare act...@>=
22922 static void sub_sup(void)
22923 {@+small_number t; /*type of previous sub/superscript*/
22924 pointer @!p; /*field to be filled by |scan_math|*/
22925 t=empty;p=null;
22926 if (tail!=head) if (scripts_allowed(tail))
22927 {@+p=supscr(tail)+cur_cmd-sup_mark; /*|supscr| or |subscr|*/
22928 t=math_type(p);
22929 }
22930 if ((p==null)||(t!=empty)) @<Insert a dummy noad to be sub/superscripted@>;
22931 scan_math(p);
22932 }
22933
22934 @ @<Insert a dummy...@>=
22935 {@+tail_append(new_noad());
22936 p=supscr(tail)+cur_cmd-sup_mark; /*|supscr| or |subscr|*/
22937 if (t!=empty)
22938 {@+if (cur_cmd==sup_mark)
22939 {@+print_err("Double superscript");
22940 @.Double superscript@>
22941 help1("I treat `x^1^2' essentially like `x^1{}^2'.");
22942 }
22943 else{@+print_err("Double subscript");
22944 @.Double subscript@>
22945 help1("I treat `x_1_2' essentially like `x_1{}_2'.");
22946 }
22947 error();
22948 }
22949 }
22950
22951 @ An operation like `\.{\\over}' causes the current mlist to go into a
22952 state of suspended animation: |incompleat_noad| points to a |fraction_noad|
22953 that contains the mlist-so-far as its numerator, while the denominator
22954 is yet to come. Finally when the mlist is finished, the denominator will
22955 go into the incompleat fraction noad, and that noad will become the
22956 whole formula, unless it is surrounded by `\.{\\left}' and `\.{\\right}'
22957 delimiters.
22958
22959 @d above_code 0 /* `\.{\\above}' */
22960 @d over_code 1 /* `\.{\\over}' */
22961 @d atop_code 2 /* `\.{\\atop}' */
22962 @d delimited_code 3 /* `\.{\\abovewithdelims}', etc.*/
22963
22964 @<Put each...@>=
22965 primitive("above", above, above_code);@/
22966 @!@:above\_}{\.{\\above} primitive@>
22967 primitive("over", above, over_code);@/
22968 @!@:over\_}{\.{\\over} primitive@>
22969 primitive("atop", above, atop_code);@/
22970 @!@:atop\_}{\.{\\atop} primitive@>
22971 primitive("abovewithdelims", above, delimited_code+above_code);@/
22972 @!@:above\_with\_delims\_}{\.{\\abovewithdelims} primitive@>
22973 primitive("overwithdelims", above, delimited_code+over_code);@/
22974 @!@:over\_with\_delims\_}{\.{\\overwithdelims} primitive@>
22975 primitive("atopwithdelims", above, delimited_code+atop_code);
22976 @!@:atop\_with\_delims\_}{\.{\\atopwithdelims} primitive@>
22977
22978 @ @<Cases of |print_cmd_chr|...@>=
22979 case above: switch (chr_code) {
22980 case over_code: print_esc("over");@+break;
22981 case atop_code: print_esc("atop");@+break;
22982 case delimited_code+above_code: print_esc("abovewithdelims");@+break;
22983 case delimited_code+over_code: print_esc("overwithdelims");@+break;
22984 case delimited_code+atop_code: print_esc("atopwithdelims");@+break;
22985 default:print_esc("above");
22986 } @+break;
22987
22988 @ @<Cases of |main_control| that build...@>=
22989 case mmode+above: math_fraction();@+break;
22990
22991 @ @<Declare act...@>=
22992 static void math_fraction(void)
22993 {@+small_number c; /*the type of generalized fraction we are scanning*/
22994 c=cur_chr;
22995 if (incompleat_noad!=null)
22996 @<Ignore the fraction operation and complain about this ambiguous case@>@;
22997 else{@+incompleat_noad=get_node(fraction_noad_size);
22998 type(incompleat_noad)=fraction_noad;
22999 subtype(incompleat_noad)=normal;
23000 math_type(numerator(incompleat_noad))=sub_mlist;
23001 info(numerator(incompleat_noad))=link(head);
23002 mem[denominator(incompleat_noad)].hh=empty_field;
23003 mem[left_delimiter(incompleat_noad)].qqqq=null_delimiter;
23004 mem[right_delimiter(incompleat_noad)].qqqq=null_delimiter;@/
23005 link(head)=null;tail=head;
23006 @<Use code |c| to distinguish between generalized fractions@>;
23007 }
23008 }
23009
23010 @ @<Use code |c|...@>=
23011 if (c >= delimited_code)
23012 {@+scan_delimiter(left_delimiter(incompleat_noad), false);
23013 scan_delimiter(right_delimiter(incompleat_noad), false);
23014 }
23015 switch (c%delimited_code) {
23016 case above_code: {@+scan_normal_dimen;
23017 thickness(incompleat_noad)=cur_val;
23018 } @+break;
23019 case over_code: thickness(incompleat_noad)=default_code;@+break;
23020 case atop_code: thickness(incompleat_noad)=0;
23021 } /*there are no other cases*/
23022
23023 @ @<Ignore the fraction...@>=
23024 {@+if (c >= delimited_code)
23025 {@+scan_delimiter(garbage, false);scan_delimiter(garbage, false);
23026 }
23027 if (c%delimited_code==above_code) scan_normal_dimen;
23028 print_err("Ambiguous; you need another { and }");
23029 @.Ambiguous...@>
23030 help3("I'm ignoring this fraction specification, since I don't",@/
23031 "know whether a construction like `x \\over y \\over z'",@/
23032 "means `{x \\over y} \\over z' or `x \\over {y \\over z}'.");
23033 error();
23034 }
23035
23036 @ At the end of a math formula or subformula, the |fin_mlist| routine is
23037 called upon to return a pointer to the newly completed mlist, and to
23038 pop the nest back to the enclosing semantic level. The parameter to
23039 |fin_mlist|, if not null, points to a |right_noad| that ends the
23040 current mlist; this |right_noad| has not yet been appended.
23041
23042 @<Declare the function called |fin_mlist|@>=
23043 static pointer fin_mlist(pointer @!p)
23044 {@+pointer q; /*the mlist to return*/
23045 if (incompleat_noad!=null) @<Compleat the incompleat noad@>@;
23046 else{@+link(tail)=p;q=link(head);
23047 }
23048 pop_nest();return q;
23049 }
23050
23051 @ @<Compleat...@>=
23052 {@+math_type(denominator(incompleat_noad))=sub_mlist;
23053 info(denominator(incompleat_noad))=link(head);
23054 if (p==null) q=incompleat_noad;
23055 else{@+q=info(numerator(incompleat_noad));
23056 if ((type(q)!=left_noad)||(delim_ptr==null)) confusion("right");
23057 @:this can't happen right}{\quad right@>
23058 info(numerator(incompleat_noad))=link(delim_ptr);
23059 link(delim_ptr)=incompleat_noad;link(incompleat_noad)=p;
23060 }
23061 }
23062
23063 @ Now at last we're ready to see what happens when a right brace occurs
23064 in a math formula. Two special cases are simplified here: Braces are effectively
23065 removed when they surround a single Ord without sub/superscripts, or when they
23066 surround an accent that is the nucleus of an Ord atom.
23067
23068 @<Cases of |handle...@>=
23069 case math_group: {@+unsave();decr(save_ptr);@/
23070 math_type(saved(0))=sub_mlist;p=fin_mlist(null);info(saved(0))=p;
23071 if (p!=null) if (link(p)==null)
23072 if (type(p)==ord_noad)
23073 {@+if (math_type(subscr(p))==empty)
23074 if (math_type(supscr(p))==empty)
23075 {@+mem[saved(0)].hh=mem[nucleus(p)].hh;
23076 free_node(p, noad_size);
23077 }
23078 }
23079 else if (type(p)==accent_noad) if (saved(0)==nucleus(tail))
23080 if (type(tail)==ord_noad) @<Replace the tail of the list by |p|@>;
23081 } @+break;
23082
23083 @ @<Replace the tail...@>=
23084 {@+q=head;while (link(q)!=tail) q=link(q);
23085 link(q)=p;free_node(tail, noad_size);tail=p;
23086 }
23087
23088 @ We have dealt with all constructions of math mode except `\.{\\left}' and
23089 `\.{\\right}', so the picture is completed by the following sections of
23090 the program.
23091
23092 @<Put each...@>=
23093 primitive("left", left_right, left_noad);
23094 @!@:left\_}{\.{\\left} primitive@>
23095 primitive("right", left_right, right_noad);
23096 @!@:right\_}{\.{\\right} primitive@>
23097 text(frozen_right)=text(cur_val);eqtb[frozen_right]=eqtb[cur_val];
23098
23099 @ @<Cases of |print_cmd_chr|...@>=
23100 case left_right: if (chr_code==left_noad) print_esc("left")
23101 @/@<Cases of |left_right| for |print_cmd_chr|@>;@/
23102 else print_esc("right");@+break;
23103
23104 @ @<Cases of |main_control| that build...@>=
23105 case mmode+left_right: math_left_right();@+break;
23106
23107 @ @<Declare act...@>=
23108 static void math_left_right(void)
23109 {@+small_number t; /*|left_noad| or |right_noad|*/
23110 pointer @!p; /*new noad*/
23111 pointer @!q; /*resulting mlist*/
23112 t=cur_chr;
23113 if ((t!=left_noad)&&(cur_group!=math_left_group))
23114 @<Try to recover from mismatched \.{\\right}@>@;
23115 else{@+p=new_noad();type(p)=t;
23116 scan_delimiter(delimiter(p), false);
23117 if (t==middle_noad)
23118 {@+type(p)=right_noad;subtype(p)=middle_noad;
23119 }
23120 if (t==left_noad) q=p;
23121 else{@+q=fin_mlist(p);unsave(); /*end of |math_left_group|*/
23122 }
23123 if (t!=right_noad)
23124 {@+push_math(math_left_group);link(head)=q;tail=p;
23125 delim_ptr=p;
23126 }
23127 else{@+
23128 tail_append(new_noad());type(tail)=inner_noad;
23129 math_type(nucleus(tail))=sub_mlist;
23130 info(nucleus(tail))=q;
23131 }
23132 }
23133 }
23134
23135 @ @<Try to recover from mismatch...@>=
23136 {@+if (cur_group==math_shift_group)
23137 {@+scan_delimiter(garbage, false);
23138 print_err("Extra ");
23139 if (t==middle_noad)
23140 {@+print_esc("middle");
23141 @.Extra \\middle.@>
23142 help1("I'm ignoring a \\middle that had no matching \\left.");
23143 }
23144 else{@+print_esc("right");
23145 @.Extra \\right.@>
23146 help1("I'm ignoring a \\right that had no matching \\left.");
23147 }
23148 error();
23149 }
23150 else off_save();
23151 }
23152
23153 @ Here is the only way out of math mode.
23154
23155 @<Cases of |main_control| that build...@>=
23156 case mmode+math_shift: if (cur_group==math_shift_group) after_math();
23157 else off_save();@+break;
23158
23159 @ @<Declare act...@>=
23160 static void after_math(void)
23161 {@+bool l; /*`\.{\\leqno}' instead of `\.{\\eqno}'*/
23162 bool @!danger; /*not enough symbol fonts are present*/
23163 int @!m; /*|mmode| or |-mmode|*/
23164 pointer @!p; /*the formula*/
23165 pointer @!a; /*box containing equation number*/
23166 @<Local variables for finishing a displayed formula@>@;
23167 danger=false;
23168 @<Check that the necessary fonts for math symbols are present; if not, flush
23169 the current math lists and set |danger:=true|@>;
23170 m=mode;l=false;p=fin_mlist(null); /*this pops the nest*/
23171 if (mode==-m) /*end of equation number*/
23172 {@+@<Check that another \.\$ follows@>;
23173 cur_mlist=p;cur_style=text_style;mlist_penalties=false;
23174 mlist_to_hlist();a=hpack(link(temp_head), natural);
23175 unsave();decr(save_ptr); /*now |cur_group==math_shift_group|*/
23176 if (saved(0)==1) l=true;
23177 danger=false;
23178 @<Check that the necessary fonts for math symbols are present; if not, flush
23179 the current math lists and set |danger:=true|@>;
23180 m=mode;p=fin_mlist(null);
23181 }
23182 else a=null;
23183 if (m < 0) @<Finish math in text@>@;
23184 else{@+if (a==null) @<Check that another \.\$ follows@>;
23185 @<Finish displayed math@>;
23186 }
23187 }
23188
23189 @ @<Check that the necessary fonts...@>=
23190 if ((font_params[fam_fnt(2+text_size)] < total_mathsy_params)||@|
23191 (font_params[fam_fnt(2+script_size)] < total_mathsy_params)||@|
23192 (font_params[fam_fnt(2+script_script_size)] < total_mathsy_params))
23193 {@+print_err("Math formula deleted: Insufficient symbol fonts");@/
23194 @.Math formula deleted...@>
23195 help3("Sorry, but I can't typeset math unless \\textfont 2",@/
23196 "and \\scriptfont 2 and \\scriptscriptfont 2 have all",@/
23197 "the \\fontdimen values needed in math symbol fonts.");
23198 error();flush_math();danger=true;
23199 }
23200 else if ((font_params[fam_fnt(3+text_size)] < total_mathex_params)||@|
23201 (font_params[fam_fnt(3+script_size)] < total_mathex_params)||@|
23202 (font_params[fam_fnt(3+script_script_size)] < total_mathex_params))
23203 {@+print_err("Math formula deleted: Insufficient extension fonts");@/
23204 help3("Sorry, but I can't typeset math unless \\textfont 3",@/
23205 "and \\scriptfont 3 and \\scriptscriptfont 3 have all",@/
23206 "the \\fontdimen values needed in math extension fonts.");
23207 error();flush_math();danger=true;
23208 }
23209
23210 @ The |unsave| is done after everything else here; hence an appearance of
23211 `\.{\\mathsurround}' inside of `\.{\$...\$}' affects the spacing at these
23212 particular \.\$'s. This is consistent with the conventions of
23213 `\.{\$\$...\$\$}', since `\.{\\abovedisplayskip}' inside a display affects the
23214 space above that display.
23215
23216 @<Finish math in text@>=
23217 {@+tail_append(new_math(math_surround, before));
23218 cur_mlist=p;cur_style=text_style;mlist_penalties=(mode > 0);mlist_to_hlist();
23219 link(tail)=link(temp_head);
23220 while (link(tail)!=null) tail=link(tail);
23221 tail_append(new_math(math_surround, after));
23222 space_factor=1000;unsave();
23223 }
23224
23225 @ \TeX\ gets to the following part of the program when the first `\.\$' ending
23226 a display has been scanned.
23227
23228 @<Check that another \.\$ follows@>=
23229 {@+get_x_token();
23230 if (cur_cmd!=math_shift)
23231 {@+print_err("Display math should end with $$");
23232 @.Display math...with \$\$@>
23233 help2("The `$' that I just saw supposedly matches a previous `$$'.",@/
23234 "So I shall assume that you typed `$$' both times.");
23235 back_error();
23236 }
23237 }
23238
23239 @ We have saved the worst for last: The fussiest part of math mode processing
23240 occurs when a displayed formula is being centered and placed with an optional
23241 equation number.
23242
23243 @<Local variables for finishing...@>=
23244 pointer @!b; /*box containing the equation*/
23245 scaled @!w; /*width of the equation*/
23246 scaled @!z; /*width of the line*/
23247 scaled @!e; /*width of equation number*/
23248 scaled @!q; /*width of equation number plus space to separate from equation*/
23249 scaled @!d; /*displacement of equation in the line*/
23250 scaled @!s; /*move the line right this much*/
23251 small_number @!g1, @!g2; /*glue parameter codes for before and after*/
23252 pointer @!r; /*kern node used to position the display*/
23253 pointer @!t; /*tail of adjustment list*/
23254
23255 @ At this time |p| points to the mlist for the formula; |a| is either
23256 |null| or it points to a box containing the equation number; and we are in
23257 vertical mode (or internal vertical mode).
23258
23259 @<Finish displayed math@>=
23260 cur_mlist=p;cur_style=display_style;mlist_penalties=false;
23261 mlist_to_hlist();p=link(temp_head);@/
23262 adjust_tail=adjust_head;b=hpack(p, natural);p=list_ptr(b);
23263 t=adjust_tail;adjust_tail=null;@/
23264 w=width(b);z=display_width;s=display_indent;
23265 if ((a==null)||danger)
23266 {@+e=0;q=0;
23267 }
23268 else{@+e=width(a);q=e+math_quad(text_size);
23269 }
23270 if (w+q > z)
23271 @<Squeeze the equation as much as possible; if there is an equation number
23272 that should go on a separate line by itself, set~|e:=0|@>;
23273 @<Determine the displacement, |d|, of the left edge of the equation, with
23274 respect to the line size |z|, assuming that |l=false|@>;
23275 @<Append the glue or equation number preceding the display@>;
23276 @<Append the display and perhaps also the equation number@>;
23277 @<Append the glue or equation number following the display@>;
23278 resume_after_display()
23279
23280 @ @<Declare act...@>=
23281 static void resume_after_display(void)
23282 {@+if (cur_group!=math_shift_group) confusion("display");
23283 @:this can't happen display}{\quad display@>
23284 unsave();prev_graf=prev_graf+3;
23285 push_nest();mode=hmode;space_factor=1000;set_cur_lang;clang=cur_lang;
23286 prev_graf=(norm_min(left_hyphen_min)*0100+norm_min(right_hyphen_min))
23287 *0200000+cur_lang;
23288 @<Scan an optional space@>;
23289 if (nest_ptr==1) build_page();
23290 }
23291
23292 @ The user can force the equation number to go on a separate line
23293 by causing its width to be zero.
23294
23295 @<Squeeze the equation as much as possible...@>=
23296 {@+if ((e!=0)&&((w-total_shrink[normal]+q <= z)||@|
23297 (total_shrink[fil]!=0)||(total_shrink[fill]!=0)||
23298 (total_shrink[filll]!=0)))
23299 {@+free_node(b, box_node_size);
23300 b=hpack(p, z-q, exactly);
23301 }
23302 else{@+e=0;
23303 if (w > z)
23304 {@+free_node(b, box_node_size);
23305 b=hpack(p, z, exactly);
23306 }
23307 }
23308 w=width(b);
23309 }
23310
23311 @ We try first to center the display without regard to the existence of
23312 the equation number. If that would make it too close (where ``too close''
23313 means that the space between display and equation number is less than the
23314 width of the equation number), we either center it in the remaining space
23315 or move it as far from the equation number as possible. The latter alternative
23316 is taken only if the display begins with glue, since we assume that the
23317 user put glue there to control the spacing precisely.
23318
23319 @<Determine the displacement, |d|, of the left edge of the equation...@>=
23320 d=half(z-w);
23321 if ((e > 0)&&(d < 2*e)) /*too close*/
23322 {@+d=half(z-w-e);
23323 if (p!=null) if (!is_char_node(p)) if (type(p)==glue_node) d=0;
23324 }
23325
23326 @ If the equation number is set on a line by itself, either before or
23327 after the formula, we append an infinite penalty so that no page break will
23328 separate the display from its number; and we use the same size and
23329 displacement for all three potential lines of the display, even though
23330 `\.{\\parshape}' may specify them differently.
23331
23332 @<Append the glue or equation number preceding the display@>=
23333 tail_append(new_penalty(pre_display_penalty));@/
23334 if ((d+s <= pre_display_size)||l) /*not enough clearance*/
23335 {@+g1=above_display_skip_code;g2=below_display_skip_code;
23336 }
23337 else{@+g1=above_display_short_skip_code;
23338 g2=below_display_short_skip_code;
23339 }
23340 if (l&&(e==0)) /*it follows that |type(a)==hlist_node|*/
23341 {@+shift_amount(a)=s;append_to_vlist(a);
23342 tail_append(new_penalty(inf_penalty));
23343 }
23344 else tail_append(new_param_glue(g1))
23345
23346 @ @<Append the display and perhaps also the equation number@>=
23347 if (e!=0)
23348 {@+r=new_kern(z-w-e-d);
23349 if (l)
23350 {@+link(a)=r;link(r)=b;b=a;d=0;
23351 }
23352 else{@+link(b)=r;link(r)=a;
23353 }
23354 b=hpack(b, natural);
23355 }
23356 shift_amount(b)=s+d;append_to_vlist(b)
23357
23358 @ @<Append the glue or equation number following the display@>=
23359 if ((a!=null)&&(e==0)&&!l)
23360 {@+tail_append(new_penalty(inf_penalty));
23361 shift_amount(a)=s+z-width(a);
23362 append_to_vlist(a);
23363 g2=0;
23364 }
23365 if (t!=adjust_head) /*migrating material comes after equation number*/
23366 {@+link(tail)=link(adjust_head);tail=t;
23367 }
23368 tail_append(new_penalty(post_display_penalty));
23369 if (g2 > 0) tail_append(new_param_glue(g2))
23370
23371 @ When \.{\\halign} appears in a display, the alignment routines operate
23372 essentially as they do in vertical mode. Then the following program is
23373 activated, with |p| and |q| pointing to the beginning and end of the
23374 resulting list, and with |aux_save| holding the |prev_depth| value.
23375
23376 @<Finish an alignment in a display@>=
23377 {@+do_assignments();
23378 if (cur_cmd!=math_shift) @<Pontificate about improper alignment in display@>@;
23379 else@<Check that another \.\$ follows@>;
23380 pop_nest();
23381 tail_append(new_penalty(pre_display_penalty));
23382 tail_append(new_param_glue(above_display_skip_code));
23383 link(tail)=p;
23384 if (p!=null) tail=q;
23385 tail_append(new_penalty(post_display_penalty));
23386 tail_append(new_param_glue(below_display_skip_code));
23387 prev_depth=aux_save.sc;resume_after_display();
23388 }
23389
23390 @ @<Pontificate...@>=
23391 {@+print_err("Missing $$ inserted");
23392 @.Missing {\$\$} inserted@>
23393 help2("Displays can use special alignments (like \\eqalignno)",@/
23394 "only if nothing but the alignment itself is between $$'s.");
23395 back_error();
23396 }
23397
23398 @* Mode-independent processing.
23399 The long |main_control| procedure has now been fully specified, except for
23400 certain activities that are independent of the current mode. These activities
23401 do not change the current vlist or hlist or mlist; if they change anything,
23402 it is the value of a parameter or the meaning of a control sequence.
23403
23404 Assignments to values in |eqtb| can be global or local. Furthermore, a
23405 control sequence can be defined to be `\.{\\long}', `\.{\\protected}',
23406 or `\.{\\outer}', and it might or might not be expanded. The prefixes
23407 `\.{\\global}', `\.{\\long}', `\.{\\protected}',
23408 and `\.{\\outer}' can occur in any order. Therefore we assign binary numeric
23409 codes, making it possible to accumulate the union of all specified prefixes
23410 by adding the corresponding codes. (\PASCAL's |set| operations could also
23411 have been used.)
23412
23413 @<Put each...@>=
23414 primitive("long", prefix, 1);
23415 @!@:long\_}{\.{\\long} primitive@>
23416 primitive("outer", prefix, 2);
23417 @!@:outer\_}{\.{\\outer} primitive@>
23418 primitive("global", prefix, 4);
23419 @!@:global\_}{\.{\\global} primitive@>
23420 primitive("def", def, 0);
23421 @!@:def\_}{\.{\\def} primitive@>
23422 primitive("gdef", def, 1);
23423 @!@:gdef\_}{\.{\\gdef} primitive@>
23424 primitive("edef", def, 2);
23425 @!@:edef\_}{\.{\\edef} primitive@>
23426 primitive("xdef", def, 3);
23427 @!@:xdef\_}{\.{\\xdef} primitive@>
23428
23429 @ @<Cases of |print_cmd_chr|...@>=
23430 case prefix: if (chr_code==1) print_esc("long");
23431 else if (chr_code==2) print_esc("outer")
23432 @/@<Cases of |prefix| for |print_cmd_chr|@>;@/
23433 else print_esc("global");@+break;
23434 case def: if (chr_code==0) print_esc("def");
23435 else if (chr_code==1) print_esc("gdef");
23436 else if (chr_code==2) print_esc("edef");
23437 else print_esc("xdef");@+break;
23438
23439 @ Every prefix, and every command code that might or might not be prefixed,
23440 calls the action procedure |prefixed_command|. This routine accumulates
23441 a sequence of prefixes until coming to a non-prefix, then it carries out
23442 the command.
23443
23444 @<Cases of |main_control| that don't...@>=
23445 any_mode(toks_register):
23446 any_mode(assign_toks):
23447 any_mode(assign_int):
23448 any_mode(assign_dimen):
23449 any_mode(assign_glue):
23450 any_mode(assign_mu_glue):
23451 any_mode(assign_font_dimen):
23452 any_mode(assign_font_int):
23453 any_mode(set_aux):
23454 any_mode(set_prev_graf):
23455 any_mode(set_page_dimen):
23456 any_mode(set_page_int):
23457 any_mode(set_box_dimen):
23458 any_mode(set_shape):
23459 any_mode(def_code):
23460 any_mode(def_family):
23461 any_mode(set_font):
23462 any_mode(def_font):
23463 any_mode(internal_register):
23464 any_mode(advance):
23465 any_mode(multiply):
23466 any_mode(divide):
23467 any_mode(prefix):
23468 any_mode(let):
23469 any_mode(shorthand_def):
23470 any_mode(read_to_cs):
23471 any_mode(def):
23472 any_mode(set_box):
23473 any_mode(hyph_data):
23474 any_mode(set_interaction): prefixed_command();@+break;
23475
23476 @ If the user says, e.g., `\.{\\global\\global}', the redundancy is
23477 silently accepted.
23478
23479 @<Declare act...@>=
23480 @t\4@>@<Declare subprocedures for |prefixed_command|@>@t@>@;@/
23481 static void prefixed_command(void)
23482 {@+
23483 small_number a; /*accumulated prefix codes so far*/
23484 internal_font_number @!f; /*identifies a font*/
23485 int @!j; /*index into a \.{\\parshape} specification*/
23486 font_index @!k; /*index into |font_info|*/
23487 pointer @!p, @!q; /*for temporary short-term use*/
23488 int @!n; /*ditto*/
23489 bool @!e; /*should a definition be expanded? or was \.{\\let} not done?*/
23490 a=0;
23491 while (cur_cmd==prefix)
23492 {@+if (!odd(a/cur_chr)) a=a+cur_chr;
23493 @<Get the next non-blank non-relax...@>;
23494 if (cur_cmd <= max_non_prefixed_command)
23495 @<Discard erroneous prefixes and |return|@>;
23496 if (tracing_commands > 2) if (eTeX_ex) show_cur_cmd_chr();
23497 }
23498 @<Discard the prefixes \.{\\long} and \.{\\outer} if they are irrelevant@>;
23499 @<Adjust \(f)for the setting of \.{\\globaldefs}@>;
23500 switch (cur_cmd) {
23501 @t\4@>@<Assignments@>@;
23502 default:confusion("prefix");
23503 @:this can't happen prefix}{\quad prefix@>
23504 }
23505 done: @<Insert a token saved by \.{\\afterassignment}, if any@>;
23506 }
23507
23508 @ @<Discard erroneous...@>=
23509 {@+print_err("You can't use a prefix with `");
23510 @.You can't use a prefix with x@>
23511 print_cmd_chr(cur_cmd, cur_chr);print_char('\'');
23512 help1("I'll pretend you didn't say \\long or \\outer or \\global.");
23513 if (eTeX_ex) help_line[0]=@|
23514 "I'll pretend you didn't say \\long or \\outer or \\global or \\protected.";
23515 back_error();return;
23516 }
23517
23518 @ @<Discard the prefixes...@>=
23519 if (a >= 8)
23520 {@+j=protected_token;a=a-8;
23521 }
23522 else j=0;
23523 if ((cur_cmd!=def)&&((a%4!=0)||(j!=0)))
23524 {@+print_err("You can't use `");print_esc("long");print("' or `");
23525 print_esc("outer");
23526 help1("I'll pretend you didn't say \\long or \\outer here.");
23527 if (eTeX_ex)
23528 {@+help_line[0]=@|
23529 "I'll pretend you didn't say \\long or \\outer or \\protected here.";
23530 print("' or `");print_esc("protected");
23531 }
23532 print("' with `");
23533 @.You can't use \\long...@>
23534 print_cmd_chr(cur_cmd, cur_chr);print_char('\'');
23535 error();
23536 }
23537
23538 @ The previous routine does not have to adjust |a| so that |a%4==0|,
23539 since the following routines test for the \.{\\global} prefix as follows.
23540
23541 @d global (a >= 4)
23542 @d define(A, B, C) if (global) geq_define(A, B, C);@+else eq_define(A, B, C)
23543 @d word_define(A, B) if (global) geq_word_define(A, B);@+else eq_word_define(A, B)
23544
23545 @<Adjust \(f)for the setting of \.{\\globaldefs}@>=
23546 if (global_defs!=0)
23547 if (global_defs < 0)
23548 {@+if (global) a=a-4;
23549 }
23550 else{@+if (!global) a=a+4;
23551 }
23552
23553 @ When a control sequence is to be defined, by \.{\\def} or \.{\\let} or
23554 something similar, the |get_r_token| routine will substitute a special
23555 control sequence for a token that is not redefinable.
23556
23557 @<Declare subprocedures for |prefixed_command|@>=
23558 static void get_r_token(void)
23559 {@+
23560 restart: @/do@+{get_token();
23561 }@+ while (!(cur_tok!=space_token));
23562 if ((cur_cs==0)||(cur_cs > frozen_control_sequence))
23563 {@+print_err("Missing control sequence inserted");
23564 @.Missing control...@>
23565 help5("Please don't say `\\def cs{...}', say `\\def\\cs{...}'.",@/
23566 "I've inserted an inaccessible control sequence so that your",@/
23567 "definition will be completed without mixing me up too badly.",@/
23568 "You can recover graciously from this error, if you're",@/
23569 "careful; see exercise 27.2 in The TeXbook.");
23570 @:TeXbook}{\sl The \TeX book@>
23571 if (cur_cs==0) back_input();
23572 cur_tok=cs_token_flag+frozen_protection;ins_error();goto restart;
23573 }
23574 }
23575
23576 @ @<Initialize table entries...@>=
23577 text(frozen_protection)=s_no("inaccessible");
23578 @.inaccessible@>
23579
23580 @ Here's an example of the way many of the following routines operate.
23581 (Unfortunately, they aren't all as simple as this.)
23582
23583 @<Assignments@>=
23584 case set_font: define(cur_font_loc, data, cur_chr);@+break;
23585
23586 @ When a |def| command has been scanned,
23587 |cur_chr| is odd if the definition is supposed to be global, and
23588 |cur_chr >= 2| if the definition is supposed to be expanded.
23589
23590 @<Assignments@>=
23591 case def: {@+uint32_t def_fl;
23592 if (odd(cur_chr)&&!global&&(global_defs >= 0)) a=a+4;
23593 e=(cur_chr >= 2);get_r_token();p=cur_cs; def_fl=cur_file_line;
23594 q=scan_toks(true, e);
23595 if (j!=0)
23596 {@+q=get_avail();info(q)=j;link(q)=link(def_ref);
23597 link(def_ref)=q;
23598 }
23599 define(p, call+(a%4), def_ref);
23600 fl_mem[def_ref]=def_fl;
23601 } @+break;
23602
23603 @ Both \.{\\let} and \.{\\futurelet} share the command code |let|.
23604
23605 @<Put each...@>=
23606 primitive("let", let, normal);@/
23607 @!@:let\_}{\.{\\let} primitive@>
23608 primitive("futurelet", let, normal+1);@/
23609 @!@:future\_let\_}{\.{\\futurelet} primitive@>
23610
23611 @ @<Cases of |print_cmd_chr|...@>=
23612 case let: if (chr_code!=normal) print_esc("futurelet");@+else print_esc("let");@+break;
23613
23614 @ @<Assignments@>=
23615 case let: {@+n=cur_chr;
23616 get_r_token();p=cur_cs;
23617 if (n==normal)
23618 {@+@/do@+{get_token();
23619 }@+ while (!(cur_cmd!=spacer));
23620 if (cur_tok==other_token+'=')
23621 {@+get_token();
23622 if (cur_cmd==spacer) get_token();
23623 }
23624 }
23625 else{@+get_token();q=cur_tok;get_token();back_input();
23626 cur_tok=q;back_input(); /*look ahead, then back up*/
23627 } /*note that |back_input| doesn't affect |cur_cmd|, |cur_chr|*/
23628 if (cur_cmd >= call) add_token_ref(cur_chr);
23629 else if ((cur_cmd==internal_register)||(cur_cmd==toks_register))
23630 if ((cur_chr < mem_bot)||(cur_chr > lo_mem_stat_max))
23631 add_sa_ref(cur_chr);
23632 define(p, cur_cmd, cur_chr);
23633 } @+break;
23634
23635 @ A \.{\\chardef} creates a control sequence whose |cmd| is |char_given|;
23636 a \.{\\mathchardef} creates a control sequence whose |cmd| is |math_given|;
23637 and the corresponding |chr| is the character code or math code. A \.{\\countdef}
23638 or \.{\\dimendef} or \.{\\skipdef} or \.{\\muskipdef} creates a control
23639 sequence whose |cmd| is |assign_int| or \dots\ or |assign_mu_glue|, and the
23640 corresponding |chr| is the |eqtb| location of the internal register in question.
23641
23642 @d char_def_code 0 /*|shorthand_def| for \.{\\chardef}*/
23643 @d math_char_def_code 1 /*|shorthand_def| for \.{\\mathchardef}*/
23644 @d count_def_code 2 /*|shorthand_def| for \.{\\countdef}*/
23645 @d dimen_def_code 3 /*|shorthand_def| for \.{\\dimendef}*/
23646 @d skip_def_code 4 /*|shorthand_def| for \.{\\skipdef}*/
23647 @d mu_skip_def_code 5 /*|shorthand_def| for \.{\\muskipdef}*/
23648 @d toks_def_code 6 /*|shorthand_def| for \.{\\toksdef}*/
23649
23650 @<Put each...@>=
23651 primitive("chardef", shorthand_def, char_def_code);@/
23652 @!@:char\_def\_}{\.{\\chardef} primitive@>
23653 primitive("mathchardef", shorthand_def, math_char_def_code);@/
23654 @!@:math\_char\_def\_}{\.{\\mathchardef} primitive@>
23655 primitive("countdef", shorthand_def, count_def_code);@/
23656 @!@:count\_def\_}{\.{\\countdef} primitive@>
23657 primitive("dimendef", shorthand_def, dimen_def_code);@/
23658 @!@:dimen\_def\_}{\.{\\dimendef} primitive@>
23659 primitive("skipdef", shorthand_def, skip_def_code);@/
23660 @!@:skip\_def\_}{\.{\\skipdef} primitive@>
23661 primitive("muskipdef", shorthand_def, mu_skip_def_code);@/
23662 @!@:mu\_skip\_def\_}{\.{\\muskipdef} primitive@>
23663 primitive("toksdef", shorthand_def, toks_def_code);@/
23664 @!@:toks\_def\_}{\.{\\toksdef} primitive@>
23665
23666 @ @<Cases of |print_cmd_chr|...@>=
23667 case shorthand_def: switch (chr_code) {
23668 case char_def_code: print_esc("chardef");@+break;
23669 case math_char_def_code: print_esc("mathchardef");@+break;
23670 case count_def_code: print_esc("countdef");@+break;
23671 case dimen_def_code: print_esc("dimendef");@+break;
23672 case skip_def_code: print_esc("skipdef");@+break;
23673 case mu_skip_def_code: print_esc("muskipdef");@+break;
23674 default:print_esc("toksdef");
23675 } @+break;
23676 case char_given: {@+print_esc("char");print_hex(chr_code);
23677 } @+break;
23678 case math_given: {@+print_esc("mathchar");print_hex(chr_code);
23679 } @+break;
23680
23681 @ We temporarily define |p| to be |relax|, so that an occurrence of |p|
23682 while scanning the definition will simply stop the scanning instead of
23683 producing an ``undefined control sequence'' error or expanding the
23684 previous meaning. This allows, for instance, `\.{\\chardef\\foo=123\\foo}'.
23685
23686 @<Assignments@>=
23687 case shorthand_def: {@+n=cur_chr;get_r_token();p=cur_cs;define(p, relax, 256);
23688 scan_optional_equals();
23689 switch (n) {
23690 case char_def_code: {@+scan_char_num();define(p, char_given, cur_val);
23691 } @+break;
23692 case math_char_def_code: {@+scan_fifteen_bit_int();define(p, math_given, cur_val);
23693 } @+break;
23694 default:{@+scan_register_num();
23695 if (cur_val > 255)
23696 {@+j=n-count_def_code; /*|int_val dotdot box_val|*/
23697 if (j > mu_val) j=tok_val; /*|int_val dotdot mu_val| or |tok_val|*/
23698 find_sa_element(j, cur_val, true);add_sa_ref(cur_ptr);
23699 if (j==tok_val) j=toks_register;@+else j=internal_register;
23700 define(p, j, cur_ptr);
23701 }
23702 else
23703 switch (n) {
23704 case count_def_code: define(p, assign_int, count_base+cur_val);@+break;
23705 case dimen_def_code: define(p, assign_dimen, scaled_base+cur_val);@+break;
23706 case skip_def_code: define(p, assign_glue, skip_base+cur_val);@+break;
23707 case mu_skip_def_code: define(p, assign_mu_glue, mu_skip_base+cur_val);@+break;
23708 case toks_def_code: define(p, assign_toks, toks_base+cur_val);
23709 } /*there are no other cases*/
23710 }
23711 }
23712 } @+break;
23713
23714 @ @<Assignments@>=
23715 case read_to_cs: {@+j=cur_chr;scan_int();n=cur_val;
23716 if (!scan_keyword("to"))
23717 @.to@>
23718 {@+print_err("Missing `to' inserted");
23719 @.Missing `to'...@>
23720 help2("You should have said `\\read<number> to \\cs'.",@/
23721 "I'm going to look for the \\cs now.");error();
23722 }
23723 get_r_token();
23724 p=cur_cs;read_toks(n, p, j);define(p, call, cur_val);
23725 } @+break;
23726
23727 @ The token-list parameters, \.{\\output} and \.{\\everypar}, etc., receive
23728 their values in the following way. (For safety's sake, we place an
23729 enclosing pair of braces around an \.{\\output} list.)
23730
23731 @<Assignments@>=
23732 case toks_register: case assign_toks: {@+uint32_t def_fl=cur_file_line; q=cur_cs;
23733 e=false; /*just in case, will be set |true| for sparse array elements*/
23734 if (cur_cmd==toks_register)
23735 if (cur_chr==mem_bot)
23736 {@+scan_register_num();
23737 if (cur_val > 255)
23738 {@+find_sa_element(tok_val, cur_val, true);
23739 cur_chr=cur_ptr;e=true;
23740 }
23741 else cur_chr=toks_base+cur_val;
23742 }
23743 else e=true;
23744 p=cur_chr; /*|p==every_par_loc| or |output_routine_loc| or \dots*/
23745 scan_optional_equals();
23746 @<Get the next non-blank non-relax non-call token@>;
23747 if (cur_cmd!=left_brace) @<If the right-hand side is a token parameter or
23748 token register, finish the assignment and |goto done|@>;
23749 back_input();cur_cs=q;q=scan_toks(false, false);
23750 if (link(def_ref)==null) /*empty list: revert to the default*/
23751 {@+sa_define(p, null, p, undefined_cs, null);free_avail(def_ref);
23752 }
23753 else{@+if ((p==output_routine_loc)&&!e) /*enclose in curlies*/
23754 {@+link(q)=get_avail();q=link(q);
23755 info(q)=right_brace_token+'}';
23756 fl_mem[q]=FILE_LINE(system_file, system_insert);
23757 q=get_avail();info(q)=left_brace_token+'{';
23758 fl_mem[q]=FILE_LINE(system_file, system_insert);
23759 link(q)=link(def_ref);link(def_ref)=q;
23760 }
23761 sa_define(p, def_ref, p, call, def_ref);
23762 fl_mem[def_ref]=def_fl;
23763 }
23764 } @+break;
23765
23766 @ @<If the right-hand side is a token parameter...@>=
23767 if ((cur_cmd==toks_register)||(cur_cmd==assign_toks))
23768 {@+if (cur_cmd==toks_register)
23769 if (cur_chr==mem_bot)
23770 {@+scan_register_num();
23771 if (cur_val < 256) q=equiv(toks_base+cur_val);
23772 else{@+find_sa_element(tok_val, cur_val, false);
23773 if (cur_ptr==null) q=null;
23774 else q=sa_ptr(cur_ptr);
23775 }
23776 }
23777 else q=sa_ptr(cur_chr);
23778 else q=equiv(cur_chr);
23779 if (q==null) sa_define(p, null, p, undefined_cs, null);
23780 else{@+add_token_ref(q);sa_define(p, q, p, call, q);
23781 }
23782 goto done;
23783 }
23784
23785 @ Similar routines are used to assign values to the numeric parameters.
23786
23787 @<Assignments@>=
23788 case assign_int: {@+p=cur_chr;scan_optional_equals();scan_int();
23789 word_define(p, cur_val);
23790 } @+break;
23791 case assign_dimen: {@+p=cur_chr;scan_optional_equals();
23792 scan_normal_dimen;word_define(p, cur_val);
23793 } @+break;
23794 case assign_glue: case assign_mu_glue: {@+p=cur_chr;n=cur_cmd;scan_optional_equals();
23795 if (n==assign_mu_glue) scan_glue(mu_val);@+else scan_glue(glue_val);
23796 trap_zero_glue();
23797 define(p, glue_ref, cur_val);
23798 } @+break;
23799
23800 @ When a glue register or parameter becomes zero, it will always point to
23801 |zero_glue| because of the following procedure. (Exception: The tabskip
23802 glue isn't trapped while preambles are being scanned.)
23803
23804 @<Declare subprocedures for |prefixed_command|@>=
23805 static void trap_zero_glue(void)
23806 {@+if ((width(cur_val)==0)&&(stretch(cur_val)==0)&&(shrink(cur_val)==0))
23807 {@+add_glue_ref(zero_glue);
23808 delete_glue_ref(cur_val);cur_val=zero_glue;
23809 }
23810 }
23811
23812 @ The various character code tables are changed by the |def_code| commands,
23813 and the font families are declared by |def_family|.
23814
23815 @<Put each...@>=
23816 primitive("catcode", def_code, cat_code_base);
23817 @!@:cat\_code\_}{\.{\\catcode} primitive@>
23818 primitive("mathcode", def_code, math_code_base);
23819 @!@:math\_code\_}{\.{\\mathcode} primitive@>
23820 primitive("lccode", def_code, lc_code_base);
23821 @!@:lc\_code\_}{\.{\\lccode} primitive@>
23822 primitive("uccode", def_code, uc_code_base);
23823 @!@:uc\_code\_}{\.{\\uccode} primitive@>
23824 primitive("sfcode", def_code, sf_code_base);
23825 @!@:sf\_code\_}{\.{\\sfcode} primitive@>
23826 primitive("delcode", def_code, del_code_base);
23827 @!@:del\_code\_}{\.{\\delcode} primitive@>
23828 primitive("textfont", def_family, math_font_base);
23829 @!@:text\_font\_}{\.{\\textfont} primitive@>
23830 primitive("scriptfont", def_family, math_font_base+script_size);
23831 @!@:script\_font\_}{\.{\\scriptfont} primitive@>
23832 primitive("scriptscriptfont", def_family, math_font_base+script_script_size);
23833 @!@:script\_script\_font\_}{\.{\\scriptscriptfont} primitive@>
23834
23835 @ @<Cases of |print_cmd_chr|...@>=
23836 case def_code: if (chr_code==cat_code_base) print_esc("catcode");
23837 else if (chr_code==math_code_base) print_esc("mathcode");
23838 else if (chr_code==lc_code_base) print_esc("lccode");
23839 else if (chr_code==uc_code_base) print_esc("uccode");
23840 else if (chr_code==sf_code_base) print_esc("sfcode");
23841 else print_esc("delcode");@+break;
23842 case def_family: print_size(chr_code-math_font_base);@+break;
23843
23844 @ The different types of code values have different legal ranges; the
23845 following program is careful to check each case properly.
23846
23847 @<Assignments@>=
23848 case def_code: {@+@<Let |n| be the largest legal code value, based on |cur_chr|@>;
23849 p=cur_chr;scan_char_num();p=p+cur_val;scan_optional_equals();
23850 scan_int();
23851 if (((cur_val < 0)&&(p < del_code_base))||(cur_val > n))
23852 {@+print_err("Invalid code (");print_int(cur_val);
23853 @.Invalid code@>
23854 if (p < del_code_base) print("), should be in the range 0..");
23855 else print("), should be at most ");
23856 print_int(n);
23857 help1("I'm going to use 0 instead of that illegal code value.");@/
23858 error();cur_val=0;
23859 }
23860 if (p < math_code_base) define(p, data, cur_val);
23861 else if (p < del_code_base) define(p, data, hi(cur_val));
23862 else word_define(p, cur_val);
23863 } @+break;
23864
23865 @ @<Let |n| be the largest...@>=
23866 if (cur_chr==cat_code_base) n=max_char_code;
23867 else if (cur_chr==math_code_base) n=0100000;
23868 else if (cur_chr==sf_code_base) n=077777;
23869 else if (cur_chr==del_code_base) n=077777777;
23870 else n=255
23871
23872 @ @<Assignments@>=
23873 case def_family: {@+p=cur_chr;scan_four_bit_int();p=p+cur_val;
23874 scan_optional_equals();scan_font_ident();define(p, data, cur_val);
23875 } @+break;
23876
23877 @ Next we consider changes to \TeX's numeric registers.
23878
23879 @<Assignments@>=
23880 case internal_register: case advance:
23881 case multiply: case divide: do_register_command(a);@+break;
23882
23883 @ We use the fact that |internal_register < advance < multiply < divide|.
23884
23885 @<Declare subprocedures for |prefixed_command|@>=
23886 static void do_register_command(small_number @!a)
23887 {@+
23888 pointer l, @!q, @!r, @!s; /*for list manipulation*/
23889 int @!p; /*type of register involved*/
23890 bool @!e; /*does |l| refer to a sparse array element?*/
23891 int @!w; /*integer or dimen value of |l|*/
23892 q=cur_cmd;
23893 e=false; /*just in case, will be set |true| for sparse array elements*/
23894 @<Compute the register location |l| and its type |p|; but |return| if invalid@>;
23895 if (q==internal_register) scan_optional_equals();
23896 else if (scan_keyword("by")) do_nothing; /*optional `\.{by}'*/
23897 @.by@>
23898 arith_error=false;
23899 if (q < multiply) @<Compute result of |register| or |advance|, put it in |cur_val|@>@;
23900 else@<Compute result of |multiply| or |divide|, put it in |cur_val|@>;
23901 if (arith_error)
23902 {@+print_err("Arithmetic overflow");
23903 @.Arithmetic overflow@>
23904 help2("I can't carry out that multiplication or division,",@/
23905 "since the result is out of range.");
23906 if (p >= glue_val) delete_glue_ref(cur_val);
23907 error();return;
23908 }
23909 if (p < glue_val) sa_word_define(l, cur_val);
23910 else{@+trap_zero_glue();sa_define(l, cur_val, l, glue_ref, cur_val);
23911 }
23912 }
23913
23914 @ Here we use the fact that the consecutive codes |int_val dotdot mu_val| and
23915 |assign_int dotdot assign_mu_glue| correspond to each other nicely.
23916
23917 @<Compute the register location |l| and its type |p|...@>=
23918 {@+if (q!=internal_register)
23919 {@+get_x_token();
23920 if ((cur_cmd >= assign_int)&&(cur_cmd <= assign_mu_glue))
23921 {@+l=cur_chr;p=cur_cmd-assign_int;goto found;
23922 }
23923 if (cur_cmd!=internal_register)
23924 {@+print_err("You can't use `");print_cmd_chr(cur_cmd, cur_chr);
23925 @.You can't use x after ...@>
23926 print("' after ");print_cmd_chr(q, 0);
23927 help1("I'm forgetting what you said and not changing anything.");
23928 error();return;
23929 }
23930 }
23931 if ((cur_chr < mem_bot)||(cur_chr > lo_mem_stat_max))
23932 {@+l=cur_chr;p=sa_type(l);e=true;
23933 }
23934 else{@+p=cur_chr-mem_bot;scan_register_num();
23935 if (cur_val > 255)
23936 {@+find_sa_element(p, cur_val, true);l=cur_ptr;e=true;
23937 }
23938 else
23939 switch (p) {
23940 case int_val: l=cur_val+count_base;@+break;
23941 case dimen_val: l=cur_val+scaled_base;@+break;
23942 case glue_val: l=cur_val+skip_base;@+break;
23943 case mu_val: l=cur_val+mu_skip_base;
23944 } /*there are no other cases*/
23945 }
23946 }
23947 found: if (p < glue_val) @+if (e) w=sa_int(l);@+else w=eqtb[l].i;
23948 else if (e) s=sa_ptr(l);@+else s=equiv(l)
23949
23950 @ @<Compute result of |register| or |advance|...@>=
23951 if (p < glue_val)
23952 {@+if (p==int_val) scan_int();@+else scan_normal_dimen;
23953 if (q==advance) cur_val=cur_val+w;
23954 }
23955 else{@+scan_glue(p);
23956 if (q==advance) @<Compute the sum of two glue specs@>;
23957 }
23958
23959 @ @<Compute the sum of two glue specs@>=
23960 {@+q=new_spec(cur_val);r=s;
23961 delete_glue_ref(cur_val);
23962 width(q)=width(q)+width(r);
23963 if (stretch(q)==0) stretch_order(q)=normal;
23964 if (stretch_order(q)==stretch_order(r)) stretch(q)=stretch(q)+stretch(r);
23965 else if ((stretch_order(q) < stretch_order(r))&&(stretch(r)!=0))
23966 {@+stretch(q)=stretch(r);stretch_order(q)=stretch_order(r);
23967 }
23968 if (shrink(q)==0) shrink_order(q)=normal;
23969 if (shrink_order(q)==shrink_order(r)) shrink(q)=shrink(q)+shrink(r);
23970 else if ((shrink_order(q) < shrink_order(r))&&(shrink(r)!=0))
23971 {@+shrink(q)=shrink(r);shrink_order(q)=shrink_order(r);
23972 }
23973 cur_val=q;
23974 }
23975
23976 @ @<Compute result of |multiply| or |divide|...@>=
23977 {@+scan_int();
23978 if (p < glue_val)
23979 if (q==multiply)
23980 if (p==int_val) cur_val=mult_integers(w, cur_val);
23981 else cur_val=nx_plus_y(w, cur_val, 0);
23982 else cur_val=x_over_n(w, cur_val);
23983 else{@+r=new_spec(s);
23984 if (q==multiply)
23985 {@+width(r)=nx_plus_y(width(s), cur_val, 0);
23986 stretch(r)=nx_plus_y(stretch(s), cur_val, 0);
23987 shrink(r)=nx_plus_y(shrink(s), cur_val, 0);
23988 }
23989 else{@+width(r)=x_over_n(width(s), cur_val);
23990 stretch(r)=x_over_n(stretch(s), cur_val);
23991 shrink(r)=x_over_n(shrink(s), cur_val);
23992 }
23993 cur_val=r;
23994 }
23995 }
23996
23997 @ The processing of boxes is somewhat different, because we may need
23998 to scan and create an entire box before we actually change the value of the old
23999 one.
24000
24001 @<Assignments@>=
24002 case set_box: {@+scan_register_num();
24003 if (global) n=global_box_flag+cur_val;@+else n=box_flag+cur_val;
24004 scan_optional_equals();
24005 if (set_box_allowed) scan_box(n);
24006 else{@+print_err("Improper ");print_esc("setbox");
24007 @.Improper \\setbox@>
24008 help2("Sorry, \\setbox is not allowed after \\halign in a display,",@/
24009 "or between \\accent and an accented character.");error();
24010 }
24011 } @+break;
24012
24013 @ The |space_factor| or |prev_depth| settings are changed when a |set_aux|
24014 command is sensed. Similarly, |prev_graf| is changed in the presence of
24015 |set_prev_graf|, and |dead_cycles| or |insert_penalties| in the presence of
24016 |set_page_int|. These definitions are always global.
24017
24018 When some dimension of a box register is changed, the change isn't exactly
24019 global; but \TeX\ does not look at the \.{\\global} switch.
24020
24021 @<Assignments@>=
24022 case set_aux: alter_aux();@+break;
24023 case set_prev_graf: alter_prev_graf();@+break;
24024 case set_page_dimen: alter_page_so_far();@+break;
24025 case set_page_int: alter_integer();@+break;
24026 case set_box_dimen: alter_box_dimen();@+break;
24027
24028 @ @<Declare subprocedures for |prefixed_command|@>=
24029 static void alter_aux(void)
24030 {@+halfword c; /*|hmode| or |vmode|*/
24031 if (cur_chr!=abs(mode)) report_illegal_case();
24032 else{@+c=cur_chr;scan_optional_equals();
24033 if (c==vmode)
24034 {@+scan_normal_dimen;prev_depth=cur_val;
24035 }
24036 else{@+scan_int();
24037 if ((cur_val <= 0)||(cur_val > 32767))
24038 {@+print_err("Bad space factor");
24039 @.Bad space factor@>
24040 help1("I allow only values in the range 1..32767 here.");
24041 int_error(cur_val);
24042 }
24043 else space_factor=cur_val;
24044 }
24045 }
24046 }
24047
24048 @ @<Declare subprocedures for |prefixed_command|@>=
24049 static void alter_prev_graf(void)
24050 {@+int p; /*index into |nest|*/
24051 nest[nest_ptr]=cur_list;p=nest_ptr;
24052 while (abs(nest[p].mode_field)!=vmode) decr(p);
24053 scan_optional_equals();scan_int();
24054 if (cur_val < 0)
24055 {@+print_err("Bad ");print_esc("prevgraf");
24056 @.Bad \\prevgraf@>
24057 help1("I allow only nonnegative values here.");
24058 int_error(cur_val);
24059 }
24060 else{@+nest[p].pg_field=cur_val;cur_list=nest[nest_ptr];
24061 }
24062 }
24063
24064 @ @<Declare subprocedures for |prefixed_command|@>=
24065 static void alter_page_so_far(void)
24066 {@+int c; /*index into |page_so_far|*/
24067 c=cur_chr;scan_optional_equals();scan_normal_dimen;
24068 page_so_far[c]=cur_val;
24069 }
24070
24071 @ @<Declare subprocedures for |prefixed_command|@>=
24072 static void alter_integer(void)
24073 {@+small_number c;
24074 /*0 for \.{\\deadcycles}, 1 for \.{\\insertpenalties}, etc.*/
24075 c=cur_chr;scan_optional_equals();scan_int();
24076 if (c==0) dead_cycles=cur_val
24077 @/@<Cases for |alter_integer|@>@;@/
24078 else insert_penalties=cur_val;
24079 }
24080
24081 @ @<Declare subprocedures for |prefixed_command|@>=
24082 static void alter_box_dimen(void)
24083 {@+small_number c; /*|width_offset| or |height_offset| or |depth_offset|*/
24084 pointer @!b; /*box register*/
24085 c=cur_chr;scan_register_num();fetch_box(b);scan_optional_equals();
24086 scan_normal_dimen;
24087 if (b!=null) mem[b+c].sc=cur_val;
24088 }
24089
24090 @ Paragraph shapes are set up in the obvious way.
24091
24092 @<Assignments@>=
24093 case set_shape: {@+q=cur_chr;scan_optional_equals();scan_int();n=cur_val;
24094 if (n <= 0) p=null;
24095 else if (q > par_shape_loc)
24096 {@+n=(cur_val/2)+1;p=get_node(2*n+1);info(p)=n;
24097 n=cur_val;mem[p+1].i=n; /*number of penalties*/
24098 for (j=p+2; j<=p+n+1; j++)
24099 {@+scan_int();mem[j].i=cur_val; /*penalty values*/
24100 }
24101 if (!odd(n)) mem[p+n+2].i=0; /*unused*/
24102 }
24103 else{@+p=get_node(2*n+1);info(p)=n;
24104 for (j=1; j<=n; j++)
24105 {@+scan_normal_dimen;
24106 mem[p+2*j-1].sc=cur_val; /*indentation*/
24107 scan_normal_dimen;
24108 mem[p+2*j].sc=cur_val; /*width*/
24109 }
24110 }
24111 define(q, shape_ref, p);
24112 } @+break;
24113
24114 @ Here's something that isn't quite so obvious. It guarantees that
24115 |info(par_shape_ptr)| can hold any positive~|n| for which |get_node(2*n+1)|
24116 doesn't overflow the memory capacity.
24117
24118 @<Check the ``constant''...@>=
24119 if (2*max_halfword < mem_top-mem_min) bad=41;
24120
24121 @ New hyphenation data is loaded by the |hyph_data| command.
24122
24123 @<Put each...@>=
24124 primitive("hyphenation", hyph_data, 0);
24125 @!@:hyphenation\_}{\.{\\hyphenation} primitive@>
24126 primitive("patterns", hyph_data, 1);
24127 @!@:patterns\_}{\.{\\patterns} primitive@>
24128
24129 @ @<Cases of |print_cmd_chr|...@>=
24130 case hyph_data: if (chr_code==1) print_esc("patterns");
24131 else print_esc("hyphenation");@+break;
24132
24133 @ @<Assignments@>=
24134 case hyph_data: if (cur_chr==1)
24135 {
24136 #ifdef @!INIT
24137 new_patterns();goto done;@;
24138 #endif
24139 print_err("Patterns can be loaded only by INITEX");
24140 @.Patterns can be...@>
24141 help0;error();
24142 @/do@+{get_token();}@+ while (!(cur_cmd==right_brace)); /*flush the patterns*/
24143 return;
24144 }
24145 else{@+new_hyph_exceptions();goto done;
24146 } @+break;
24147
24148 @ All of \TeX's parameters are kept in |eqtb| except the font information,
24149 the interaction mode, and the hyphenation tables; these are strictly global.
24150
24151 @<Assignments@>=
24152 case assign_font_dimen: {@+find_font_dimen(true);k=cur_val;
24153 scan_optional_equals();scan_normal_dimen;font_info[k].sc=cur_val;
24154 } @+break;
24155 case assign_font_int: {@+n=cur_chr;scan_font_ident();f=cur_val;
24156 scan_optional_equals();scan_int();
24157 if (n==0) hyphen_char[f]=cur_val;@+else skew_char[f]=cur_val;
24158 } @+break;
24159
24160 @ @<Put each...@>=
24161 primitive("hyphenchar", assign_font_int, 0);
24162 @!@:hyphen\_char\_}{\.{\\hyphenchar} primitive@>
24163 primitive("skewchar", assign_font_int, 1);
24164 @!@:skew\_char\_}{\.{\\skewchar} primitive@>
24165
24166 @ @<Cases of |print_cmd_chr|...@>=
24167 case assign_font_int: if (chr_code==0) print_esc("hyphenchar");
24168 else print_esc("skewchar");@+break;
24169
24170 @ Here is where the information for a new font gets loaded.
24171
24172 @<Assignments@>=
24173 case def_font: new_font(a);@+break;
24174
24175 @ @<Declare subprocedures for |prefixed_command|@>=
24176 static void new_font(small_number @!a)
24177 {@+
24178 pointer u; /*user's font identifier*/
24179 scaled @!s; /*stated ``at'' size, or negative of scaled magnification*/
24180 int @!f; /*runs through existing fonts*/
24181 str_number @!t; /*name for the frozen font identifier*/
24182 int @!old_setting; /*holds |selector| setting*/
24183 str_number @!flushable_string; /*string not yet referenced*/
24184 if (job_name==0) open_log_file();
24185 /*avoid confusing \.{texput} with the font name*/
24186 @.texput@>
24187 get_r_token();u=cur_cs;
24188 if (u >= hash_base) t=text(u);
24189 else if (u >= single_base)
24190 if (u==null_cs) t=s_no("FONT");@+else t=u-single_base;
24191 else{@+old_setting=selector;selector=new_string;
24192 print("FONT");printn(u-active_base);selector=old_setting;
24193 @.FONTx@>
24194 str_room(1);t=make_string();
24195 }
24196 define(u, set_font, null_font);scan_optional_equals();scan_file_name();
24197 @<Scan the font size specification@>;
24198 @<If this font has already been loaded, set |f| to the internal font number
24199 and |goto common_ending|@>;
24200 f=read_font_info(u, cur_name, cur_area, s);
24201 common_ending: define(u, set_font, f);eqtb[font_id_base+f]=eqtb[u];font_id_text(f)=t;
24202 }
24203
24204 @ @<Scan the font size specification@>=
24205 name_in_progress=true; /*this keeps |cur_name| from being changed*/
24206 if (scan_keyword("at")) @<Put the \(p)(positive) `at' size into |s|@>@;
24207 @.at@>
24208 else if (scan_keyword("scaled"))
24209 @.scaled@>
24210 {@+scan_int();s=-cur_val;
24211 if ((cur_val <= 0)||(cur_val > 32768))
24212 {@+print_err("Illegal magnification has been changed to 1000");@/
24213 @.Illegal magnification...@>
24214 help1("The magnification ratio must be between 1 and 32768.");
24215 int_error(cur_val);s=-1000;
24216 }
24217 }
24218 else s=-1000;
24219 name_in_progress=false
24220
24221 @ @<Put the \(p)(positive) `at' size into |s|@>=
24222 {@+scan_normal_dimen;s=cur_val;
24223 if ((s <= 0)||(s >= 01000000000))
24224 {@+print_err("Improper `at' size (");
24225 print_scaled(s);print("pt), replaced by 10pt");
24226 @.Improper `at' size...@>
24227 help2("I can only handle fonts at positive sizes that are",@/
24228 "less than 2048pt, so I've changed what you said to 10pt.");
24229 error();s=10*unity;
24230 }
24231 }
24232
24233 @ When the user gives a new identifier to a font that was previously loaded,
24234 the new name becomes the font identifier of record. Font names `\.{xyz}' and
24235 `\.{XYZ}' are considered to be different.
24236
24237 @<If this font has already been loaded...@>=
24238 flushable_string=str_ptr-1;
24239 for (f=font_base+1; f<=font_ptr; f++)
24240 if (str_eq_str(font_name[f], cur_name)&&str_eq_str(font_area[f], cur_area))
24241 {@+if (cur_name==flushable_string)
24242 {@+flush_string;cur_name=font_name[f];
24243 }
24244 if (s > 0)
24245 {@+if (s==font_size[f]) goto common_ending;
24246 }
24247 else if (font_size[f]==xn_over_d(font_dsize[f],-s, 1000))
24248 goto common_ending;
24249 }
24250
24251 @ @<Cases of |print_cmd_chr|...@>=
24252 case set_font: {@+print("select font ");slow_print(font_name[chr_code]);
24253 if (font_size[chr_code]!=font_dsize[chr_code])
24254 {@+print(" at ");print_scaled(font_size[chr_code]);
24255 print("pt");
24256 }
24257 } @+break;
24258
24259 @ @<Put each...@>=
24260 primitive("batchmode", set_interaction, batch_mode);
24261 @!@:batch\_mode\_}{\.{\\batchmode} primitive@>
24262 primitive("nonstopmode", set_interaction, nonstop_mode);
24263 @!@:nonstop\_mode\_}{\.{\\nonstopmode} primitive@>
24264 primitive("scrollmode", set_interaction, scroll_mode);
24265 @!@:scroll\_mode\_}{\.{\\scrollmode} primitive@>
24266 primitive("errorstopmode", set_interaction, error_stop_mode);
24267 @!@:error\_stop\_mode\_}{\.{\\errorstopmode} primitive@>
24268
24269 @ @<Cases of |print_cmd_chr|...@>=
24270 case set_interaction: switch (chr_code) {
24271 case batch_mode: print_esc("batchmode");@+break;
24272 case nonstop_mode: print_esc("nonstopmode");@+break;
24273 case scroll_mode: print_esc("scrollmode");@+break;
24274 default:print_esc("errorstopmode");
24275 } @+break;
24276
24277 @ @<Assignments@>=
24278 case set_interaction: new_interaction();@+break;
24279
24280 @ @<Declare subprocedures for |prefixed_command|@>=
24281 static void new_interaction(void)
24282 {@+print_ln();
24283 interaction=cur_chr;
24284 @<Initialize the print |selector| based on |interaction|@>;
24285 if (log_opened) selector=selector+2;
24286 }
24287
24288 @ The \.{\\afterassignment} command puts a token into the global
24289 variable |after_token|. This global variable is examined just after
24290 every assignment has been performed.
24291
24292 @<Glob...@>=
24293 static halfword @!after_token; /*zero, or a saved token*/
24294
24295 @ @<Set init...@>=
24296 after_token=0;
24297
24298 @ @<Cases of |main_control| that don't...@>=
24299 any_mode(after_assignment): {@+get_token();after_token=cur_tok;
24300 } @+break;
24301
24302 @ @<Insert a token saved by \.{\\afterassignment}, if any@>=
24303 if (after_token!=0)
24304 {@+cur_tok=after_token;back_input();after_token=0;
24305 }
24306
24307 @ Here is a procedure that might be called `Get the next non-blank non-relax
24308 non-call non-assignment token'.
24309
24310 @<Declare act...@>=
24311 static void do_assignments(void)
24312 {@+
24313 loop{@+@<Get the next non-blank non-relax...@>;
24314 if (cur_cmd <= max_non_prefixed_command) return;
24315 set_box_allowed=false;prefixed_command();set_box_allowed=true;
24316 }
24317 }
24318
24319 @ @<Cases of |main_control| that don't...@>=
24320 any_mode(after_group): {@+get_token();save_for_after(cur_tok);
24321 } @+break;
24322
24323 @ Files for \.{\\read} are opened and closed by the |in_stream| command.
24324
24325 @<Put each...@>=
24326 primitive("openin", in_stream, 1);
24327 @!@:open\_in\_}{\.{\\openin} primitive@>
24328 primitive("closein", in_stream, 0);
24329 @!@:close\_in\_}{\.{\\closein} primitive@>
24330
24331 @ @<Cases of |print_cmd_chr|...@>=
24332 case in_stream: if (chr_code==0) print_esc("closein");
24333 else print_esc("openin");@+break;
24334
24335 @ @<Cases of |main_control| that don't...@>=
24336 any_mode(in_stream): open_or_close_in();@+break;
24337
24338 @ @<Declare act...@>=
24339 static void open_or_close_in(void)
24340 {@+int c; /*1 for \.{\\openin}, 0 for \.{\\closein}*/
24341 int @!n; /*stream number*/
24342 c=cur_chr;scan_four_bit_int();n=cur_val;
24343 if (read_open[n]!=closed)
24344 {@+a_close(&read_file[n]);read_open[n]=closed;
24345 }
24346 if (c!=0)
24347 {@+scan_optional_equals();scan_file_name();
24348 pack_cur_name(".tex");
24349 if (a_open_in(&read_file[n]))
24350 { read_open[n]=just_open;
24351 @<Set new |read_file_num[n]|@>@;
24352 }
24353 }
24354 }
24355
24356 @ The user can issue messages to the terminal, regardless of the
24357 current mode.
24358
24359 @<Cases of |main_control| that don't...@>=
24360 any_mode(message): issue_message();@+break;
24361
24362 @ @<Put each...@>=
24363 primitive("message", message, 0);
24364 @!@:message\_}{\.{\\message} primitive@>
24365 primitive("errmessage", message, 1);
24366 @!@:err\_message\_}{\.{\\errmessage} primitive@>
24367
24368 @ @<Cases of |print_cmd_chr|...@>=
24369 case message: if (chr_code==0) print_esc("message");
24370 else print_esc("errmessage");@+break;
24371
24372 @ @<Declare act...@>=
24373 static void issue_message(void)
24374 {@+int old_setting; /*holds |selector| setting*/
24375 int @!c; /*identifies \.{\\message} and \.{\\errmessage}*/
24376 str_number @!s; /*the message*/
24377 c=cur_chr;link(garbage)=scan_toks(false, true);
24378 old_setting=selector;selector=new_string;
24379 token_show(def_ref);selector=old_setting;
24380 flush_list(def_ref);
24381 str_room(1);s=make_string();
24382 if (c==0) @<Print string |s| on the terminal@>@;
24383 else@<Print string |s| as an error message@>;
24384 flush_string;
24385 }
24386
24387 @ @<Print string |s| on the terminal@>=
24388 {@+if (term_offset+length(s) > max_print_line-2) print_ln();
24389 else if ((term_offset > 0)||(file_offset > 0)) print_char(' ');
24390 slow_print(s);update_terminal;
24391 }
24392
24393 @ If \.{\\errmessage} occurs often in |scroll_mode|, without user-defined
24394 \.{\\errhelp}, we don't want to give a long help message each time. So we
24395 give a verbose explanation only once.
24396
24397 @<Glob...@>=
24398 static bool @!long_help_seen; /*has the long \.{\\errmessage} help been used?*/
24399
24400 @ @<Set init...@>=long_help_seen=false;
24401
24402 @ @<Print string |s| as an error message@>=
24403 {@+print_err("");slow_print(s);
24404 if (err_help!=null) use_err_help=true;
24405 else if (long_help_seen) help1("(That was another \\errmessage.)")@;
24406 else{@+if (interaction < error_stop_mode) long_help_seen=true;
24407 help4("This error message was generated by an \\errmessage",@/
24408 "command, so I can't give any explicit help.",@/
24409 "Pretend that you're Hercule Poirot: Examine all clues,",@/
24410 @^Poirot, Hercule@>
24411 "and deduce the truth by order and method.");
24412 }
24413 error();use_err_help=false;
24414 }
24415
24416 @ The |error| routine calls on |give_err_help| if help is requested from
24417 the |err_help| parameter.
24418
24419 @p static void give_err_help(void)
24420 {@+token_show(err_help);
24421 }
24422
24423 @ The \.{\\uppercase} and \.{\\lowercase} commands are implemented by
24424 building a token list and then changing the cases of the letters in it.
24425
24426 @<Cases of |main_control| that don't...@>=
24427 any_mode(case_shift): shift_case();@+break;
24428
24429 @ @<Put each...@>=
24430 primitive("lowercase", case_shift, lc_code_base);
24431 @!@:lowercase\_}{\.{\\lowercase} primitive@>
24432 primitive("uppercase", case_shift, uc_code_base);
24433 @!@:uppercase\_}{\.{\\uppercase} primitive@>
24434
24435 @ @<Cases of |print_cmd_chr|...@>=
24436 case case_shift: if (chr_code==lc_code_base) print_esc("lowercase");
24437 else print_esc("uppercase");@+break;
24438
24439 @ @<Declare act...@>=
24440 static void shift_case(void)
24441 {@+pointer b; /*|lc_code_base| or |uc_code_base|*/
24442 pointer @!p; /*runs through the token list*/
24443 halfword @!t; /*token*/
24444 eight_bits @!c; /*character code*/
24445 b=cur_chr;p=scan_toks(false, false);p=link(def_ref);
24446 while (p!=null)
24447 {@+@<Change the case of the token in |p|, if a change is appropriate@>;
24448 p=link(p);
24449 }
24450 back_list(link(def_ref));free_avail(def_ref); /*omit reference count*/
24451 }
24452
24453 @ When the case of a |chr_code| changes, we don't change the |cmd|.
24454 We also change active characters, using the fact that
24455 |cs_token_flag+active_base| is a multiple of~256.
24456 @^data structure assumptions@>
24457
24458 @<Change the case of the token in |p|, if a change is appropriate@>=
24459 t=info(p);
24460 if (t < cs_token_flag+single_base)
24461 {@+c=t%256;
24462 if (equiv(b+c)!=0) info(p)=t-c+equiv(b+c);
24463 }
24464
24465 @ We come finally to the last pieces missing from |main_control|, namely the
24466 `\.{\\show}' commands that are useful when debugging.
24467
24468 @<Cases of |main_control| that don't...@>=
24469 any_mode(xray): show_whatever();@+break;
24470
24471 @ @d show_code 0 /* \.{\\show} */
24472 @d show_box_code 1 /* \.{\\showbox} */
24473 @d show_the_code 2 /* \.{\\showthe} */
24474 @d show_lists_code 3 /* \.{\\showlists} */
24475
24476 @<Put each...@>=
24477 primitive("show", xray, show_code);
24478 @!@:show\_}{\.{\\show} primitive@>
24479 primitive("showbox", xray, show_box_code);
24480 @!@:show\_box\_}{\.{\\showbox} primitive@>
24481 primitive("showthe", xray, show_the_code);
24482 @!@:show\_the\_}{\.{\\showthe} primitive@>
24483 primitive("showlists", xray, show_lists_code);
24484 @!@:show\_lists\_code\_}{\.{\\showlists} primitive@>
24485
24486 @ @<Cases of |print_cmd_chr|...@>=
24487 case xray: switch (chr_code) {
24488 case show_box_code: print_esc("showbox");@+break;
24489 case show_the_code: print_esc("showthe");@+break;
24490 case show_lists_code: print_esc("showlists");@+break;
24491 @<Cases of |xray| for |print_cmd_chr|@>@;@/
24492 default:print_esc("show");
24493 } @+break;
24494
24495 @ @<Declare act...@>=
24496 static void show_whatever(void)
24497 {@+
24498 pointer p; /*tail of a token list to show*/
24499 small_number @!t; /*type of conditional being shown*/
24500 int @!m; /*upper bound on |fi_or_else| codes*/
24501 int @!l; /*line where that conditional began*/
24502 int @!n; /*level of \.{\\if...\\fi} nesting*/
24503 switch (cur_chr) {
24504 case show_lists_code: {@+begin_diagnostic();show_activities();
24505 } @+break;
24506 case show_box_code: @<Show the current contents of a box@>@;@+break;
24507 case show_code: @<Show the current meaning of a token, then |goto common_ending|@>@;
24508 @<Cases for |show_whatever|@>@;@/
24509 default:@<Show the current value of some parameter or register, then |goto
24510 common_ending|@>@;
24511 } @/
24512 @<Complete a potentially long \.{\\show} command@>;
24513 common_ending: if (interaction < error_stop_mode)
24514 {@+help0;decr(error_count);
24515 }
24516 else if (tracing_online > 0)
24517 {@+@t@>@;@/
24518 help3("This isn't an error message; I'm just \\showing something.",@/
24519 "Type `I\\show...' to show more (e.g., \\show\\cs,",@/
24520 "\\showthe\\count10, \\showbox255, \\showlists).");
24521 }
24522 else{@+@t@>@;@/
24523 help5("This isn't an error message; I'm just \\showing something.",@/
24524 "Type `I\\show...' to show more (e.g., \\show\\cs,",@/
24525 "\\showthe\\count10, \\showbox255, \\showlists).",@/
24526 "And type `I\\tracingonline=1\\show...' to show boxes and",@/
24527 "lists on your terminal as well as in the transcript file.");
24528 }
24529 error();
24530 }
24531
24532 @ @<Show the current meaning of a token...@>=
24533 {@+get_token();
24534 if (interaction==error_stop_mode) wake_up_terminal;
24535 print_nl("> ");
24536 if (cur_cs!=0)
24537 {@+sprint_cs(cur_cs);print_char('=');
24538 }
24539 print_meaning();goto common_ending;
24540 }
24541
24542 @ @<Cases of |print_cmd_chr|...@>=
24543 case undefined_cs: print("undefined");@+break;
24544 case call: case long_call: case outer_call:
24545 case long_outer_call: {@+n=cmd-call;
24546 if (info(link(chr_code))==protected_token) n=n+4;
24547 if (odd(n/4)) print_esc("protected");
24548 if (odd(n)) print_esc("long");
24549 if (odd(n/2)) print_esc("outer");
24550 if (n > 0) print_char(' ');
24551 print("macro");
24552 } @+break;
24553 case end_template: print_esc("outer endtemplate");@+break;
24554
24555 @ @<Show the current contents of a box@>=
24556 {@+scan_register_num();fetch_box(p);begin_diagnostic();
24557 print_nl("> \\box");print_int(cur_val);print_char('=');
24558 if (p==null) print("void");@+else show_box(p);
24559 }
24560
24561 @ @<Show the current value of some parameter...@>=
24562 {@+the_toks();
24563 if (interaction==error_stop_mode) wake_up_terminal;
24564 print_nl("> ");token_show(temp_head);
24565 flush_list(link(temp_head));goto common_ending;
24566 }
24567
24568 @ @<Complete a potentially long \.{\\show} command@>=
24569 end_diagnostic(true);print_err("OK");
24570 @.OK@>
24571 if (selector==term_and_log) if (tracing_online <= 0)
24572 {@+selector=term_only;print(" (see the transcript file)");
24573 selector=term_and_log;
24574 }
24575
24576 @* Dumping and undumping the tables.
24577 After \.{INITEX} has seen a collection of fonts and macros, it
24578 can write all the necessary information on an auxiliary file so
24579 that production versions of \TeX\ are able to initialize their
24580 memory at high speed. The present section of the program takes
24581 care of such output and input. We shall consider simultaneously
24582 the processes of storing and restoring,
24583 so that the inverse relation between them is clear.
24584 @.INITEX@>
24585
24586 The global variable |format_ident| is a string that is printed right
24587 after the |banner| line when \TeX\ is ready to start. For \.{INITEX} this
24588 string says simply `\.{ (INITEX)}'; for other versions of \TeX\ it says,
24589 for example, `\.{ (preloaded format=plain 1982.11.19)}', showing the year,
24590 month, and day that the format file was created. We have |format_ident==0|
24591 before \TeX's tables are loaded.
24592
24593 @<Glob...@>=
24594 static str_number @!format_ident, frozen_format_ident;
24595
24596 @ @<Set init...@>=
24597 format_ident=frozen_format_ident=0;
24598
24599 @ We keep a copy of the initial value, be able to test for it later.
24600
24601 @<Initialize table entries...@>=
24602 format_ident=frozen_format_ident=s_no(" (INITEX)");
24603
24604 @ @<Declare act...@>=
24605 #ifdef @!INIT
24606 static void store_fmt_file(void)
24607 {@+
24608 int j, @!k, @!l; /*all-purpose indices*/
24609 int @!p, @!q; /*all-purpose pointers*/
24610 int @!x; /*something to dump*/
24611 four_quarters @!w; /*four ASCII codes*/
24612 @<If dumping is not allowed, abort@>;
24613 @<Create the |format_ident|, open the format file, and inform the user that
24614 dumping has begun@>;
24615 @<Dump constants for consistency check@>;
24616 @<Dump the string pool@>;
24617 @<Dump the dynamic memory@>;
24618 @<Dump the table of equivalents@>;
24619 @<Dump the font information@>;
24620 @<Dump the hyphenation tables@>;
24621 @<Dump the full file names@>;
24622 @<Dump the file and line information@>;
24623 @<Dump a couple more things and the closing check word@>;
24624 @<Close the format file@>;
24625 }
24626 #endif
24627
24628 @ Corresponding to the procedure that dumps a format file, we have a function
24629 that reads one in. The function returns |false| if the dumped format is
24630 incompatible with the present \TeX\ table sizes, etc.
24631
24632 @d too_small(X) {@+wake_up_terminal;
24633 wterm_ln("---! Must increase the %s", X);
24634 @.Must increase the x@>
24635 goto bad_fmt;
24636 }
24637
24638 @p @t\4@>@<Declare the function called |open_fmt_file|@>@;
24639 static bool load_fmt_file(void)
24640 {@+
24641 int j, @!k; /*all-purpose indices*/
24642 int @!p, @!q; /*all-purpose pointers*/
24643 int @!x; /*something undumped*/
24644 four_quarters @!w; /*four ASCII codes*/
24645 @<Undump constants for consistency check@>;
24646 @<Undump the string pool@>;
24647 @<Undump the dynamic memory@>;
24648 @<Undump the table of equivalents@>;
24649 @<Undump the font information@>;
24650 @<Undump the hyphenation tables@>;
24651 @<Undump the full file names@>;
24652 @<Undump the file and line information@>;
24653 @<Undump a couple more things and the closing check word@>;
24654 return true; /*it worked!*/
24655 bad_fmt: wake_up_terminal;
24656 wterm_ln("(Fatal format file error; I'm stymied)");
24657 @.Fatal format file error@>
24658 return false;
24659 }
24660
24661 @ The user is not allowed to dump a format file unless |save_ptr==0|.
24662 This condition implies that |cur_level==level_one|, hence
24663 the |xeq_level| array is constant and it need not be dumped.
24664
24665 @<If dumping is not allowed, abort@>=
24666 if (save_ptr!=0)
24667 {@+print_err("You can't dump inside a group");
24668 @.You can't dump...@>
24669 help1("`{...\\dump}' is a no-no.");succumb;
24670 }
24671
24672 @ Format files consist of |memory_word| items, and we use the following
24673 macros to dump words of different types:
24674
24675 @d dump_wd(A) {@+fmt_file.d=A;put(fmt_file);@+}
24676 @d dump_int(A) {@+fmt_file.d.i=A;put(fmt_file);@+}
24677 @d dump_hh(A) {@+fmt_file.d.hh=A;put(fmt_file);@+}
24678 @d dump_qqqq(A) {@+fmt_file.d.qqqq=A;put(fmt_file);@+}
24679
24680 @<Glob...@>=
24681 static word_file @!fmt_file; /*for input or output of format information*/
24682
24683 @ The inverse macros are slightly more complicated, since we need to check
24684 the range of the values we are reading in. We say `|undump(a)(b)(x)|' to
24685 read an integer value |x| that is supposed to be in the range |a <= x <= b|.
24686 System error messages should be suppressed when undumping.
24687 @^system dependencies@>
24688
24689 @d undump_wd(A) {@+get(fmt_file);A=fmt_file.d;@+}
24690 @d undump_int(A) {@+get(fmt_file);A=fmt_file.d.i;@+}
24691 @d undump_hh(A) {@+get(fmt_file);A=fmt_file.d.hh;@+}
24692 @d undump_qqqq(A) {@+get(fmt_file);A=fmt_file.d.qqqq;@+}
24693 @d undump(A, B, C) {@+undump_int(x);if ((x < A)||(x > B)) goto bad_fmt;@+else C=x;@+}
24694 @d undump_size(A, B, C, D) {@+undump_int(x);
24695 if (x < A) goto bad_fmt;if (x > B) too_small(C)@;@+else D=x;@+}
24696
24697 @ The next few sections of the program should make it clear how we use the
24698 dump/undump macros.
24699
24700 @<Dump constants for consistency check@>=
24701 dump_int(0);@/
24702 @<Dump the \eTeX\ state@>@/
24703 @<Dump the \Prote\ state@>@/
24704 @<Dump the |ROM| array@>@/
24705 dump_int(mem_bot);@/
24706 dump_int(mem_top);@/
24707 dump_int(eqtb_size);@/
24708 dump_int(hash_prime);@/
24709 dump_int(hyph_size)
24710
24711 @ Sections of a \.{WEB} program that are ``commented out'' still contribute
24712 strings to the string pool; therefore \.{INITEX} and \TeX\ will have
24713 the same strings. (And it is, of course, a good thing that they do.)
24714 @.WEB@>
24715 @^string pool@>
24716
24717 @<Undump constants for consistency check@>=
24718 x=fmt_file.d.i;
24719 if (x!=0) goto bad_fmt; /*check that strings are the same*/
24720 @/@<Undump the \eTeX\ state@>@/
24721 @/@<Undump the \Prote\ state@>@/
24722 @/@<Undump the |ROM| array@>@/
24723 undump_int(x);
24724 if (x!=mem_bot) goto bad_fmt;
24725 undump_int(x);
24726 if (x!=mem_top) goto bad_fmt;
24727 undump_int(x);
24728 if (x!=eqtb_size) goto bad_fmt;
24729 undump_int(x);
24730 if (x!=hash_prime) goto bad_fmt;
24731 undump_int(x);
24732 if (x!=hyph_size) goto bad_fmt
24733
24734 @ @d dump_four_ASCII
24735 w.b0=qi(so(str_pool[k]));w.b1=qi(so(str_pool[k+1]));
24736 w.b2=qi(so(str_pool[k+2]));w.b3=qi(so(str_pool[k+3]));
24737 dump_qqqq(w)
24738
24739 @<Dump the string pool@>=
24740 dump_int(pool_ptr);
24741 dump_int(str_ptr);
24742 for (k=0; k<=str_ptr; k++) dump_int(str_start[k]);
24743 k=0;
24744 while (k+4 < pool_ptr)
24745 {@+dump_four_ASCII;k=k+4;
24746 }
24747 k=pool_ptr-4;dump_four_ASCII;
24748 print_ln();print_int(str_ptr);print(" strings of total length ");
24749 print_int(pool_ptr)
24750
24751 @ @d undump_four_ASCII
24752 undump_qqqq(w);
24753 str_pool[k]=si(qo(w.b0));str_pool[k+1]=si(qo(w.b1));
24754 str_pool[k+2]=si(qo(w.b2));str_pool[k+3]=si(qo(w.b3))
24755
24756 @<Undump the string pool@>=
24757 undump_size(0, pool_size,"string pool size", pool_ptr);
24758 undump_size(0, max_strings,"max strings", str_ptr);
24759 for (k=0; k<=str_ptr; k++) undump(0, pool_ptr, str_start[k]);
24760 k=0;
24761 while (k+4 < pool_ptr)
24762 {@+undump_four_ASCII;k=k+4;
24763 }
24764 k=pool_ptr-4;undump_four_ASCII;
24765 init_str_ptr=str_ptr;init_pool_ptr=pool_ptr
24766
24767 @ By sorting the list of available spaces in the variable-size portion of
24768 |mem|, we are usually able to get by without having to dump very much
24769 of the dynamic memory.
24770
24771 We recompute |var_used| and |dyn_used|, so that \.{INITEX} dumps valid
24772 information even when it has not been gathering statistics.
24773
24774 @<Dump the dynamic memory@>=
24775 sort_avail();var_used=0;
24776 dump_int(lo_mem_max);dump_int(rover);
24777 if (eTeX_ex) for (k=int_val; k<=tok_val; k++) dump_int(sa_root[k]);
24778 p=mem_bot;q=rover;x=0;
24779 @/do@+{for (k=p; k<=q+1; k++) dump_wd(mem[k]);
24780 x=x+q+2-p;var_used=var_used+q-p;
24781 p=q+node_size(q);q=rlink(q);
24782 }@+ while (!(q==rover));
24783 var_used=var_used+lo_mem_max-p;dyn_used=mem_end+1-hi_mem_min;@/
24784 for (k=p; k<=lo_mem_max; k++) dump_wd(mem[k]);
24785 x=x+lo_mem_max+1-p;
24786 dump_int(hi_mem_min);dump_int(avail);
24787 for (k=hi_mem_min; k<=mem_end; k++) dump_wd(mem[k]);
24788 p=avail;
24789 while (p!=null)
24790 {@+fl_mem[p]=0; /*clear unallocated |fl_mem|*/
24791 decr(dyn_used);p=link(p);
24792 }
24793 dump_int(var_used);dump_int(dyn_used);
24794 print_ln();print_int(x);print_char('&');print_int(mem_end+1-hi_mem_min);
24795 print(" memory locations dumped; current usage is ");
24796 print_int(var_used);print_char('&');print_int(dyn_used)
24797
24798 @ @<Undump the dynamic memory@>=
24799 undump(lo_mem_stat_max+1000, hi_mem_stat_min-1, lo_mem_max);
24800 undump(lo_mem_stat_max+1, lo_mem_max, rover);
24801 if (eTeX_ex) for (k=int_val; k<=tok_val; k++)
24802 undump(null, lo_mem_max, sa_root[k]);
24803 p=mem_bot;q=rover;
24804 @/do@+{for (k=p; k<=q+1; k++) undump_wd(mem[k]);
24805 p=q+node_size(q);
24806 if ((p > lo_mem_max)||((q >= rlink(q))&&(rlink(q)!=rover))) goto bad_fmt;
24807 q=rlink(q);
24808 }@+ while (!(q==rover));
24809 for (k=p; k<=lo_mem_max; k++) undump_wd(mem[k]);
24810 if (mem_min < mem_bot-2) /*make more low memory available*/
24811 {@+p=llink(rover);q=mem_min+1;
24812 link(mem_min)=null;info(mem_min)=null; /*we don't use the bottom word*/
24813 rlink(p)=q;llink(rover)=q;@/
24814 rlink(q)=rover;llink(q)=p;link(q)=empty_flag;
24815 node_size(q)=mem_bot-q;
24816 }
24817 undump(lo_mem_max+1, hi_mem_stat_min, hi_mem_min);
24818 undump(null, mem_top, avail);mem_end=mem_top;
24819 for (k=hi_mem_min; k<=mem_end; k++) undump_wd(mem[k]);
24820 undump_int(var_used);undump_int(dyn_used)
24821
24822 @ @<Dump the table of equivalents@>=
24823 @<Dump regions 1 to 4 of |eqtb|@>;
24824 @<Dump regions 5 and 6 of |eqtb|@>;
24825 dump_int(par_loc);dump_int(write_loc);@/
24826 dump_int(input_loc);@/
24827 @<Dump the hash table@>@;
24828
24829 @ @<Undump the table of equivalents@>=
24830 @<Undump regions 1 to 6 of |eqtb|@>;
24831 undump(hash_base, frozen_control_sequence, par_loc);
24832 par_token=cs_token_flag+par_loc;@/
24833 undump(hash_base, frozen_control_sequence, write_loc);@/
24834 undump(hash_base, frozen_control_sequence, input_loc);
24835 input_token=cs_token_flag+input_loc;@/
24836 @<Undump the hash table@>@;
24837
24838 @ The table of equivalents usually contains repeated information, so we dump it
24839 in compressed form: The sequence of $n+2$ values $(n,x_1,\ldots,x_n,m)$ in the
24840 format file represents $n+m$ consecutive entries of |eqtb|, with |m| extra
24841 copies of $x_n$, namely $(x_1,\ldots,x_n,x_n,\ldots,x_n)$.
24842
24843 @<Dump regions 1 to 4 of |eqtb|@>=
24844 k=active_base;
24845 @/do@+{j=k;
24846 while (j < int_base-1)
24847 {@+if ((equiv(j)==equiv(j+1))&&(eq_type(j)==eq_type(j+1))&&@|
24848 (eq_level(j)==eq_level(j+1))) goto found1;
24849 incr(j);
24850 }
24851 l=int_base;goto done1; /*|j==int_base-1|*/
24852 found1: incr(j);l=j;
24853 while (j < int_base-1)
24854 {@+if ((equiv(j)!=equiv(j+1))||(eq_type(j)!=eq_type(j+1))||@|
24855 (eq_level(j)!=eq_level(j+1))) goto done1;
24856 incr(j);
24857 }
24858 done1: dump_int(l-k);
24859 while (k < l)
24860 {@+dump_wd(eqtb[k]);incr(k);
24861 }
24862 k=j+1;dump_int(k-l);
24863 }@+ while (!(k==int_base))
24864
24865 @ @<Dump regions 5 and 6 of |eqtb|@>=
24866 @/do@+{j=k;
24867 while (j < eqtb_size)
24868 {@+if (eqtb[j].i==eqtb[j+1].i) goto found2;
24869 incr(j);
24870 }
24871 l=eqtb_size+1;goto done2; /*|j==eqtb_size|*/
24872 found2: incr(j);l=j;
24873 while (j < eqtb_size)
24874 {@+if (eqtb[j].i!=eqtb[j+1].i) goto done2;
24875 incr(j);
24876 }
24877 done2: dump_int(l-k);
24878 while (k < l)
24879 {@+dump_wd(eqtb[k]);incr(k);
24880 }
24881 k=j+1;dump_int(k-l);
24882 }@+ while (!(k > eqtb_size))
24883
24884 @ @<Undump regions 1 to 6 of |eqtb|@>=
24885 k=active_base;
24886 @/do@+{undump_int(x);
24887 if ((x < 1)||(k+x > eqtb_size+1)) goto bad_fmt;
24888 for (j=k; j<=k+x-1; j++) undump_wd(eqtb[j]);
24889 k=k+x;
24890 undump_int(x);
24891 if ((x < 0)||(k+x > eqtb_size+1)) goto bad_fmt;
24892 for (j=k; j<=k+x-1; j++) eqtb[j]=eqtb[k-1];
24893 k=k+x;
24894 }@+ while (!(k > eqtb_size))
24895
24896 @ A different scheme is used to compress the hash table, since its lower
24897 region is usually sparse. When |text(p)!=0| for |p <= hash_used|, we output
24898 two words, |p| and |hash[p]|. The hash table is, of course, densely packed
24899 for |p >= hash_used|, so the remaining entries are output in a~block.
24900
24901 @<Dump the hash table@>=
24902 dump_int(hash_used);cs_count=frozen_control_sequence-1-hash_used;
24903 for (p=hash_base; p<=hash_used; p++) if (text(p)!=0)
24904 {@+dump_int(p);dump_hh(hash[p]);incr(cs_count);
24905 }
24906 for (p=hash_used+1; p<=undefined_control_sequence-1; p++) dump_hh(hash[p]);
24907 dump_int(cs_count);@/
24908 print_ln();print_int(cs_count);print(" multiletter control sequences")
24909
24910 @ @<Undump the hash table@>=
24911 undump(hash_base, frozen_control_sequence, hash_used);p=hash_base-1;
24912 @/do@+{undump(p+1, hash_used, p);undump_hh(hash[p]);
24913 }@+ while (!(p==hash_used));
24914 for (p=hash_used+1; p<=undefined_control_sequence-1; p++) undump_hh(hash[p]);
24915 undump_int(cs_count)
24916
24917 @ @<Dump the font information@>=
24918 dump_int(fmem_ptr);
24919 for (k=0; k<=fmem_ptr-1; k++) dump_wd(font_info[k]);
24920 dump_int(font_ptr);
24921 for (k=null_font; k<=font_ptr; k++)
24922 @<Dump the array info for internal font number |k|@>;
24923 print_ln();print_int(fmem_ptr-7);print(" words of font info for ");
24924 print_int(font_ptr-font_base);print(" preloaded font");
24925 if (font_ptr!=font_base+1) print_char('s')
24926
24927 @ @<Undump the font information@>=
24928 undump_size(7, font_mem_size,"font mem size", fmem_ptr);
24929 for (k=0; k<=fmem_ptr-1; k++) undump_wd(font_info[k]);
24930 undump_size(font_base, font_max,"font max", font_ptr);
24931 for (k=null_font; k<=font_ptr; k++)
24932 @<Undump the array info for internal font number |k|@>@;
24933
24934 @ @<Dump the array info for internal font number |k|@>=
24935 {@+dump_qqqq(font_check[k]);
24936 dump_int(font_size[k]);
24937 dump_int(font_dsize[k]);
24938 dump_int(font_params[k]);@/
24939 dump_int(hyphen_char[k]);
24940 dump_int(skew_char[k]);@/
24941 dump_int(font_name[k]);
24942 dump_int(font_area[k]);@/
24943 dump_int(font_bc[k]);
24944 dump_int(font_ec[k]);@/
24945 dump_int(char_base[k]);
24946 dump_int(width_base[k]);
24947 dump_int(height_base[k]);@/
24948 dump_int(depth_base[k]);
24949 dump_int(italic_base[k]);
24950 dump_int(lig_kern_base[k]);@/
24951 dump_int(kern_base[k]);
24952 dump_int(exten_base[k]);
24953 dump_int(param_base[k]);@/
24954 dump_int(font_glue[k]);@/
24955 dump_int(bchar_label[k]);
24956 dump_int(font_bchar[k]);
24957 dump_int(font_false_bchar[k]);@/
24958 print_nl("\\font");printn_esc(font_id_text(k));print_char('=');
24959 print_file_name(font_name[k], font_area[k],empty_string);
24960 if (font_size[k]!=font_dsize[k])
24961 {@+print(" at ");print_scaled(font_size[k]);print("pt");
24962 }
24963 }
24964
24965 @ @<Undump the array info for internal font number |k|@>=
24966 {@+undump_qqqq(font_check[k]);@/
24967 undump_int(font_size[k]);
24968 undump_int(font_dsize[k]);
24969 undump(min_halfword, max_halfword, font_params[k]);@/
24970 undump_int(hyphen_char[k]);
24971 undump_int(skew_char[k]);@/
24972 undump(0, str_ptr, font_name[k]);
24973 undump(0, str_ptr, font_area[k]);@/
24974 undump(0, 255, font_bc[k]);
24975 undump(0, 255, font_ec[k]);@/
24976 undump_int(char_base[k]);
24977 undump_int(width_base[k]);
24978 undump_int(height_base[k]);@/
24979 undump_int(depth_base[k]);
24980 undump_int(italic_base[k]);
24981 undump_int(lig_kern_base[k]);@/
24982 undump_int(kern_base[k]);
24983 undump_int(exten_base[k]);
24984 undump_int(param_base[k]);@/
24985 undump(min_halfword, lo_mem_max, font_glue[k]);@/
24986 undump(0, fmem_ptr-1, bchar_label[k]);
24987 undump(min_quarterword, non_char, font_bchar[k]);
24988 undump(min_quarterword, non_char, font_false_bchar[k]);
24989 }
24990
24991 @ @<Dump the hyphenation tables@>=
24992 dump_int(hyph_count);
24993 for (k=0; k<=hyph_size; k++) if (hyph_word[k]!=0)
24994 {@+dump_int(k);dump_int(hyph_word[k]);dump_int(hyph_list[k]);
24995 }
24996 print_ln();print_int(hyph_count);print(" hyphenation exception");
24997 if (hyph_count!=1) print_char('s');
24998 if (trie_not_ready) init_trie();
24999 dump_int(trie_max);
25000 dump_int(hyph_start);
25001 for (k=0; k<=trie_max; k++) dump_hh(trie[k]);
25002 dump_int(trie_op_ptr);
25003 for (k=1; k<=trie_op_ptr; k++)
25004 {@+dump_int(hyf_distance[k]);
25005 dump_int(hyf_num[k]);
25006 dump_int(hyf_next[k]);
25007 }
25008 print_nl("Hyphenation trie of length ");print_int(trie_max);
25009 @.Hyphenation trie...@>
25010 print(" has ");print_int(trie_op_ptr);print(" op");
25011 if (trie_op_ptr!=1) print_char('s');
25012 print(" out of ");print_int(trie_op_size);
25013 for (k=255; k>=0; k--) if (trie_used[k] > min_quarterword)
25014 {@+print_nl(" ");print_int(qo(trie_used[k]));
25015 print(" for language ");print_int(k);
25016 dump_int(k);dump_int(qo(trie_used[k]));
25017 }
25018
25019 @ Only ``nonempty'' parts of |op_start| need to be restored.
25020
25021 @<Undump the hyphenation tables@>=
25022 undump(0, hyph_size, hyph_count);
25023 for (k=1; k<=hyph_count; k++)
25024 {@+undump(0, hyph_size, j);
25025 undump(0, str_ptr, hyph_word[j]);
25026 undump(min_halfword, max_halfword, hyph_list[j]);
25027 }
25028 undump_size(0, trie_size,"trie size", j);
25029 #ifdef @!INIT
25030 trie_max=j;
25031 #endif
25032 undump(0, j, hyph_start);
25033 for (k=0; k<=j; k++) undump_hh(trie[k]);
25034 undump_size(0, trie_op_size,"trie op size", j);
25035 #ifdef @!INIT
25036 trie_op_ptr=j;
25037 #endif
25038 for (k=1; k<=j; k++)
25039 {@+undump(0, 63, hyf_distance[k]); /*a |small_number|*/
25040 undump(0, 63, hyf_num[k]);
25041 undump(min_quarterword, max_quarterword, hyf_next[k]);
25042 }
25043 #ifdef @!INIT
25044 for (k=0; k<=255; k++) trie_used[k]=min_quarterword;
25045 #endif
25046 @;@/
25047 k=256;
25048 while (j > 0)
25049 {@+undump(0, k-1, k);undump(1, j, x);
25050 #ifdef @!INIT
25051 trie_used[k]=qi(x);
25052 #endif
25053 @;@/
25054 j=j-x;op_start[k]=qo(j);
25055 }
25056 #ifdef @!INIT
25057 trie_not_ready=false
25058 #endif
25059
25060 @ We have already printed a lot of statistics, so we set |tracing_stats=0|
25061 to prevent them from appearing again.
25062
25063 @<Dump a couple more things and the closing check word@>=
25064 dump_int(interaction);dump_int(format_ident);dump_int(69069);
25065 tracing_stats=0
25066
25067 @ @<Undump a couple more things and the closing check word@>=
25068 undump(batch_mode, error_stop_mode, interaction);
25069 if (interaction_option>=0) interaction=interaction_option; /* \TeX\ Live */
25070 undump(0, str_ptr, format_ident);
25071 undump_int(x);
25072 if ((x!=69069)||eof(fmt_file)) goto bad_fmt
25073
25074 @ @<Create the |format_ident|...@>=
25075 selector=new_string;
25076 print(" (preloaded format=");printn(job_name);print_char(' ');
25077 print_int(year);print_char('.');
25078 print_int(month);print_char('.');print_int(day);print_char(')');
25079 if (interaction==batch_mode) selector=log_only;
25080 else selector=term_and_log;
25081 str_room(1);
25082 format_ident=make_string();
25083 pack_job_name(format_extension);
25084 while (!w_open_out(&fmt_file))
25085 prompt_file_name("format file name", format_extension);
25086 print_nl("Beginning to dump on file ");
25087 @.Beginning to dump...@>
25088 slow_print(w_make_name_string(&fmt_file));flush_string;
25089 print_nl("");slow_print(format_ident)
25090
25091 @ @<Close the format file@>=
25092 w_close(&fmt_file)
25093
25094 @* The main program.
25095 This is it: the part of \TeX\ that executes all those procedures we have
25096 written.
25097
25098 Well---almost. Let's leave space for a few more routines that we may
25099 have forgotten.
25100
25101 @p @<Last-minute procedures@>@;
25102
25103 @ We have noted that there are two versions of \TeX82. One, called \.{INITEX},
25104 @.INITEX@>
25105 has to be run first; it initializes everything from scratch, without
25106 reading a format file, and it has the capability of dumping a format file.
25107 The other one is called `\.{VIRTEX}'; it is a ``virgin'' program that needs
25108 @.VIRTEX@>
25109 to input a format file in order to get started. \.{VIRTEX} typically has
25110 more memory capacity than \.{INITEX}, because it does not need the space
25111 consumed by the auxiliary hyphenation tables and the numerous calls on
25112 |primitive|, etc.
25113
25114 The \.{VIRTEX} program cannot read a format file instantaneously, of course;
25115 the best implementations therefore allow for production versions of \TeX\ that
25116 not only avoid the loading routine for \PASCAL\ object code, they also have
25117 a format file pre-loaded. This is impossible to do if we stick to standard
25118 \PASCAL; but there is a simple way to fool many systems into avoiding the
25119 initialization, as follows:\quad(1)~We declare a global integer variable
25120 called |ready_already|. The probability is negligible that this
25121 variable holds any particular value like 314159 when \.{VIRTEX} is first
25122 loaded.\quad(2)~After we have read in a format file and initialized
25123 everything, we set |ready_already=314159|.\quad(3)~Soon \.{VIRTEX}
25124 will print `\.*', waiting for more input; and at this point we
25125 interrupt the program and save its core image in some form that the
25126 operating system can reload speedily.\quad(4)~When that core image is
25127 activated, the program starts again at the beginning; but now
25128 |ready_already==314159| and all the other global variables have
25129 their initial values too. The former chastity has vanished!
25130
25131 In other words, if we allow ourselves to test the condition
25132 |ready_already==314159|, before |ready_already| has been
25133 assigned a value, we can avoid the lengthy initialization. Dirty tricks
25134 rarely pay off so handsomely.
25135 @^dirty \PASCAL@>
25136 @^system dependencies@>
25137
25138 On systems that allow such preloading, the standard program called \.{TeX}
25139 should be the one that has \.{plain} format preloaded, since that agrees
25140 with {\sl The \TeX book}. Other versions, e.g., \.{AmSTeX}, should also
25141 @:TeXbook}{\sl The \TeX book@>
25142 @.AmSTeX@>
25143 @.plain@>
25144 be provided for commonly used formats.
25145
25146 @<Glob...@>=
25147 static int @!ready_already; /*a sacrifice of purity for economy*/
25148
25149 @ Now this is really it: \TeX\ starts and ends here.
25150
25151 The initial test involving |ready_already| should be deleted if the
25152 \PASCAL\ runtime system is smart enough to detect such a ``mistake.''
25153 @^system dependencies@>
25154
25155 @p
25156 int main(int argc, char *argv[]) {@! /*|start_here|*/
25157 main_init(argc, argv); /* \TeX\ Live */
25158 history=fatal_error_stop; /*in case we quit during initialization*/
25159 t_open_out; /*open the terminal for output*/
25160 if (ready_already==314159) goto start_of_TEX;
25161 @<Check the ``constant'' values...@>@;
25162 if (bad > 0)
25163 {@+wterm_ln("Ouch---my internal constants have been clobbered!"
25164 "---case %d", bad);
25165 @.Ouch...clobbered@>
25166 exit(0);
25167 }
25168 get_strings_started();
25169 initialize(); /*set global variables to their starting values*/
25170 #ifdef @!INIT
25171 if (iniversion) /* \TeX\ Live */
25172 { init_prim(); /*call |primitive| for each primitive*/
25173 init_str_ptr=str_ptr;init_pool_ptr=pool_ptr;fix_date_and_time(); }
25174 #endif
25175 ready_already=314159;
25176 start_of_TEX: @<Initialize the output routines@>;
25177 @<Get the first line of input and prepare to start@>;
25178 history=spotless; /*ready to go!*/
25179 main_control(); /*come to life*/
25180 final_cleanup(); /*prepare for death*/
25181 close_files_and_terminate();
25182 ready_already=0;
25183 return 0; }
25184
25185 @ Here we do whatever is needed to complete \TeX's job gracefully on the
25186 local operating system. The code here might come into play after a fatal
25187 error; it must therefore consist entirely of ``safe'' operations that
25188 cannot produce error messages. For example, it would be a mistake to call
25189 |str_room| or |make_string| at this time, because a call on |overflow|
25190 might lead to an infinite loop.
25191 @^system dependencies@>
25192 (Actually there's one way to get error messages, via |prepare_mag|;
25193 but that can't cause infinite recursion.)
25194 @^recursion@>
25195
25196 If |final_cleanup| is bypassed, this program doesn't bother to close
25197 the input files that may still be open.
25198
25199 @<Last-minute...@>=
25200 static void close_files_and_terminate(void)
25201 {@+int k; /*all-purpose index*/
25202 @<Finish the extensions@>;new_line_char=-1;
25203 #ifdef @!STAT
25204 if (tracing_stats > 0) @<Output statistics about this job@>;@;
25205 #endif
25206 wake_up_terminal;@<Finish the \.{DVI} file@>;
25207 if (log_opened)
25208 {@+wlog_cr;a_close(&log_file);selector=selector-2;
25209 if (selector==term_only)
25210 {@+print_nl("Transcript written on ");
25211 @.Transcript written...@>
25212 slow_print(log_name);print_char('.');print_nl("");
25213 }
25214 }
25215 }
25216
25217 @ The present section goes directly to the log file instead of using
25218 |print| commands, because there's no need for these strings to take
25219 up |str_pool| memory when a non-{\bf stat} version of \TeX\ is being used.
25220
25221 @<Output statistics...@>=
25222 if (log_opened)
25223 {@+wlog_ln(" ");
25224 wlog_ln("Here is how much of TeX's memory you used:");
25225 @.Here is how much...@>
25226 wlog(" %d string", str_ptr-init_str_ptr);
25227 if (str_ptr!=init_str_ptr+1) wlog( "s" );
25228 wlog_ln( " out of %d", max_strings-init_str_ptr);@/
25229 wlog_ln( " %d string characters out of %d", pool_ptr-init_pool_ptr,
25230 pool_size-init_pool_ptr);@/
25231 wlog_ln(" %d words of memory out of %d", lo_mem_max-mem_min+mem_end-hi_mem_min+2,@|
25232 mem_end+1-mem_min);@/
25233 wlog_ln(" %d multiletter control sequences out of %d", cs_count, hash_size);@/
25234 wlog(" %d words of font info for %d font", fmem_ptr, font_ptr-font_base);
25235 if (font_ptr!=font_base+1) wlog("s");
25236 wlog_ln( ", out of %d for %d", font_mem_size, font_max-font_base);@/
25237 wlog(" %d hyphenation exception", hyph_count);
25238 if (hyph_count!=1) wlog("s");
25239 wlog_ln( " out of %d", hyph_size);@/
25240 wlog_ln(" %di,%dn,%dp,%db,%ds stack positions out of %di,%dn,%dp,%db,%ds",
25241 max_in_stack, max_nest_stack,@|
25242 max_param_stack,@|
25243 max_buf_stack+1,@|
25244 max_save_stack+6,@|
25245 stack_size,
25246 nest_size,
25247 param_size,
25248 buf_size,
25249 save_size );
25250 }
25251
25252 @ We get to the |final_cleanup| routine when \.{\\end} or \.{\\dump} has
25253 been scanned and |its_all_over|\kern-2pt.
25254
25255 @<Last-minute...@>=
25256 static void final_cleanup(void)
25257 {@+
25258 int c; /*0 for \.{\\end}, 1 for \.{\\dump}*/
25259 c=cur_chr;if (c!=1) new_line_char=-1;
25260 if (job_name==0) open_log_file();
25261 while (input_ptr > 0)
25262 if (state==token_list) end_token_list();@+else end_file_reading();
25263 while (open_parens > 0)
25264 {@+print(" )");decr(open_parens);
25265 }
25266 if (cur_level > level_one)
25267 {@+print_nl("(");print_esc("end occurred ");
25268 print("inside a group at level ");
25269 @:end\_}{\.{(\\end occurred...)}@>
25270 print_int(cur_level-level_one);print_char(')');
25271 if (eTeX_ex) show_save_groups();
25272 }
25273 while (cond_ptr!=null)
25274 {@+print_nl("(");print_esc("end occurred ");
25275 print("when ");print_cmd_chr(if_test, cur_if);
25276 if (if_line!=0)
25277 {@+print(" on line ");print_int(if_line);
25278 }
25279 print(" was incomplete)");
25280 if_line=if_line_field(cond_ptr);
25281 cur_if=subtype(cond_ptr);temp_ptr=cond_ptr;
25282 cond_ptr=link(cond_ptr);free_node(temp_ptr, if_node_size);
25283 }
25284 if (history!=spotless)
25285 if (((history==warning_issued)||(interaction < error_stop_mode)))
25286 if (selector==term_and_log)
25287 {@+selector=term_only;
25288 print_nl("(see the transcript file for additional information)");
25289 @.see the transcript file...@>
25290 selector=term_and_log;
25291 }
25292 if (c==1)
25293 {
25294 #ifdef @!INIT
25295 for (c=top_mark_code; c<=split_bot_mark_code; c++)
25296 if (cur_mark[c]!=null) delete_token_ref(cur_mark[c]);
25297 if (sa_mark!=null)
25298 if (do_marks(destroy_marks, 0, sa_mark)) sa_mark=null;
25299 for (c=last_box_code; c<=vsplit_code; c++) flush_node_list(disc_ptr[c]);
25300 if (last_glue!=max_halfword) delete_glue_ref(last_glue);
25301 store_fmt_file();return;
25302 #endif
25303 print_nl("(\\dump is performed only by INITEX)");return;
25304 @:dump\_}{\.{\\dump...only by INITEX}@>
25305 }
25306 }
25307
25308 @ @<Last-minute...@>=
25309 #ifdef @!INIT
25310 static void init_prim(void) /*initialize all the primitives*/
25311 {@+no_new_control_sequence=false;
25312 first=0;
25313 @<Put each...@>;
25314 no_new_control_sequence=true;
25315 }
25316 #endif
25317
25318 @ When we begin the following code, \TeX's tables may still contain garbage;
25319 the strings might not even be present. Thus we must proceed cautiously to get
25320 bootstrapped in.
25321
25322 But when we finish this part of the program, \TeX\ is ready to call on the
25323 |main_control| routine to do its work.
25324
25325 @<Get the first line...@>=
25326 {@+@<Initialize the input routines@>;
25327 @<Enable \eTeX\ and furthermore Prote, if requested@>@;@/
25328 if ((format_ident==0)||(buffer[loc]=='&'))
25329 {@+if (format_ident!=0) initialize(); /*erase preloaded format*/
25330 if (!open_fmt_file()) exit(0);
25331 if (!load_fmt_file())
25332 {@+w_close(&fmt_file);exit(0);
25333 }
25334 w_close(&fmt_file);
25335 while ((loc < limit)&&(buffer[loc]==' ')) incr(loc);
25336 }
25337 if (eTeX_ex) wterm_ln("entering extended mode");
25338 if (Prote_ex) {@+Prote_initialize();
25339 }
25340 if (end_line_char_inactive) decr(limit);
25341 else buffer[limit]=end_line_char;
25342 fix_date_and_time();@/
25343 @<Initialize the print |selector|...@>;
25344 if ((loc < limit)&&(cat_code(buffer[loc])!=escape)) start_input();
25345 /*\.{\\input} assumed*/
25346 }
25347
25348 @* Debugging.
25349 Once \TeX\ is working, you should be able to diagnose most errors with
25350 the \.{\\show} commands and other diagnostic features. But for the initial
25351 stages of debugging, and for the revelation of really deep mysteries, you
25352 can compile \TeX\ with a few more aids, including the \PASCAL\ runtime
25353 checks and its debugger. An additional routine called |debug_help|
25354 will also come into play when you type `\.D' after an error message;
25355 |debug_help| also occurs just before a fatal error causes \TeX\ to succumb.
25356 @^debugging@>
25357 @^system dependencies@>
25358
25359 The interface to |debug_help| is primitive, but it is good enough when used
25360 with a \PASCAL\ debugger that allows you to set breakpoints and to read
25361 variables and change their values. After getting the prompt `\.{debug \#}', you
25362 type either a negative number (this exits |debug_help|), or zero (this
25363 goes to a location where you can set a breakpoint, thereby entering into
25364 dialog with the \PASCAL\ debugger), or a positive number |m| followed by
25365 an argument |n|. The meaning of |m| and |n| will be clear from the
25366 program below. (If |m==13|, there is an additional argument, |l|.)
25367 @.debug \#@>
25368
25369 @<Last-minute...@>=
25370 #ifdef @!DEBUG
25371 static void debug_help(void) /*routine to display various things*/
25372 {@+
25373 int k, @!l, @!m, @!n;
25374 clear_terminal;
25375 loop{@+wake_up_terminal;
25376 print_nl("debug # (-1 to exit):");update_terminal;
25377 @.debug \#@>
25378 if (fscanf(term_in.f," %d",&m)<1 ||
25379 m < 0) return;
25380 else if (m==0)
25381 {@+goto breakpoint;@/ /*go to every declared label at least once*/
25382 breakpoint: m=0; /*'BREAKPOINT'*/@/
25383 }
25384 else{@+fscanf(term_in.f," %d",&n);
25385 switch (m) {
25386 @t\4@>@<Numbered cases for |debug_help|@>@;
25387 default:print("?");
25388 }
25389 }
25390 }
25391 }
25392 #endif
25393
25394 @ @<Numbered cases...@>=
25395 case 1: print_word(mem[n]);@+break; /*display |mem[n]| in all forms*/
25396 case 2: print_int(info(n));@+break;
25397 case 3: print_int(link(n));@+break;
25398 case 4: print_word(eqtb[n]);@+break;
25399 case 5: print_word(font_info[n]);@+break;
25400 case 6: print_word(save_stack[n]);@+break;
25401 case 7: show_box(n);@+break;
25402 /*show a box, abbreviated by |show_box_depth| and |show_box_breadth|*/
25403 case 8: {@+breadth_max=10000;depth_threshold=pool_size-pool_ptr-10;
25404 show_node_list(n); /*show a box in its entirety*/
25405 } @+break;
25406 case 9: show_token_list(n, null, 1000);@+break;
25407 case 10: slow_print(n);@+break;
25408 case 11: check_mem(n > 0);@+break; /*check wellformedness; print new busy locations if |n > 0|*/
25409 case 12: search_mem(n);@+break; /*look for pointers to |n|*/
25410 case 13: {@+fscanf(term_in.f," %d",&l);print_cmd_chr(n, l);
25411 } @+break;
25412 case 14: for (k=0; k<=n; k++) printn(buffer[k]);@+break;
25413 case 15: {@+font_in_short_display=null_font;short_display(n);
25414 } @+break;
25415 case 16: panicking=!panicking;@+break;
25416
25417 @* Extensions.
25418 The program above includes a bunch of ``hooks'' that allow further
25419 capabilities to be added without upsetting \TeX's basic structure.
25420 Most of these hooks are concerned with ``whatsit'' nodes, which are
25421 intended to be used for special purposes; whenever a new extension to
25422 \TeX\ involves a new kind of whatsit node, a corresponding change needs
25423 to be made to the routines below that deal with such nodes,
25424 but it will usually be unnecessary to make many changes to the
25425 other parts of this program.
25426
25427 In order to demonstrate how extensions can be made, we shall treat
25428 `\.{\\write}', `\.{\\openout}', `\.{\\closeout}', `\.{\\immediate}',
25429 `\.{\\special}', and `\.{\\setlanguage}' as if they were extensions.
25430 These commands are actually primitives of \TeX, and they should
25431 appear in all implementations of the system; but let's try to imagine
25432 that they aren't. Then the program below illustrates how a person
25433 could add them.
25434
25435 Sometimes, of course, an extension will require changes to \TeX\ itself;
25436 no system of hooks could be complete enough for all conceivable extensions.
25437 The features associated with `\.{\\write}' are almost all confined to the
25438 following paragraphs, but there are small parts of the |print_ln| and
25439 |print_char| procedures that were introduced specifically to \.{\\write}
25440 characters. Furthermore one of the token lists recognized by the scanner
25441 is a |write_text|; and there are a few other miscellaneous places where we
25442 have already provided for some aspect of \.{\\write}. The goal of a \TeX\
25443 extender should be to minimize alterations to the standard parts of the
25444 program, and to avoid them completely if possible. He or she should also
25445 be quite sure that there's no easy way to accomplish the desired goals
25446 with the standard features that \TeX\ already has. ``Think thrice before
25447 extending,'' because that may save a lot of work, and it will also keep
25448 incompatible extensions of \TeX\ from proliferating.
25449 @^system dependencies@>
25450 @^extensions to \TeX@>
25451
25452 @ First let's consider the format of whatsit nodes that are used to represent
25453 the data associated with \.{\\write} and its relatives. Recall that a whatsit
25454 has |type==whatsit_node|, and the |subtype| is supposed to distinguish
25455 different kinds of whatsits. Each node occupies two or more words; the
25456 exact number is immaterial, as long as it is readily determined from the
25457 |subtype| or other data.
25458
25459 We shall introduce five |subtype| values here, corresponding to the
25460 control sequences \.{\\openout}, \.{\\write}, \.{\\closeout}, \.{\\special}, and
25461 \.{\\setlanguage}. The second word of I/O whatsits has a |write_stream| field
25462 that identifies the write-stream number (0 to 15, or 16 for out-of-range and
25463 positive, or 17 for out-of-range and negative).
25464 In the case of \.{\\write} and \.{\\special}, there is also a field that
25465 points to the reference count of a token list that should be sent. In the
25466 case of \.{\\openout}, we need three words and three auxiliary subfields
25467 to hold the string numbers for name, area, and extension.
25468
25469 @d write_node_size 2 /*number of words in a write/whatsit node*/
25470 @d open_node_size 3 /*number of words in an open/whatsit node*/
25471 @d open_node 0 /*|subtype| in whatsits that represent files to \.{\\openout}*/
25472 @d write_node 1 /*|subtype| in whatsits that represent things to \.{\\write}*/
25473 @d close_node 2 /*|subtype| in whatsits that represent streams to \.{\\closeout}*/
25474 @d special_node 3 /*|subtype| in whatsits that represent \.{\\special} things*/
25475 @d language_node 4 /*|subtype| in whatsits that change the current language*/
25476 @d what_lang(A) link(A+1) /*language number, in the range |0 dotdot 255|*/
25477 @d what_lhm(A) type(A+1) /*minimum left fragment, in the range |1 dotdot 63|*/
25478 @d what_rhm(A) subtype(A+1) /*minimum right fragment, in the range |1 dotdot 63|*/
25479 @d write_tokens(A) link(A+1) /*reference count of token list to write*/
25480 @d write_stream(A) info(A+1) /*stream number (0 to 17)*/
25481 @d open_name(A) link(A+1) /*string number of file name to open*/
25482 @d open_area(A) info(A+2) /*string number of file area for |open_name|*/
25483 @d open_ext(A) link(A+2) /*string number of file extension for |open_name|*/
25484
25485 @ The sixteen possible \.{\\write} streams are represented by the |write_file|
25486 array. The |j|th file is open if and only if |write_open[j]==true|. The last
25487 two streams are special; |write_open[16]| represents a stream number
25488 greater than 15, while |write_open[17]| represents a negative stream number,
25489 and both of these variables are always |false|.
25490
25491 @<Glob...@>=
25492 static alpha_file @!write_file[16];
25493 static bool @!write_open[18];
25494
25495 @ @<Set init...@>=
25496 for (k=0; k<=17; k++) write_open[k]=false;
25497
25498 @ Extensions might introduce new command codes; but it's best to use
25499 |extension| with a modifier, whenever possible, so that |main_control|
25500 stays the same.
25501
25502 @d immediate_code 4 /*command modifier for \.{\\immediate}*/
25503 @d latex_first_extension_code 5
25504 @d latespecial_node (latex_first_extension_code+0) /*|subtype| in whatsits that represent \.{\\special} things expanded during output*/
25505 @d set_language_code (latex_first_extension_code+1) /*command modifier for \.{\\setlanguage}*/
25506 @d TeX_last_extension_cmd_mod set_language_code
25507
25508 @<Put each...@>=
25509 primitive("openout", extension, open_node);@/
25510 @!@:open\_out\_}{\.{\\openout} primitive@>
25511 primitive("write", extension, write_node);write_loc=cur_val;@/
25512 @!@:write\_}{\.{\\write} primitive@>
25513 primitive("closeout", extension, close_node);@/
25514 @!@:close\_out\_}{\.{\\closeout} primitive@>
25515 primitive("special", extension, special_node);@/
25516 @!@:special\_}{\.{\\special} primitive@>
25517 primitive("immediate", extension, immediate_code);@/
25518 @!@:immediate\_}{\.{\\immediate} primitive@>
25519 primitive("setlanguage", extension, set_language_code);@/
25520 @!@:set\_language\_}{\.{\\setlanguage} primitive@>
25521
25522 @ The variable |write_loc| just introduced is used to provide an
25523 appropriate error message in case of ``runaway'' write texts.
25524
25525 @<Glob...@>=
25526 static pointer @!write_loc; /*|eqtb| address of \.{\\write}*/
25527
25528 @ @<Cases of |print_cmd_chr|...@>=
25529 case extension: switch (chr_code) {
25530 case open_node: print_esc("openout");@+break;
25531 case write_node: print_esc("write");@+break;
25532 case close_node: print_esc("closeout");@+break;
25533 case special_node: print_esc("special");@+break;
25534 case immediate_code: print_esc("immediate");@+break;
25535 case set_language_code: print_esc("setlanguage");@+break;
25536 @/@<Cases of |extension| for |print_cmd_chr|@>@/
25537 default:print("[unknown extension!]");
25538 } @+break;
25539
25540
25541
25542 @ When an |extension| command occurs in |main_control|, in any mode,
25543 the |do_extension| routine is called.
25544
25545 @<Cases of |main_control| that are for extensions...@>=
25546 any_mode(extension): do_extension();
25547
25548 @ @<Declare act...@>=
25549 @t\4@>@<Declare procedures needed in |do_extension|@>@;
25550 static void do_extension(void)
25551 {@+int @!k; /*all-purpose integer*/
25552 pointer @!p; /*all-purpose pointer*/
25553 switch (cur_chr) {
25554 case open_node: @<Implement \.{\\openout}@>@;@+break;
25555 case write_node: @<Implement \.{\\write}@>@;@+break;
25556 case close_node: @<Implement \.{\\closeout}@>@;@+break;
25557 case special_node: @<Implement \.{\\special}@>@;@+break;
25558 case immediate_code: @<Implement \.{\\immediate}@>@;@+break;
25559 case set_language_code: @<Implement \.{\\setlanguage}@>@;@+break;
25560 @/@<Cases for |do_extension|@>@/
25561 default:confusion("ext1");
25562 @:this can't happen ext1}{\quad ext1@>
25563 }
25564 }
25565
25566 @ Here is a subroutine that creates a whatsit node having a given |subtype|
25567 and a given number of words. It initializes only the first word of the whatsit,
25568 and appends it to the current list.
25569
25570 @<Declare procedures needed in |do_extension|@>=
25571 static void new_whatsit(small_number @!s, small_number @!w)
25572 {@+pointer p; /*the new node*/
25573 p=get_node(w);type(p)=whatsit_node;subtype(p)=s;
25574 link(tail)=p;tail=p;
25575 }
25576
25577 @ The next subroutine uses |cur_chr| to decide what sort of whatsit is
25578 involved, and also inserts a |write_stream| number.
25579
25580 @<Declare procedures needed in |do_ext...@>=
25581 static void new_write_whatsit(small_number @!w)
25582 {@+new_whatsit(cur_chr, w);
25583 if (w!=write_node_size) scan_four_bit_int();
25584 else{@+scan_int();
25585 if (cur_val < 0) cur_val=17;
25586 else if (cur_val > 15) cur_val=16;
25587 }
25588 write_stream(tail)=cur_val;
25589 }
25590
25591 @ @<Implement \.{\\openout}@>=
25592 {@+new_write_whatsit(open_node_size);
25593 scan_optional_equals();scan_file_name();@/
25594 open_name(tail)=cur_name;open_area(tail)=cur_area;open_ext(tail)=cur_ext;
25595 }
25596
25597 @ When `\.{\\write 12\{...\}}' appears, we scan the token list `\.{\{...\}}'
25598 without expanding its macros; the macros will be expanded later when this
25599 token list is rescanned.
25600
25601 @<Implement \.{\\write}@>=
25602 {@+k=cur_cs;new_write_whatsit(write_node_size);@/
25603 cur_cs=k;p=scan_toks(false, false);write_tokens(tail)=def_ref;
25604 }
25605
25606 @ @<Implement \.{\\closeout}@>=
25607 {@+new_write_whatsit(write_node_size);write_tokens(tail)=null;
25608 }
25609
25610 @ When `\.{\\special\{...\}}' appears, we expand the macros in the token
25611 list as in \.{\\xdef} and \.{\\mark}. When marked with \.{shipout}, we keep
25612 tokens unexpanded for now.
25613
25614 @<Implement \.{\\special}@>=
25615 {@+if (scan_keyword("shipout"))
25616 {@+new_whatsit(latespecial_node, write_node_size);write_stream(tail)=null;
25617 p=scan_toks(false, false);write_tokens(tail)=def_ref;
25618 } else
25619 {@+new_whatsit(special_node, write_node_size);write_stream(tail)=null;
25620 p=scan_toks(false, true);write_tokens(tail)=def_ref;
25621 } }
25622
25623 @ Each new type of node that appears in our data structure must be capable
25624 of being displayed, copied, destroyed, and so on. The routines that we
25625 need for write-oriented whatsits are somewhat like those for mark nodes;
25626 other extensions might, of course, involve more subtlety here.
25627
25628 @<Basic printing...@>=
25629 static void print_write_whatsit(char *@!s, pointer @!p)
25630 {@+print_esc(s);
25631 if (write_stream(p) < 16) print_int(write_stream(p));
25632 else if (write_stream(p)==16) print_char('*');
25633 @.*\relax@>
25634 else print_char('-');
25635 }
25636
25637 @ @<Display the whatsit...@>=
25638 switch (subtype(p)) {
25639 case open_node: {@+print_write_whatsit("openout", p);
25640 print_char('=');print_file_name(open_name(p), open_area(p), open_ext(p));
25641 } @+break;
25642 case write_node: {@+print_write_whatsit("write", p);
25643 print_mark(write_tokens(p));
25644 } @+break;
25645 case close_node: print_write_whatsit("closeout", p);@+break;
25646 case latespecial_node: {@+print_esc("special");print(" shipout");
25647 print_mark(write_tokens(p));
25648 } @+break;
25649 case special_node: {@+print_esc("special");
25650 print_mark(write_tokens(p));
25651 } @+break;
25652 case language_node: {@+print_esc("setlanguage");
25653 print_int(what_lang(p));print(" (hyphenmin ");
25654 print_int(what_lhm(p));print_char(',');
25655 print_int(what_rhm(p));print_char(')');
25656 } @+break;
25657 @/@<Cases for displaying the |whatsit| node@>@/
25658 default:print("whatsit?");
25659 }
25660
25661 @ @<Make a partial copy of the whatsit...@>=
25662 switch (subtype(p)) {
25663 case open_node: {@+r=get_node(open_node_size);words=open_node_size;
25664 } @+break;
25665 case write_node: case special_node: case latespecial_node: {@+r=get_node(write_node_size);
25666 add_token_ref(write_tokens(p));words=write_node_size;
25667 } @+break;
25668 case close_node: case language_node: {@+r=get_node(small_node_size);
25669 words=small_node_size;
25670 } @+break;
25671 @/@<Cases for making a partial copy of the whatsit node@>@/
25672 default:confusion("ext2");
25673 @:this can't happen ext2}{\quad ext2@>
25674 }
25675
25676 @ @<Wipe out the whatsit...@>=
25677 {@+switch (subtype(p)) {
25678 case open_node: free_node(p, open_node_size);@+break;
25679 case write_node: case special_node: case latespecial_node: {@+delete_token_ref(write_tokens(p));
25680 free_node(p, write_node_size);goto done;
25681 }
25682 case close_node: case language_node: free_node(p, small_node_size);@+break;
25683 @/@<Cases for wiping out the whatsit node@>@/
25684 default:confusion("ext3");
25685 @:this can't happen ext3}{\quad ext3@>
25686 } @/
25687 goto done;
25688 }
25689
25690 @ @<Incorporate a whatsit node into a vbox@>=do_nothing
25691
25692 @ @<Incorporate a whatsit node into an hbox@>=do_nothing
25693
25694 @ @<Let |d| be the width of the whatsit |p|@>=d=0
25695
25696 @ @d adv_past(A) @+if (subtype(A)==language_node)
25697 {@+cur_lang=what_lang(A);l_hyf=what_lhm(A);r_hyf=what_rhm(A);
25698 set_hyph_index;
25699 }
25700
25701 @<Advance \(p)past a whatsit node in the \(l)|line_break| loop@>=@+
25702 adv_past(cur_p)
25703
25704 @ @<Advance \(p)past a whatsit node in the \(p)pre-hyphenation loop@>=@+
25705 adv_past(s)
25706
25707 @ @<Prepare to move whatsit |p| to the current page, then |goto contribute|@>=
25708 goto contribute
25709
25710 @ @<Process whatsit |p| in |vert_break| loop, |goto not_found|@>=
25711 goto not_found
25712
25713 @ @<Output the whatsit node |p| in a vlist@>=
25714 out_what(p)
25715
25716 @ @<Output the whatsit node |p| in an hlist@>=
25717 out_what(p)
25718
25719 @ After all this preliminary shuffling, we come finally to the routines
25720 that actually send out the requested data. Let's do \.{\\special} first
25721 (it's easier).
25722
25723 @<Declare procedures needed in |hlist_out|, |vlist_out|@>=
25724 static void special_out(pointer @!p)
25725 {@+pointer @!q, @!r; /*temporary variables for list manipulation*/
25726 int @!old_mode; /*saved |mode|*/
25727
25728 if (subtype(p)==latespecial_node)
25729 {@+@<Expand macros in the token list and make |link(def_ref)| point to the
25730 result@>;
25731 write_tokens(p)=def_ref;
25732 }
25733 }
25734
25735 @ To write a token list, we must run it through \TeX's scanner, expanding
25736 macros and \.{\\the} and \.{\\number}, etc. This might cause runaways,
25737 if a delimited macro parameter isn't matched, and runaways would be
25738 extremely confusing since we are calling on \TeX's scanner in the middle
25739 of a \.{\\shipout} command. Therefore we will put a dummy control sequence as
25740 a ``stopper,'' right after the token list. This control sequence is
25741 artificially defined to be \.{\\outer}.
25742 @:end\_write\_}{\.{\\endwrite}@>
25743
25744 @<Initialize table...@>=
25745 text(end_write)=s_no("endwrite");eq_level(end_write)=level_one;
25746 eq_type(end_write)=outer_call;equiv(end_write)=null;
25747
25748 @ @<Declare procedures needed in |hlist_out|, |vlist_out|@>=
25749 static void write_out(pointer @!p)
25750 {@+int old_setting; /*holds print |selector|*/
25751 int @!old_mode; /*saved |mode|*/
25752 small_number @!j; /*write stream number*/
25753 pointer @!q, @!r; /*temporary variables for list manipulation*/
25754 @<Expand macros in the token list and make |link(def_ref)| point to the result@>;
25755 old_setting=selector;j=write_stream(p);
25756 if (write_open[j]) selector=j;
25757 else{@+ /*write to the terminal if file isn't open*/
25758 if ((j==17)&&(selector==term_and_log)) selector=log_only;
25759 print_nl("");
25760 }
25761 token_show(def_ref);print_ln();
25762 flush_list(def_ref);selector=old_setting;
25763 }
25764
25765 @ The final line of this routine is slightly subtle; at least, the author
25766 didn't think about it until getting burnt! There is a used-up token list
25767 @^Knuth, Donald Ervin@>
25768 on the stack, namely the one that contained |end_write_token|. (We
25769 insert this artificial `\.{\\endwrite}' to prevent runaways, as explained
25770 above.) If it were not removed, and if there were numerous writes on a
25771 single page, the stack would overflow.
25772
25773 @d end_write_token cs_token_flag+end_write
25774
25775 @<Expand macros in the token list and...@>=
25776 q=get_avail();info(q)=right_brace_token+'}';@/
25777 fl_mem[q]=FILE_LINE(system_file,system_insert);
25778 r=get_avail();link(q)=r;info(r)=end_write_token;ins_list(q);@/
25779 fl_mem[r]=FILE_LINE(system_file,system_insert);
25780 begin_token_list(write_tokens(p), write_text);@/
25781 q=get_avail();info(q)=left_brace_token+'{';ins_list(q);
25782 fl_mem[q]=FILE_LINE(system_file,system_insert);
25783
25784 /*now we're ready to scan
25785 `\.\{$\langle\,$token list$\,\rangle$\.{\} \\endwrite}'*/
25786 old_mode=mode;mode=0;
25787 /*disable \.{\\prevdepth}, \.{\\spacefactor}, \.{\\lastskip}, \.{\\prevgraf}*/
25788 cur_cs=write_loc;q=scan_toks(false, true); /*expand macros, etc.*/
25789 get_token();@+if (cur_tok!=end_write_token)
25790 @<Recover from an unbalanced write command@>;
25791 mode=old_mode;
25792 end_token_list() /*conserve stack space*/
25793
25794 @ @<Recover from an unbalanced write command@>=
25795 {@+print_err("Unbalanced write command");
25796 @.Unbalanced write...@>
25797 help2("On this page there's a \\write with fewer real {'s than }'s.",@/
25798 "I can't handle that very well; good luck.");error();
25799 @/do@+{get_token();
25800 }@+ while (!(cur_tok==end_write_token));
25801 }
25802
25803 @ The |out_what| procedure takes care of outputting whatsit nodes for
25804 |vlist_out| and |hlist_out|\kern-.3pt.
25805
25806 @<Declare procedures needed in |hlist_out|, |vlist_out|@>=
25807 @t\4@>@<Declare procedures needed in |out_what|@>@;
25808 static void out_what(pointer @!p)
25809 {@+small_number j; /*write stream number*/
25810 switch (subtype(p)) {
25811 case open_node: case write_node: case close_node: @<Do some work that has
25812 been queued up for \.{\\write}@>@;@+break;
25813 case special_node: special_out(p);@+break;
25814 case language_node: do_nothing;@+break;
25815 @/@<Cases for |out_what|@>@/
25816 default:confusion("ext4");
25817 @:this can't happen ext4}{\quad ext4@>
25818 }
25819 }
25820
25821 @ We don't implement \.{\\write} inside of leaders. (The reason is that
25822 the number of times a leader box appears might be different in different
25823 implementations, due to machine-dependent rounding in the glue calculations.)
25824 @^leaders@>
25825
25826 @<Do some work that has been queued up...@>=
25827 if (!doing_leaders)
25828 {@+j=write_stream(p);
25829 if (subtype(p)==write_node) write_out(p);
25830 else{@+if (write_open[j]) a_close(&write_file[j]);
25831 if (subtype(p)==close_node) write_open[j]=false;
25832 else if (j < 16)
25833 {@+cur_name=open_name(p);cur_area=open_area(p);
25834 cur_ext=open_ext(p);
25835 pack_cur_name(".tex");
25836 while (!a_open_out(&write_file[j]))
25837 prompt_file_name("output file name",".tex");
25838 write_open[j]=true;
25839 }
25840 }
25841 }
25842
25843 @ The presence of `\.{\\immediate}' causes the |do_extension| procedure
25844 to descend to one level of recursion. Nothing happens unless \.{\\immediate}
25845 is followed by `\.{\\openout}', `\.{\\write}', or `\.{\\closeout}'.
25846 @^recursion@>
25847
25848 @<Implement \.{\\immediate}@>=
25849 {@+get_x_token();
25850 if ((cur_cmd==extension)&&(cur_chr <= close_node))
25851 {@+p=tail;do_extension(); /*append a whatsit node*/
25852 out_what(tail); /*do the action immediately*/
25853 flush_node_list(tail);tail=p;link(p)=null;
25854 }
25855 else back_input();
25856 }
25857
25858 @ The \.{\\language} extension is somewhat different.
25859 We need a subroutine that comes into play when a character of
25860 a non-|clang| language is being appended to the current paragraph.
25861
25862 @<Declare action...@>=
25863 static void fix_language(void)
25864 {@+ASCII_code @!l; /*the new current language*/
25865 if (language <= 0) l=0;
25866 else if (language > 255) l=0;
25867 else l=language;
25868 if (l!=clang)
25869 {@+new_whatsit(language_node, small_node_size);
25870 what_lang(tail)=l;clang=l;@/
25871 what_lhm(tail)=norm_min(left_hyphen_min);
25872 what_rhm(tail)=norm_min(right_hyphen_min);
25873 }
25874 }
25875
25876 @ @<Implement \.{\\setlanguage}@>=
25877 if (abs(mode)!=hmode) report_illegal_case();
25878 else{@+new_whatsit(language_node, small_node_size);
25879 scan_int();
25880 if (cur_val <= 0) clang=0;
25881 else if (cur_val > 255) clang=0;
25882 else clang=cur_val;
25883 what_lang(tail)=clang;
25884 what_lhm(tail)=norm_min(left_hyphen_min);
25885 what_rhm(tail)=norm_min(right_hyphen_min);
25886 }
25887
25888 @ @<Finish the extensions@>=
25889 for (k=0; k<=15; k++) if (write_open[k]) a_close(&write_file[k]);
25890
25891 @* The extended features of \eTeX.
25892 The program has three modes of operation: (1)~In \TeX\ compatibility mode
25893 it fully deserves the name \TeX\ and there are neither extended features
25894 nor additional primitive commands. There are, however, a few
25895 modifications that would be legitimate in any implementation of \TeX\
25896 such as, e.g., preventing inadequate results of the glue to \.{DVI}
25897 unit conversion during |ship_out|. (2)~In extended mode there are
25898 additional primitive commands and the extended features of \eTeX\ are
25899 available. (3)~In \Prote\ mode there are supplementary primitive
25900 commands that will be discussed in the section below.
25901
25902 The distinction between these three modes of operation initially takes
25903 place when a `virgin' \.{eINITEX} starts without reading a format file.
25904 Later on the values of all \eTeX\ state variables are inherited when
25905 \.{eVIRTEX} (or \.{eINITEX}) reads a format file.
25906
25907 The code below is designed to work for cases where `$|@t\#\&{ifdef} \.{INIT}@>|\ldots|@t\#\&{endif}@>|$'
25908 is a run-time switch.
25909
25910 @<Enable \eTeX\ and furthermore Prote, if requested@>=
25911 #ifdef @!INIT
25912 if (iniversion && (buffer[loc]=='*'||etexp)) /* \TeX\ Live */
25913 {@+no_new_control_sequence=false;
25914 @<Generate all \eTeX\ primitives@>@;
25915 if (buffer[loc]=='*') incr(loc); /* \TeX\ Live */
25916 eTeX_mode=1; /*enter extended mode*/
25917 @<Initialize variables for \eTeX\ extended mode@>@;
25918 if (buffer[loc]=='*'||ltxp) {@+
25919 @<Check \Prote\ ``constant'' values for consistency@>@;
25920 @<Generate all \Prote\ primitives@>@;
25921 if (buffer[loc]=='*')incr(loc);
25922 Prote_mode=1; /*enter \Prote\ mode*/
25923 }
25924 }
25925 #endif
25926 @;@/
25927 if (!no_new_control_sequence) /*just entered extended mode ?*/
25928 no_new_control_sequence=true;@+else
25929
25930 @ The \eTeX\ features available in extended mode are grouped into two
25931 categories: (1)~Some of them are permanently enabled and have no
25932 semantic effect as long as none of the additional primitives are
25933 executed. (2)~The remaining \eTeX\ features are optional and can be
25934 individually enabled and disabled. For each optional feature there is
25935 an \eTeX\ state variable named \.{\\...state}; the feature is enabled,
25936 resp.\ disabled by assigning a positive, resp.\ non-positive value to
25937 that integer.
25938
25939 @d eTeX_state_base (int_base+eTeX_state_code)
25940 @d eTeX_state(A) eqtb[eTeX_state_base+A].i /*an \eTeX\ state variable*/
25941 @#
25942 @d eTeX_version_code eTeX_int /*code for \.{\\eTeXversion}*/
25943
25944 @<Generate all \eTeX...@>=
25945 primitive("lastnodetype", last_item, last_node_type_code);
25946 @!@:last\_node\_type\_}{\.{\\lastnodetype} primitive@>
25947 primitive("eTeXversion", last_item, eTeX_version_code);
25948 @!@:eTeX\_version\_}{\.{\\eTeXversion} primitive@>
25949 primitive("eTeXrevision", convert, eTeX_revision_code);@/
25950 @!@:eTeX\_revision\_}{\.{\\eTeXrevision} primitive@>
25951
25952 @ @<Cases of |last_item| for |print_cmd_chr|@>=
25953 case last_node_type_code: print_esc("lastnodetype");@+break;
25954 case eTeX_version_code: print_esc("eTeXversion");@+break;
25955
25956 @ @<Cases for fetching an integer value@>=
25957 case eTeX_version_code: cur_val=eTeX_version;@+break;
25958
25959 @ @d eTeX_ex (eTeX_mode==1) /*is this extended mode?*/
25960
25961 @<Glob...@>=
25962 static int @!eTeX_mode; /*identifies compatibility and extended mode*/
25963
25964 @ @<Initialize table entries...@>=
25965 eTeX_mode=0; /*initially we are in compatibility mode*/
25966 @<Initialize variables for \eTeX\ compatibility mode@>@;
25967
25968 @ @<Dump the \eTeX\ state@>=
25969 dump_int(eTeX_mode);
25970 for (j=0; j<=eTeX_states-1; j++) eTeX_state(j)=0; /*disable all enhancements*/
25971
25972 @ @<Undump the \eTeX\ state@>=
25973 undump(0, 1, eTeX_mode);
25974 if (eTeX_ex)
25975 {@+@<Initialize variables for \eTeX\ extended mode@>;
25976 }
25977 else{@+@<Initialize variables for \eTeX\ compatibility mode@>;
25978 }
25979
25980 @ The |eTeX_enabled| function simply returns its first argument as
25981 result. This argument is |true| if an optional \eTeX\ feature is
25982 currently enabled; otherwise, if the argument is |false|, the function
25983 gives an error message.
25984
25985 @<Declare \eTeX\ procedures for use...@>=
25986 static bool eTeX_enabled(bool @!b, quarterword @!j, halfword @!k)
25987 {@+if (!b)
25988 {@+print_err("Improper ");print_cmd_chr(j, k);
25989 help1("Sorry, this optional e-TeX feature has been disabled.");error();
25990 }
25991 return b;
25992 }
25993
25994 @ First we implement the additional \eTeX\ parameters in the table of
25995 equivalents.
25996
25997 @<Generate all \eTeX...@>=
25998 primitive("everyeof", assign_toks, every_eof_loc);
25999 @!@:every\_eof\_}{\.{\\everyeof} primitive@>
26000 primitive("tracingassigns", assign_int, int_base+tracing_assigns_code);@/
26001 @!@:tracing\_assigns\_}{\.{\\tracingassigns} primitive@>
26002 primitive("tracinggroups", assign_int, int_base+tracing_groups_code);@/
26003 @!@:tracing\_groups\_}{\.{\\tracinggroups} primitive@>
26004 primitive("tracingifs", assign_int, int_base+tracing_ifs_code);@/
26005 @!@:tracing\_ifs\_}{\.{\\tracingifs} primitive@>
26006 primitive("tracingscantokens", assign_int, int_base+tracing_scan_tokens_code);@/
26007 @!@:tracing\_scan\_tokens\_}{\.{\\tracingscantokens} primitive@>
26008 primitive("tracingnesting", assign_int, int_base+tracing_nesting_code);@/
26009 @!@:tracing\_nesting\_}{\.{\\tracingnesting} primitive@>
26010 primitive("savingvdiscards", assign_int, int_base+saving_vdiscards_code);@/
26011 @!@:saving\_vdiscards\_}{\.{\\savingvdiscards} primitive@>
26012 primitive("savinghyphcodes", assign_int, int_base+saving_hyph_codes_code);@/
26013 @!@:saving\_hyph\_codes\_}{\.{\\savinghyphcodes} primitive@>
26014
26015 @ @d every_eof equiv(every_eof_loc)
26016
26017 @<Cases of |assign_toks| for |print_cmd_chr|@>=
26018 case every_eof_loc: print_esc("everyeof");@+break;
26019
26020 @ @<Cases for |print_param|@>=
26021 case tracing_assigns_code: print_esc("tracingassigns");@+break;
26022 case tracing_groups_code: print_esc("tracinggroups");@+break;
26023 case tracing_ifs_code: print_esc("tracingifs");@+break;
26024 case tracing_scan_tokens_code: print_esc("tracingscantokens");@+break;
26025 case tracing_nesting_code: print_esc("tracingnesting");@+break;
26026 case saving_vdiscards_code: print_esc("savingvdiscards");@+break;
26027 case saving_hyph_codes_code: print_esc("savinghyphcodes");@+break;
26028
26029 @ In order to handle \.{\\everyeof} we need an array |eof_seen| of
26030 boolean variables.
26031
26032 @<Glob...@>=
26033 static bool @!eof_seen0[max_in_open],
26034 *const @!eof_seen = @!eof_seen0-1; /*has eof been seen?*/
26035
26036 @ The |print_group| procedure prints the current level of grouping and
26037 the name corresponding to |cur_group|.
26038
26039 @<Declare \eTeX\ procedures for tr...@>=
26040 static void print_group(bool @!e)
26041 {@+
26042 switch (cur_group) {
26043 case bottom_level: {@+print("bottom level");return;
26044 }
26045 case simple_group: case semi_simple_group:
26046 {@+if (cur_group==semi_simple_group) print("semi ");
26047 print("simple");
26048 } @+break;
26049 case hbox_group: case adjusted_hbox_group:
26050 {@+if (cur_group==adjusted_hbox_group) print("adjusted ");
26051 print("hbox");
26052 } @+break;
26053 case vbox_group: print("vbox");@+break;
26054 case vtop_group: print("vtop");@+break;
26055 case align_group: case no_align_group:
26056 {@+if (cur_group==no_align_group) print("no ");
26057 print("align");
26058 } @+break;
26059 case output_group: print("output");@+break;
26060 case disc_group: print("disc");@+break;
26061 case insert_group: print("insert");@+break;
26062 case vcenter_group: print("vcenter");@+break;
26063 case math_group: case math_choice_group:
26064 case math_shift_group: case math_left_group:
26065 {@+print("math");
26066 if (cur_group==math_choice_group) print(" choice");
26067 else if (cur_group==math_shift_group) print(" shift");
26068 else if (cur_group==math_left_group) print(" left");
26069 }
26070 } /*there are no other cases*/
26071 print(" group (level ");print_int(qo(cur_level));print_char(')');
26072 if (saved(-1)!=0)
26073 {@+if (e) print(" entered at line ");else print(" at line ");
26074 print_int(saved(-1));
26075 }
26076 }
26077
26078 @ The |group_trace| procedure is called when a new level of grouping
26079 begins (|e==false|) or ends (|e==true|) with |saved(-1)| containing the
26080 line number.
26081
26082 @<Declare \eTeX\ procedures for tr...@>=
26083 #ifdef @!STAT
26084 static void group_trace(bool @!e)
26085 {@+begin_diagnostic();print_char('{');
26086 if (e) print("leaving ");else print("entering ");
26087 print_group(e);print_char('}');end_diagnostic(false);
26088 }
26089 #endif
26090
26091 @ The \.{\\currentgrouplevel} and \.{\\currentgrouptype} commands return
26092 the current level of grouping and the type of the current group
26093 respectively.
26094
26095 @d current_group_level_code (eTeX_int+1) /*code for \.{\\currentgrouplevel}*/
26096 @d current_group_type_code (eTeX_int+2) /*code for \.{\\currentgrouptype}*/
26097
26098 @<Generate all \eTeX...@>=
26099 primitive("currentgrouplevel", last_item, current_group_level_code);
26100 @!@:current\_group\_level\_}{\.{\\currentgrouplevel} primitive@>
26101 primitive("currentgrouptype", last_item, current_group_type_code);
26102 @!@:current\_group\_type\_}{\.{\\currentgrouptype} primitive@>
26103
26104 @ @<Cases of |last_item| for |print_cmd_chr|@>=
26105 case current_group_level_code: print_esc("currentgrouplevel");@+break;
26106 case current_group_type_code: print_esc("currentgrouptype");@+break;
26107
26108 @ @<Cases for fetching an integer value@>=
26109 case current_group_level_code: cur_val=cur_level-level_one;@+break;
26110 case current_group_type_code: cur_val=cur_group;@+break;
26111
26112 @ The \.{\\currentiflevel}, \.{\\currentiftype}, and
26113 \.{\\currentifbranch} commands return the current level of conditionals
26114 and the type and branch of the current conditional.
26115
26116 @d current_if_level_code (eTeX_int+3) /*code for \.{\\currentiflevel}*/
26117 @d current_if_type_code (eTeX_int+4) /*code for \.{\\currentiftype}*/
26118 @d current_if_branch_code (eTeX_int+5) /*code for \.{\\currentifbranch}*/
26119
26120 @<Generate all \eTeX...@>=
26121 primitive("currentiflevel", last_item, current_if_level_code);
26122 @!@:current\_if\_level\_}{\.{\\currentiflevel} primitive@>
26123 primitive("currentiftype", last_item, current_if_type_code);
26124 @!@:current\_if\_type\_}{\.{\\currentiftype} primitive@>
26125 primitive("currentifbranch", last_item, current_if_branch_code);
26126 @!@:current\_if\_branch\_}{\.{\\currentifbranch} primitive@>
26127
26128 @ @<Cases of |last_item| for |print_cmd_chr|@>=
26129 case current_if_level_code: print_esc("currentiflevel");@+break;
26130 case current_if_type_code: print_esc("currentiftype");@+break;
26131 case current_if_branch_code: print_esc("currentifbranch");@+break;
26132
26133 @ @<Cases for fetching an integer value@>=
26134 case current_if_level_code: {@+q=cond_ptr;cur_val=0;
26135 while (q!=null)
26136 {@+incr(cur_val);q=link(q);
26137 }
26138 } @+break;
26139 case current_if_type_code: if (cond_ptr==null) cur_val=0;
26140 else if (cur_if < unless_code) cur_val=cur_if+1;
26141 else cur_val=-(cur_if-unless_code+1);@+break;
26142 case current_if_branch_code:
26143 if ((if_limit==or_code)||(if_limit==else_code)) cur_val=1;
26144 else if (if_limit==fi_code) cur_val=-1;
26145 else cur_val=0;@+break;
26146
26147 @ The \.{\\fontcharwd}, \.{\\fontcharht}, \.{\\fontchardp}, and
26148 \.{\\fontcharic} commands return information about a character in a
26149 font.
26150
26151 @d font_char_wd_code eTeX_dim /*code for \.{\\fontcharwd}*/
26152 @d font_char_ht_code (eTeX_dim+1) /*code for \.{\\fontcharht}*/
26153 @d font_char_dp_code (eTeX_dim+2) /*code for \.{\\fontchardp}*/
26154 @d font_char_ic_code (eTeX_dim+3) /*code for \.{\\fontcharic}*/
26155
26156 @<Generate all \eTeX...@>=
26157 primitive("fontcharwd", last_item, font_char_wd_code);
26158 @!@:font\_char\_wd\_}{\.{\\fontcharwd} primitive@>
26159 primitive("fontcharht", last_item, font_char_ht_code);
26160 @!@:font\_char\_ht\_}{\.{\\fontcharht} primitive@>
26161 primitive("fontchardp", last_item, font_char_dp_code);
26162 @!@:font\_char\_dp\_}{\.{\\fontchardp} primitive@>
26163 primitive("fontcharic", last_item, font_char_ic_code);
26164 @!@:font\_char\_ic\_}{\.{\\fontcharic} primitive@>
26165
26166 @ @<Cases of |last_item| for |print_cmd_chr|@>=
26167 case font_char_wd_code: print_esc("fontcharwd");@+break;
26168 case font_char_ht_code: print_esc("fontcharht");@+break;
26169 case font_char_dp_code: print_esc("fontchardp");@+break;
26170 case font_char_ic_code: print_esc("fontcharic");@+break;
26171
26172 @ @<Cases for fetching a dimension value@>=
26173 case font_char_wd_code:
26174 case font_char_ht_code:
26175 case font_char_dp_code:
26176 case font_char_ic_code: {@+scan_font_ident();q=cur_val;scan_char_num();
26177 if ((font_bc[q] <= cur_val)&&(font_ec[q] >= cur_val))
26178 {@+i=char_info(q, qi(cur_val));
26179 switch (m) {
26180 case font_char_wd_code: cur_val=char_width(q, i);@+break;
26181 case font_char_ht_code: cur_val=char_height(q, height_depth(i));@+break;
26182 case font_char_dp_code: cur_val=char_depth(q, height_depth(i));@+break;
26183 case font_char_ic_code: cur_val=char_italic(q, i);
26184 } /*there are no other cases*/
26185 }
26186 else cur_val=0;
26187 } @+break;
26188
26189 @ The \.{\\parshapedimen}, \.{\\parshapeindent}, and \.{\\parshapelength}
26190 commands return the indent and length parameters of the current
26191 \.{\\parshape} specification.
26192
26193 @d par_shape_length_code (eTeX_dim+4) /*code for \.{\\parshapelength}*/
26194 @d par_shape_indent_code (eTeX_dim+5) /*code for \.{\\parshapeindent}*/
26195 @d par_shape_dimen_code (eTeX_dim+6) /*code for \.{\\parshapedimen}*/
26196
26197 @<Generate all \eTeX...@>=
26198 primitive("parshapelength", last_item, par_shape_length_code);
26199 @!@:par\_shape\_length\_}{\.{\\parshapelength} primitive@>
26200 primitive("parshapeindent", last_item, par_shape_indent_code);
26201 @!@:par\_shape\_indent\_}{\.{\\parshapeindent} primitive@>
26202 primitive("parshapedimen", last_item, par_shape_dimen_code);
26203 @!@:par\_shape\_dimen\_}{\.{\\parshapedimen} primitive@>
26204
26205 @ @<Cases of |last_item| for |print_cmd_chr|@>=
26206 case par_shape_length_code: print_esc("parshapelength");@+break;
26207 case par_shape_indent_code: print_esc("parshapeindent");@+break;
26208 case par_shape_dimen_code: print_esc("parshapedimen");@+break;
26209
26210 @ @<Cases for fetching a dimension value@>=
26211 case par_shape_length_code:
26212 case par_shape_indent_code:
26213 case par_shape_dimen_code: {@+q=cur_chr-par_shape_length_code;scan_int();
26214 if ((par_shape_ptr==null)||(cur_val <= 0)) cur_val=0;
26215 else{@+if (q==2)
26216 {@+q=cur_val%2;cur_val=(cur_val+q)/2;
26217 }
26218 if (cur_val > info(par_shape_ptr)) cur_val=info(par_shape_ptr);
26219 cur_val=mem[par_shape_ptr+2*cur_val-q].sc;
26220 }
26221 cur_val_level=dimen_val;
26222 } @+break;
26223
26224 @ The \.{\\showgroups} command displays all currently active grouping
26225 levels.
26226
26227 @d show_groups 4 /* \.{\\showgroups} */
26228
26229 @<Generate all \eTeX...@>=
26230 primitive("showgroups", xray, show_groups);
26231 @!@:show\_groups\_}{\.{\\showgroups} primitive@>
26232
26233 @ @<Cases of |xray| for |print_cmd_chr|@>=
26234 case show_groups: print_esc("showgroups");@+break;
26235
26236 @ @<Cases for |show_whatever|@>=
26237 case show_groups: {@+begin_diagnostic();show_save_groups();
26238 } @+break;
26239
26240 @ @<Types...@>=
26241 typedef int32_t save_pointer; /*index into |save_stack|*/
26242
26243 @ The modifications of \TeX\ required for the display produced by the
26244 |show_save_groups| procedure were first discussed by Donald~E. Knuth in
26245 {\sl TUGboat\/} {\bf 11}, 165--170 and 499--511, 1990.
26246 @^Knuth, Donald Ervin@>
26247
26248 In order to understand a group type we also have to know its mode.
26249 Since unrestricted horizontal modes are not associated with grouping,
26250 they are skipped when traversing the semantic nest.
26251
26252 @<Declare \eTeX\ procedures for use...@>=
26253 static void show_save_groups(void)
26254 {@+
26255 int p; /*index into |nest|*/
26256 int @!m; /*mode*/
26257 save_pointer @!v; /*saved value of |save_ptr|*/
26258 quarterword @!l; /*saved value of |cur_level|*/
26259 group_code @!c; /*saved value of |cur_group|*/
26260 int @!a; /*to keep track of alignments*/
26261 int @!i;
26262 quarterword @!j;
26263 char *@!s;
26264 p=nest_ptr;nest[p]=cur_list; /*put the top level into the array*/
26265 v=save_ptr;l=cur_level;c=cur_group;
26266 save_ptr=cur_boundary;decr(cur_level);@/
26267 a=1;
26268 print_nl("");print_ln();
26269 loop@+{@+print_nl("### ");print_group(true);
26270 if (cur_group==bottom_level) goto done;
26271 @/do@+{m=nest[p].mode_field;
26272 if (p > 0) decr(p);else m=vmode;
26273 }@+ while (!(m!=hmode));
26274 print(" (");
26275 switch (cur_group) {
26276 case simple_group: {@+incr(p);goto found2;
26277 }
26278 case hbox_group: case adjusted_hbox_group: s="hbox";@+break;
26279 case vbox_group: s="vbox";@+break;
26280 case vtop_group: s="vtop";@+break;
26281 case align_group: if (a==0)
26282 {@+if (m==-vmode) s="halign";else s="valign";
26283 a=1;goto found1;
26284 }
26285 else{@+if (a==1) print("align entry");else print_esc("cr");
26286 if (p >= a) p=p-a;
26287 a=0;goto found;
26288 } @+break;
26289 case no_align_group:
26290 {@+incr(p);a=-1;print_esc("noalign");goto found2;
26291 }
26292 case output_group:
26293 {@+print_esc("output");goto found;
26294 }
26295 case math_group: goto found2;
26296 case disc_group: case math_choice_group:
26297 {@+if (cur_group==disc_group) print_esc("discretionary");
26298 else print_esc("mathchoice");
26299 for (i=1; i<=3; i++) if (i <= saved(-2)) print("{}");
26300 goto found2;
26301 }
26302 case insert_group:
26303 {@+if (saved(-2)==255) print_esc("vadjust");
26304 else{@+print_esc("insert");print_int(saved(-2));
26305 }
26306 goto found2;
26307 }
26308 case vcenter_group: {@+s="vcenter";goto found1;
26309 }
26310 case semi_simple_group: {@+incr(p);print_esc("begingroup");goto found;
26311 }
26312 case math_shift_group:
26313 {@+if (m==mmode) print_char('$');
26314 else if (nest[p].mode_field==mmode)
26315 {@+print_cmd_chr(eq_no, saved(-2));goto found;
26316 }
26317 print_char('$');goto found;
26318 }
26319 case math_left_group:
26320 {@+if (type(nest[p+1].eTeX_aux_field)==left_noad) print_esc("left");
26321 else print_esc("middle");
26322 goto found;
26323 }
26324 } /*there are no other cases*/
26325 @<Show the box context@>;
26326 found1: print_esc(s);@<Show the box packaging info@>;
26327 found2: print_char('{');
26328 found: print_char(')');decr(cur_level);
26329 cur_group=save_level(save_ptr);save_ptr=save_index(save_ptr);
26330 }
26331 done: save_ptr=v;cur_level=l;cur_group=c;
26332 }
26333
26334 @ @<Show the box packaging info@>=
26335 if (saved(-2)!=0)
26336 {@+print_char(' ');
26337 if (saved(-3)==exactly) print("to");else print("spread");
26338 print_scaled(saved(-2));print("pt");
26339 }
26340
26341 @ @<Show the box context@>=
26342 i=saved(-4);
26343 if (i!=0)
26344 if (i < box_flag)
26345 {@+if (abs(nest[p].mode_field)==vmode) j=hmove;else j=vmove;
26346 if (i > 0) print_cmd_chr(j, 0);else print_cmd_chr(j, 1);
26347 print_scaled(abs(i));print("pt");
26348 }
26349 else if (i < ship_out_flag)
26350 {@+if (i >= global_box_flag)
26351 {@+print_esc("global");i=i-(global_box_flag-box_flag);
26352 }
26353 print_esc("setbox");print_int(i-box_flag);print_char('=');
26354 }
26355 else print_cmd_chr(leader_ship, i-(leader_flag-a_leaders))
26356
26357 @ The |scan_general_text| procedure is much like |scan_toks(false, false)|,
26358 but will be invoked via |expand|, i.e., recursively.
26359 @^recursion@>
26360
26361 @<Declare \eTeX\ procedures for sc...@>=
26362 static void scan_general_text(void);
26363
26364 @ The token list (balanced text) created by |scan_general_text| begins
26365 at |link(temp_head)| and ends at |cur_val|. (If |cur_val==temp_head|,
26366 the list is empty.)
26367
26368 @<Declare \eTeX\ procedures for tok...@>=
26369 static void scan_general_text(void)
26370 {@+
26371 int s; /*to save |scanner_status|*/
26372 pointer @!w; /*to save |warning_index|*/
26373 pointer @!d; /*to save |def_ref|*/
26374 pointer @!p; /*tail of the token list being built*/
26375 pointer @!q; /*new node being added to the token list via |store_new_token|*/
26376 halfword @!unbalance; /*number of unmatched left braces*/
26377 s=scanner_status;w=warning_index;d=def_ref;
26378 scanner_status=absorbing;warning_index=cur_cs;
26379 def_ref=get_avail();token_ref_count(def_ref)=null;p=def_ref;
26380 scan_left_brace(); /*remove the compulsory left brace*/
26381 unbalance=1;
26382 loop@+{@+get_token();
26383 if (cur_tok < right_brace_limit)
26384 if (cur_cmd < right_brace) incr(unbalance);
26385 else{@+decr(unbalance);
26386 if (unbalance==0) goto found;
26387 }
26388 store_new_token(cur_tok);
26389 }
26390 found: q=link(def_ref);free_avail(def_ref); /*discard reference count*/
26391 if (q==null) cur_val=temp_head;@+else cur_val=p;
26392 link(temp_head)=q;
26393 scanner_status=s;warning_index=w;def_ref=d;
26394 }
26395
26396 @ The \.{\\showtokens} command displays a token list.
26397
26398 @d show_tokens 5 /* \.{\\showtokens} , must be odd! */
26399
26400 @<Generate all \eTeX...@>=
26401 primitive("showtokens", xray, show_tokens);
26402 @!@:show\_tokens\_}{\.{\\showtokens} primitive@>
26403
26404 @ @<Cases of |xray| for |print_cmd_chr|@>=
26405 case show_tokens: print_esc("showtokens");@+break;
26406
26407 @ The \.{\\unexpanded} primitive prevents expansion of tokens much as
26408 the result from \.{\\the} applied to a token variable. The
26409 \.{\\detokenize} primitive converts a token list into a list of
26410 character tokens much as if the token list were written to a file. We
26411 use the fact that the command modifiers for \.{\\unexpanded} and
26412 \.{\\detokenize} are odd whereas those for \.{\\the} and \.{\\showthe}
26413 are even.
26414
26415 @<Generate all \eTeX...@>=
26416 primitive("unexpanded", the, 1);@/
26417 @!@:unexpanded\_}{\.{\\unexpanded} primitive@>
26418 primitive("detokenize", the, show_tokens);@/
26419 @!@:detokenize\_}{\.{\\detokenize} primitive@>
26420
26421 @ @<Cases of |the| for |print_cmd_chr|@>=;
26422 else if (chr_code==1) print_esc("unexpanded");
26423 else print_esc("detokenize")
26424
26425 @ @<Handle \.{\\unexpanded} or \.{\\detokenize} and |return|@>=
26426 if (odd(cur_chr))
26427 {@+c=cur_chr;scan_general_text();
26428 if (c==1) return cur_val;
26429 else{@+old_setting=selector;selector=new_string;b=pool_ptr;
26430 p=get_avail();link(p)=link(temp_head);
26431 token_show(p);flush_list(p);
26432 selector=old_setting;return str_toks(b);
26433 }
26434
26435 }
26436
26437 @ The \.{\\showifs} command displays all currently active conditionals.
26438
26439 @d show_ifs 6 /* \.{\\showifs} */
26440
26441 @<Generate all \eTeX...@>=
26442 primitive("showifs", xray, show_ifs);
26443 @!@:show\_ifs\_}{\.{\\showifs} primitive@>
26444
26445 @ @<Cases of |xray| for |print_cmd_chr|@>=
26446 case show_ifs: print_esc("showifs");@+break;
26447
26448 @ @d print_if_line(A) if (A!=0)
26449 {@+print(" entered on line ");print_int(A);
26450 }
26451
26452 @<Cases for |show_whatever|@>=
26453 case show_ifs: {@+begin_diagnostic();print_nl("");print_ln();
26454 if (cond_ptr==null)
26455 {@+print_nl("### ");print("no active conditionals");
26456 }
26457 else{@+p=cond_ptr;n=0;
26458 @/do@+{incr(n);p=link(p);@+}@+ while (!(p==null));
26459 p=cond_ptr;t=cur_if;l=if_line;m=if_limit;
26460 @/do@+{print_nl("### level ");print_int(n);print(": ");
26461 print_cmd_chr(if_test, t);
26462 if (m==fi_code) print_esc("else");
26463 print_if_line(l);
26464 decr(n);t=subtype(p);l=if_line_field(p);m=type(p);p=link(p);
26465 }@+ while (!(p==null));
26466 }
26467 } @+break;
26468
26469 @ The \.{\\interactionmode} primitive allows to query and set the
26470 interaction mode.
26471
26472 @<Generate all \eTeX...@>=
26473 primitive("interactionmode", set_page_int, 2);
26474 @!@:interaction\_mode\_}{\.{\\interactionmode} primitive@>
26475
26476 @ @<Cases of |set_page_int| for |print_cmd_chr|@>=;
26477 else if (chr_code==2) print_esc("interactionmode")
26478
26479 @ @<Cases for `Fetch the |dead_cycles| or the |insert_penalties|'@>=;
26480 else if (m==2) cur_val=interaction
26481
26482 @ @<Declare \eTeX\ procedures for use...@>=
26483 static void new_interaction(void);
26484
26485 @ @<Cases for |alter_integer|@>=;
26486 else if (c==2)
26487 {@+if ((cur_val < batch_mode)||(cur_val > error_stop_mode))
26488 {@+print_err("Bad interaction mode");
26489 @.Bad interaction mode@>
26490 help2("Modes are 0=batch, 1=nonstop, 2=scroll, and",@/
26491 "3=errorstop. Proceed, and I'll ignore this case.");
26492 int_error(cur_val);
26493 }
26494 else{@+cur_chr=cur_val;new_interaction();
26495 }
26496 }
26497
26498 @ The |middle| feature of \eTeX\ allows one ore several \.{\\middle}
26499 delimiters to appear between \.{\\left} and \.{\\right}.
26500
26501 @<Generate all \eTeX...@>=
26502 primitive("middle", left_right, middle_noad);
26503 @!@:middle\_}{\.{\\middle} primitive@>
26504
26505 @ @<Cases of |left_right| for |print_cmd_chr|@>=;
26506 else if (chr_code==middle_noad) print_esc("middle")
26507
26508 @ The |scan_tokens| feature of \eTeX\ defines the \.{\\scantokens}
26509 primitive.
26510
26511 @<Generate all \eTeX...@>=
26512 primitive("scantokens", input, 2);
26513 @!@:scan\_tokens\_}{\.{\\scantokens} primitive@>
26514
26515 @ @<Cases of |input| for |print_cmd_chr|@>=;
26516 else if (chr_code==2) print_esc("scantokens")
26517
26518 @ @<Cases for |input|@>=;
26519 else if (cur_chr==2) pseudo_start()
26520
26521 @ The global variable |pseudo_files| is used to maintain a stack of
26522 pseudo files. The |info| field of each pseudo file points to a linked
26523 list of variable size nodes representing lines not yet processed: the
26524 |info| field of the first word contains the size of this node, all the
26525 following words contain ASCII codes.
26526
26527 @<Glob...@>=
26528 static pointer @!pseudo_files; /*stack of pseudo files*/
26529
26530 @ @<Set init...@>=
26531 pseudo_files=null;
26532
26533 @ The |pseudo_start| procedure initiates reading from a pseudo file.
26534
26535 @<Declare \eTeX\ procedures for ex...@>=
26536 static void pseudo_start(void);
26537
26538 @ @<Declare \eTeX\ procedures for tok...@>=
26539 static void pseudo_start(void)
26540 {@+int old_setting; /*holds |selector| setting*/
26541 str_number @!s; /*string to be converted into a pseudo file*/
26542 pool_pointer @!l, @!m; /*indices into |str_pool|*/
26543 pointer @!p, @!q, @!r; /*for list construction*/
26544 four_quarters @!w; /*four ASCII codes*/
26545 int @!nl, @!sz;
26546 scan_general_text();
26547 old_setting=selector;selector=new_string;
26548 token_show(temp_head);selector=old_setting;
26549 flush_list(link(temp_head));
26550 str_room(1);s=make_string();
26551 @<Convert string |s| into a new pseudo file@>;
26552 flush_string;
26553 @<Initiate input from new pseudo file@>;
26554 }
26555
26556 @ @<Convert string |s| into a new pseudo file@>=
26557 str_pool[pool_ptr]=si(' ');l=str_start[s];
26558 nl=si(new_line_char);
26559 p=get_avail();q=p;
26560 while (l < pool_ptr)
26561 {@+m=l;
26562 while ((l < pool_ptr)&&(str_pool[l]!=nl)) incr(l);
26563 sz=(l-m+7)/4;
26564 if (sz==1) sz=2;
26565 r=get_node(sz);link(q)=r;q=r;info(q)=hi(sz);
26566 while (sz > 2)
26567 {@+decr(sz);incr(r);
26568 w.b0=qi(so(str_pool[m]));w.b1=qi(so(str_pool[m+1]));
26569 w.b2=qi(so(str_pool[m+2]));w.b3=qi(so(str_pool[m+3]));
26570 mem[r].qqqq=w;m=m+4;
26571 }
26572 w.b0=qi(' ');w.b1=qi(' ');w.b2=qi(' ');w.b3=qi(' ');
26573 if (l > m)
26574 {@+w.b0=qi(so(str_pool[m]));
26575 if (l > m+1)
26576 {@+w.b1=qi(so(str_pool[m+1]));
26577 if (l > m+2)
26578 {@+w.b2=qi(so(str_pool[m+2]));
26579 if (l > m+3) w.b3=qi(so(str_pool[m+3]));
26580 }
26581 }
26582 }
26583 mem[r+1].qqqq=w;
26584 if (str_pool[l]==nl) incr(l);
26585 }
26586 info(p)=link(p);link(p)=pseudo_files;pseudo_files=p
26587
26588 @ @<Initiate input from new pseudo file@>=
26589 begin_file_reading(); /*set up |cur_file| and new level of input*/
26590 line=0;limit=start;loc=limit+1; /*force line read*/
26591 if (tracing_scan_tokens > 0)
26592 {@+if (term_offset > max_print_line-3) print_ln();
26593 else if ((term_offset > 0)||(file_offset > 0)) print_char(' ');
26594 name=19;print("( ");incr(open_parens);update_terminal;
26595 }
26596 else name=18
26597
26598 @ Here we read a line from the current pseudo file into |buffer|.
26599
26600 @<Declare \eTeX\ procedures for tr...@>=
26601 static bool pseudo_input(void) /*inputs the next line or returns |false|*/
26602 {@+pointer p; /*current line from pseudo file*/
26603 int @!sz; /*size of node |p|*/
26604 four_quarters @!w; /*four ASCII codes*/
26605 int @!r; /*loop index*/
26606 last=first; /*cf.\ Matthew 19\thinspace:\thinspace30*/
26607 p=info(pseudo_files);
26608 if (p==null) return false;
26609 else{@+info(pseudo_files)=link(p);sz=ho(info(p));
26610 if (4*sz-3 >= buf_size-last)
26611 @<Report overflow of the input buffer, and abort@>;
26612 last=first;
26613 for (r=p+1; r<=p+sz-1; r++)
26614 {@+w=mem[r].qqqq;
26615 buffer[last]=w.b0;buffer[last+1]=w.b1;
26616 buffer[last+2]=w.b2;buffer[last+3]=w.b3;
26617 last=last+4;
26618 }
26619 if (last >= max_buf_stack) max_buf_stack=last+1;
26620 while ((last > first)&&(buffer[last-1]==' ')) decr(last);
26621 free_node(p, sz);
26622 return true;
26623 }
26624 }
26625
26626 @ When we are done with a pseudo file we `close' it.
26627
26628 @<Declare \eTeX\ procedures for tr...@>=
26629 static void pseudo_close(void) /*close the top level pseudo file*/
26630 {@+pointer p, @!q;
26631 p=link(pseudo_files);q=info(pseudo_files);
26632 free_avail(pseudo_files);pseudo_files=p;
26633 while (q!=null)
26634 {@+p=q;q=link(p);free_node(p, ho(info(p)));
26635 }
26636 }
26637
26638 @ @<Dump the \eTeX\ state@>=
26639 while (pseudo_files!=null) pseudo_close(); /*flush pseudo files*/
26640
26641 @ @<Generate all \eTeX...@>=
26642 primitive("readline", read_to_cs, 1);@/
26643 @!@:read\_line\_}{\.{\\readline} primitive@>
26644
26645 @ @<Cases of |read| for |print_cmd_chr|@>=;
26646 else print_esc("readline")
26647
26648 @ @<Handle \.{\\readline} and |goto done|@>=
26649 if (j==1)
26650 {@+while (loc <= limit) /*current line not yet finished*/
26651 {@+cur_chr=buffer[loc];incr(loc);
26652 if (cur_chr==' ') cur_tok=space_token;
26653 @+else cur_tok=cur_chr+other_token;
26654 store_new_token(cur_tok);
26655 }
26656 goto done;
26657 }
26658
26659 @ Here we define the additional conditionals of \eTeX\ as well as the
26660 \.{\\unless} prefix.
26661
26662 @d if_def_code 17 /* `\.{\\ifdefined}' */
26663 @d if_cs_code 18 /* `\.{\\ifcsname}' */
26664 @d if_font_char_code 19 /* `\.{\\iffontchar}' */
26665 @d eTeX_last_if_test_cmd_mod if_font_char_code
26666 @d eTeX_last_expand_after_cmd_mod 1
26667
26668 @<Generate all \eTeX...@>=
26669 primitive("unless", expand_after, 1);@/
26670 @!@:unless\_}{\.{\\unless} primitive@>
26671 primitive("ifdefined", if_test, if_def_code);
26672 @!@:if\_defined\_}{\.{\\ifdefined} primitive@>
26673 primitive("ifcsname", if_test, if_cs_code);
26674 @!@:if\_cs\_name\_}{\.{\\ifcsname} primitive@>
26675 primitive("iffontchar", if_test, if_font_char_code);
26676 @!@:if\_font\_char\_}{\.{\\iffontchar} primitive@>
26677
26678 @ @<Cases of |expandafter| for |print_cmd_chr|@>=
26679 case 1: print_esc("unless");@+break;
26680
26681 @ @<Cases of |if_test| for |print_cmd_chr|@>=
26682 case if_def_code: print_esc("ifdefined");@+break;
26683 case if_cs_code: print_esc("ifcsname");@+break;
26684 case if_font_char_code: print_esc("iffontchar");@+break;
26685
26686 @ The result of a boolean condition is reversed when the conditional is
26687 preceded by \.{\\unless}.
26688
26689 @<Negate a boolean conditional and |goto reswitch|@>=
26690 {@+get_token();
26691 if ((cur_cmd==if_test)&&(cur_chr!=if_case_code))
26692 {@+cur_chr=cur_chr+unless_code;goto reswitch;
26693 }
26694 print_err("You can't use `");print_esc("unless");print("' before `");
26695 @.You can't use \\unless...@>
26696 print_cmd_chr(cur_cmd, cur_chr);print_char('\'');
26697 help1("Continue, and I'll forget that it ever happened.");
26698 back_error();
26699 }
26700
26701 @ The conditional \.{\\ifdefined} tests if a control sequence is
26702 defined.
26703
26704 We need to reset |scanner_status|, since \.{\\outer} control sequences
26705 are allowed, but we might be scanning a macro definition or preamble.
26706
26707 @<Cases for |conditional|@>=
26708 case if_def_code: {@+save_scanner_status=scanner_status;
26709 scanner_status=normal;
26710 get_next();b=(cur_cmd!=undefined_cs);
26711 scanner_status=save_scanner_status;
26712 } @+break;
26713
26714 @ The conditional \.{\\ifcsname} is equivalent to \.{\{\\expandafter}
26715 \.{\}\\expandafter} \.{\\ifdefined} \.{\\csname}, except that no new
26716 control sequence will be entered into the hash table (once all tokens
26717 preceding the mandatory \.{\\endcsname} have been expanded).
26718
26719 @<Cases for |conditional|@>=
26720 case if_cs_code: {@+n=get_avail();p=n; /*head of the list of characters*/
26721 @/do@+{get_x_token();
26722 if (cur_cs==0) store_new_token(cur_tok);
26723 }@+ while (!(cur_cs!=0));
26724 if (cur_cmd!=end_cs_name) @<Complain about missing \.{\\endcsname}@>;
26725 @<Look up the characters of list |n| in the hash table, and set |cur_cs|@>;
26726 flush_list(n);
26727 b=(eq_type(cur_cs)!=undefined_cs);
26728 } @+break;
26729
26730 @ @<Look up the characters of list |n| in the hash table...@>=
26731 m=first;p=link(n);
26732 while (p!=null)
26733 {@+if (m >= max_buf_stack)
26734 {@+max_buf_stack=m+1;
26735 if (max_buf_stack==buf_size)
26736 overflow("buffer size", buf_size);
26737 @:TeX capacity exceeded buffer size}{\quad buffer size@>
26738 }
26739 buffer[m]=info(p)%0400;incr(m);p=link(p);
26740 }
26741 if (m==first) cur_cs=null_cs; /*the list is empty*/
26742 else if (m > first+1)
26743 cur_cs=id_lookup(first, m-first); /*|no_new_control_sequence| is |true|*/
26744 else cur_cs=single_base+buffer[first] /*the list has length one*/
26745
26746 @ The conditional \.{\\iffontchar} tests the existence of a character in
26747 a font.
26748
26749 @<Cases for |conditional|@>=
26750 case if_font_char_code: {@+scan_font_ident();n=cur_val;scan_char_num();
26751 if ((font_bc[n] <= cur_val)&&(font_ec[n] >= cur_val))
26752 b=char_exists(char_info(n, qi(cur_val)));
26753 else b=false;
26754 } @+break;
26755
26756 @ The \.{protected} feature of \eTeX\ defines the \.{\\protected} prefix
26757 command for macro definitions. Such macros are protected against
26758 expansions when lists of expanded tokens are built, e.g., for \.{\\edef}
26759 or during \.{\\write}.
26760
26761 @<Generate all \eTeX...@>=
26762 primitive("protected", prefix, 8);
26763 @!@:protected\_}{\.{\\protected} primitive@>
26764
26765 @ @<Cases of |prefix| for |print_cmd_chr|@>=;
26766 else if (chr_code==8) print_esc("protected")
26767
26768 @ The |get_x_or_protected| procedure is like |get_x_token| except that
26769 protected macros are not expanded.
26770
26771 @<Declare \eTeX\ procedures for sc...@>=
26772 static void get_x_or_protected(void) /*sets |cur_cmd|, |cur_chr|, |cur_tok|,
26773 and expands non-protected macros*/
26774 {@+
26775 loop@+{@+get_token();
26776 if (cur_cmd <= max_command) return;
26777 if ((cur_cmd >= call)&&(cur_cmd < end_template))
26778 if (info(link(cur_chr))==protected_token) return;
26779 expand();
26780 }
26781 }
26782
26783 @ A group entered (or a conditional started) in one file may end in a
26784 different file. Such slight anomalies, although perfectly legitimate,
26785 may cause errors that are difficult to locate. In order to be able to
26786 give a warning message when such anomalies occur, \eTeX\ uses the
26787 |grp_stack| and |if_stack| arrays to record the initial |cur_boundary|
26788 and |cond_ptr| values for each input file.
26789
26790 @<Glob...@>=
26791 static save_pointer @!grp_stack[max_in_open+1]; /*initial |cur_boundary|*/
26792 static pointer @!if_stack[max_in_open+1]; /*initial |cond_ptr|*/
26793
26794 @ When a group ends that was apparently entered in a different input
26795 file, the |group_warning| procedure is invoked in order to update the
26796 |grp_stack|. If moreover \.{\\tracingnesting} is positive we want to
26797 give a warning message. The situation is, however, somewhat complicated
26798 by two facts: (1)~There may be |grp_stack| elements without a
26799 corresponding \.{\\input} file or \.{\\scantokens} pseudo file (e.g.,
26800 error insertions from the terminal); and (2)~the relevant information is
26801 recorded in the |name_field| of the |input_stack| only loosely
26802 synchronized with the |in_open| variable indexing |grp_stack|.
26803
26804 @<Declare \eTeX\ procedures for tr...@>=
26805 static void group_warning(void)
26806 {@+int i; /*index into |grp_stack|*/
26807 bool @!w; /*do we need a warning?*/
26808 base_ptr=input_ptr;input_stack[base_ptr]=cur_input;
26809 /*store current state*/
26810 i=in_open;w=false;
26811 while ((grp_stack[i]==cur_boundary)&&(i > 0))
26812 {@+@<Set variable |w| to indicate if this case should be reported@>;
26813 grp_stack[i]=save_index(save_ptr);decr(i);
26814 }
26815 if (w)
26816 {@+print_nl("Warning: end of ");print_group(true);
26817 @.Warning: end of...@>
26818 print(" of a different file");print_ln();
26819 if (tracing_nesting > 1) show_context();
26820 if (history==spotless) history=warning_issued;
26821 }
26822 }
26823
26824 @ This code scans the input stack in order to determine the type of the
26825 current input file.
26826
26827 @<Set variable |w| to...@>=
26828 if (tracing_nesting > 0)
26829 {@+while ((input_stack[base_ptr].state_field==token_list)||@|
26830 (input_stack[base_ptr].index_field > i)) decr(base_ptr);
26831 if (input_stack[base_ptr].name_field > 17) w=true;
26832 }
26833
26834 @ When a conditional ends that was apparently started in a different
26835 input file, the |if_warning| procedure is invoked in order to update the
26836 |if_stack|. If moreover \.{\\tracingnesting} is positive we want to
26837 give a warning message (with the same complications as above).
26838
26839 @<Declare \eTeX\ procedures for tr...@>=
26840 static void if_warning(void)
26841 {@+int i; /*index into |if_stack|*/
26842 bool @!w; /*do we need a warning?*/
26843 base_ptr=input_ptr;input_stack[base_ptr]=cur_input;
26844 /*store current state*/
26845 i=in_open;w=false;
26846 while (if_stack[i]==cond_ptr)
26847 {@+@<Set variable |w| to...@>;
26848 if_stack[i]=link(cond_ptr);decr(i);
26849 }
26850 if (w)
26851 {@+print_nl("Warning: end of ");print_cmd_chr(if_test, cur_if);
26852 @.Warning: end of...@>
26853 print_if_line(if_line);print(" of a different file");print_ln();
26854 if (tracing_nesting > 1) show_context();
26855 if (history==spotless) history=warning_issued;
26856 }
26857 }
26858
26859 @ Conversely, the |file_warning| procedure is invoked when a file ends
26860 and some groups entered or conditionals started while reading from that
26861 file are still incomplete.
26862
26863 @<Declare \eTeX\ procedures for tr...@>=
26864 static void file_warning(void)
26865 {@+pointer p; /*saved value of |save_ptr| or |cond_ptr|*/
26866 quarterword @!l; /*saved value of |cur_level| or |if_limit|*/
26867 quarterword @!c; /*saved value of |cur_group| or |cur_if|*/
26868 int @!i; /*saved value of |if_line|*/
26869 p=save_ptr;l=cur_level;c=cur_group;save_ptr=cur_boundary;
26870 while (grp_stack[in_open]!=save_ptr)
26871 {@+decr(cur_level);
26872 print_nl("Warning: end of file when ");
26873 @.Warning: end of file when...@>
26874 print_group(true);print(" is incomplete");@/
26875 cur_group=save_level(save_ptr);save_ptr=save_index(save_ptr);
26876 }
26877 save_ptr=p;cur_level=l;cur_group=c; /*restore old values*/
26878 p=cond_ptr;l=if_limit;c=cur_if;i=if_line;
26879 while (if_stack[in_open]!=cond_ptr)
26880 {@+print_nl("Warning: end of file when ");
26881 @.Warning: end of file when...@>
26882 print_cmd_chr(if_test, cur_if);
26883 if (if_limit==fi_code) print_esc("else");
26884 print_if_line(if_line);print(" is incomplete");@/
26885 if_line=if_line_field(cond_ptr);cur_if=subtype(cond_ptr);
26886 if_limit=type(cond_ptr);cond_ptr=link(cond_ptr);
26887 }
26888 cond_ptr=p;if_limit=l;cur_if=c;if_line=i; /*restore old values*/
26889 print_ln();
26890 if (tracing_nesting > 1) show_context();
26891 if (history==spotless) history=warning_issued;
26892 }
26893
26894 @ Here are the additional \eTeX\ primitives for expressions.
26895
26896 @<Generate all \eTeX...@>=
26897 primitive("numexpr", last_item, eTeX_expr-int_val+int_val);
26898 @!@:num\_expr\_}{\.{\\numexpr} primitive@>
26899 primitive("dimexpr", last_item, eTeX_expr-int_val+dimen_val);
26900 @!@:dim\_expr\_}{\.{\\dimexpr} primitive@>
26901 primitive("glueexpr", last_item, eTeX_expr-int_val+glue_val);
26902 @!@:glue\_expr\_}{\.{\\glueexpr} primitive@>
26903 primitive("muexpr", last_item, eTeX_expr-int_val+mu_val);
26904 @!@:mu\_expr\_}{\.{\\muexpr} primitive@>
26905
26906 @ @<Cases of |last_item| for |print_cmd_chr|@>=
26907 case eTeX_expr-int_val+int_val: print_esc("numexpr");@+break;
26908 case eTeX_expr-int_val+dimen_val: print_esc("dimexpr");@+break;
26909 case eTeX_expr-int_val+glue_val: print_esc("glueexpr");@+break;
26910 case eTeX_expr-int_val+mu_val: print_esc("muexpr");@+break;
26911
26912 @ This code for reducing |cur_val_level| and\slash or negating the
26913 result is similar to the one for all the other cases of
26914 |scan_something_internal|, with the difference that |scan_expr| has
26915 already increased the reference count of a glue specification.
26916
26917 @<Process an expression and |return|@>=
26918 {@+if (m < eTeX_mu)
26919 {@+switch (m) {
26920 @/@<Cases for fetching a glue value@>@/
26921 } /*there are no other cases*/
26922 cur_val_level=glue_val;
26923 }
26924 else if (m < eTeX_expr)
26925 {@+switch (m) {
26926 @/@<Cases for fetching a mu value@>@/
26927 } /*there are no other cases*/
26928 cur_val_level=mu_val;
26929 }
26930 else{@+cur_val_level=m-eTeX_expr+int_val;scan_expr();
26931 }
26932 while (cur_val_level > level)
26933 {@+if (cur_val_level==glue_val)
26934 {@+m=cur_val;cur_val=width(m);delete_glue_ref(m);
26935 }
26936 else if (cur_val_level==mu_val) mu_error();
26937 decr(cur_val_level);
26938 }
26939 if (negative)
26940 if (cur_val_level >= glue_val)
26941 {@+m=cur_val;cur_val=new_spec(m);delete_glue_ref(m);
26942 @<Negate all three glue components of |cur_val|@>;
26943 }
26944 else negate(cur_val);
26945 return;
26946 }
26947
26948 @ @<Declare \eTeX\ procedures for sc...@>=
26949 static void scan_expr(void);
26950
26951 @ The |scan_expr| procedure scans and evaluates an expression.
26952
26953 @<Declare procedures needed for expressions@>=
26954 @t\4@>@<Declare subprocedures for |scan_expr|@>@;
26955 static void scan_expr(void) /*scans and evaluates an expression*/
26956 {@+
26957 bool a, @!b; /*saved values of |arith_error|*/
26958 small_number @!l; /*type of expression*/
26959 small_number @!r; /*state of expression so far*/
26960 small_number @!s; /*state of term so far*/
26961 small_number @!o; /*next operation or type of next factor*/
26962 int @!e; /*expression so far*/
26963 int @!t; /*term so far*/
26964 int @!f; /*current factor*/
26965 int @!n; /*numerator of combined multiplication and division*/
26966 pointer @!p; /*top of expression stack*/
26967 pointer @!q; /*for stack manipulations*/
26968 l=cur_val_level;a=arith_error;b=false;p=null;
26969 @<Scan and evaluate an expression |e| of type |l|@>;
26970 if (b)
26971 {@+print_err("Arithmetic overflow");
26972 @.Arithmetic overflow@>
26973 help2("I can't evaluate this expression,",@/
26974 "since the result is out of range.");
26975 error();
26976 if (l >= glue_val)
26977 {@+delete_glue_ref(e);e=zero_glue;add_glue_ref(e);
26978 }
26979 else e=0;
26980 }
26981 arith_error=a;cur_val=e;cur_val_level=l;
26982 }
26983
26984 @ Evaluating an expression is a recursive process: When the left
26985 parenthesis of a subexpression is scanned we descend to the next level
26986 of recursion; the previous level is resumed with the matching right
26987 parenthesis.
26988
26989 @d expr_none 0 /*\.( seen, or \.( $\langle\it expr\rangle$ \.) seen*/
26990 @d expr_add 1 /*\.( $\langle\it expr\rangle$ \.+ seen*/
26991 @d expr_sub 2 /*\.( $\langle\it expr\rangle$ \.- seen*/
26992 @d expr_mult 3 /*$\langle\it term\rangle$ \.* seen*/
26993 @d expr_div 4 /*$\langle\it term\rangle$ \./ seen*/
26994 @d expr_scale 5 /*$\langle\it term\rangle$ \.*
26995 $\langle\it factor\rangle$ \./ seen*/
26996
26997 @<Scan and eval...@>=
26998 restart: r=expr_none;e=0;s=expr_none;t=0;n=0;
26999 resume: if (s==expr_none) o=l;@+else o=int_val;
27000 @<Scan a factor |f| of type |o| or start a subexpression@>;
27001 found: @<Scan the next operator and set |o|@>;
27002 arith_error=b;
27003 @<Make sure that |f| is in the proper range@>;
27004 switch (s) {@<Cases for evaluation of the current term@>@;
27005 } /*there are no other cases*/
27006 if (o > expr_sub) s=o;@+else@<Evaluate the current expression@>;
27007 b=arith_error;
27008 if (o!=expr_none) goto resume;
27009 if (p!=null) @<Pop the expression stack and |goto found|@>@;
27010
27011 @ @<Scan the next op...@>=
27012 @<Get the next non-blank non-call token@>;
27013 if (cur_tok==other_token+'+') o=expr_add;
27014 else if (cur_tok==other_token+'-') o=expr_sub;
27015 else if (cur_tok==other_token+'*') o=expr_mult;
27016 else if (cur_tok==other_token+'/') o=expr_div;
27017 else{@+o=expr_none;
27018 if (p==null)
27019 {@+if (cur_cmd!=relax) back_input();
27020 }
27021 else if (cur_tok!=other_token+')')
27022 {@+print_err("Missing ) inserted for expression");
27023 @.Missing ) inserted@>
27024 help1("I was expecting to see `+', `-', `*', `/', or `)'. Didn't.");
27025 back_error();
27026 }
27027 }
27028
27029 @ @<Scan a factor...@>=
27030 @<Get the next non-blank non-call token@>;
27031 if (cur_tok==other_token+'(')
27032 @<Push the expression stack and |goto restart|@>;
27033 back_input();
27034 if (o==int_val) scan_int();
27035 else if (o==dimen_val) scan_normal_dimen;
27036 else if (o==glue_val) scan_normal_glue();
27037 else scan_mu_glue();
27038 f=cur_val
27039
27040 @ @<Declare \eTeX\ procedures for sc...@>=
27041 static void scan_normal_glue(void);@/
27042 static void scan_mu_glue(void);
27043
27044 @ Here we declare two trivial procedures in order to avoid mutually
27045 recursive procedures with parameters.
27046
27047 @<Declare procedures needed for expressions@>=
27048 static void scan_normal_glue(void)
27049 {@+scan_glue(glue_val);
27050 }
27051 @#
27052 static void scan_mu_glue(void)
27053 {@+scan_glue(mu_val);
27054 }
27055
27056 @ Parenthesized subexpressions can be inside expressions, and this
27057 nesting has a stack. Seven local variables represent the top of the
27058 expression stack: |p| points to pushed-down entries, if any; |l|
27059 specifies the type of expression currently being evaluated; |e| is the
27060 expression so far and |r| is the state of its evaluation; |t| is the
27061 term so far and |s| is the state of its evaluation; finally |n| is the
27062 numerator for a combined multiplication and division, if any.
27063
27064 @d expr_node_size 4 /*number of words in stack entry for subexpressions*/
27065 @d expr_e_field(A) mem[A+1].i /*saved expression so far*/
27066 @d expr_t_field(A) mem[A+2].i /*saved term so far*/
27067 @d expr_n_field(A) mem[A+3].i /*saved numerator*/
27068
27069 @<Push the expression...@>=
27070 {@+q=get_node(expr_node_size);link(q)=p;type(q)=l;
27071 subtype(q)=4*s+r;
27072 expr_e_field(q)=e;expr_t_field(q)=t;expr_n_field(q)=n;
27073 p=q;l=o;goto restart;
27074 }
27075
27076 @ @<Pop the expression...@>=
27077 {@+f=e;q=p;
27078 e=expr_e_field(q);t=expr_t_field(q);n=expr_n_field(q);
27079 s=subtype(q)/4;r=subtype(q)%4;
27080 l=type(q);p=link(q);free_node(q, expr_node_size);
27081 goto found;
27082 }
27083
27084 @ We want to make sure that each term and (intermediate) result is in
27085 the proper range. Integer values must not exceed |infinity|
27086 ($2^{31}-1$) in absolute value, dimensions must not exceed |max_dimen|
27087 ($2^{30}-1$). We avoid the absolute value of an integer, because this
27088 might fail for the value $-2^{31}$ using 32-bit arithmetic.
27089
27090 @d num_error(A) /*clear a number or dimension and set |arith_error|*/
27091 {@+arith_error=true;A=0;
27092 }
27093 @d glue_error(A) /*clear a glue spec and set |arith_error|*/
27094 {@+arith_error=true;delete_glue_ref(A);A=new_spec(zero_glue);
27095 }
27096
27097 @<Make sure that |f|...@>=
27098 if ((l==int_val)||(s > expr_sub))
27099 {@+if ((f > infinity)||(f < -infinity)) num_error(f);
27100 }
27101 else if (l==dimen_val)
27102 {@+if (abs(f) > max_dimen) num_error(f);
27103 }
27104 else{@+if ((abs(width(f)) > max_dimen)||@|
27105 (abs(stretch(f)) > max_dimen)||@|
27106 (abs(shrink(f)) > max_dimen)) glue_error(f);
27107 }
27108
27109 @ Applying the factor |f| to the partial term |t| (with the operator
27110 |s|) is delayed until the next operator |o| has been scanned. Here we
27111 handle the first factor of a partial term. A glue spec has to be copied
27112 unless the next operator is a right parenthesis; this allows us later on
27113 to simply modify the glue components.
27114
27115 @d normalize_glue(A)
27116 if (stretch(A)==0) stretch_order(A)=normal;
27117 if (shrink(A)==0) shrink_order(A)=normal
27118
27119 @<Cases for evaluation of the current term@>=
27120 case expr_none: if ((l >= glue_val)&&(o!=expr_none))
27121 {@+t=new_spec(f);delete_glue_ref(f);normalize_glue(t);
27122 }
27123 else t=f;@+break;
27124
27125 @ When a term |t| has been completed it is copied to, added to, or
27126 subtracted from the expression |e|.
27127
27128 @d expr_add_sub(A, B, C) add_or_sub(A, B, C, r==expr_sub)
27129 @d expr_a(A, B) expr_add_sub(A, B, max_dimen)
27130
27131 @<Evaluate the current expression@>=
27132 {@+s=expr_none;
27133 if (r==expr_none) e=t;
27134 else if (l==int_val) e=expr_add_sub(e, t, infinity);
27135 else if (l==dimen_val) e=expr_a(e, t);
27136 else@<Compute the sum or difference of two glue specs@>;
27137 r=o;
27138 }
27139
27140 @ The function |add_or_sub(x, y, max_answer, negative)| computes the sum
27141 (for |negative==false|) or difference (for |negative==true|) of |x| and
27142 |y|, provided the absolute value of the result does not exceed
27143 |max_answer|.
27144
27145 @<Declare subprocedures for |scan_expr|@>=
27146 static int add_or_sub(int @!x, int @!y, int @!max_answer, bool @!negative)
27147 {@+int a; /*the answer*/
27148 if (negative) negate(y);
27149 if (x >= 0)
27150 if (y <= max_answer-x) a=x+y;@+else num_error(a)@;
27151 else if (y >= -max_answer-x) a=x+y;@+else num_error(a);
27152 return a;
27153 }
27154
27155 @ We know that |stretch_order(e) > normal| implies |stretch(e)!=0| and
27156 |shrink_order(e) > normal| implies |shrink(e)!=0|.
27157
27158 @<Compute the sum or diff...@>=
27159 {@+width(e)=expr_a(width(e), width(t));
27160 if (stretch_order(e)==stretch_order(t))
27161 stretch(e)=expr_a(stretch(e), stretch(t));
27162 else if ((stretch_order(e) < stretch_order(t))&&(stretch(t)!=0))
27163 {@+stretch(e)=stretch(t);stretch_order(e)=stretch_order(t);
27164 }
27165 if (shrink_order(e)==shrink_order(t))
27166 shrink(e)=expr_a(shrink(e), shrink(t));
27167 else if ((shrink_order(e) < shrink_order(t))&&(shrink(t)!=0))
27168 {@+shrink(e)=shrink(t);shrink_order(e)=shrink_order(t);
27169 }
27170 delete_glue_ref(t);normalize_glue(e);
27171 }
27172
27173 @ If a multiplication is followed by a division, the two operations are
27174 combined into a `scaling' operation. Otherwise the term |t| is
27175 multiplied by the factor |f|.
27176
27177 @d expr_m(A) A=nx_plus_y(A, f, 0)
27178
27179 @<Cases for evaluation of the current term@>=
27180 case expr_mult: if (o==expr_div)
27181 {@+n=f;o=expr_scale;
27182 }
27183 else if (l==int_val) t=mult_integers(t, f);
27184 else if (l==dimen_val) expr_m(t);
27185 else{@+expr_m(width(t));expr_m(stretch(t));expr_m(shrink(t));
27186 } @+break;
27187
27188 @ Here we divide the term |t| by the factor |f|.
27189
27190 @d expr_d(A) A=quotient(A, f)
27191
27192 @<Cases for evaluation of the current term@>=
27193 case expr_div: if (l < glue_val) expr_d(t);
27194 else{@+expr_d(width(t));expr_d(stretch(t));expr_d(shrink(t));
27195 } @+break;
27196
27197 @ The function |quotient(n, d)| computes the rounded quotient
27198 $q=\lfloor n/d+{1\over2}\rfloor$, when $n$ and $d$ are positive.
27199
27200 @<Declare subprocedures for |scan_expr|@>=
27201 static int quotient(int @!n, int @!d)
27202 {@+bool negative; /*should the answer be negated?*/
27203 int @!a; /*the answer*/
27204 if (d==0) num_error(a)@;
27205 else{@+if (d > 0) negative=false;
27206 else{@+negate(d);negative=true;
27207 }
27208 if (n < 0)
27209 {@+negate(n);negative=!negative;
27210 }
27211 a=n/d;n=n-a*d;d=n-d; /*avoid certain compiler optimizations!*/
27212 if (d+n >= 0) incr(a);
27213 if (negative) negate(a);
27214 }
27215 return a;
27216 }
27217
27218 @ Here the term |t| is multiplied by the quotient $n/f$.
27219
27220 @d expr_s(A) A=fract(A, n, f, max_dimen)
27221
27222 @<Cases for evaluation of the current term@>=
27223 case expr_scale: if (l==int_val) t=fract(t, n, f, infinity);
27224 else if (l==dimen_val) expr_s(t);
27225 else{@+expr_s(width(t));expr_s(stretch(t));expr_s(shrink(t));
27226 }
27227
27228 @ Finally, the function |fract(x, n, d, max_answer)| computes the integer
27229 $q=\lfloor xn/d+{1\over2}\rfloor$, when $x$, $n$, and $d$ are positive
27230 and the result does not exceed |max_answer|. We can't use floating
27231 point arithmetic since the routine must produce identical results in all
27232 cases; and it would be too dangerous to multiply by~|n| and then divide
27233 by~|d|, in separate operations, since overflow might well occur. Hence
27234 this subroutine simulates double precision arithmetic, somewhat
27235 analogous to \MF's |make_fraction| and |take_fraction| routines.
27236
27237 @<Declare subprocedures for |scan_expr|@>=
27238 static int fract(int @!x, int @!n, int @!d, int @!max_answer)
27239 {@+
27240 bool negative; /*should the answer be negated?*/
27241 int @!a; /*the answer*/
27242 int @!f; /*a proper fraction*/
27243 int @!h; /*smallest integer such that |2*h >= d|*/
27244 int @!r; /*intermediate remainder*/
27245 int @!t; /*temp variable*/
27246 if (d==0) goto too_big;
27247 a=0;
27248 if (d > 0) negative=false;
27249 else{@+negate(d);negative=true;
27250 }
27251 if (x < 0)
27252 {@+negate(x);negative=!negative;
27253 }
27254 else if (x==0) goto done;
27255 if (n < 0)
27256 {@+negate(n);negative=!negative;
27257 }
27258 t=n/d;
27259 if (t > max_answer/x) goto too_big;
27260 a=t*x;n=n-t*d;
27261 if (n==0) goto found;
27262 t=x/d;
27263 if (t > (max_answer-a)/n) goto too_big;
27264 a=a+t*n;x=x-t*d;
27265 if (x==0) goto found;
27266 if (x < n)
27267 {@+t=x;x=n;n=t;
27268 } /*now |0 < n <= x < d|*/
27269 @<Compute \(f)$f=\lfloor xn/d+{1\over2}\rfloor$@>@;
27270 if (f > (max_answer-a)) goto too_big;
27271 a=a+f;
27272 found: if (negative) negate(a);
27273 goto done;
27274 too_big: num_error(a);
27275 done: return a;
27276 }
27277
27278 @ The loop here preserves the following invariant relations
27279 between |f|, |x|, |n|, and~|r|:
27280 (i)~$f+\lfloor(xn+(r+d))/d\rfloor=\lfloor x_0n_0/d+{1\over2}\rfloor$;
27281 (ii)~|-d <= r < 0 < n <= x < d|, where $x_0$, $n_0$ are the original values of~$x$
27282 and $n$.
27283
27284 Notice that the computation specifies |(x-d)+x| instead of |(x+x)-d|,
27285 because the latter could overflow.
27286
27287 @<Compute \(f)$f=\lfloor xn/d+{1\over2}\rfloor$@>=
27288 f=0;r=(d/2)-d;h=-r;
27289 loop@+{@+if (odd(n))
27290 {@+r=r+x;
27291 if (r >= 0)
27292 {@+r=r-d;incr(f);
27293 }
27294 }
27295 n=n/2;
27296 if (n==0) goto found1;
27297 if (x < h) x=x+x;
27298 else{@+t=x-d;x=t+x;f=f+n;
27299 if (x < n)
27300 {@+if (x==0) goto found1;
27301 t=x;x=n;n=t;
27302 }
27303 }
27304 }
27305 found1:
27306
27307 @ The \.{\\gluestretch}, \.{\\glueshrink}, \.{\\gluestretchorder}, and
27308 \.{\\glueshrinkorder} commands return the stretch and shrink components
27309 and their orders of ``infinity'' of a glue specification.
27310
27311 @d glue_stretch_order_code (eTeX_int+6) /*code for \.{\\gluestretchorder}*/
27312 @d glue_shrink_order_code (eTeX_int+7) /*code for \.{\\glueshrinkorder}*/
27313 @d glue_stretch_code (eTeX_dim+7) /*code for \.{\\gluestretch}*/
27314 @d glue_shrink_code (eTeX_dim+8) /*code for \.{\\glueshrink}*/
27315
27316 @<Generate all \eTeX...@>=
27317 primitive("gluestretchorder", last_item, glue_stretch_order_code);
27318 @!@:glue\_stretch\_order\_}{\.{\\gluestretchorder} primitive@>
27319 primitive("glueshrinkorder", last_item, glue_shrink_order_code);
27320 @!@:glue\_shrink\_order\_}{\.{\\glueshrinkorder} primitive@>
27321 primitive("gluestretch", last_item, glue_stretch_code);
27322 @!@:glue\_stretch\_}{\.{\\gluestretch} primitive@>
27323 primitive("glueshrink", last_item, glue_shrink_code);
27324 @!@:glue\_shrink\_}{\.{\\glueshrink} primitive@>
27325
27326 @ @<Cases of |last_item| for |print_cmd_chr|@>=
27327 case glue_stretch_order_code: print_esc("gluestretchorder");@+break;
27328 case glue_shrink_order_code: print_esc("glueshrinkorder");@+break;
27329 case glue_stretch_code: print_esc("gluestretch");@+break;
27330 case glue_shrink_code: print_esc("glueshrink");@+break;
27331
27332 @ @<Cases for fetching an integer value@>=
27333 case glue_stretch_order_code: case glue_shrink_order_code:
27334 {@+scan_normal_glue();q=cur_val;
27335 if (m==glue_stretch_order_code) cur_val=stretch_order(q);
27336 else cur_val=shrink_order(q);
27337 delete_glue_ref(q);
27338 }
27339
27340 @ @<Cases for fetching a dimension value@>=
27341 case glue_stretch_code: case glue_shrink_code:
27342 {@+scan_normal_glue();q=cur_val;
27343 if (m==glue_stretch_code) cur_val=stretch(q);
27344 else cur_val=shrink(q);
27345 delete_glue_ref(q);
27346 }
27347
27348 @ The \.{\\mutoglue} and \.{\\gluetomu} commands convert ``math'' glue
27349 into normal glue and vice versa; they allow to manipulate math glue with
27350 \.{\\gluestretch} etc.
27351
27352 @d mu_to_glue_code eTeX_glue /*code for \.{\\mutoglue}*/
27353 @d glue_to_mu_code eTeX_mu /*code for \.{\\gluetomu}*/
27354
27355 @<Generate all \eTeX...@>=
27356 primitive("mutoglue", last_item, mu_to_glue_code);
27357 @!@:mu\_to\_glue\_}{\.{\\mutoglue} primitive@>
27358 primitive("gluetomu", last_item, glue_to_mu_code);
27359 @!@:glue\_to\_mu\_}{\.{\\gluetomu} primitive@>
27360
27361 @ @<Cases of |last_item| for |print_cmd_chr|@>=
27362 case mu_to_glue_code: print_esc("mutoglue");@+break;
27363 case glue_to_mu_code: print_esc("gluetomu");@+break;
27364
27365 @ @<Cases for fetching a glue value@>=
27366 case mu_to_glue_code: scan_mu_glue();
27367
27368 @ @<Cases for fetching a mu value@>=
27369 case glue_to_mu_code: scan_normal_glue();
27370
27371 @ \eTeX\ (in extended mode) supports 32768 (i.e., $2^{15}$) count,
27372 dimen, skip, muskip, box, and token registers. As in \TeX\ the first
27373 256 registers of each kind are realized as arrays in the table of
27374 equivalents; the additional registers are realized as tree structures
27375 built from variable-size nodes with individual registers existing only
27376 when needed. Default values are used for nonexistent registers: zero
27377 for count and dimen values, |zero_glue| for glue (skip and muskip)
27378 values, void for boxes, and |null| for token lists (and current marks
27379 discussed below).
27380
27381 Similarly there are 32768 mark classes; the command \.{\\marks}|n|
27382 creates a mark node for a given mark class |0 <= n <= 32767| (where
27383 \.{\\marks0} is synonymous to \.{\\mark}). The page builder (actually
27384 the |fire_up| routine) and the |vsplit| routine maintain the current
27385 values of |top_mark|, |first_mark|, |bot_mark|, |split_first_mark|, and
27386 |split_bot_mark| for each mark class. They are accessed as
27387 \.{\\topmarks}|n| etc., and \.{\\topmarks0} is again synonymous to
27388 \.{\\topmark}. As in \TeX\ the five current marks for mark class zero
27389 are realized as |cur_mark| array. The additional current marks are
27390 again realized as tree structure with individual mark classes existing
27391 only when needed.
27392
27393 @<Generate all \eTeX...@>=
27394 primitive("marks", mark, marks_code);
27395 @!@:marks\_}{\.{\\marks} primitive@>
27396 primitive("topmarks", top_bot_mark, top_mark_code+marks_code);
27397 @!@:top\_marks\_}{\.{\\topmarks} primitive@>
27398 primitive("firstmarks", top_bot_mark, first_mark_code+marks_code);
27399 @!@:first\_marks\_}{\.{\\firstmarks} primitive@>
27400 primitive("botmarks", top_bot_mark, bot_mark_code+marks_code);
27401 @!@:bot\_marks\_}{\.{\\botmarks} primitive@>
27402 primitive("splitfirstmarks", top_bot_mark, split_first_mark_code+marks_code);
27403 @!@:split\_first\_marks\_}{\.{\\splitfirstmarks} primitive@>
27404 primitive("splitbotmarks", top_bot_mark, split_bot_mark_code+marks_code);
27405 @!@:split\_bot\_marks\_}{\.{\\splitbotmarks} primitive@>
27406
27407 @ The |scan_register_num| procedure scans a register number that must
27408 not exceed 255 in compatibility mode resp.\ 32767 in extended mode.
27409
27410 @<Declare \eTeX\ procedures for ex...@>=
27411 static void scan_register_num(void);
27412
27413 @ @<Declare procedures that scan restricted classes of integers@>=
27414 static void scan_register_num(void)
27415 {@+scan_int();
27416 if ((cur_val < 0)||(cur_val > max_reg_num))
27417 {@+print_err("Bad register code");
27418 @.Bad register code@>
27419 help2(max_reg_help_line,"I changed this one to zero.");
27420 int_error(cur_val);cur_val=0;
27421 }
27422 }
27423
27424 @ @<Initialize variables for \eTeX\ comp...@>=
27425 max_reg_num=255;
27426 max_reg_help_line="A register number must be between 0 and 255.";
27427
27428 @ @<Initialize variables for \eTeX\ ext...@>=
27429 max_reg_num=32767;
27430 max_reg_help_line="A register number must be between 0 and 32767.";
27431
27432 @ @<Glob...@>=
27433 static halfword @!max_reg_num; /*largest allowed register number*/
27434 static char *@!max_reg_help_line; /*first line of help message*/
27435
27436 @ There are seven almost identical doubly linked trees, one for the
27437 sparse array of the up to 32512 additional registers of each kind and
27438 one for the sparse array of the up to 32767 additional mark classes.
27439 The root of each such tree, if it exists, is an index node containing 16
27440 pointers to subtrees for 4096 consecutive array elements. Similar index
27441 nodes are the starting points for all nonempty subtrees for 4096, 256,
27442 and 16 consecutive array elements. These four levels of index nodes are
27443 followed by a fifth level with nodes for the individual array elements.
27444
27445 Each index node is nine words long. The pointers to the 16 possible
27446 subtrees or are kept in the |info| and |link| fields of the last eight
27447 words. (It would be both elegant and efficient to declare them as
27448 array, unfortunately \PASCAL\ doesn't allow this.)
27449
27450 The fields in the first word of each index node and in the nodes for the
27451 array elements are closely related. The |link| field points to the next
27452 lower index node and the |sa_index| field contains four bits (one
27453 hexadecimal digit) of the register number or mark class. For the lowest
27454 index node the |link| field is |null| and the |sa_index| field indicates
27455 the type of quantity (|int_val|, |dimen_val|, |glue_val|, |mu_val|,
27456 |box_val|, |tok_val|, or |mark_val|). The |sa_used| field in the index
27457 nodes counts how many of the 16 pointers are non-null.
27458
27459 The |sa_index| field in the nodes for array elements contains the four
27460 bits plus 16 times the type. Therefore such a node represents a count
27461 or dimen register if and only if |sa_index < dimen_val_limit|; it
27462 represents a skip or muskip register if and only if
27463 |dimen_val_limit <= sa_index < mu_val_limit|; it represents a box register
27464 if and only if |mu_val_limit <= sa_index < box_val_limit|; it represents a
27465 token list register if and only if
27466 |box_val_limit <= sa_index < tok_val_limit|; finally it represents a mark
27467 class if and only if |tok_val_limit <= sa_index|.
27468
27469 The |new_index| procedure creates an index node (returned in |cur_ptr|)
27470 having given contents of the |sa_index| and |link| fields.
27471
27472 @d box_val 4 /*the additional box registers*/
27473 @d mark_val 6 /*the additional mark classes*/
27474 @#
27475 @d dimen_val_limit 0x20 /*$2^4\cdot(|dimen_val|+1)$*/
27476 @d mu_val_limit 0x40 /*$2^4\cdot(|mu_val|+1)$*/
27477 @d box_val_limit 0x50 /*$2^4\cdot(|box_val|+1)$*/
27478 @d tok_val_limit 0x60 /*$2^4\cdot(|tok_val|+1)$*/
27479 @#
27480 @d index_node_size 9 /*size of an index node*/
27481 @d sa_index(A) type(A) /*a four-bit address or a type or both*/
27482 @d sa_used(A) subtype(A) /*count of non-null pointers*/
27483
27484 @<Declare \eTeX\ procedures for ex...@>=
27485 static void new_index(quarterword @!i, pointer @!q)
27486 {@+int k; /*loop index*/
27487 cur_ptr=get_node(index_node_size);sa_index(cur_ptr)=i;
27488 sa_used(cur_ptr)=0;link(cur_ptr)=q;
27489 for (k=1; k<=index_node_size-1; k++) /*clear all 16 pointers*/
27490 mem[cur_ptr+k]=sa_null;
27491 }
27492
27493 @ The roots of the seven trees for the additional registers and mark
27494 classes are kept in the |sa_root| array. The first six locations must
27495 be dumped and undumped; the last one is also known as |sa_mark|.
27496
27497 @d sa_mark sa_root[mark_val] /*root for mark classes*/
27498
27499 @<Glob...@>=
27500 static pointer @!sa_root0[mark_val-int_val+1],
27501 *const @!sa_root = @!sa_root0-int_val; /*roots of sparse arrays*/
27502 static pointer @!cur_ptr; /*value returned by |new_index| and |find_sa_element|*/
27503 static memory_word @!sa_null; /*two |null| pointers*/
27504
27505 @ @<Set init...@>=
27506 sa_mark=null;sa_null.hh.lh=null;sa_null.hh.rh=null;
27507
27508 @ @<Initialize table...@>=
27509 for (i=int_val; i<=tok_val; i++) sa_root[i]=null;
27510
27511 @ Given a type |t| and a sixteen-bit number |n|, the |find_sa_element|
27512 procedure returns (in |cur_ptr|) a pointer to the node for the
27513 corresponding array element, or |null| when no such element exists. The
27514 third parameter |w| is set |true| if the element must exist, e.g.,
27515 because it is about to be modified. The procedure has two main
27516 branches: one follows the existing tree structure, the other (only used
27517 when |w| is |true|) creates the missing nodes.
27518
27519 We use macros to extract the four-bit pieces from a sixteen-bit register
27520 number or mark class and to fetch or store one of the 16 pointers from
27521 an index node.
27522
27523 @d if_cur_ptr_is_null_then_return_or_goto(A) /*some tree element is missing*/
27524 {@+if (cur_ptr==null)
27525 if (w) goto A;@+else return;
27526 }
27527 @#
27528 @d hex_dig1(A) A/4096 /*the fourth lowest hexadecimal digit*/
27529 @d hex_dig2(A) (A/256)%16 /*the third lowest hexadecimal digit*/
27530 @d hex_dig3(A) (A/16)%16 /*the second lowest hexadecimal digit*/
27531 @d hex_dig4(A) A%16 /*the lowest hexadecimal digit*/
27532 @#
27533 @d get_sa_ptr if (odd(i)) cur_ptr=link(q+(i/2)+1);
27534 else cur_ptr=info(q+(i/2)+1)
27535 /*set |cur_ptr| to the pointer indexed by |i| from index node |q|*/
27536 @d put_sa_ptr(A) if (odd(i)) link(q+(i/2)+1)=A;
27537 else info(q+(i/2)+1)=A
27538 /*store the pointer indexed by |i| in index node |q|*/
27539 @d add_sa_ptr {@+put_sa_ptr(cur_ptr);incr(sa_used(q));
27540 } /*add |cur_ptr| as the pointer indexed by |i| in index node |q|*/
27541 @d delete_sa_ptr {@+put_sa_ptr(null);decr(sa_used(q));
27542 } /*delete the pointer indexed by |i| in index node |q|*/
27543
27544 @<Declare \eTeX\ procedures for ex...@>=
27545 static void find_sa_element(small_number @!t, halfword @!n, bool @!w)
27546 /*sets |cur_val| to sparse array element location or |null|*/
27547 {@+
27548 pointer q; /*for list manipulations*/
27549 small_number @!i; /*a four bit index*/
27550 cur_ptr=sa_root[t];
27551 if_cur_ptr_is_null_then_return_or_goto(not_found);@/
27552 q=cur_ptr;i=hex_dig1(n);get_sa_ptr;
27553 if_cur_ptr_is_null_then_return_or_goto(not_found1);@/
27554 q=cur_ptr;i=hex_dig2(n);get_sa_ptr;
27555 if_cur_ptr_is_null_then_return_or_goto(not_found2);@/
27556 q=cur_ptr;i=hex_dig3(n);get_sa_ptr;
27557 if_cur_ptr_is_null_then_return_or_goto(not_found3);@/
27558 q=cur_ptr;i=hex_dig4(n);get_sa_ptr;
27559 if ((cur_ptr==null)&&w) goto not_found4;
27560 return;
27561 not_found: new_index(t, null); /*create first level index node*/
27562 sa_root[t]=cur_ptr;q=cur_ptr;i=hex_dig1(n);
27563 not_found1: new_index(i, q); /*create second level index node*/
27564 add_sa_ptr;q=cur_ptr;i=hex_dig2(n);
27565 not_found2: new_index(i, q); /*create third level index node*/
27566 add_sa_ptr;q=cur_ptr;i=hex_dig3(n);
27567 not_found3: new_index(i, q); /*create fourth level index node*/
27568 add_sa_ptr;q=cur_ptr;i=hex_dig4(n);
27569 not_found4: @<Create a new array element of type |t| with index |i|@>;
27570 link(cur_ptr)=q;add_sa_ptr;
27571 }
27572
27573 @ The array elements for registers are subject to grouping and have an
27574 |sa_lev| field (quite analogous to |eq_level|) instead of |sa_used|.
27575 Since saved values as well as shorthand definitions (created by e.g.,
27576 \.{\\countdef}) refer to the location of the respective array element,
27577 we need a reference count that is kept in the |sa_ref| field. An array
27578 element can be deleted (together with all references to it) when its
27579 |sa_ref| value is |null| and its value is the default value.
27580 @^reference counts@>
27581
27582 Skip, muskip, box, and token registers use two word nodes, their values
27583 are stored in the |sa_ptr| field.
27584 Count and dimen registers use three word nodes, their
27585 values are stored in the |sa_int| resp.\ |sa_dim| field in the third
27586 word; the |sa_ptr| field is used under the name |sa_num| to store
27587 the register number. Mark classes use four word nodes. The last three
27588 words contain the five types of current marks
27589
27590 @d sa_lev sa_used /*grouping level for the current value*/
27591 @d pointer_node_size 2 /*size of an element with a pointer value*/
27592 @d sa_type(A) (sa_index(A)/16) /*type part of combined type/index*/
27593 @d sa_ref(A) info(A+1) /*reference count of a sparse array element*/
27594 @d sa_ptr(A) link(A+1) /*a pointer value*/
27595 @#
27596 @d word_node_size 3 /*size of an element with a word value*/
27597 @d sa_num(A) sa_ptr(A) /*the register number*/
27598 @d sa_int(A) mem[A+2].i /*an integer*/
27599 @d sa_dim(A) mem[A+2].sc /*a dimension (a somewhat esotheric distinction)*/
27600 @#
27601 @d mark_class_node_size 4 /*size of an element for a mark class*/
27602 @#
27603 @d fetch_box(A) /*fetch |box(cur_val)|*/
27604 if (cur_val < 256) A=box(cur_val);
27605 else{@+find_sa_element(box_val, cur_val, false);
27606 if (cur_ptr==null) A=null;@+else A=sa_ptr(cur_ptr);
27607 }
27608
27609 @<Create a new array element...@>=
27610 if (t==mark_val) /*a mark class*/
27611 {@+cur_ptr=get_node(mark_class_node_size);
27612 mem[cur_ptr+1]=sa_null;mem[cur_ptr+2]=sa_null;mem[cur_ptr+3]=sa_null;
27613 }
27614 else{@+if (t <= dimen_val) /*a count or dimen register*/
27615 {@+cur_ptr=get_node(word_node_size);sa_int(cur_ptr)=0;
27616 sa_num(cur_ptr)=n;
27617 }
27618 else{@+cur_ptr=get_node(pointer_node_size);
27619 if (t <= mu_val) /*a skip or muskip register*/
27620 {@+sa_ptr(cur_ptr)=zero_glue;add_glue_ref(zero_glue);
27621 }
27622 else sa_ptr(cur_ptr)=null; /*a box or token list register*/
27623 }
27624 sa_ref(cur_ptr)=null; /*all registers have a reference count*/
27625 }
27626 sa_index(cur_ptr)=16*t+i;sa_lev(cur_ptr)=level_one
27627
27628 @ The |delete_sa_ref| procedure is called when a pointer to an array
27629 element representing a register is being removed; this means that the
27630 reference count should be decreased by one. If the reduced reference
27631 count is |null| and the register has been (globally) assigned its
27632 default value the array element should disappear, possibly together with
27633 some index nodes. This procedure will never be used for mark class
27634 nodes.
27635 @^reference counts@>
27636
27637 @d add_sa_ref(A) incr(sa_ref(A)) /*increase reference count*/
27638 @#
27639 @d change_box(A) /*change |box(cur_val)|, the |eq_level| stays the same*/
27640 if (cur_val < 256) box(cur_val)=A;@+else set_sa_box(A)
27641 @#
27642 @d set_sa_box(X) {@+find_sa_element(box_val, cur_val, false);
27643 if (cur_ptr!=null)
27644 {@+sa_ptr(cur_ptr)=X;add_sa_ref(cur_ptr);delete_sa_ref(cur_ptr);
27645 }
27646 }
27647
27648 @<Declare \eTeX\ procedures for tr...@>=
27649 static void delete_sa_ref(pointer @!q) /*reduce reference count*/
27650 {@+
27651 pointer p; /*for list manipulations*/
27652 small_number @!i; /*a four bit index*/
27653 small_number @!s; /*size of a node*/
27654 decr(sa_ref(q));
27655 if (sa_ref(q)!=null) return;
27656 if (sa_index(q) < dimen_val_limit)
27657 if (sa_int(q)==0) s=word_node_size;
27658 else return;
27659 else{@+if (sa_index(q) < mu_val_limit)
27660 if (sa_ptr(q)==zero_glue) delete_glue_ref(zero_glue);
27661 else return;
27662 else if (sa_ptr(q)!=null) return;
27663 s=pointer_node_size;
27664 }
27665 @/do@+{i=hex_dig4(sa_index(q));p=q;q=link(p);free_node(p, s);
27666 if (q==null) /*the whole tree has been freed*/
27667 {@+sa_root[i]=null;return;
27668 }
27669 delete_sa_ptr;s=index_node_size; /*node |q| is an index node*/
27670 }@+ while (!(sa_used(q) > 0));
27671 }
27672
27673 @ The |print_sa_num| procedure prints the register number corresponding
27674 to an array element.
27675
27676 @<Basic print...@>=
27677 static void print_sa_num(pointer @!q) /*print register number*/
27678 {@+halfword @!n; /*the register number*/
27679 if (sa_index(q) < dimen_val_limit) n=sa_num(q); /*the easy case*/
27680 else{@+n=hex_dig4(sa_index(q));q=link(q);n=n+16*sa_index(q);
27681 q=link(q);n=n+256*(sa_index(q)+16*sa_index(link(q)));
27682 }
27683 print_int(n);
27684 }
27685
27686 @ Here is a procedure that displays the contents of an array element
27687 symbolically. It is used under similar circumstances as is
27688 |restore_trace| (together with |show_eqtb|) for the quantities kept in
27689 the |eqtb| array.
27690
27691 @<Declare \eTeX\ procedures for tr...@>=
27692 #ifdef @!STAT
27693 static void show_sa(pointer @!p, char *@!s)
27694 {@+small_number t; /*the type of element*/
27695 begin_diagnostic();print_char('{');print(s);print_char(' ');
27696 if (p==null) print_char('?'); /*this can't happen*/
27697 else{@+t=sa_type(p);
27698 if (t < box_val) print_cmd_chr(internal_register, p);
27699 else if (t==box_val)
27700 {@+print_esc("box");print_sa_num(p);
27701 }
27702 else if (t==tok_val) print_cmd_chr(toks_register, p);
27703 else print_char('?'); /*this can't happen either*/
27704 print_char('=');
27705 if (t==int_val) print_int(sa_int(p));
27706 else if (t==dimen_val)
27707 {@+print_scaled(sa_dim(p));print("pt");
27708 }
27709 else{@+p=sa_ptr(p);
27710 if (t==glue_val) print_spec(p,"pt");
27711 else if (t==mu_val) print_spec(p,"mu");
27712 else if (t==box_val)
27713 if (p==null) print("void");
27714 else{@+depth_threshold=0;breadth_max=1;show_node_list(p);
27715 }
27716 else if (t==tok_val)
27717 {@+if (p!=null) show_token_list(link(p), null, 32);
27718 }
27719 else print_char('?'); /*this can't happen either*/
27720 }
27721 }
27722 print_char('}');end_diagnostic(false);
27723 }
27724 #endif
27725
27726 @ Here we compute the pointer to the current mark of type |t| and mark
27727 class |cur_val|.
27728
27729 @<Compute the mark pointer...@>=
27730 {@+find_sa_element(mark_val, cur_val, false);
27731 if (cur_ptr!=null)
27732 if (odd(t)) cur_ptr=link(cur_ptr+(t/2)+1);
27733 else cur_ptr=info(cur_ptr+(t/2)+1);
27734 }
27735
27736 @ The current marks for all mark classes are maintained by the |vsplit|
27737 and |fire_up| routines and are finally destroyed (for \.{INITEX} only)
27738 @.INITEX@>
27739 by the |final_cleanup| routine. Apart from updating the current marks
27740 when mark nodes are encountered, these routines perform certain actions
27741 on all existing mark classes. The recursive |do_marks| procedure walks
27742 through the whole tree or a subtree of existing mark class nodes and
27743 preforms certain actions indicted by its first parameter |a|, the action
27744 code. The second parameter |l| indicates the level of recursion (at
27745 most four); the third parameter points to a nonempty tree or subtree.
27746 The result is |true| if the complete tree or subtree has been deleted.
27747
27748 @d vsplit_init 0 /*action code for |vsplit| initialization*/
27749 @d fire_up_init 1 /*action code for |fire_up| initialization*/
27750 @d fire_up_done 2 /*action code for |fire_up| completion*/
27751 @d destroy_marks 3 /*action code for |final_cleanup|*/
27752 @#
27753 @d sa_top_mark(A) info(A+1) /*\.{\\topmarks}|n|*/
27754 @d sa_first_mark(A) link(A+1) /*\.{\\firstmarks}|n|*/
27755 @d sa_bot_mark(A) info(A+2) /*\.{\\botmarks}|n|*/
27756 @d sa_split_first_mark(A) link(A+2) /*\.{\\splitfirstmarks}|n|*/
27757 @d sa_split_bot_mark(A) info(A+3) /*\.{\\splitbotmarks}|n|*/
27758
27759 @<Declare the function called |do_marks|@>=
27760 static bool do_marks(small_number @!a, small_number @!l, pointer @!q)
27761 {@+int i; /*a four bit index*/
27762 if (l < 4) /*|q| is an index node*/
27763 {@+for (i=0; i<=15; i++)
27764 {@+get_sa_ptr;
27765 if (cur_ptr!=null) if (do_marks(a, l+1, cur_ptr)) delete_sa_ptr;
27766 }
27767 if (sa_used(q)==0)
27768 {@+free_node(q, index_node_size);q=null;
27769 }
27770 }
27771 else /*|q| is the node for a mark class*/
27772 {@+switch (a) {
27773 @<Cases for |do_marks|@>@;
27774 } /*there are no other cases*/
27775 if (sa_bot_mark(q)==null) if (sa_split_bot_mark(q)==null)
27776 {@+free_node(q, mark_class_node_size);q=null;
27777 }
27778 }
27779 return(q==null);
27780 }
27781
27782 @ At the start of the |vsplit| routine the existing |split_fist_mark|
27783 and |split_bot_mark| are discarded.
27784
27785 @<Cases for |do_marks|@>=
27786 case vsplit_init: if (sa_split_first_mark(q)!=null)
27787 {@+delete_token_ref(sa_split_first_mark(q));sa_split_first_mark(q)=null;
27788 delete_token_ref(sa_split_bot_mark(q));sa_split_bot_mark(q)=null;
27789 } @+break;
27790
27791 @ We use again the fact that |split_first_mark==null| if and only if
27792 |split_bot_mark==null|.
27793
27794 @<Update the current marks for |vsplit|@>=
27795 {@+find_sa_element(mark_val, mark_class(p), true);
27796 if (sa_split_first_mark(cur_ptr)==null)
27797 {@+sa_split_first_mark(cur_ptr)=mark_ptr(p);
27798 add_token_ref(mark_ptr(p));
27799 }
27800 else delete_token_ref(sa_split_bot_mark(cur_ptr));
27801 sa_split_bot_mark(cur_ptr)=mark_ptr(p);
27802 add_token_ref(mark_ptr(p));
27803 }
27804
27805 @ At the start of the |fire_up| routine the old |top_mark| and
27806 |first_mark| are discarded, whereas the old |bot_mark| becomes the new
27807 |top_mark|. An empty new |top_mark| token list is, however, discarded
27808 as well in order that mark class nodes can eventually be released. We
27809 use again the fact that |bot_mark!=null| implies |first_mark!=null|; it
27810 also knows that |bot_mark==null| implies |top_mark==first_mark==null|.
27811
27812 @<Cases for |do_marks|@>=
27813 case fire_up_init: if (sa_bot_mark(q)!=null)
27814 {@+if (sa_top_mark(q)!=null) delete_token_ref(sa_top_mark(q));
27815 delete_token_ref(sa_first_mark(q));sa_first_mark(q)=null;
27816 if (link(sa_bot_mark(q))==null) /*an empty token list*/
27817 {@+delete_token_ref(sa_bot_mark(q));sa_bot_mark(q)=null;
27818 }
27819 else add_token_ref(sa_bot_mark(q));
27820 sa_top_mark(q)=sa_bot_mark(q);
27821 } @+break;
27822
27823 @ @<Cases for |do_marks|@>=
27824 case fire_up_done: if ((sa_top_mark(q)!=null)&&(sa_first_mark(q)==null))
27825 {@+sa_first_mark(q)=sa_top_mark(q);add_token_ref(sa_top_mark(q));
27826 } @+break;
27827
27828 @ @<Update the current marks for |fire_up|@>=
27829 {@+find_sa_element(mark_val, mark_class(p), true);
27830 if (sa_first_mark(cur_ptr)==null)
27831 {@+sa_first_mark(cur_ptr)=mark_ptr(p);
27832 add_token_ref(mark_ptr(p));
27833 }
27834 if (sa_bot_mark(cur_ptr)!=null) delete_token_ref(sa_bot_mark(cur_ptr));
27835 sa_bot_mark(cur_ptr)=mark_ptr(p);add_token_ref(mark_ptr(p));
27836 }
27837
27838 @ Here we use the fact that the five current mark pointers in a mark
27839 class node occupy the same locations as the the first five pointers of
27840 an index node. For systems using a run-time switch to distinguish
27841 between \.{VIRTEX} and \.{INITEX}, the codewords `$|@t\#\&{ifdef} \.{INIT}@>|\ldots|@t\#\&{endif}@>|$'
27842 surrounding the following piece of code should be removed.
27843 @.INITEX@>
27844 @^system dependencies@>
27845
27846 @<Cases for |do_marks|@>=
27847 #ifdef @!INIT
27848 case destroy_marks: for (i=top_mark_code; i<=split_bot_mark_code; i++)
27849 {@+get_sa_ptr;
27850 if (cur_ptr!=null)
27851 {@+delete_token_ref(cur_ptr);put_sa_ptr(null);
27852 }
27853 }
27854 #endif
27855
27856 @ The command code |internal_register| is used for `\.{\\count}', `\.{\\dimen}',
27857 etc., as well as for references to sparse array elements defined by
27858 `\.{\\countdef}', etc.
27859
27860 @<Cases of |register| for |print_cmd_chr|@>=
27861 {@+if ((chr_code < mem_bot)||(chr_code > lo_mem_stat_max))
27862 cmd=sa_type(chr_code);
27863 else{@+cmd=chr_code-mem_bot;chr_code=null;
27864 }
27865 if (cmd==int_val) print_esc("count");
27866 else if (cmd==dimen_val) print_esc("dimen");
27867 else if (cmd==glue_val) print_esc("skip");
27868 else print_esc("muskip");
27869 if (chr_code!=null) print_sa_num(chr_code);
27870 }
27871
27872 @ Similarly the command code |toks_register| is used for `\.{\\toks}' as
27873 well as for references to sparse array elements defined by
27874 `\.{\\toksdef}'.
27875
27876 @<Cases of |toks_register| for |print_cmd_chr|@>=
27877 {@+print_esc("toks");
27878 if (chr_code!=mem_bot) print_sa_num(chr_code);
27879 }
27880
27881 @ When a shorthand definition for an element of one of the sparse arrays
27882 is destroyed, we must reduce the reference count.
27883
27884 @<Cases for |eq_destroy|@>=
27885 case toks_register: case internal_register:
27886 if ((equiv_field(w) < mem_bot)||(equiv_field(w) > lo_mem_stat_max))
27887 delete_sa_ref(equiv_field(w));@+break;
27888
27889 @ The task to maintain (change, save, and restore) register values is
27890 essentially the same when the register is realized as sparse array
27891 element or entry in |eqtb|. The global variable |sa_chain| is the head
27892 of a linked list of entries saved at the topmost level |sa_level|; the
27893 lists for lowel levels are kept in special save stack entries.
27894
27895 @<Glob...@>=
27896 static pointer @!sa_chain; /*chain of saved sparse array entries*/
27897 static quarterword @!sa_level; /*group level for |sa_chain|*/
27898
27899 @ @<Set init...@>=
27900 sa_chain=null;sa_level=level_zero;
27901
27902 @ The individual saved items are kept in pointer or word nodes similar
27903 to those used for the array elements: a word node with value zero is,
27904 however, saved as pointer node with the otherwise impossible |sa_index|
27905 value |tok_val_limit|.
27906
27907 @d sa_loc(A) sa_ref(A) /*location of saved item*/
27908
27909 @<Declare \eTeX\ procedures for tr...@>=
27910 static void sa_save(pointer @!p) /*saves value of |p|*/
27911 {@+pointer q; /*the new save node*/
27912 quarterword @!i; /*index field of node*/
27913 if (cur_level!=sa_level)
27914 {@+check_full_save_stack;save_type(save_ptr)=restore_sa;
27915 save_level(save_ptr)=sa_level;save_index(save_ptr)=sa_chain;
27916 incr(save_ptr);sa_chain=null;sa_level=cur_level;
27917 }
27918 i=sa_index(p);
27919 if (i < dimen_val_limit)
27920 {@+if (sa_int(p)==0)
27921 {@+q=get_node(pointer_node_size);i=tok_val_limit;
27922 }
27923 else{@+q=get_node(word_node_size);sa_int(q)=sa_int(p);
27924 }
27925 sa_ptr(q)=null;
27926 }
27927 else{@+q=get_node(pointer_node_size);sa_ptr(q)=sa_ptr(p);
27928 }
27929 sa_loc(q)=p;sa_index(q)=i;sa_lev(q)=sa_lev(p);
27930 link(q)=sa_chain;sa_chain=q;add_sa_ref(p);
27931 }
27932
27933 @ @<Declare \eTeX\ procedures for tr...@>=
27934 static void sa_destroy(pointer @!p) /*destroy value of |p|*/
27935 {@+if (sa_index(p) < mu_val_limit) delete_glue_ref(sa_ptr(p));
27936 else if (sa_ptr(p)!=null)
27937 if (sa_index(p) < box_val_limit) flush_node_list(sa_ptr(p));
27938 else delete_token_ref(sa_ptr(p));
27939 }
27940
27941 @ The procedure |sa_def| assigns a new value to sparse array elements,
27942 and saves the former value if appropriate. This procedure is used only
27943 for skip, muskip, box, and token list registers. The counterpart of
27944 |sa_def| for count and dimen registers is called |sa_w_def|.
27945
27946 @d sa_define(A, B, C, D, E) if (e)
27947 if (global) gsa_def(A, B);@+else sa_def(A, B);
27948 else if (global) geq_define(C, D, E);@+else eq_define(C, D, E)
27949 @#
27950 @d sa_def_box /*assign |cur_box| to |box(cur_val)|*/
27951 {@+find_sa_element(box_val, cur_val, true);
27952 if (global) gsa_def(cur_ptr, cur_box);@+else sa_def(cur_ptr, cur_box);
27953 }
27954 @#
27955 @d sa_word_define(A, B) if (e)
27956 if (global) gsa_w_def(A, B);@+else sa_w_def(A, B);
27957 else word_define(A, B)
27958
27959 @<Declare \eTeX\ procedures for tr...@>=
27960 static void sa_def(pointer @!p, halfword @!e)
27961 /*new data for sparse array elements*/
27962 {@+add_sa_ref(p);
27963 if (sa_ptr(p)==e)
27964 {
27965 #ifdef @!STAT
27966 if (tracing_assigns > 0) show_sa(p,"reassigning");
27967 #endif
27968 @;@/
27969 sa_destroy(p);
27970 }
27971 else{
27972 #ifdef @!STAT
27973 if (tracing_assigns > 0) show_sa(p,"changing");
27974 #endif
27975 @;@/
27976 if (sa_lev(p)==cur_level) sa_destroy(p);@+else sa_save(p);
27977 sa_lev(p)=cur_level;sa_ptr(p)=e;
27978 #ifdef @!STAT
27979 if (tracing_assigns > 0) show_sa(p,"into");
27980 #endif
27981 @;@/
27982 }
27983 delete_sa_ref(p);
27984 }
27985 @#
27986 static void sa_w_def(pointer @!p, int @!w)
27987 {@+add_sa_ref(p);
27988 if (sa_int(p)==w)
27989 {
27990 #ifdef @!STAT
27991 if (tracing_assigns > 0) show_sa(p,"reassigning");
27992 #endif
27993 @;@/
27994 }
27995 else{
27996 #ifdef @!STAT
27997 if (tracing_assigns > 0) show_sa(p,"changing");
27998 #endif
27999 @;@/
28000 if (sa_lev(p)!=cur_level) sa_save(p);
28001 sa_lev(p)=cur_level;sa_int(p)=w;
28002 #ifdef @!STAT
28003 if (tracing_assigns > 0) show_sa(p,"into");
28004 #endif
28005 @;@/
28006 }
28007 delete_sa_ref(p);
28008 }
28009
28010 @ The |sa_def| and |sa_w_def| routines take care of local definitions.
28011 @^global definitions@>
28012 Global definitions are done in almost the same way, but there is no need
28013 to save old values, and the new value is associated with |level_one|.
28014
28015 @<Declare \eTeX\ procedures for tr...@>=
28016 static void gsa_def(pointer @!p, halfword @!e) /*global |sa_def|*/
28017 {@+add_sa_ref(p);
28018 #ifdef @!STAT
28019 if (tracing_assigns > 0) show_sa(p,"globally changing");
28020 #endif
28021 @;@/
28022 sa_destroy(p);sa_lev(p)=level_one;sa_ptr(p)=e;
28023 #ifdef @!STAT
28024 if (tracing_assigns > 0) show_sa(p,"into");
28025 #endif
28026 @;@/
28027 delete_sa_ref(p);
28028 }
28029 @#
28030 static void gsa_w_def(pointer @!p, int @!w) /*global |sa_w_def|*/
28031 {@+add_sa_ref(p);
28032 #ifdef @!STAT
28033 if (tracing_assigns > 0) show_sa(p,"globally changing");
28034 #endif
28035 @;@/
28036 sa_lev(p)=level_one;sa_int(p)=w;
28037 #ifdef @!STAT
28038 if (tracing_assigns > 0) show_sa(p,"into");
28039 #endif
28040 @;@/
28041 delete_sa_ref(p);
28042 }
28043
28044 @ The |sa_restore| procedure restores the sparse array entries pointed
28045 at by |sa_chain|
28046
28047 @<Declare \eTeX\ procedures for tr...@>=
28048 static void sa_restore(void)
28049 {@+pointer p; /*sparse array element*/
28050 @/do@+{p=sa_loc(sa_chain);
28051 if (sa_lev(p)==level_one)
28052 {@+if (sa_index(p) >= dimen_val_limit) sa_destroy(sa_chain);
28053 #ifdef @!STAT
28054 if (tracing_restores > 0) show_sa(p,"retaining");
28055 #endif
28056 @;@/
28057 }
28058 else{@+if (sa_index(p) < dimen_val_limit)
28059 if (sa_index(sa_chain) < dimen_val_limit) sa_int(p)=sa_int(sa_chain);
28060 else sa_int(p)=0;
28061 else{@+sa_destroy(p);sa_ptr(p)=sa_ptr(sa_chain);
28062 }
28063 sa_lev(p)=sa_lev(sa_chain);
28064 #ifdef @!STAT
28065 if (tracing_restores > 0) show_sa(p,"restoring");
28066 #endif
28067 @;@/
28068 }
28069 delete_sa_ref(p);
28070 p=sa_chain;sa_chain=link(p);
28071 if (sa_index(p) < dimen_val_limit) free_node(p, word_node_size);
28072 else free_node(p, pointer_node_size);
28073 }@+ while (!(sa_chain==null));
28074 }
28075
28076 @ When reading \.{\\patterns} while \.{\\savinghyphcodes} is positive
28077 the current |lc_code| values are stored together with the hyphenation
28078 patterns for the current language. They will later be used instead of
28079 the |lc_code| values for hyphenation purposes.
28080
28081 The |lc_code| values are stored in the linked trie analogous to patterns
28082 $p_1$ of length~1, with |hyph_root==trie_r[0]| replacing |trie_root| and
28083 |lc_code(p_1)| replacing the |trie_op| code. This allows to compress
28084 and pack them together with the patterns with minimal changes to the
28085 existing code.
28086
28087 @d hyph_root trie_r[0] /*root of the linked trie for |hyph_codes|*/
28088
28089 @<Initialize table entries...@>=
28090 hyph_root=0;hyph_start=0;
28091
28092 @ @<Store hyphenation codes for current language@>=
28093 {@+c=cur_lang;first_child=false;p=0;
28094 @/do@+{q=p;p=trie_r[q];
28095 }@+ while (!((p==0)||(c <= so(trie_c[p]))));
28096 if ((p==0)||(c < so(trie_c[p])))
28097 @<Insert a new trie node between |q| and |p|, and make |p| point to it@>;
28098 q=p; /*now node |q| represents |cur_lang|*/
28099 @<Store all current |lc_code| values@>;
28100 }
28101
28102 @ We store all nonzero |lc_code| values, overwriting any previously
28103 stored values (and possibly wasting a few trie nodes that were used
28104 previously and are not needed now). We always store at least one
28105 |lc_code| value such that |hyph_index| (defined below) will not be zero.
28106
28107 @<Store all current |lc_code| values@>=
28108 p=trie_l[q];first_child=true;
28109 for (c=0; c<=255; c++)
28110 if ((lc_code(c) > 0)||((c==255)&&first_child))
28111 {@+if (p==0)
28112 @<Insert a new trie node between |q| and |p|, and make |p| point to
28113 it@>@;
28114 else trie_c[p]=si(c);
28115 trie_o[p]=qi(lc_code(c));
28116 q=p;p=trie_r[q];first_child=false;
28117 }
28118 if (first_child) trie_l[q]=0;@+else trie_r[q]=0
28119
28120 @ We must avoid to ``take'' location~1, in order to distinguish between
28121 |lc_code| values and patterns.
28122
28123 @<Pack all stored |hyph_codes|@>=
28124 {@+if (trie_root==0) for (p=0; p<=255; p++) trie_min[p]=p+2;
28125 first_fit(hyph_root);trie_pack(hyph_root);
28126 hyph_start=trie_ref[hyph_root];
28127 }
28128
28129 @ The global variable |hyph_index| will point to the hyphenation codes
28130 for the current language.
28131
28132 @d set_hyph_index /*set |hyph_index| for current language*/
28133 if (trie_char(hyph_start+cur_lang)!=qi(cur_lang)
28134 ) hyph_index=0; /*no hyphenation codes for |cur_lang|*/
28135 else hyph_index=trie_link(hyph_start+cur_lang)
28136 @#
28137 @d set_lc_code(A) /*set |hc[0]| to hyphenation or lc code for |A|*/
28138 if (hyph_index==0) hc[0]=lc_code(A);
28139 else if (trie_char(hyph_index+A)!=qi(A)) hc[0]=0;
28140 else hc[0]=qo(trie_op(hyph_index+A))
28141
28142 @<Glob...@>=
28143 static trie_pointer @!hyph_start; /*root of the packed trie for |hyph_codes|*/
28144 static trie_pointer @!hyph_index; /*pointer to hyphenation codes for |cur_lang|*/
28145
28146 @ When |saving_vdiscards| is positive then the glue, kern, and penalty
28147 nodes removed by the page builder or by \.{\\vsplit} from the top of a
28148 vertical list are saved in special lists instead of being discarded.
28149
28150 @d tail_page_disc disc_ptr[copy_code] /*last item removed by page builder*/
28151 @d page_disc disc_ptr[last_box_code] /*first item removed by page builder*/
28152 @d split_disc disc_ptr[vsplit_code] /*first item removed by \.{\\vsplit}*/
28153
28154 @<Glob...@>=
28155 static pointer @!disc_ptr0[vsplit_code-copy_code+1],
28156 *const @!disc_ptr = @!disc_ptr0-copy_code; /*list pointers*/
28157
28158 @ @<Set init...@>=
28159 page_disc=null;split_disc=null;
28160
28161 @ The \.{\\pagediscards} and \.{\\splitdiscards} commands share the
28162 command code |un_vbox| with \.{\\unvbox} and \.{\\unvcopy}, they are
28163 distinguished by their |chr_code| values |last_box_code| and
28164 |vsplit_code|. These |chr_code| values are larger than |box_code| and
28165 |copy_code|.
28166
28167 @<Generate all \eTeX...@>=
28168 primitive("pagediscards", un_vbox, last_box_code);@/
28169 @!@:page\_discards\_}{\.{\\pagediscards} primitive@>
28170 primitive("splitdiscards", un_vbox, vsplit_code);@/
28171 @!@:split\_discards\_}{\.{\\splitdiscards} primitive@>
28172
28173 @ @<Cases of |un_vbox| for |print_cmd_chr|@>=;
28174 else if (chr_code==last_box_code) print_esc("pagediscards");
28175 else if (chr_code==vsplit_code) print_esc("splitdiscards")
28176
28177 @ @<Handle saved items and |goto done|@>=
28178 {@+link(tail)=disc_ptr[cur_chr];disc_ptr[cur_chr]=null;
28179 goto done;
28180 }
28181
28182 @ The \.{\\interlinepenalties}, \.{\\clubpenalties}, \.{\\widowpenalties},
28183 and \.{\\displaywidowpenalties} commands allow to define arrays of
28184 penalty values to be used instead of the corresponding single values.
28185
28186 @d inter_line_penalties_ptr equiv(inter_line_penalties_loc)
28187 @<Generate all \eTeX...@>=
28188 primitive("interlinepenalties", set_shape, inter_line_penalties_loc);@/
28189 @!@:inter\_line\_penalties\_}{\.{\\interlinepenalties} primitive@>
28190 primitive("clubpenalties", set_shape, club_penalties_loc);@/
28191 @!@:club\_penalties\_}{\.{\\clubpenalties} primitive@>
28192 primitive("widowpenalties", set_shape, widow_penalties_loc);@/
28193 @!@:widow\_penalties\_}{\.{\\widowpenalties} primitive@>
28194 primitive("displaywidowpenalties", set_shape, display_widow_penalties_loc);@/
28195 @!@:display\_widow\_penalties\_}{\.{\\displaywidowpenalties} primitive@>
28196
28197 @ @<Cases of |set_shape| for |print_cmd_chr|@>=
28198 case inter_line_penalties_loc: print_esc("interlinepenalties");@+break;
28199 case club_penalties_loc: print_esc("clubpenalties");@+break;
28200 case widow_penalties_loc: print_esc("widowpenalties");@+break;
28201 case display_widow_penalties_loc: print_esc("displaywidowpenalties");
28202
28203 @ @<Fetch a penalties array element@>=
28204 {@+scan_int();
28205 if ((equiv(m)==null)||(cur_val < 0)) cur_val=0;
28206 else{@+if (cur_val > penalty(equiv(m))) cur_val=penalty(equiv(m));
28207 cur_val=penalty(equiv(m)+cur_val);
28208 }
28209 }
28210
28211 @ |expand_depth| and |expand_depth_count| are used in the \eTeX\ code
28212 above, but not defined. So we correct this in the following modules,
28213 |expand_depth| having been defined by us as an integer paramater (hence
28214 there is a new primitive to create in \eTeX\ mode), and
28215 |expand_depth_count| needing to be a global. Both have to be defined to
28216 some sensible value.
28217
28218 @<Glob...@>=
28219 static int @!expand_depth_count; /*current expansion depth*/
28220
28221 @ @<Generate all \eTeX...@>=
28222 primitive("expanddepth", assign_int, int_base+expand_depth_code);@/
28223 @!@:expand\_depth\_}{\.{\\expanddepth} primitive@>
28224
28225 @ @<Cases for |print_param|@>=
28226 case expand_depth_code: print_esc("expanddepth");@+break;
28227
28228 @ @<Initialize variables for \eTeX\ extended mode@>=
28229 expand_depth=10000; /*value taken for compatibility with Web2C*/
28230 expand_depth_count=0;
28231
28232 @* The extended features of \Prote.
28233 \Prote\ extends furthermore \eTeX\ i.e. \eTeX\ is thus required
28234 before adding \Prote\ own extensions. But if \eTeX\ mode has not
28235 be enabled, the engine is still compatible with \TeX with no added
28236 primitive commands and with a modification of code---from
28237 \eTeX\ exclusively for now---that is sufficiently minor so that
28238 the engine still deserves the name \TeX.
28239
28240 @d Prote_ex (Prote_mode==1) /*is this prote mode?*/
28241
28242 @<Glob...@>=
28243 static int @!Prote_mode; /*to be or not to be; but an int to dump*/
28244
28245 @ We begin in \TeX\ compatibility mode. The state |Prote_mode| will be
28246 set to $1$ only if activated by the supplementary `*' added to the one
28247 activating the \eTeX\ extensions (in fact, this means for the user two
28248 initial `*' in a row).
28249
28250 @<Initialize table entries...@>=
28251 Prote_mode=0; /*initially we are in compatibility mode*/
28252
28253 @ @<Dump the \Prote\ state@>=
28254 dump_int(Prote_mode);
28255
28256 @ @<Undump the \Prote\ state@>=
28257 undump(0, 1, Prote_mode);
28258
28259 @ In order to not clobber the global scope with variables that are
28260 locally used, the initializations for \Prote, if the mode is
28261 activated, are done in a dedicated procedure. These are not part of
28262 what is dumped.
28263
28264 @<Last-minute procedures@>=
28265 static void Prote_initialize(void)
28266 {@+int k; /*all-purpose index*/
28267 @<\Prote\ initializations@>;
28268 }
28269
28270 @ There are commands and command modifiers, these command modifiers
28271 maybe encoding too a type. So we must not step on each other toes.
28272
28273 @ When we are adding primitives that deal intimately with the variables
28274 of \TeX, in the |eqtb| regions (in our case regions 5 for integers, and
28275 6 for dimensions), the command modifier to the various
28276 \.{assign\_*} classes is simply the address. So we have interpolated
28277 our added variables above since this is done by the way of WEB
28278 pre-processing.
28279
28280 @ For the conditional primitives, the way is straightforward.
28281
28282 @d if_incsname_code (eTeX_last_if_test_cmd_mod+1) /* `\.{\\ifincsname}' */
28283 @d if_primitive_code (eTeX_last_if_test_cmd_mod+2) /* `\.{\\ifprimitive}' */
28284 @ The |last_item| class is for secondary internal values, that can be
28285 dereferenced by \.{\\the} but are read-only and are mainly related to
28286 the value of a current state or are such values but their assignation
28287 shall trigger an action, and we shall not hook in the \.{assign\_*}
28288 processing.
28289
28290 The command modifiers for the |last_item| class were, originally,
28291 encoding too the type of the item (see m.410). But \eTeX\ has added its
28292 extensions and we won't try to be smart: the type |cur_val_level| will
28293 be set by switching between contiguous ranges of values of the same
28294 type.
28295
28296 And we will define here all the instances of |last_item| that we add
28297 in order to keep our number assignations gathered.
28298
28299 @d Prote_version_code (eTeX_last_last_item_cmd_mod+1)
28300 /*code for \.{\\Proteversion}*/
28301 @d random_seed_code (eTeX_last_last_item_cmd_mod+2) /* \.{\\randomseed} */
28302 @d elapsed_time_code (eTeX_last_last_item_cmd_mod+3) /* \.{\\elapsedtime} */
28303 @d shell_escape_code (eTeX_last_last_item_cmd_mod+4) /* \.{\\shellescape} */
28304 @d last_xpos_code (eTeX_last_last_item_cmd_mod+5) /* \.{\\lastxpos} */
28305 @d last_ypos_code (eTeX_last_last_item_cmd_mod+6) /* \.{\\lastypos} */
28306
28307 @ The \.{convert} class is for conversion of some external stuff to put
28308 it, as a token list, into the scanner. It is not an internal value that
28309 could be dereferenced by \.{\\the} and it is obviously not settable: it
28310 expands to the token list.
28311
28312 @d Prote_revision_code (eTeX_last_convert_cmd_mod+1) /* \.{\\Proterevision}*/
28313 @d strcmp_code (eTeX_last_convert_cmd_mod+2) /* \.{\\strcmp} */
28314 @d set_random_seed_code (eTeX_last_convert_cmd_mod+3) /* \.{\\setrandomseed} */
28315 @d normal_deviate_code (eTeX_last_convert_cmd_mod+4) /* \.{\\normaldeviate} */
28316 @d uniform_deviate_code (eTeX_last_convert_cmd_mod+5) /* \.{\\uniformdeviate} */
28317 @d creation_date_code (eTeX_last_convert_cmd_mod+6) /* \.{\\creationdate} */
28318 @d file_size_code (eTeX_last_convert_cmd_mod+7) /* \.{\\filesize} */
28319 @d file_mod_date_code (eTeX_last_convert_cmd_mod+8) /* \.{\\filemodedate} */
28320 @d file_dump_code (eTeX_last_convert_cmd_mod+9) /* \.{\\filedump} */
28321 @d mdfive_sum_code (eTeX_last_convert_cmd_mod+10) /* \.{\\mdfivesum} */
28322 @d Prote_last_convert_code mdfive_sum_code
28323
28324 @ When modifying the meaning of something---in this case, for now,
28325 switching to the primitive meaning if it exists---or modifying the
28326 way expansion is done, it seems that it can be thought as a special
28327 case of expansion, hence a variant of |expand_after|.
28328
28329 @d primitive_code (eTeX_last_expand_after_cmd_mod+1) /* `\.{\\primitive}' */
28330 @d expanded_code (eTeX_last_expand_after_cmd_mod+2) /* `\.{\\expanded}' */
28331 @ When the primitive manipulate something really external, whether
28332 trying to insert something in the output format---\.{DVI} for
28333 us---or dealing with the system, it doesn't fit in any cmd group and
28334 could be called an exception. So it will be a variant of the |extension|
28335 cmd group.
28336
28337 \eTeX\ didn't add new primitives to the extension command group, so we
28338 add a related macro, equal to |TeX_last_extension_cmd_mod|, simply so
28339 that it is locally obvious.
28340
28341 @d eTeX_last_extension_cmd_mod TeX_last_extension_cmd_mod /*none added*/
28342 @d reset_timer_code (eTeX_last_extension_cmd_mod+1) /* `\.{\\resettimer}' */
28343 @d save_pos_code (eTeX_last_extension_cmd_mod+2) /* `\.{\\savepos}' */
28344
28345 @*1 Identifying \Prote.
28346
28347 We will start by giving a mean to test that \Prote\ is activated and
28348 to identify the version.
28349
28350 @<Generate all \Prote\ primitives@>=
28351 if (!pdf_on) {
28352 primitive("Proteversion", last_item, Prote_version_code);
28353 @!@:Prote\_version\_}{\.{\\Proteversion} primitive@>
28354 primitive("Proterevision", convert, Prote_revision_code);@/
28355 @!@:Prote\_revision\_}{\.{\\Proterevision} primitive@>
28356 }
28357 @ We use the different hooks added to insert our cases.
28358
28359 @<Cases of |last_item| for |print_cmd_chr|@>=
28360 case Prote_version_code: print_esc("Proteversion");@+break;
28361
28362 @ @<Cases for fetching a \Prote\ int value@>=
28363 case Prote_version_code: cur_val=Prote_version;@+break;
28364
28365 @ @<Cases of |convert| for |print_cmd_chr|@>=
28366 case Prote_revision_code: print_esc("Proterevision");@+break;
28367
28368 @ @<Cases of `Scan the argument for command |c|'@>=
28369 case Prote_revision_code: do_nothing;@+break;
28370
28371 @ @<Cases of `Print the result of command |c|'@>=
28372 case Prote_revision_code: print(Prote_revision);@+break;
28373
28374 @*1 \Prote\ added token lists routines.
28375
28376 We will, more than once, convert a general normally expanded text
28377 to a string. Due to the unfelicity of \PASCAL\ about forward
28378 declarations of functions, we declare procedures that do their task
28379 by defining global variables. In this case, |garbage| is used.
28380
28381 |link(garbage)| will hold the pointer to the head of the token list,
28382 |info(garbage)| to the tail. If the two are equals, then the list is
28383 empty. The routine making a string will take |link(garbage)| and
28384 put the number in |info(garbage)|.
28385
28386 @ The first procedure scan a general text (normally) expanded. The
28387 head of the reference count is returned in |link(garbage)|, the
28388 tail in |info(garbage)| and if the two are equals, the list is empty.
28389 User must keep in mind that this has to be flushed when done with!
28390
28391 @<Forward declarations@>=
28392 static void scan_general_x_text(void);
28393
28394 @ @<Declare \Prote\ procedures for token lists@>=
28395 static void scan_general_x_text(void)
28396 {@+pointer d; /*to save |def_ref|*/
28397 d=def_ref;info(garbage)=scan_toks(false, true);
28398 link(garbage)=def_ref;
28399 def_ref=d; /*restore whatever*/
28400 }
28401
28402 @ The second procedure takes a token list defined in |link(garbage)|
28403 and converts it to a string number that is returned in |info(garbage)|.
28404 Neither the token list nor the string (obviously) are flushed.
28405
28406 @<Forward declarations@>=
28407 static void toks_to_str(void);
28408
28409 @ Here we are using |token_show| that has to take a reference count.
28410
28411 @<Declare \Prote\ procedures for token lists@>=
28412 static void toks_to_str(void)
28413 {@+int old_setting; /*holds |selector| setting*/
28414 old_setting=selector;selector=new_string;
28415 token_show(link(garbage));selector=old_setting;
28416 str_room(1); /*flirting with the limit means probably truncation*/
28417 info(garbage)=make_string();
28418 }
28419
28420 @*1 \Prote\ added strings routines.
28421
28422 The next procedure sets |name_of_file| from the string given as an
28423 argument, mimicking the |input| primitive by adding an |.tex| extension
28424 if there is none. It silently truncates if the length of the string
28425 exceeds the size of the name buffer and doesn't use |cur_area| and
28426 |cur_ext|, but |name_length| is set to the real name length (without
28427 truncating) so a test about |k <= file_name_size| allows to detect the
28428 impossibility of opening the file without having to call external code.
28429 The string is not flushed: it is the responsability of the code calling
28430 the procedure to flush it if wanted.
28431
28432 @<Declare \Prote\ procedures for strings@>=
28433 static void str_to_name(str_number @!s)
28434 {@+int k; /*number of positions filled in |name_of_file|*/
28435 ASCII_code @!c; /*character being packed*/
28436 int @!j; /*index into |str_pool|*/
28437 k=0;for (j=str_start[s]; j<=str_start[s+1]-1; j++) {@+
28438 c=so(str_pool[j]);incr(k);
28439 if (k <= file_name_size) name_of_file[k]=xchr[c];
28440 }
28441 name_length=k;
28442 name_of_file[name_length+1]=0;
28443 }
28444
28445 @*1 Exchanging data with external routines.
28446
28447 In order to try to sever external handling from our core, we
28448 introduce an all purpose exchange buffer |xchg_buffer|, that will
28449 be an array of bytes (these can be interpreted as \.{text\_char}
28450 or \.{ASCII\_char} or \.{eight\_bits}).
28451
28452 The data to be used starts at index $1$ and ends at index
28453 |xchg_buffer_length|.
28454
28455 For the moment, this buffer must accommodate a numerical MD5
28456 hash value, i.e. $16$ bytes long; will also be used to exchange $64$
28457 bytes chunks to feed MD5 hash generation, and will have to accommodate
28458 too the maximal size of the date returned by \.{\\creationdate} or
28459 \.{\\filemoddate} that is $23$ \.{text\_char}. So at least $64$ for now.
28460
28461 @<Global...@>=
28462 static eight_bits @!xchg_buffer0[xchg_buffer_size],
28463 *const @!xchg_buffer = @!xchg_buffer0-1;
28464 /*exchange buffer for interaction with system routines*/
28465 static int @!xchg_buffer_length; /*last valid index in this buf; 0 means no data*/
28466 @ @<Check \Prote\ ``constant'' values for consistency@>=
28467 if (xchg_buffer_size < 64) bad=51;
28468
28469 @ When there is data in the exchange buffer, the length of the data has
28470 to be set. When an external routine has consumed the data, it shall
28471 reset the length to $0$.
28472
28473 @<\Prote\ initializations@>=
28474 xchg_buffer_length=0;
28475
28476 @*1 \Prote\ states.
28477
28478 \.{\\shellescape} depends on a pdf\TeX\ feature, namely the ability to
28479 escape to shell. There is no such thing in \Prote. So it expands to $0$.
28480 Note: this a status primitive; it does not allow to set the status but
28481 simply expands to a read-only integer reflecting it. In \Prote, it is
28482 always $0$.
28483
28484 @<Generate all \Prote\ primitives@>=
28485 if (pdf_on) {
28486 primitive("pdfshellescape", last_item, shell_escape_code);
28487 @!@:pdfshellescape\_}{\.{\\pdfshellescape} primitive@>
28488 } else { primitive("shellescape", last_item, shell_escape_code);
28489 @!@:shellescape\_}{\.{\\shellescape} primitive@>
28490 }
28491
28492 @ @<Cases of |last_item| for |print_cmd_chr|@>=
28493 case shell_escape_code:
28494 if (pdf_on) print_esc("pdfshellescape");
28495 else print_esc("shellescape");
28496 @+break;
28497
28498 @ @<Cases for fetching a \Prote\ int value@>=
28499 case shell_escape_code: cur_val=0;@+break;
28500
28501 @*1 \Prote\ conditionals.
28502
28503 We add the following conditionals, that are susceptible of the same
28504 expansion rules as the other |if_test| ones.
28505
28506 @<Generate all \Prote\ primitives@>=
28507 primitive("ifincsname", if_test, if_incsname_code);
28508 @!@:if\_incsname\_}{\.{\\if} primitive@>
28509 if (pdf_on)
28510 primitive("ifpdfprimitive", if_test, if_primitive_code);
28511 @!@:if\_pdfprimitive\_}{\.{\\if} pdfprimitive@>
28512 else primitive("ifprimitive", if_test, if_primitive_code);
28513 @!@:if\_primitive\_}{\.{\\if} primitive@>
28514
28515
28516 @ @<Cases of |if_test| for |print_cmd_chr|@>=
28517 case if_incsname_code: print_esc("ifincsname");@+break;
28518 case if_primitive_code:
28519 if (pdf_on) print_esc("ifpdfprimitive");
28520 else print_esc("ifprimitive");
28521 @+break;
28522
28523 @ The conditional \.{\\ifincsname} is simple since we increment a global
28524 variable |incsname_state| when we enter the \.{\\csname} command and
28525 decrement it when we have reached and passed the \.{\\endcsname}---a
28526 scope depth index.
28527
28528 @<\Prote\ initializations@>=
28529 incsname_state=0;
28530
28531 @ @<Cases for |conditional|@>=
28532 case if_incsname_code: b=(incsname_state > 0);@+break;
28533
28534 @ The conditional \.{\\ifprimitive} is true when the following control
28535 sequence is a primitive; false otherwise. |id_lookup| can return
28536 |undefined_control_sequence| (for a control sequence not entered in the
28537 hash since |no_new_control_sequence| is |true|), but since it has the
28538 \.{eq\_type} set to |undefined_cs|, the test of this latter works as
28539 for a control sequence entered but never defined.
28540
28541 @ @<Cases for |conditional|@>=
28542 case if_primitive_code: {@+@/do@+{get_token();}@+ while (!(cur_tok!=space_token));
28543 if ((cur_cs!=0)&&(cur_cmd!=undefined_cs)&&(cur_cmd < call)) b=true;else b=false;
28544 } @+break;
28545
28546 @*1 \Prote\ primitives changing definition or expansion.
28547
28548 The next primitives, here, are more involved since they are whether
28549 changing the definition of a control sequence, or modifying how the
28550 tokens will be treated.
28551
28552 @ Since a user level control sequence can give a new definition to a
28553 primitive, the \.{primitive}... primitive, if the argument is a control
28554 sequence whose name is the name of a primitive, will make this primitive
28555 meaning the meaning of the control sequence {\it hic et nunc}. If there
28556 was no primitive meaning, no error is raised and nothing is changed.
28557 It can be seen as a kind of \.{expand\_after} command since it is in the
28558 external handling of the token list creation.
28559
28560 Since we need to redefine the token and hence give a valid control
28561 sequence in the |eqtb|, we have defined |frozen_primitive|. This
28562 ``frozen'' is, actually, not quite frozen by itself since we will
28563 redefine its values according to the primitive definition we have
28564 to restablish momentarily. But it is indeed ``permanent'' since
28565 it only refers to the permanently defined meanings. Hence, the
28566 initialization of the |frozen_primitive| address is just to document
28567 the code: these values will be overwritten on each actual call.
28568
28569 @<Generate all \Prote\ primitives@>=
28570 if (pdf_on)
28571 primitive("pdfprimitive", expand_after, primitive_code);
28572 @!@:pdfprimitive\_}{\.{\\pdfprimitive} primitive@>
28573 else
28574 primitive("primitive", expand_after, primitive_code);
28575 @!@:primitive\_}{\.{\\primitive} primitive@>
28576 text(frozen_primitive)=text(cur_val);eqtb[frozen_primitive]=eqtb[cur_val];
28577
28578 @ @<Cases of |expandafter| for |print_cmd_chr|@>=
28579 case primitive_code:
28580 if (pdf_on) print_esc("pdfprimitive");
28581 else print_esc("primitive");
28582 @+break;
28583
28584 @ The problem is that the primitives are added at |level_one| and that a
28585 redefinition as a macro at this same level by a user simply overwrites
28586 the definition. We need then to keep these definitions.
28587
28588 Primitives are only added by \.{INITEX}. So we can consider what we will
28589 call a |ROM|, since it can be only ``flashed'' by \.{INITEX} and is
28590 read-only afterwards, a kind of BIOS table holding initial system calls
28591 (primitives).
28592
28593 Since primitives are not macros (they don't need to expand or to
28594 evaluate parameters since their definition is directly in the code),
28595 the definition of a primitive is a couple: the command class (|cur_cmd|)
28596 and the modifier (|cur_chr|) to distinguish between the cases---the
28597 instances. But since, at the user level, a primitive is identified by
28598 its name, and that a redefinition is, mandatorily, a homonym, the
28599 location of the macro shadowing the primitive is at the same address as
28600 was the primitive in the |eqtb|. So in order to speed-up the check, we
28601 should organize things so that the address in the |eqtb| of a control
28602 sequence (one character or multiletter) can be readily
28603 converted in an address in the |ROM| array.
28604
28605 This array will be an array of memory word, of type |two_halves|, in
28606 order to re-use the macro definitions set for the table of equivalents.
28607
28608 The one character primitives are added by direct addressing relative to
28609 |single_base|. The multiletter primitives are added starting at
28610 |frozen_control_sequence-1|, downwards; but there are only, at the
28611 moment, $322$ multileter primitives defined by \TeX, $78$ such
28612 primitives defined by \eTeX, and we are adding $24$ more. It is clear
28613 that, looking at primitives, region 2 of |eqtb| is really a sparse array
28614 and that, when |hash_size| is increased for format needs, there will be
28615 a fair amount of space wasted if we simply copy, in fact, second part
28616 of region 1 and region 2 in the |ROM|.
28617
28618 Yes, but it is simpler as a first approach---premature optimization is
28619 the root of all evil. So a simple translation scheme will be enough.
28620
28621 The index in |ROM| will start at $1$ and will go up to $256 + 1 +
28622 hash\_size$, that is a simple translation from |single_base| to
28623 |ROM_base|, but only for addresses of interest, the other pointing to
28624 an |ROM_undefined_primitive| that will allow an easy test.
28625
28626 @d ROM_base 1
28627 @d ROM_size (256+1+hash_size) /*256 oc, undefined and ml*/
28628 @d ROM_undefined_primitive 257
28629 @d ROM_type_field(A) A.hh.b0
28630 @d ROM_equiv_field(X) X.hh.rh
28631 @d ROM_type(A) ROM_type_field(ROM[A]) /*command code for equivalent*/
28632 @d set_ROM_p_from_cs(A) if ((A >= single_base)
28633 &&(A < frozen_control_sequence))
28634 p=A-single_base+ROM_base;
28635 else p=ROM_undefined_primitive
28636
28637 @<Global...@>=
28638 static memory_word @!ROM0[ROM_size-ROM_base+1],
28639 *const @!ROM = @!ROM0-ROM_base;
28640
28641 @ Even if it will be unused in \TeX\ or \eTeX\ modes, we will initialize
28642 it since we add code to the |primitive| procedure and we need \TeX\
28643 and \eTeX\ ones to be registered as well, whether \.{INITEX} switches to
28644 \Prote\ mode later or not.
28645
28646 @<Initialize table entries...@>=
28647 ROM[ROM_undefined_primitive]=eqtb[undefined_control_sequence];
28648 for (k=ROM_base; k<=256; k++) ROM[k]=ROM[ROM_undefined_primitive];
28649 for (k=ROM_undefined_primitive+1; k<=ROM_size; k++)
28650 ROM[k]=ROM[ROM_undefined_primitive];
28651
28652 @ When a primitive is added---and this only happens in \.{INITEX}---we
28653 have to define the corresponding address in the \.{ROM}.
28654
28655 @ |cur_val| has the pointer in second part of region 1 or in region 2
28656 of |eqtb|.
28657
28658 @<Add primitive definition to the |ROM| array@>=
28659 set_ROM_p_from_cs(cur_val);
28660 ROM[p]=eqtb[cur_val];
28661
28662 @ This array has to be dumped since it is only defined by \.{INITEX}. It
28663 is always dumped even if it is unused unless in \Prote\ mode.
28664
28665 @<Dump the |ROM| array@>=
28666 for (k=ROM_base; k<=ROM_size; k++) dump_wd(ROM[k]);
28667
28668 @ And what has been dumped shall be undumped.
28669
28670 @<Undump the |ROM| array@>=
28671 for (k=ROM_base; k<=ROM_size; k++) undump_wd(ROM[k]);
28672
28673 @ Once all this is done, the processing of \.{\\primitive} is simple:
28674 we read the next token that has to be a control sequence. If this
28675 control sequence belongs to region 1 or 2 and is defined in |ROM|, we
28676 redefine the token to be the |frozen_primitive| control sequence,
28677 redefining its codes from the |ROM| and setting the text associated for
28678 printing purposes. If not, the token is unchanged. Then we put back the
28679 token so that it will be processed again, maybe redefined.
28680
28681 @<Cases for |expandafter|@>=
28682 case primitive_code: {@+get_token();
28683 set_ROM_p_from_cs(cur_cs);
28684 if ((p!=ROM_undefined_primitive)&&(ROM_type(p)!=undefined_cs)) {@+
28685 eqtb[frozen_primitive]=ROM[p];
28686 text(frozen_primitive)=text(cur_cs);
28687 cur_tok=cs_token_flag+frozen_primitive;
28688 }
28689 back_input();
28690 } @+break;
28691
28692 @ The next primitive changes the expansion of its argument that is like
28693 a general text expanded, except that protected macros (an \eTeX\
28694 extension) are not extanded.
28695
28696 @ @<Generate all \Prote\ primitives@>=
28697 primitive("expanded", expand_after, expanded_code);@/
28698 @!@:expanded\_}{\.{\\expanded} primitive@>
28699
28700 @ @<Cases of |expandafter| for |print_cmd_chr|@>=
28701 case expanded_code: print_esc("expanded");
28702
28703 @ This intervenes in |expand| and we must substitute a token list to our
28704 current token, putting it back for further reprocessing.
28705
28706 @<Cases for |expandafter|@>=
28707 case expanded_code: {@+scan_general_x_text();
28708 back_list(link(link(garbage)));
28709 free_avail(link(garbage)); /*drop reference count*/
28710 }
28711
28712 @*1 \Prote\ strings related primitives.
28713
28714 The primitive \.{\\strcmp} text two parameters that are general text
28715 without expansion. The two token lists created are converted to strings
28716 and this couple of strings is then compared, character by character. If
28717 the first string is lexicographically sorted before the second, the
28718 expansion is $-1$; if the two strings are equal, the expansion is $0$;
28719 if the first string is lexicographically sorted after the second, the
28720 expansion is $1$.
28721
28722 @<Generate all \Prote\ primitives@>=
28723 if (pdf_on)
28724 primitive("pdfstrcmp", convert, strcmp_code);@/
28725 @!@:pdf\_strcmp\_}{\.{\\pdfstrcmp} primitive@>
28726 else
28727 primitive("strcmp", convert, strcmp_code);
28728 @!@:strcmp\_}{\.{\\strcmp} primitive@>
28729
28730
28731 @ @<Cases of |convert| for |print_cmd_chr|@>=
28732 case strcmp_code:
28733 if (pdf_on) print_esc("pdfstrcmp");
28734 else print_esc("strcmp");
28735 @+break;
28736
28737 @ It should be noted that the strings comparison is \TeX\ strings
28738 comparison: the arguments are subject to the manipulation done when
28739 scanning a general text (squeezing non escaped blanks), and the
28740 characters are converted according to the |xord| array. Thus it is
28741 an |ASCII_code|---in the \TeX\ sense explained at the very beginning
28742 of the web file, part 2---comparison and the result is the same,
28743 as long as relative characters are mapped to the same value, whatever
28744 the system. Nul strings are valid.
28745
28746 @<Cases of `Scan the argument for command |c|'@>=
28747 case strcmp_code: @<Scan the argument for |strcmp_code|@>@;@+break;
28748
28749 @ @<Scan the argument for |strcmp_code|@>=
28750 {@+scan_general_x_text();toks_to_str();
28751 s=info(garbage);flush_list(link(garbage));
28752 scan_general_x_text();toks_to_str();
28753 t=info(garbage);flush_list(link(garbage));
28754 if ((length(s)==0)&&(length(t)==0)) cur_val=0;
28755 else if (length(s)==0) cur_val=-1;
28756 else if (length(t)==0) cur_val=1;
28757 else{@+m=str_start[s];n=str_start[t];r=false;
28758 while ((!r)&&(m < str_start[s+1])&&(n < str_start[t+1])) {@+
28759 cur_val=str_pool[m]-str_pool[n];if (cur_val!=0) r=true;
28760 incr(m);incr(n);
28761 }
28762 if (cur_val==0) {@+if (length(s)!=length(t))
28763 if (m!=str_start[s+1]) cur_val=1;else cur_val=-1;
28764 }
28765 else cur_val=cur_val/(double)abs(cur_val);
28766 }
28767 flush_string;flush_string;
28768 }
28769
28770 @ @<Cases of `Print the result of command |c|'@>=
28771 case strcmp_code: print_int(cur_val);@+break;
28772
28773 @*1 \Prote\ date and time related primitives.
28774
28775 The following primitives are related to the time elapsed since a
28776 defined moment in time. The creation date is fixed at the moment when
28777 |fix_date_and_time| has been called and stays fixed afterwards. This
28778 moment is also, by default, the reference moment for computing the time
28779 elapsed.
28780
28781 @ The creation date is retrieved by the \.{\\creationdate} primitive. As
28782 explained above, the date corresponds to the moment when
28783 |fix_date_and_time| was called taking into account |FORCE_SOURCE_DATE|
28784 and |SOURCE_DATE_EPOCH| (see above, m.241). If the creation date is
28785 forced, the string will be UTC related.
28786
28787 The format of the string is |D: YYYYMMDDHHmmSSOHH"mm"|, `O' being the
28788 relationship of local time to UT, that is `-' (minus), `+' or `Z';
28789 HH followed by a single quote being the absolute value of the offset
28790 from UT in hours (00--23), mm followed by a single quote being the
28791 absolute value of the offset from UT in minutes (00--59). All fields
28792 after the year are optional and default to zero values.
28793
28794 @ @<Generate all \Prote\ primitives@>=
28795 if (!pdf_on)
28796 primitive("pdfcreationdate", convert, creation_date_code);@/
28797 @!@:pdf\_creation\_date\_}{\.{\\pdfcreationdate} primitive@>
28798 else
28799 primitive("creationdate", convert, creation_date_code);@/
28800 @!@:creationdate\_}{\.{\\creationdate} primitive@>
28801
28802
28803 @ @<Cases of |convert| for |print_cmd_chr|@>=
28804 case creation_date_code:
28805 if (pdf_on) print_esc("pdfcreationdate");
28806 else print_esc("creationdate");
28807 @+break;
28808
28809 @ |get_creation_date| has to be provided by the system.
28810 @^system dependencies@>
28811
28812 @<Cases of `Scan the argument for command |c|'@>=
28813 case creation_date_code: get_creation_date();@+break;
28814
28815 @ The date is in the |time_str| so we have simply to convert the
28816 characters.
28817
28818 @<Cases of `Print the result of command |c|'@>=
28819 case creation_date_code: for (k=0; time_str[k]!='\0'; k++)
28820 print_char(time_str[k]);@+break;
28821
28822 @ The time elapsed is a scaled integer the unit being scaled seconds,
28823 i.e. $1/65536$ of a second. Since our scaled integers have a
28824 defined range, the value can not reach or pass, in plain seconds,
28825 $32767$.
28826
28827 The elapsed time returned is relative to some defined moment. At
28828 start, the reference moment is the time the date was set for
28829 |fix_date_and_time|. This requires system support and the default
28830 implementation here will then fix this moment at noon on 4 July 1776
28831 and what would be returned by the function is here simply defined by
28832 a macro: with this reference time and this basic code, |infinity| is
28833 the permanent answer.
28834 @^system dependencies@>
28835
28836 @d get_elapsed_time infinity /*a function should be implemented*/
28837
28838 @ @<Generate all \Prote\ primitives@>=
28839 if (pdf_on) {
28840 primitive("pdfresettimer", extension, reset_timer_code);@/
28841 @!@:reset\_timer\_}{\.{\\pdfresettimer} primitive@>
28842 primitive("pdfelapsedtime", last_item, elapsed_time_code);
28843 @!@:elapsed\_time\_}{\.{\\pdfelapsedtime} primitive@>
28844 } else {
28845 primitive("resettimer", extension, reset_timer_code);@/
28846 @!@:resettimer\_}{\.{\\resettimer} primitive@>
28847 primitive("elapsedtime", last_item, elapsed_time_code);@/
28848 @!@:elapsedtime\_}{\.{\\elapsedtime} primitive@>
28849 }
28850
28851 @ @<Cases of |last_item| for |print_cmd_chr|@>=
28852 case elapsed_time_code:
28853 if (pdf_on) print_esc("pdfelapsedtime");
28854 else print_esc("elapsedtime");
28855 @+break;
28856
28857 @ @<Cases of |extension| for |print_cmd_chr|@>=
28858 case reset_timer_code:
28859 if (pdf_on) print_esc("pdfresettimer");
28860 else print_esc("resettimer");
28861 @+break;
28862
28863 @ @<Cases for fetching a \Prote\ int value@>=
28864 case elapsed_time_code:
28865 { double t=(start_sec*1.0+start_nsec/1000000000.0-reset_timer)*0x10000;
28866 if (t>=infinity) cur_val=infinity;
28867 else cur_val=(scaled)t;
28868 @+break;
28869 }
28870
28871 @ The reference moment can be reset by a call to the primitive
28872 \.{\\resettimer}. It simply resets the reference moment to the moment
28873 the primitive was called. The counter is not regularily incremented.
28874 When asked about the time elapsed what is returned is the difference, in
28875 scaled seconds, from the moment of the call to the moment of reference.
28876 So there is no persistent variable neither a kind of clock implemented.
28877 @^system dependencies@>
28878
28879 Since we maintain the time anyway, we implement the timing function.
28880 @<Glob...@>=
28881 static double reset_timer=0.0; /*time of the last reset in seconds*/
28882
28883
28884 @ Since to reset the timer a simple call to the routine is necessary,
28885 we simply add it to \.{main\_control} by adding it to the cases handled
28886 by \.{do\_extension}. It contributes nothing to the token list: it is a
28887 ``fire and forget'', so no need to handle the special \.{subtype} in the
28888 other hooks.
28889
28890 @<Cases for |do_extension|@>=
28891 case reset_timer_code: reset_timer=start_sec*1.0+start_nsec/1000000000.0;@+break;
28892
28893 @*1 \Prote\ file related primitives.
28894
28895 The presence of the following primitives in the engine can be
28896 questioned. Since they are very external, and their implementation, for
28897 example in C, requires things that are not in the C standard (the
28898 date of modification of the file, for example). So these should not be
28899 multiplied.
28900
28901 @ The \.{\\filesize} primitive expands to the size, in bytes, of the
28902 file.
28903
28904 @<Generate all \Prote\ primitives@>=
28905 if (pdf_on)
28906 primitive("pdffilesize", convert, file_size_code);@/
28907 @!@:pdf\_file\_size\_}{\.{\\pdffilesize} primitive@>
28908 else
28909 primitive("filesize", convert, file_size_code);
28910 @!@:filesize\_}{\.{\\filesize} primitive@>
28911
28912
28913 @ @<Cases of |convert| for |print_cmd_chr|@>=
28914 case file_size_code:
28915 if (pdf_on) print_esc("pdffilesize");
28916 else print_esc("filesize");
28917 @+break;
28918
28919 @ In order to be able to treat the problem when trying to open the file,
28920 we open here and pass the file pointer, if success, to a dedicated
28921 function in order to get its size. In case of problem, nothing is
28922 returned.
28923 @^system dependencies@>
28924
28925 @<Cases of `Scan the argument for command |c|'@>=
28926 case file_size_code: @<Scan the argument for |file_size_code|@>@;@+break;
28927
28928 @ @<Scan the argument for |file_size_code|@>=
28929 {@+scan_general_x_text();toks_to_str();
28930 s=info(garbage);flush_list(link(garbage));str_to_name(s);
28931 cur_val=-1; /*invalid value if error*/
28932 cur_val=get_file_size();
28933 flush_string;
28934 }
28935
28936 @ @<Cases of `Print the result of command |c|'@>=
28937 case file_size_code: if (cur_val!=-1) print_int(cur_val);@+break;
28938
28939 @ The \.{\\filemoddate} expands to a date with the same format as the
28940 creation date (see \.{\\creationdate}).
28941
28942 @<Generate all \Prote\ primitives@>=
28943 if (pdf_on)
28944 primitive("pdffilemoddate", convert, file_mod_date_code);@/
28945 @!@:pdf\_file\_mod\_date\_}{\.{\\pdffilemoddate} primitive@>
28946 else
28947 primitive("filemoddate", convert, file_mod_date_code);
28948 @!@:filemoddate\_}{\.{\\filemoddate} primitive@>
28949
28950
28951 @ @<Cases of |convert| for |print_cmd_chr|@>=
28952 case file_mod_date_code:
28953 if (pdf_on) print_esc("pdffilemoddate");
28954 else print_esc("filemoddate");
28955 @+break;
28956
28957 @ For getting the argument, the treatment resembles that of
28958 \.{\\filesize} obviously, since it is only the type of information
28959 returned that changes. The availability of this information in system
28960 dependent. The information shall be set in |xchg_buffer|.
28961 @^system dependencies@>
28962
28963 In this basic implementation, we set the string to the empty one by
28964 simply setting |xchg_buffer_length| to $0$.
28965
28966 @d get_file_mtime xchg_buffer_length=0
28967
28968 @<Cases of `Scan the argument for command |c|'@>=
28969 case file_mod_date_code: @<Scan the argument for |file_mod_date_code|@>@;@+break;
28970
28971 @ @<Scan the argument for |file_mod_date_code|@>=
28972 {@+scan_general_x_text();toks_to_str();
28973 s=info(garbage);flush_list(link(garbage));str_to_name(s);
28974 get_file_mod_date();
28975 flush_string;
28976 } @+break;
28977
28978 @ Printing the result consists simply in printing every
28979 |text_char| in |time_str|.
28980 If the length is $0$, nothing is printed.
28981
28982 @<Cases of `Print the result of command |c|'@>=
28983 case file_mod_date_code: for (k=0; time_str[k]!='\0'; k++)
28984 print_char(time_str[k]);@+break;
28985
28986 @ The primitive \.{\\filedump} expands to the dump of the first
28987 \.{length} bytes of the file, starting from \.{offset}. Offset and
28988 length are optional integers given, in that order, introduced resp.
28989 by the keywords ``offset'' and ``length''. If not specified, they
28990 default to $0$. A length of $0$ expands to nothing (it is not an error).
28991 The file name is given as a |general text|.
28992
28993 @<Generate all \Prote\ primitives@>=
28994 if (pdf_on)
28995 primitive("pdffiledump", convert, file_dump_code);@/
28996 @!@:pdf\_file\_dump\_}{\.{\\pdffiledump} primitive@>
28997 else
28998 primitive("filedump", convert, file_dump_code);
28999 @!@:filedump\_}{\.{\\filedump} primitive@>
29000
29001
29002 @ @<Cases of |convert| for |print_cmd_chr|@>=
29003 case file_dump_code:
29004 if (pdf_on) print_esc("pdffiledump");
29005 else print_esc("filedump");
29006 @+break;
29007
29008 @ The scanning of the arguments is obvious from the syntax above.
29009
29010 Since ``offset'' and ``length'' may be given in that order, we assign
29011 the variables \.{k} and \.{l}, in alphabetical order. These have to be
29012 positive or nul values.
29013
29014 Contrary to other blocks, and for optimization purposes (in order not to
29015 clobber the string pool with data that we can read, when necessary, one
29016 byte at a time), \.{k}, \.{l} and \.{f} will be defined here and used
29017 when printing.
29018
29019 @<Cases of `Scan the argument for command |c|'@>=
29020 case file_dump_code: @<Scan the argument for |file_dump_code|@>@;@+break;
29021
29022 @ @<Scan the argument for |file_dump_code|@>=
29023 {@+k=0;l=0; /*defaults*/
29024 if (scan_keyword("offset")) {@+scan_int();
29025 if (cur_val < 0) {@+print_err("Bad ");print_esc("filedump");
29026 @.Bad \\filedump@>
29027 help2("I allow only nonnegative values here.",@/
29028 "I changed this one to zero.");int_error(cur_val);
29029 }
29030 else k=cur_val;
29031 }
29032 if (scan_keyword("length")) {@+scan_int();
29033 if (cur_val < 0) {@+print_err("Bad ");print_esc("filedump");
29034 @.Bad \\filedump@>
29035 help2("I allow only nonnegative values here.",@/
29036 "I changed this one to zero.");int_error(cur_val);
29037 }
29038 else l=cur_val;
29039 }
29040 scan_general_x_text();toks_to_str();s=info(garbage);
29041 flush_list(link(garbage));str_to_name(s);
29042 flush_string; /*this one was the filename argument*/
29043 }
29044
29045 @ The variables have been set, and the file name has been defined. We
29046 simply print the uppercase hexadecimal transcription of every byte
29047 requested before closing the file. Here we deal with bytes
29048 (\.{eight\_bits} values) so there is no transcription.
29049
29050 @<Cases of `Print the result of command |c|'@>=
29051 case file_dump_code:
29052 { FILE *f=fopen((char*)name_of_file0,"rb");
29053 if (f!=NULL) {@+
29054 fseek(f,k,SEEK_SET);
29055 do@+{i=fgetc(f); if (i==EOF) break;
29056 dig[0]=i%16;dig[1]=i/16;
29057 print_the_digs(2);decr(l);
29058 }@+ while (!(feof(f)||(l==0)));
29059 fclose(f);
29060 }
29061 } @+break;
29062
29063 @ The \.{\\mdfivesum} is obviously a variant of the \.{convert} class since
29064 it takes values from external and put them as a token list in the
29065 stream.
29066
29067 @<Generate all \Prote\ primitives@>=
29068 if (pdf_on)
29069 primitive("pdfmdfivesum", convert, mdfive_sum_code);@/
29070 @!@:pdf\_mdfive\_sum\_}{\.{\\pdfmdfivesum} primitive@>
29071 else
29072 primitive("mdfivesum", convert, mdfive_sum_code);
29073 @!@:mdfivesum\_}{\.{\\mdfivesum} primitive@>
29074
29075
29076 @ @<Cases of |convert| for |print_cmd_chr|@>=
29077 case mdfive_sum_code:
29078 if (pdf_on) print_esc("pdfmdfivesum");
29079 else print_esc("mdfivesum");
29080 @+break;
29081
29082 @ There is an optional keyword "file" that will tell us if the | < general
29083 text > | is to be taken as a filename or just as the string to hash. The
29084 | < balanced text > | is expanded in both cases.
29085
29086 Once this is done, we ask to init the MD5 state; then fill the exchange
29087 buffer with chunks of data and update the MD5 hash with every chunk
29088 until source is exhausted and ask for the final ($16$ bytes numerical
29089 value) result that will be put in the |xchg_buffer|.
29090
29091 Since we are looking for a ``general text'', that must be enclosed (at
29092 least: ended; the opening brace can be implicit) by a |right_brace|,
29093 an error will be caught with runaways.
29094
29095 The general text is converted to a string. It is legal to have an empty
29096 string if the argument is not a file.
29097
29098 @<Cases of `Scan the argument for command |c|'@>=
29099 case mdfive_sum_code: @<Scan the argument for |mdfive_sum_code|@>@; @+break;
29100
29101 @ @<Scan the argument for |mdfive_sum_code|@>=
29102 {@+r=scan_keyword("file");scan_general_x_text();
29103 toks_to_str();s=info(garbage);flush_list(link(garbage));
29104 l=get_md5_sum(s,r);
29105 flush_string; /*done with the filename or string to hash*/
29106 }
29107
29108 @ As a result, there is $16$ bytes in the |md5_digest| representing the
29109 MD5 hash. We simply print, byte by byte, the uppercase hexadecimal
29110 representation of this hash.
29111
29112 @<Cases of `Print the result of command |c|'@>=
29113 case mdfive_sum_code: for (k=0; k<l; k++)
29114 {@+dig[0]=md5_digest[k]%16;@+dig[1]=md5_digest[k]/16;print_the_digs(2);
29115 } @+break;
29116
29117 @*1 Pseudo-random number generation.
29118
29119 These routines come from John Hobby's \MP\ and generate pseudo-random
29120 numbers with the additive scheme recommended in Section 3.6 of
29121 {\sl The Art of Computer Programming}; however, the results are
29122 random fractions between 0 and |mpfract_one-1|, inclusive.
29123
29124 \MP\ uses 28~significant bits of precision and we have kept this in
29125 order for the routines to behave the same way as in \MP. So the name
29126 |mpfract| will be used instead of |scaled|, while the two are integers,
29127 in the range defined by \TeX.
29128
29129 @d double(A) A=A+A /*multiply a variable by two*/
29130 @d halfp(A) (A)/2 /*when quantity is known to be positive or zero*/
29131
29132 @ The subroutines for logarithm and exponential involve two tables.
29133 The first is simple: |two_to_the[k]| equals $2^k$. The second involves
29134 a bit more calculation, which the author claims to have done correctly:
29135 |spec_log[k]| is $2^{27}$ times $\ln\bigl(1/(1-2^{-k})\bigr)=
29136 2^{-k}+{1\over2}2^{-2k}+{1\over3}2^{-3k}+\cdots\,$, rounded to the
29137 nearest integer.
29138
29139 @<Glob...@>=
29140 static int @!two_to_the[31]; /*powers of two*/
29141 static int @!spec_log0[28], *const @!spec_log = @!spec_log0-1; /*special logarithms*/
29142
29143 @ @<\Prote\ initializations@>=
29144 two_to_the[0]=1;
29145 for (k=1; k<=30; k++) two_to_the[k]=2*two_to_the[k-1];
29146 spec_log[1]=93032640;
29147 spec_log[2]=38612034;
29148 spec_log[3]=17922280;
29149 spec_log[4]=8662214;
29150 spec_log[5]=4261238;
29151 spec_log[6]=2113709;
29152 spec_log[7]=1052693;
29153 spec_log[8]=525315;
29154 spec_log[9]=262400;
29155 spec_log[10]=131136;
29156 spec_log[11]=65552;
29157 spec_log[12]=32772;
29158 spec_log[13]=16385;
29159 for (k=14; k<=27; k++) spec_log[k]=two_to_the[27-k];
29160 spec_log[28]=1;
29161
29162 @ Here is the routine that calculates $2^8$ times the natural logarithm
29163 of a |scaled| quantity; it is an integer approximation to $2^{24}\ln(x/2^{16})$,
29164 when |x| is a given positive integer.
29165
29166 The method is based on exercise 1.2.2--25 in {\sl The Art of Computer
29167 Programming\/}: During the main iteration we have $1\L 2^{-30}x<1/(1-2^{1-k})$,
29168 and the logarithm of $2^{30}x$ remains to be added to an accumulator
29169 register called~$y$. Three auxiliary bits of accuracy are retained in~$y$
29170 during the calculation, and sixteen auxiliary bits to extend |y| are
29171 kept in~|z| during the initial argument reduction. (We add
29172 $100\cdot2^{16}=6553600$ to~|z| and subtract 100 from~|y| so that |z| will
29173 not become negative; also, the actual amount subtracted from~|y| is~96,
29174 not~100, because we want to add~4 for rounding before the final division by~8.)
29175
29176 @<Declare \Prote\ arithmetic routines@>=
29177 static scaled m_log(scaled @!x)
29178 {@+int @!y, @!z; /*auxiliary registers*/
29179 int @!k; /*iteration counter*/
29180 if (x <= 0) @<Handle non-positive logarithm@>@;
29181 else{@+y=1302456956+4-100; /*$14\times2^{27}\ln2\approx1302456956.421063$*/
29182 z=27595+6553600; /*and $2^{16}\times .421063\approx 27595$*/
29183 while (x < mpfract_four)
29184 {@+double(x);y=y-93032639;z=z-48782;
29185 } /*$2^{27}\ln2\approx 93032639.74436163$
29186 and $2^{16}\times.74436163\approx 48782$*/
29187 y=y+(z/unity);k=2;
29188 while (x > mpfract_four+4)
29189 @<Increase |k| until |x| can be multiplied by a factor of $2^{-k}$, and
29190 adjust $y$ accordingly@>;
29191 return y/8;
29192 }
29193 }
29194
29195 @ @<Increase |k| until |x| can...@>=
29196 {@+z=((x-1)/two_to_the[k])+1; /*$z=\lceil x/2^k\rceil$*/
29197 while (x < mpfract_four+z)
29198 {@+z=halfp(z+1);k=k+1;
29199 }
29200 y=y+spec_log[k];x=x-z;
29201 }
29202
29203 @ @<Handle non-positive logarithm@>=
29204 {@+print_err("Logarithm of ");
29205 @.Logarithm...replaced by 0@>
29206 print_scaled(x);print(" has been replaced by 0");
29207 help2("Since I don't take logs of non-positive numbers,",@/
29208 "I'm zeroing this one. Proceed, with fingers crossed.");
29209 error();return 0;
29210 }
29211
29212 @ Here is introduced the special 28bits significand |mpfract|.
29213
29214 @d el_gordo 017777777777 /*$2^{31}-1$, the largest value that \TeX\ likes*/
29215 @d mpfract_half 01000000000 /*$2^{27}$, represents 0.50000000*/
29216 @d mpfract_one 02000000000 /*$2^{28}$, represents 1.00000000*/
29217 @d mpfract_four 010000000000 /*$2^{30}$, represents 4.00000000*/
29218
29219 @<Types...@>=
29220 typedef int mpfract; /*this type is used for pseudo-random numbers*/
29221
29222 @ The |make_mpfract| routine produces the |mpfract| equivalent of
29223 |p/(double)q|, given integers |p| and~|q|; it computes the integer
29224 $f=\lfloor2^{28}p/q+{1\over2}\rfloor$, when $p$ and $q$ are
29225 positive. If |p| and |q| are both of the same scaled type |t|,
29226 the ``type relation'' |make_mpfract(t, t)==mpfract| is valid;
29227 and it's also possible to use the subroutine ``backwards,'' using
29228 the relation |make_mpfract(t, mpfract)==t| between scaled types.
29229
29230 If the result would have magnitude $2^{31}$ or more, |make_mpfract|
29231 sets |arith_error=true|. Most of \TeX's internal computations have
29232 been designed to avoid this sort of error.
29233
29234 If this subroutine were programmed in assembly language on a typical
29235 machine, we could simply compute |(@t$2^{28}$@>*p)/q|, since a
29236 double-precision product can often be input to a fixed-point division
29237 instruction. But when we are restricted to \PASCAL\ arithmetic it
29238 is necessary either to resort to multiple-precision maneuvering
29239 or to use a simple but slow iteration. The multiple-precision technique
29240 would be about three times faster than the code adopted here, but it
29241 would be comparatively long and tricky, involving about sixteen
29242 additional multiplications and divisions.
29243
29244 The present implementation is highly portable, but slow; it avoids
29245 multiplication and division except in the initial stage. But since it is
29246 not part of \TeX\ inner loop, it doesn't matter.
29247
29248 @<Declare \Prote\ arithmetic routines@>=
29249 static mpfract make_mpfract(int @!p, int @!q)
29250 {@+int @!f; /*the fraction bits, with a leading 1 bit*/
29251 int @!n; /*the integer part of $\vert p/q\vert$*/
29252 bool @!negative; /*should the result be negated?*/
29253 int @!be_careful; /*disables certain compiler optimizations*/
29254 if (p >= 0) negative=false;
29255 else{@+negate(p);negative=true;
29256 }
29257 if (q <= 0)
29258 {
29259 #ifdef @!DEBUG
29260 if (q==0) confusion("/");@;
29261 #endif
29262 @;@/
29263 @:this can't happen /}{\quad \./@>
29264 negate(q);negative=!negative;
29265 }
29266 n=p/q;p=p%q;
29267 if (n >= 8)
29268 {@+arith_error=true;
29269 if (negative) return-el_gordo;@+else return el_gordo;
29270 }
29271 else{@+n=(n-1)*mpfract_one;
29272 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>;
29273 if (negative) return-(f+n);@+else return f+n;
29274 }
29275 }
29276
29277 @ The |@/do@+{| loop here preserves the following invariant relations
29278 between |f|, |p|, and~|q|:
29279 (i)~|0 <= p < q|; (ii)~$fq+p=2^k(q+p_0)$, where $k$ is an integer and
29280 $p_0$ is the original value of~$p$.
29281
29282 Notice that the computation specifies
29283 |(p-q)+p| instead of |(p+p)-q|, because the latter could overflow.
29284 Let us hope that optimizing compilers do not miss this point; a
29285 special variable |be_careful| is used to emphasize the necessary
29286 order of computation. Optimizing compilers should keep |be_careful|
29287 in a register, not store it in memory.
29288 @^inner loop@>
29289
29290 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>=
29291 f=1;
29292 @/do@+{be_careful=p-q;p=be_careful+p;
29293 if (p >= 0) f=f+f+1;
29294 else{@+double(f);p=p+q;
29295 }
29296 }@+ while (!(f >= mpfract_one));
29297 be_careful=p-q;
29298 if (be_careful+p >= 0) incr(f)
29299
29300 @ The dual of |make_mpfract| is |take_mpfract|, which multiplies a
29301 given integer~|q| by a fraction~|f|. When the operands are positive, it
29302 computes $p=\lfloor qf/2^{28}+{1\over2}\rfloor$, a symmetric function
29303 of |q| and~|f|.
29304
29305 @<Declare \Prote\ arithmetic routines@>=
29306 static int take_mpfract(int @!q, mpfract @!f)
29307 {@+int @!p; /*the fraction so far*/
29308 bool @!negative; /*should the result be negated?*/
29309 int @!n; /*additional multiple of $q$*/
29310 int @!be_careful; /*disables certain compiler optimizations*/
29311 @<Reduce to the case that |f>=0| and |q>0|@>;
29312 if (f < mpfract_one) n=0;
29313 else{@+n=f/mpfract_one;f=f%mpfract_one;
29314 if (q <= el_gordo/n) n=n*q;
29315 else{@+arith_error=true;n=el_gordo;
29316 }
29317 }
29318 f=f+mpfract_one;
29319 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>;
29320 be_careful=n-el_gordo;
29321 if (be_careful+p > 0)
29322 {@+arith_error=true;n=el_gordo-p;
29323 }
29324 if (negative) return-(n+p);
29325 else return n+p;
29326 }
29327
29328 @ @<Reduce to the case that |f>=0| and |q>0|@>=
29329 if (f >= 0) negative=false;
29330 else{@+negate(f);negative=true;
29331 }
29332 if (q < 0)
29333 {@+negate(q);negative=!negative;
29334 }
29335
29336 @ The invariant relations in this case are (i)~$\lfloor(qf+p)/2^k\rfloor
29337 =\lfloor qf_0/2^{28}+{1\over2}\rfloor$, where $k$ is an integer and
29338 $f_0$ is the original value of~$f$; (ii)~$2^k\L f<2^{k+1}$.
29339 @^inner loop@>
29340
29341 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>=
29342 p=mpfract_half; /*that's $2^{27}$; the invariants hold now with $k=28$*/
29343 if (q < mpfract_four)
29344 @/do@+{if (odd(f)) p=halfp(p+q);@+else p=halfp(p);
29345 f=halfp(f);
29346 }@+ while (!(f==1));
29347 else@/do@+{if (odd(f)) p=p+halfp(q-p);@+else p=halfp(p);
29348 f=halfp(f);
29349 }@+ while (!(f==1))
29350
29351 @ There's an auxiliary array |randoms| that contains 55 pseudo-random
29352 fractions. Using the recurrence $x_n=(x_{n-55}-x_{n-31})\bmod 2^{28}$,
29353 we generate batches of 55 new $x_n$'s at a time by calling |new_randoms|.
29354 The global variable |j_random| tells which element has most recently
29355 been consumed.
29356
29357 @<Glob...@>=
29358 static mpfract @!randoms[55]; /*the last 55 random values generated*/
29359 static int @!j_random; /*the number of unused |randoms|*/
29360
29361 @ This array of pseudo-random numbers is set starting from a seed value,
29362 that is kept in the global integer |random_seed|.
29363
29364 @<Global...@>=
29365 static int @!random_seed; /*seed for pseudo-random number generation*/
29366
29367 @ @<Generate all \Prote\ primitives@>=
29368 if (pdf_on)
29369 primitive("pdfrandomseed", last_item, random_seed_code);
29370 @!@:random\_seed\_}{\.{\\pdfrandomseed} primitive@>
29371 else
29372 primitive("randomseed", last_item, random_seed_code);@/
29373 @!@:randomseed\_}{\.{\\randomseed} primitive@>
29374
29375
29376 @ @<Cases of |last_item| for |print_cmd_chr|@>=
29377 case random_seed_code:
29378 if (pdf_on) print_esc("pdfrandomseed");
29379 else print_esc("randomseed");
29380 @+break;
29381
29382 @ @<Cases for fetching a \Prote\ int value@>=
29383 case random_seed_code: cur_val=random_seed;@+break;
29384
29385 @ We set the initial value from the system time. System integrators
29386 could provide a better source of pseudo-randomness.
29387
29388 Every time a new seed value is assigned, the array has to be
29389 regenerated for consumption by routines explained a little later.
29390
29391 @<\Prote\ initializations@>=
29392 random_seed=sys_time;
29393 init_randoms();
29394
29395 @ Since changing the value must trigger the redefinition of the array,
29396 a dedicated primitive is defined to take the new seed and call
29397 |init_randoms|.
29398
29399 @<Generate all \Prote\ primitives@>=
29400 if (pdf_on)
29401 primitive("pdfsetrandomseed", convert, set_random_seed_code);@/
29402 @!@:set\_random\_seed\_code}{\.{\\pdfsetrandomseed} primitive@>
29403 else
29404 primitive("setrandomseed", convert, set_random_seed_code);@/
29405 @!@:setrandomseed\_}{\.{\\setrandomseed} primitive@>
29406
29407
29408 @ @<Cases of |convert| for |print_cmd_chr|@>=
29409 case set_random_seed_code:
29410 if (pdf_on) print_esc("pdfsetrandomseed");
29411 else print_esc("setrandomseed");
29412 @+break;
29413
29414 @ Once we have retrieved and redefined |random_seed|, we must regenerate
29415 the |randoms| array.
29416
29417 @<Cases of `Scan the argument for command |c|'@>=
29418 case set_random_seed_code: {@+scan_int();random_seed=cur_val;
29419 init_randoms();
29420 } @+break;
29421
29422 @ @<Cases of `Print the result of command |c|'@>=
29423 case set_random_seed_code: print_int(random_seed);@+break;
29424
29425 @ To consume a random fraction, the program below will say `|next_random|'
29426 and then it will fetch |randoms[j_random]|.
29427
29428 @d next_random if (j_random==0) new_randoms();
29429 else decr(j_random)
29430
29431 @<Declare \Prote\ arithmetic routines@>=
29432 static void new_randoms(void)
29433 {@+int @!k; /*index into |randoms|*/
29434 int @!x; /*accumulator*/
29435 for (k=0; k<=23; k++)
29436 {@+x=randoms[k]-randoms[k+31];
29437 if (x < 0) x=x+mpfract_one;
29438 randoms[k]=x;
29439 }
29440 for (k=24; k<=54; k++)
29441 {@+x=randoms[k]-randoms[k-24];
29442 if (x < 0) x=x+mpfract_one;
29443 randoms[k]=x;
29444 }
29445 j_random=54;
29446 }
29447
29448 @ To initialize the |randoms| table, we call the following routine.
29449
29450 @<Declare \Prote\ arithmetic routines@>=
29451 static void init_randoms(void)
29452 {@+mpfract @!j, @!jj, @!k; /*more or less random integers*/
29453 int @!i; /*index into |randoms|*/
29454 j=abs(random_seed);
29455 while (j >= mpfract_one) j=halfp(j);
29456 k=1;
29457 for (i=0; i<=54; i++)
29458 {@+jj=k;k=j-k;j=jj;
29459 if (k < 0) k=k+mpfract_one;
29460 randoms[(i*21)%55]=j;
29461 }
29462 new_randoms();new_randoms();new_randoms(); /*``warm up'' the array*/
29463 }
29464
29465 @ To produce a uniform random number in the range |0 <= u < x| or |0 >= u > x|
29466 or |0==u==x|, given a |scaled| value~|x|, we proceed as shown here.
29467
29468 Note that the call of |mult_integers| will produce the values 0 and~|x|
29469 with about half the probability that it will produce any other particular
29470 values between 0 and~|x|, because it rounds its answers.
29471
29472 @<Declare \Prote\ arithmetic routines@>=
29473 static scaled unif_rand(scaled @!x)
29474 {@+scaled @!y; /*trial value*/
29475 next_random;y=take_mpfract(abs(x), randoms[j_random]);
29476 if (y==abs(x)) return 0;
29477 else if (x > 0) return y;
29478 else return-y;
29479 }
29480
29481 @ This can be used by calling the following primitive.
29482
29483 @<Generate all \Prote\ primitives@>=
29484 if (pdf_on)
29485 primitive("pdfuniformdeviate", convert, uniform_deviate_code);@/
29486 @!@:uniform\_deviate\_}{\.{\\pdfuniformdeviate} primitive@>
29487 else
29488 primitive("uniformdeviate", convert, uniform_deviate_code);@/
29489 @!@:uniformdeviate\_}{\.{\\uniformdeviate} primitive@>
29490
29491
29492 @ @<Cases of |convert| for |print_cmd_chr|@>=
29493 case uniform_deviate_code:
29494 if (pdf_on) print_esc("pdfuniformdeviate");
29495 else print_esc("uniformdeviate");
29496 @+break;
29497
29498 @ It takes one integer argument obviously that will be the argument
29499 to the function.
29500
29501 @<Cases of `Scan the argument for command |c|'@>=
29502 case uniform_deviate_code: {@+scan_int();
29503 cur_val=unif_rand(cur_val);
29504 } @+break;
29505
29506 @ @<Cases of `Print the result of command |c|'@>=
29507 case uniform_deviate_code: print_int(cur_val);@+break;
29508
29509 @ The following somewhat different subroutine tests rigorously if $ab$ is
29510 greater than, equal to, or less than~$cd$,
29511 given integers $(a,b,c,d)$. In most cases a quick decision is reached.
29512 The result is $+1$, 0, or~$-1$ in the three respective cases.
29513
29514 @d return_sign(A) {@+return A;
29515 }
29516
29517 @<Declare \Prote\ arithmetic routines@>=
29518 static int ab_vs_cd(int @!a, int b, int c, int d)
29519 {@+
29520 int @!q, @!r; /*temporary registers*/
29521 @<Reduce to the case that |a,c>=0|, |b,d>0|@>;
29522 loop@+{@+q=a/d;r=c/b;
29523 if (q!=r)
29524 if (q > r) return_sign(1)@;@+else return_sign(-1);
29525 q=a%d;r=c%b;
29526 if (r==0)
29527 if (q==0) return_sign(0)@;@+else return_sign(1);
29528 if (q==0) return_sign(-1);
29529 a=b;b=q;c=d;d=r;
29530 } /*now |a > d > 0| and |c > b > 0|*/
29531 }
29532
29533 @ @<Reduce to the case that |a...@>=
29534 if (a < 0)
29535 {@+negate(a);negate(b);
29536 }
29537 if (c < 0)
29538 {@+negate(c);negate(d);
29539 }
29540 if (d <= 0)
29541 {@+if (b >= 0)
29542 if (((a==0)||(b==0))&&((c==0)||(d==0))) return_sign(0)@;
29543 else return_sign(1);
29544 if (d==0)
29545 if (a==0) return_sign(0)@;@+else return_sign(-1);
29546 q=a;a=c;c=q;q=-b;b=-d;d=q;
29547 }
29548 else if (b <= 0)
29549 {@+if (b < 0) if (a > 0) return_sign(-1);
29550 if (c==0) return_sign(0)@;else return_sign(-1);
29551 }
29552
29553 @ Finally, a normal deviate with mean zero and unit standard deviation
29554 can readily be obtained with the ratio method (Algorithm 3.4.1R in
29555 {\sl The Art of Computer Programming\/}).
29556
29557 @<Declare \Prote\ arithmetic routines@>=
29558 static scaled norm_rand(void)
29559 {@+int @!x, @!u, @!l; /*what the book would call $2^{16}X$, $2^{28}U$,
29560 and $-2^{24}\ln U$*/
29561 @/do@+{
29562 @/do@+{next_random;
29563 x=take_mpfract(112429, randoms[j_random]-mpfract_half);
29564 /*$2^{16}\sqrt{8/e}\approx 112428.82793$*/
29565 next_random;u=randoms[j_random];
29566 }@+ while (!(abs(x) < u));
29567 x=make_mpfract(x, u);
29568 l=139548960-m_log(u); /*$2^{24}\cdot12\ln2\approx139548959.6165$*/
29569 }@+ while (!(ab_vs_cd(1024, l, x, x) >= 0));
29570 return x;
29571 }
29572
29573 @ This can be used by calling the following primitive.
29574
29575 @<Generate all \Prote\ primitives@>=
29576 if (pdf_on)
29577 primitive("pdfnormaldeviate", convert, normal_deviate_code);@/
29578 @!@:normal\_deviate\_}{\.{\\pdfnormaldeviate} primitive@>
29579 else
29580 primitive("normaldeviate", convert, normal_deviate_code);@/
29581 @!@:normaldeviate\_}{\.{\\normaldeviate} primitive@>
29582
29583
29584 @ @<Cases of |convert| for |print_cmd_chr|@>=
29585 case normal_deviate_code:
29586 if (pdf_on) print_esc("pdfnormaldeviate");
29587 else print_esc("normaldeviate");
29588 @+break;
29589
29590
29591 @ @<Cases of `Scan the argument for command |c|'@>=
29592 case normal_deviate_code: cur_val=norm_rand();@+break;
29593
29594 @ @<Cases of `Print the result of command |c|'@>=
29595 case normal_deviate_code: print_int(cur_val);@+break;
29596
29597 @*1 DVI related primitives.
29598
29599 These primitives are related to positions in the DVI output.
29600
29601 The \TeX\ and DVI system coordinates relate to an origin that is at the
29602 upper left corner. The \TeX\ coordinates are computed relative to an
29603 origin that has $(0,0)$ coordinates. Coordinates grow then rightward and
29604 downward. This is the {\sl page} coordinates relative to what is
29605 typeset (what \TeX\ is dealing with).
29606
29607 But this typesetting material has to be put on what we will call {\sl
29608 paper}. The material put into shape by \TeX\ is put on the paper. On
29609 this paper, where will be put the \TeX\ origin? It is considered to be
29610 $1in$ at the right and $1in$ down from the upper left corner of the
29611 paper (see m.590, alinea 2).
29612
29613 @d DVI_std_x_offset 4736286 /*1 inch in sp*/
29614 @d DVI_std_y_offset 4736286 /*1 inch in sp*/
29615
29616 @ But the paper size is not specified in the DVI file and is not being
29617 dealt with by \TeX.
29618
29619 In order to have a common reference point, and since the \.{\\lastxpos}
29620 and \.{\\lastypos} primitives originated in pdf\TeX, these two
29621 primitives give positions, in scaled points, relative to the lower left
29622 corner of the paper.
29623
29624 Hence the need, for these primitive, to define the paper size, with the
29625 (misnamed) \.{\\pagewidth} and \.{\\pageheight}.
29626
29627 \.{\\pagewidth} and \.{\\pageheight} are dimension parameters,
29628 initialized to $0$ by the generic \TeX\ code.
29629
29630 @<Generate all \Prote\ primitives@>=
29631 if (!pdf_on) {
29632 primitive("pdfpagewidth", assign_dimen, dimen_base+page_width_code);@/
29633 @!@:pdf\_page\_width\_}{\.{\\pdfpagewidth} primitive@>
29634 primitive("pdfpageheight", assign_dimen, dimen_base+page_height_code);@/
29635 @!@:pdf\_page\_height\_}{\.{\\pdfpageheight} primitive@>
29636 } else {
29637 primitive("pagewidth", assign_dimen, dimen_base+page_width_code);@/
29638 @!@:pagewidth\_}{\.{\\pagewidth} primitive@>
29639 primitive("pageheight", assign_dimen, dimen_base+page_height_code);@/
29640 @!@:pageheight\_}{\.{\\pageheight} primitive@>
29641 }
29642
29643
29644
29645 @ When instructed to, the \.{h} and \.{v} last values are transformed,
29646 in the coordinates system defined above and saved in the global
29647 variables |last_saved_xpos| and |last_saved_ypos|. They are
29648 initialized to $0$ and we do not make any verification that a
29649 call to the \.{\\savepos} primitive---to come---has been made before
29650 retrieving their values.
29651
29652 @<Global...@>=
29653 static scaled @!last_saved_xpos, last_saved_ypos; /*last (x,y) DVI pos saved*/
29654
29655 @ @<\Prote\ initializations@>=
29656 last_saved_xpos=0;last_saved_ypos=0;
29657
29658 @ @<Set |last_saved_xpos| and |last_saved_ypos| with transformed coordinates@>=
29659 last_saved_xpos=cur_h+DVI_std_x_offset;
29660 last_saved_ypos=page_height-(cur_v+DVI_std_y_offset);
29661
29662 @ @<Generate all \Prote\ primitives@>=
29663 if (!pdf_on) {
29664 primitive("pdflastxpos", last_item, last_xpos_code);@/
29665 @!@:pdflastxpos\_}{\.{\\pdflastxpos} primitive@>
29666 primitive("lastypos", last_item, last_ypos_code);@/
29667 @!@:pdflastypos\_}{\.{\\pdflastypos} primitive@>
29668 } else {
29669 primitive("lastxpos", last_item, last_xpos_code);@/
29670 @!@:lastxpos\_}{\.{\\lastxpos} primitive@>
29671 primitive("lastypos", last_item, last_ypos_code);@/
29672 @!@:lastypos\_}{\.{\\lastypos} primitive@>
29673 }
29674
29675 @ @<Cases of |last_item| for |print_cmd_chr|@>=
29676 case last_xpos_code:
29677 if (pdf_on) print_esc("pdflastxpos");
29678 else print_esc("lastxpos");
29679 @+break;
29680 case last_ypos_code:
29681 if (pdf_on) print_esc("pdflastypos");
29682 else print_esc("lastypos");
29683 @+break;
29684
29685 @ @<Cases for fetching a \Prote\ int value@>=
29686 case last_xpos_code: cur_val=last_saved_xpos;@+break;
29687 case last_ypos_code: cur_val=last_saved_ypos;
29688
29689 @ |last_saved_xpos| and |last_saved_ypos| are only defined when
29690 instructed to by the call the the \.{\\savepos} primitive. Since the
29691 real work has to be done at \.{shipout} time, it is a case to be treated
29692 like the \.{\\special} primitive, that is it belongs to the
29693 \.{extension} class.
29694
29695 We will add something more in the handling of the primitive: it will
29696 insert a \.{whatsit} in the DVI file so that one, using the program
29697 |dvitype|, could retrieve more than one {\it hic}. So there is a counter
29698 incremented whenever the primitive is called.
29699
29700 @<Global...@>=
29701 static int last_save_pos_number; /*identifying the order of the call*/
29702
29703 @ @<\Prote\ initializations@>=
29704 last_save_pos_number=0; /*i.e. none*/
29705
29706 @ @<Generate all \Prote\ primitives@>=
29707 if (pdf_on)
29708 primitive("pdfsavepos", extension, save_pos_code);@/
29709 @!@:pdf\_save\_pos\_}{\.{\\pdfsavepos} primitive@>
29710 else
29711 primitive("savepos", extension, save_pos_code);@/
29712 @!@:savepos\_}{\.{\\savepos} primitive@>
29713
29714
29715 @ @<Cases of |extension| for |print_cmd_chr|@>=
29716 case save_pos_code:
29717 if (pdf_on) print_esc("pdfsavepos");
29718 else print_esc("savepos");
29719 @+break;
29720 @ @<Cases for |do_extension|@>=
29721 case save_pos_code: @<Implement \.{\\savepos}@>@;@+break;
29722
29723 @ We need the basic two words node, since we don't pass any parameter
29724 and it is just an instruction to do something. So the \.{whatsit} node
29725 is just the call.
29726
29727 @<Implement \.{\\savepos}@>=
29728 {@+new_whatsit(save_pos_code, small_node_size);write_stream(tail)=null;
29729 write_tokens(tail)=null;
29730 }
29731
29732 @ @<Cases for displaying the |whatsit| node@>=
29733 case save_pos_code:
29734 if (pdf_on) print_esc("pdfsavepos");
29735 else print_esc("savepos");
29736 @+break;
29737 @ @<Cases for making a partial copy of the whatsit node@>=
29738 case save_pos_code: {@+r=get_node(small_node_size);
29739 words=small_node_size;
29740 } @+break;
29741
29742 @ @<Cases for wiping out the whatsit node@>=
29743 case save_pos_code: free_node(p, small_node_size);@+break;
29744
29745 @ So, after these trivial initializations, what will we effectively do?
29746 When the following procedure will be called, we define |last_saved_xpos|,
29747 |last_saved_ypos|, increment |last_save_pos_number|, and a |warning|
29748 followed by three
29749 |key==value| space separated definitions as a \.{\\special}, the first
29750 being prefixed by the string |__PROTE_| (shall be considered a reserved
29751 prefix) and the string |SAVEPOS_|, equal to the index of the call, and
29752 the |XPOS| and |YPOS| definitions.
29753
29754 This is obviously, from the previous description, a variation around
29755 |special_out|.
29756
29757 @<Declare procedures needed in |out_what|@>=
29758 static void save_pos_out(pointer @!p)
29759 {@+int old_setting; /*holds print |selector|*/
29760 int @!k; /*index into |str_pool|*/
29761 synch_h;synch_v;incr(last_save_pos_number);
29762 @<Set |last_saved_xpos| and |last_saved_ypos|...@>@;
29763 old_setting=selector;selector=new_string;
29764 print("warning __PROTE_");print("SAVEPOS");print_char('=');
29765 print_int(last_save_pos_number);print_char(' ');
29766 print("XPOS");print("=");print_int(last_saved_xpos);print_char(' ');
29767 print("YPOS");print("=");print_int(last_saved_ypos);
29768 selector=old_setting;
29769 str_room(1); /*abort if probably overflowed and truncated*/
29770 dvi_out(xxx1);dvi_out(cur_length); /*it's less than 256*/
29771 for (k=str_start[str_ptr]; k<=pool_ptr-1; k++) dvi_out(so(str_pool[k]));
29772 pool_ptr=str_start[str_ptr]; /*forget the not commited tentative string*/
29773 }
29774
29775 @ @<Cases for |out_what|@>=
29776 case save_pos_code: save_pos_out(p);@+break;
29777
29778 @* System-dependent changes.
29779 This section should be replaced, if necessary, by any special
29780 modifications of the program
29781 that are necessary to make \TeX\ work at a particular installation.
29782 It is usually best to design your change file so that all changes to
29783 previous sections preserve the section numbering; then everybody's version
29784 will be consistent with the published program. More extensive changes,
29785 which introduce new sections, can be inserted here; then only the index
29786 itself will get a new section number.
29787 @^system dependencies@>
29788
29789 @* \TeX\ Live Integration.
29790 A \TeX\ engine that aspires
29791 to become a member of the \TeX\ Live family of programs
29792 must
29793
29794 $-$ respect the \TeX\ Live conventions for command line parameters,\par
29795 $-$ find its input files using the \.{kpathsearch} library, and\par
29796 $-$ implement \TeX\ primitives to support
29797 \LaTeX.
29798
29799 \noindent Naturally, the functions that follow here are taken, with small
29800 modifications, from the \TeX\ Live sources. What is
29801 added here, or rather subtracted here, are the parts that are specific
29802 to some of the \TeX\ engines included in \TeX\ Live. New is also
29803 that the code is presented in literate programming style.
29804
29805 The code that follows is organized in three parts.
29806 Some code for \TeX\ Live must come before
29807 the definition of \TeX's macros because
29808 it uses include files containing identifiers that are in conflict
29809 with \TeX's macros or modify these macros. For example
29810 \TeX's |banner| is modified by adding the \TeX\ Live version.
29811
29812 @<Header files and function declarations@>=
29813 #ifdef WEB2CVERSION
29814 #define TL_VERSION "(TeX Live "WEB2CVERSION")"
29815 #else
29816 #define TL_VERSION
29817 #endif
29818
29819 @ The remaining two parts are first auxiliary variables and functions and then
29820 those functions that are called from the ``classic'' \TeX\ code.
29821
29822 @p @<\TeX\ Live auxiliary variables@>@;
29823 @<\TeX\ Live auxiliary functions@>@;
29824 @<\TeX\ Live functions@>@;
29825
29826 @
29827 Most of the code that we present next comes together in the
29828 function |main_init|
29829 which is the first function called in the main program of a \TeX\ engine
29830 belonging to \TeX\ Live. Before doing so, we make copies of
29831 argument count and argument vector putting them in global variables.
29832 @<Global...@>=
29833 static char **argv;
29834 static int argc;
29835
29836 @ @<\TeX\ Live functions@>=
29837 static void main_init(int ac, char *av[])
29838 {@+
29839 char* main_input_file;
29840 argc = ac;
29841 argv = av;
29842 interaction = error_stop_mode;
29843 kpse_record_input = recorder_record_input;
29844 kpse_record_output = recorder_record_output;
29845
29846 @<parse options@>@;
29847 @<set the program and engine name@>@;
29848 @<activate configuration lines@>@;
29849 @<set the input file name@>@;
29850 @<set defaults from the {\tt texmf.cfg} file@>@;
29851 @<set the format name@>@;
29852 @<enable the generation of input files@>@;
29853 }
29854
29855 @ @<Forward declarations@>=
29856 static void main_init(int ac, char *av[]);
29857
29858
29859 @*1 Command Line.
29860 Let's begin with the beginning: the command line.
29861 To see how a command line is structured, we first look at the
29862 help text that is displayed if the user asks for it (or if \TeX\
29863 decides that the user needs it). The help text is produced by the
29864 function |usage_help|.
29865 \def\SP{ }% disable visible spaces in strings.
29866
29867 @<\TeX\ Live auxiliary functions@>=
29868 static void usage_help(void)
29869 {@+@<explain the command line@>@;
29870 fprintf(stdout,"Options:\n"@,@[@<explain the options@>@]);
29871 fprintf(stdout,"\nFor further information and reporting bugs see https://hint.userweb.mwn.de/\n");
29872 exit(0);
29873 }
29874
29875 @ The command line comes in three slightly different versions:
29876
29877 @<explain the command line@>=
29878 fprintf(stdout,@/
29879 "Usage: %s [OPTION]... [TEXNAME[.tex]] [COMMANDS]\n"@/
29880 " or: %s [OPTION]... \\FIRST-LINE\n"@/
29881 " or: %s [OPTION]... &FMT ARGS\n\n",@/
29882 argv[0],argv[0],argv[0]);@/
29883 fprintf(stdout,@/
29884 " Run TeX on TEXNAME, creating TEXNAME.dvi.\n"@/
29885 " Any remaining COMMANDS are processed\n"@/
29886 " as TeX input after TEXNAME is read.\n"@/
29887 " If the first line of TEXNAME starts with %%&FMT, and FMT is\n"@/
29888 " an existing .fmt file, use it. Else use `NAME.fmt', where\n"@/
29889 " NAME is the program invocation name.\n"@/
29890 "\n"@/
29891 " Alternatively, if the first non-option argument begins\n"@/
29892 " with a backslash, interpret all non-option arguments as\n"@/
29893 " a line of TeX input.\n"@/
29894 "\n"@/
29895 " Alternatively, if the first non-option argument begins\n"@/
29896 " with a &, the next word is taken as the FMT to read,\n"@/
29897 " overriding all else. Any remaining arguments are\n"@/
29898 " processed as above.\n"@/
29899 "\n"@/
29900 " If no arguments or options are specified, prompt for input.\n"@/
29901 "\n");
29902
29903
29904 @*1 Options.
29905 Here is the list of possible options and their explanation:
29906
29907 @<explain the options@>=
29908 " -help "@/
29909 @t\qquad@>"\t display this help and exit\n"@/
29910 " -version "@/
29911 @t\qquad@>"\t output version information and exit\n"@/
29912 " -etex "@/
29913 @t\qquad@>"\t enable e-TeX extensions\n"@/
29914 " -ltx "@/
29915 @t\qquad@>"\t enable LaTeX extensions, implies -etex\n"@/
29916 " -ini "@/
29917 @t\qquad@>"\t be initex for dumping formats; this is\n"@/
29918 @t\qquad@>"\t\t\t also true if the program name is `kinitex'\n"@/
29919 " -progname=STRING "@/
29920 @t\qquad@>"\t set program (and fmt) name to STRING\n"@/
29921 " -fmt=FMTNAME "@/
29922 @t\qquad@>"\t use FMTNAME instead of program name or a %%& line\n"@/
29923 " -output-directory=DIR "@/
29924 @t\qquad@>"\t use existing DIR as the directory to write files to\n"@/
29925 " -jobname=STRING "@/
29926 @t\qquad@>"\t set the TeX \\jobname to STRING\n"@/
29927 " [-no]-mktex=FMT "@/
29928 @t\qquad@>"\t disable/enable mktexFMT generation (FMT=tex/tfm/fmt)\n"@/
29929 " -interaction=STRING "@/
29930 @t\qquad@>"\t set interaction mode (STRING=batchmode/\n"@/
29931 @t\qquad@>"\t\t\t nonstopmode/scrollmode/errorstopmode)\n"@/
29932 " -kpathsea-debug=NUMBER"@/
29933 @t\qquad@>"\t set path searching debugging flags according\n"@/
29934 @t\qquad@>"\t\t\t to the bits of NUMBER\n"@/
29935 " -recorder"@/
29936 @t\qquad@>"\t\t enable filename recorder\n"@/
29937 " [-no]-parse-first-line"@/
29938 @t\qquad@>"\t disable/enable parsing of the first line of\n"@/
29939 @t\qquad@>"\t\t\t the input file\n"@/
29940 " [-no]-file-line-error"@/
29941 @t\qquad@>"\t disable/enable file:line:error style\n"@/
29942 " -cnf-line=STRING"@/
29943 @t\qquad@>"\t process STRING like a line in texmf.cnf\n"@/
29944
29945
29946 @ The processing of command line options is controlled by the |long_options|
29947 \def\SP{{\tt\char`\ }}% restore the visible space in a string
29948 array. Each entry in this array contains first the name of the option,
29949 then a flag that tells whether the option takes an argument or not.
29950 If next the (optional) address of a flag variable is given,
29951 it is followed by the value to store in the flag variable.
29952 In this case, setting the flag variable is handled by
29953 the |getopt_long_only| function.
29954
29955 Besides the flag variables that occur in the table,
29956 a few string variables may be set using the options.
29957 The following is a complete list of these variables.
29958 Variables are initialized with |-1| to indicate an undefined value;
29959 string variables are initialized with |NULL|.
29960
29961 @<Global variables@>=
29962 static int iniversion=false, etexp=false, ltxp=false, recorder_enabled=false;
29963 static int parsefirstlinep=-1, filelineerrorstylep=-1, interaction_option=-1;
29964 static const char *user_progname=NULL, *output_directory=NULL, *c_job_name=NULL,
29965 *dump_name=NULL;@#
29966
29967 @ @<\TeX\ Live auxiliary variables@>=
29968 static struct option long_options[] = {@/
29969 { "help", 0, 0, 0 },@/
29970 { "version", 0, 0, 0 },@/
29971 { "interaction", 1, 0, 0 },@/
29972 { "mktex", 1, 0, 0 },@/
29973 { "no-mktex", 1, 0, 0 },@/
29974 { "kpathsea-debug", 1, 0, 0 },@/
29975 { "progname", 1, 0, 0 },@/
29976 { "fmt", 1, 0, 0 },@/
29977 { "output-directory", 1, 0, 0 },@/
29978 { "jobname", 1, 0, 0 },@/
29979 { "cnf-line", 1, 0, 0 },@/
29980 { "ini", 0, &iniversion, 1 },@/
29981 { "etex", 0, &etexp, 1 },@/
29982 { "ltx", 0, &ltxp, 1 },@/
29983 { "recorder", 0, &recorder_enabled, 1 },@/
29984 { "parse-first-line", 0, &parsefirstlinep, 1 },@/
29985 { "no-parse-first-line", 0, &parsefirstlinep, 0 },@/
29986 { "file-line-error", 0, &filelineerrorstylep, 1 },@/
29987 { "no-file-line-error", 0, &filelineerrorstylep, 0 },@/
29988 @<more options@>@/
29989 { 0, 0, 0, 0 }@+}@+;
29990
29991
29992 @ Parsing the command line options is accomplished with the
29993 |parse_options| function which in turn uses the |getopt_long_only|
29994 function from the \CEE/ library. This function returns 0 and sets the
29995 |option_index| parameter to the option found, or it returns $-1$ if
29996 the end of all options is reached.
29997 @<\TeX\ Live functions@>=
29998 static void parse_options (int argc, char *argv[])
29999 {@+ while (true) {
30000 int option_index;
30001 int g = getopt_long_only (argc, argv, "+", long_options, &option_index);
30002 if (g==0)
30003 { @<handle the options@>@;@+ }
30004 else if (g == '?')
30005 { fprintf(stderr,"Try '%s --help' for more information\n",argv[0]);
30006 exit(1);
30007 }
30008 else if (g == -1) break;
30009 }
30010 @<Check the environment for extra settings@>@;
30011 }
30012
30013 @ @<Forward declarations@>=
30014 static void parse_options (int argc, char *argv[]);
30015
30016 @ Before we can call the |parse_options| function,
30017 we might need some special preparations for Windows.
30018
30019 @<parse options@>=
30020 #if defined(WIN32)
30021 {@+ char* enc;
30022 kpse_set_program_name (argv[0], NULL);
30023 enc = kpse_var_value("command_line_encoding");
30024 get_command_line_args_utf8(enc, &argc, &argv);@/
30025 parse_options (argc, argv);
30026 @<record {\tt texmf.cnf}@>@;
30027 }
30028 #else
30029 parse_options (ac, av);
30030 #endif
30031
30032
30033 @ To handle the options, we compare the name at the given |option_index| with
30034 the different option names. This is not a very efficient method, but the
30035 impact is low and it's simple to write.
30036
30037 Comparing the name of the argument with the |name| field in the |option|
30038 structure is done in the auxiliary function |argument_is|.
30039 Unfortunately the |name| field is in conflict with the |name| macro
30040 defined by \TeX. To avoid the conflict, the |argument_is| function
30041 goes just after the \.{kpathsea.h} header file that defines
30042 the option structure.
30043
30044
30045 @<Header files and function declarations@>=
30046 #include <kpathsea/kpathsea.h>
30047 static int argument_is(struct option *opt, char * s)
30048 {@+ return STREQ(opt->name, s); @+}
30049 #define ARGUMENT_IS(S) argument_is(long_options+option_index,S)
30050
30051 @ Now we can handle the first two options:
30052
30053 @<handle the options@>=
30054 if (ARGUMENT_IS("help")) usage_help();
30055 else if (ARGUMENT_IS("version")){@+
30056 printf("TeXprof Version "@, TeXprof_version@; "\n"@/
30057 "\tis based on TeX Version "@, TeX_version_string@, "\n"@/
30058 "\tusing eTeX Version "@, eTeX_version_string@, "\n"@/
30059 "\tusing Prote Version "@, Prote_version_string@, "\n");
30060 exit(0);@+
30061 }
30062
30063
30064 @ The ``interaction'' option sets the |interaction_option| variable
30065 based on its string argument contained in the |optarg| variable.
30066 If defined, the |interaction_option| will be used to set \TeX's
30067 |interaction| variable in the |initialize| and the |undump| functions.
30068
30069 @<handle the options@>=
30070 else @+if (ARGUMENT_IS ("interaction"))@t\2@> {
30071 if (STREQ (optarg, "batchmode")) interaction_option = batch_mode;
30072 else if (STREQ (optarg, "nonstopmode")) interaction_option = nonstop_mode;
30073 else if (STREQ (optarg, "scrollmode")) interaction_option = scroll_mode;
30074 else if (STREQ (optarg, "errorstopmode")) interaction_option = error_stop_mode;
30075 else WARNING1 ("Ignoring unknown argument `%s' to --interaction", optarg);
30076 }
30077
30078 @ The next two options pass the string argument to the
30079 \.{kpathsearch} library.
30080
30081 @<handle the options@>=
30082 else @+if (ARGUMENT_IS ("mktex")) @t\2@> kpse_maketex_option (optarg, true);
30083 else if (ARGUMENT_IS ("no-mktex")) kpse_maketex_option (optarg, false);
30084
30085
30086 @ To debug the searching done by the \.{kpathsearch} library,
30087 the following option can be used.
30088 The argument value 3 is a good choice to start with.
30089
30090 @<handle the options@>=
30091 else @+if (ARGUMENT_IS ("kpathsea-debug")) @t\2@>
30092 kpathsea_debug |= atoi (optarg);
30093
30094
30095
30096 @ The next set of options take a string argument
30097 and assign it to the corresponding string variable.
30098
30099 @<handle the options@>=
30100 else @+if (ARGUMENT_IS ("progname"))@t\2@>
30101 user_progname = normalize_quotes(optarg,"program name");
30102 else if (ARGUMENT_IS ("fmt"))
30103 dump_name = normalize_quotes(optarg,"format name");
30104 else if (ARGUMENT_IS ("output-directory"))
30105 output_directory = normalize_quotes(optarg,"output directory");
30106 else if (ARGUMENT_IS ("jobname"))
30107 c_job_name = normalize_quotes (optarg, "job name");
30108
30109 @ When string arguments specify files or directories,
30110 special care is needed if arguments are quoted and/or contain spaces.
30111 The function |normalize_quotes| makes sure that arguments containing
30112 spaces get quotes around them and it checks for unbalanced quotes.
30113
30114
30115 @<\TeX\ Live auxiliary functions@>=
30116 static char *normalize_quotes (const char *nom, const char *mesg)
30117 {@+ int quoted = false;
30118 int must_quote = (strchr(nom, ' ') != NULL);
30119 char *ret = xmalloc(strlen(nom)+3);/*room for two quotes and NUL*/
30120 char *p=ret;
30121 const char *q;
30122
30123 if (must_quote)
30124 *p++ = '"';
30125 for (q = nom; *q; q++)
30126 if (*q == '"')
30127 quoted = !quoted;@+
30128 else
30129 *p++ = *q;
30130
30131 if (must_quote)
30132 *p++ = '"';
30133 *p = '\0';
30134 if (quoted) {
30135 fprintf(stderr, "! Unbalanced quotes in %s %s\n", mesg, nom);
30136 exit(1);
30137 }
30138 return ret;
30139 }
30140
30141 @ If the output directory was specified on the command line,
30142 we save it in an environment variable so that subbrocesses can
30143 get the value. If on the other hand the environment specifies
30144 a directory and the command line does not, save the value from
30145 the environment to the global variable so that it is used in the
30146 rest of the code.
30147
30148 @<Check the environment for extra settings@>=
30149 if (output_directory)
30150 xputenv ("TEXMF_OUTPUT_DIRECTORY", output_directory);
30151 else if (getenv ("TEXMF_OUTPUT_DIRECTORY"))
30152 output_directory = getenv ("TEXMF_OUTPUT_DIRECTORY");
30153
30154 @*1 Passing a file name as a general text argument.
30155
30156 |scan_file_name| uses the following code to parse a file name given
30157 as a general text argument. Such an argument can be any token list
30158 starting with a left brace and ending with a right brace.
30159 This token list is then expanded (without the leading and trailing braces)
30160 and printed into the string pool without making it yet an official string.
30161 After removing all double quotes, because this is current practice
30162 for \TeX\ engines that are part of \TeX\ Live,
30163 and setting the area and extension delimiters,
30164 all temporary garbage used so far is freed.
30165
30166 Due to the expansion of the token list, this code and hence the
30167 |scan_file_name| procedure is recursive.
30168 One can provide the name of a file as the content of an other file.
30169
30170
30171 % Thierry Laronde
30172 @<Define a general text file name and |goto done|@>=
30173 {@+back_input();name_in_progress=false; /*this version is recursive...*/
30174 cur_cs=input_loc; /*|scan_toks| will set |warning_index| from it*/
30175 scan_general_x_text();
30176 old_setting=selector;selector=new_string;
30177 token_show(link(garbage));selector=old_setting;
30178 @<Suppress double quotes in braced input file name@>@;
30179 j=pool_ptr-1;while ((j >= str_start[str_ptr])&&(area_delimiter==0))
30180 {@+
30181 if ((str_pool[j]=='/')) area_delimiter=j-str_start[str_ptr];
30182 if ((ext_delimiter==0)&&(str_pool[j]=='.'))
30183 ext_delimiter=j-str_start[str_ptr];
30184 decr(j);
30185 }
30186 flush_list(link(garbage));
30187 goto done;
30188 }
30189
30190 @ A simple loop removes the double quotes and adjusts the |pool_ptr|.
30191
30192 @<Suppress double quotes in braced input file name@>=
30193 for (k=j=str_start[str_ptr]; k < pool_ptr; k++) {@+
30194 if (str_pool[k]!='"') {@+str_pool[j]=str_pool[k];incr(j);}
30195 }
30196 pool_ptr=j;
30197
30198 @*1 The {\tt -recorder} Option.
30199 The recorder option can be used to enable the file name recorder.
30200 It is crucial for getting a reliable list of files used in a given run.
30201 Many post-processors use it, and it is used in \TeX\ Live for
30202 checking the format building infrastructure.
30203
30204 When we start the file name recorder,
30205 we would like to use mkstemp, but it is not portable,
30206 and doing the autoconfiscation (and providing fallbacks) is more
30207 than we want to cope with. So we have to be content with using a
30208 default name. We throw in the pid so at least parallel builds might
30209 work. Windows, however, seems to have no |pid_t|, so instead of storing the
30210 value returned by |getpid|, we immediately consume it.
30211
30212 @<\TeX\ Live auxiliary functions@>=
30213 static char *recorder_name=NULL;
30214 static FILE *recorder_file=NULL;
30215 static void
30216 recorder_start(void)
30217 { char *cwd;
30218 char pid_str[MAX_INT_LENGTH];
30219 sprintf (pid_str, "%ld", (long) getpid());
30220 recorder_name = concat3(kpse_program_name, pid_str, ".fls");
30221 if (output_directory) {
30222 char *temp = concat3(output_directory, DIR_SEP_STRING, recorder_name);
30223 free(recorder_name);
30224 recorder_name = temp;
30225 }
30226 recorder_file = xfopen(recorder_name, FOPEN_W_MODE);
30227 cwd = xgetcwd();
30228 fprintf(recorder_file, "PWD %s\n", cwd);
30229 free(cwd);
30230 }
30231
30232 @ After we know the log file name, we have used |recorder_change_filename|
30233 to change the name of the recorder file to the usual thing.
30234 @<Forward declarations@>=
30235 static void recorder_change_filename (const char *new_name);
30236
30237 @ Now its time to define this function.
30238 Unfortunately, we have to explicitly take
30239 the output directory into account, since the new name we are
30240 called with does not; it is just the log file name with {\tt .log}
30241 replaced by {\tt .fls}.
30242
30243 @ @<\TeX\ Live auxiliary functions@>=
30244 static void
30245 recorder_change_filename (const char *new_name)
30246 { char *temp = NULL;
30247 if (!recorder_file)
30248 return;
30249 #if defined(_WIN32)
30250 fclose (recorder_file); /* An open file cannot be renamed. */
30251 #endif /* |_WIN32| */
30252 if (output_directory) {
30253 temp = concat3(output_directory, DIR_SEP_STRING, new_name);
30254 new_name = temp;
30255 }
30256
30257 #if defined(_WIN32)
30258 remove (new_name); /* A file with the |new_name| must not exist. */
30259 #endif /* |_WIN32| */
30260 rename(recorder_name, new_name);
30261 free(recorder_name);
30262 recorder_name = xstrdup(new_name);
30263 #if defined(_WIN32)
30264 recorder_file = xfopen (recorder_name, FOPEN_A_MODE); /* A closed file must be opened. */
30265 #endif /* |_WIN32| */
30266 if (temp)
30267 free (temp);
30268 }
30269
30270 @ Now we are ready to record file names. The prefix INPUT is added
30271 to an input file and the prefix OUTPUT to an output file.
30272 But both functions for recording a file name use the same
30273 function otherwise, which on first use will start the recorder.
30274
30275 @<\TeX\ Live auxiliary functions@>=
30276 static void
30277 recorder_record_name (const char *pfx, const char *fname)
30278 { @+if (recorder_enabled) {
30279 if (!recorder_file)
30280 recorder_start();
30281 fprintf(recorder_file, "%s %s\n", pfx, fname);
30282 fflush(recorder_file);
30283 }
30284 }
30285
30286
30287 static void
30288 recorder_record_input (const char *fname)
30289 { recorder_record_name ("INPUT", fname);
30290 }
30291
30292 static void
30293 recorder_record_output (const char * fname)
30294 { recorder_record_name ("OUTPUT", fname);
30295 }
30296
30297 @ Because input files are also recorded when writing the optional sections,
30298 we need the following declaration.
30299
30300 @<Forward declarations@>=
30301 static void recorder_record_input (const char *fname);
30302
30303 @ In WIN32, texmf.cnf is not recorded in
30304 the case of {\tt -recorder}, because |parse_options| is executed
30305 after the start of kpathsea due to special initializations.
30306 Therefore we record {\tt texmf.cnf} with the following code:
30307
30308 @<record {\tt texmf.cnf}@>=
30309 if (recorder_enabled) {
30310 char **p = kpse_find_file_generic ("texmf.cnf", kpse_cnf_format, 0, 1);
30311 if (p && *p) {
30312 char **pp = p;
30313 while (*p) {
30314 recorder_record_input (*p);
30315 free (*p);
30316 p++;
30317 }
30318 free (pp);
30319 }
30320 }
30321
30322
30323
30324
30325 @*1 The {\tt -cnf-line} Option.
30326 With the \.{-cnf-line} option it is possible to specify
30327 a line of text as if this line were part of \TeX's configuration
30328 file---even taking precedence over conflicting lines in the configuration
30329 file. For example it is possible to change \TeX's
30330 \.{TEXINPUTS} variable by saying \.{--cnf-line=TEXINPUTS=/foo}.
30331 The configuration lines are temporarily stored in the variable
30332 |cnf_lines| and counted in |cnf_count| because we can send them
30333 to the \.{kpathsearch} library only after the library has been
30334 initialized sufficiently.
30335
30336 @<Global...@>=
30337 static char **cnf_lines=NULL;
30338 static int cnf_count=0;
30339
30340 @ @<handle the options@>=
30341 else @+if (ARGUMENT_IS ("cnf-line"))
30342 add_cnf_line(optarg);
30343
30344 @ The function |add_cnf_line| stores the
30345 given command line argument in the variable |cnf_lines|.
30346
30347 @<\TeX\ Live auxiliary functions@>=
30348 static void add_cnf_line(char *arg)
30349 {@+ cnf_count++;
30350 cnf_lines=xrealloc(cnf_lines,sizeof(char*)*cnf_count);
30351 cnf_lines[cnf_count-1]=arg;
30352 }
30353
30354 @ To activate the configuration lines they are passed to the
30355 \.{kpathsearch} library.
30356
30357 @<activate configuration lines@>=
30358 #if 1 /* this function does not exists always */
30359 {@+ int i;
30360 for (i=0;i<cnf_count;i++)
30361 kpathsea_cnf_line_env_progname (kpse_def, cnf_lines[i]);
30362 free(cnf_lines);
30363 }
30364 #endif
30365
30366
30367 @*1 The Input File.
30368 After we are done with the options,
30369 we inform the \.{kpathsearch} library about the program name.
30370 This is an important piece of information for the library
30371 because the library serves quite different programs
30372 and its behavior can be customized for each program
30373 using configuration files.
30374 After the program and engine name is set,
30375 the library is ready to use.
30376 @<set the program and engine name@>=
30377 if (!user_progname)
30378 user_progname = dump_name;
30379 #if defined(WIN32)
30380 if (user_progname)
30381 kpse_reset_program_name (user_progname);
30382 #else
30383 kpse_set_program_name (argv[0], user_progname);
30384 #endif
30385 xputenv ("engine", "texprof");@/
30386
30387
30388 @ After the options, the command line usually continues with the name of the input
30389 file. Getting a hold of the input file name can be quite complicated,
30390 but the \.{kpathsearch} library will help us to do the job.
30391
30392 We start by looking at the first argument after the options:
30393 If it does not start with an
30394 ``\.{\AM}'' and neither with a ``\.{\BS}'', it's a simple file name.
30395 Under Windows, however, filenames might start with a drive letter
30396 followed by a colon and a ``\.{\BS}'' which is used to separate
30397 directory names. Finally, if the filename is a quoted string, we need
30398 to remove the quotes before we use the \.{kpathsearch} library to find it
30399 and reattach the quotes afterward.
30400
30401 @<\TeX\ Live auxiliary functions@>=
30402 #ifdef WIN32
30403 static void clean_windows_filename(char *filename)
30404 {@+if (strlen (filename) > 2 && isalpha (filename[0]) &&
30405 filename[1] == ':' && filename[2] == '\\')
30406 { char *pp;
30407 for (pp = filename; *pp; pp++)
30408 if (*pp == '\\')
30409 *pp = '/';
30410 }
30411 }
30412 #endif
30413
30414 static char *find_file(char *fname, kpse_file_format_type t, int mx)
30415 {@+char *filename;
30416 int final_quote=(int)strlen(fname)-1;
30417 int quoted = final_quote>1 && fname[0] == '"' && fname[final_quote]=='"';
30418 if (quoted) {
30419 /* Overwrite last quote and skip first quote. */
30420 fname[final_quote] = '\0';
30421 fname++;
30422 }
30423 filename = kpse_find_file(fname, t, mx);
30424 if (full_name_of_file!=NULL)
30425 { free(full_name_of_file); full_name_of_file=NULL;}
30426 if (filename!=NULL)
30427 full_name_of_file=strdup(filename);
30428 if (quoted) {
30429 /* Undo modifications */
30430 fname--;
30431 fname[final_quote] = '"';
30432 }
30433 return filename;
30434 }
30435
30436 static char *get_input_file_name (void)
30437 {@+
30438 char *input_file_name = NULL;
30439
30440 if (argv[optind] && argv[optind][0] != '&' && argv[optind][0] != '\\')
30441 {
30442 #ifdef WIN32
30443 clean_windows_filename(argv[optind]);
30444 #endif
30445 argv[optind] = normalize_quotes(argv[optind], "input file");
30446 input_file_name=find_file(argv[optind],kpse_tex_format, false);
30447 }
30448 return input_file_name;
30449 }
30450
30451
30452 @ After we called |get_input_file_name|, we might need to look at |argv[argc-1]|
30453 in case we run under Windows.
30454
30455 @<set the input file name@>=
30456 main_input_file = get_input_file_name ();
30457
30458 #ifdef WIN32
30459 /* Were we given a simple filename? */
30460 if (main_input_file == NULL) {
30461 char *file_name=argv[argc-1];
30462 if (file_name && file_name[0] != '-' && file_name[0] != '&' && file_name[0] != '\\') {
30463 clean_windows_filename(file_name);
30464 file_name = normalize_quotes(file_name, "argument");
30465 main_input_file=find_file(file_name,kpse_tex_format, false);
30466 argv[argc-1] = file_name;
30467 }
30468 }
30469 #endif
30470
30471
30472 @ After we have an input file, we make an attempt at filling in options
30473 from the {\tt texmf.cfg} file.
30474
30475 @<set defaults from the {\tt texmf.cfg} file@>=
30476 if (filelineerrorstylep < 0)
30477 filelineerrorstylep = texmf_yesno ("file_line_error_style");
30478 if (parsefirstlinep < 0)
30479 parsefirstlinep = texmf_yesno ("parse_first_line");@/@t~@>
30480
30481 @ We needed:
30482 @<\TeX\ Live auxiliary functions@>=
30483 static int texmf_yesno(const char *var)
30484 {@+
30485 char *value = kpse_var_value (var);
30486 return value && (*value == 't' || *value == 'y' || *value == '1');
30487 }
30488
30489 @ We need a stack, matching the |line_stack| that
30490 contains the source file names. For the full source filenames we use
30491 poiters to |char| because these names are just used for output.
30492
30493 @<Global...@>=
30494 static char * @!source_filename_stack0[max_in_open]={NULL}, **const @!source_filename_stack = @!source_filename_stack0-1;
30495 static char * @!full_source_filename_stack0[max_in_open]={NULL}, **const @!full_source_filename_stack = @!full_source_filename_stack0-1;
30496 static char *full_name_of_file=NULL;
30497
30498 @ The function |print_file_line|
30499 prints ``file:line:error'' style messages using
30500 the |source_filename_stack|. If it fails to find the file name, it
30501 falls back to the ``non-file:line:error'' style.
30502
30503 @<Basic printing...@>=
30504 static void print_file_line(void)
30505 {@+int level=in_open;
30506 while (level>0 && full_source_filename_stack[level]==NULL) level--;
30507 if (level==0) print_nl("! ");
30508 else
30509 { print_nl(""); print(full_source_filename_stack[level]); print_char(':');
30510 if (level==in_open) print_int(line);
30511 else print_int(line_stack[level]);
30512 print(": ");
30513 }
30514 }
30515
30516 @*1 The Format File.
30517 Most of the time \TeX\ is not running as \.{initex}
30518 but it runs with a format file preloaded.
30519 To set the format name, we first check if the format name was given on the
30520 command line with an ``\.{\AM}'' prefix,
30521 second we might check the first line of the input file,
30522 and last, we check if the program is an initex program.
30523
30524 If we still don't have a format, the program
30525 name is our best guess.
30526 There is no need to check for an extension, because the
30527 \.{kpathsearch} library will take care of that.
30528 We store the format file name in |dump_name| which is
30529 used in the function |w_open_in| below.
30530
30531 @<set the format name@>=
30532 if (parsefirstlinep && !dump_name)
30533 parse_first_line (main_input_file);
30534 if (!main_input_file && argv[1] && argv[1][0] == '&')
30535 dump_name = argv[1] + 1;
30536 if (strcmp(kpse_program_name, "initexprof")==0) iniversion = true;
30537 if (!dump_name)
30538 dump_name = kpse_program_name;
30539 if (!dump_name)
30540 { fprintf(stderr,"Unable to determine format name\n");
30541 exit(1);
30542 }
30543 if (ltxp) etexp=1;
30544 if (etexp && !iniversion)
30545 { fprintf(stderr,"-etex and -ltx require -ini\n");
30546 exit(1);
30547 }
30548
30549 @ Here is the function |parse_first_line |. It searches the first line of
30550 the file for a \TeX\ comment of the form ``\%\AM format''\footnote{${}^1$}{The idea of using this format came from Wlodzimierz Bzyl.}.
30551 If found, we will use the format given there.
30552
30553 @<\TeX\ Live auxiliary functions@>=
30554 static void parse_first_line(char*filename)
30555 {@+ FILE *f=NULL;
30556 if (filename==NULL) return;
30557 f = open_in(filename,kpse_tex_format,"r");
30558 if (f!=NULL)
30559 { char *r,*s,*t=read_line (f);
30560 xfclose (f, filename);
30561 if (t==NULL) return;
30562 s=t;
30563 if (s[0] == '%' && s[1] == '&') {
30564 s = s+2;
30565 while ( ISBLANK(*s)) ++s;
30566 r=s;
30567 while (*s!=0 && *s!=' ' && *s!='\r' && *s!='\n') s++;
30568 *s=0;
30569 if (dump_name==NULL) {
30570 char *f_name = concat (r, format_extension);
30571 char *d_name = kpse_find_file (f_name,kpse_fmt_format, false);
30572 if (d_name && kpse_readable_file (d_name)) {
30573 dump_name = xstrdup (r);
30574 kpse_reset_program_name (dump_name);
30575 }
30576 free (f_name);
30577 }
30578 }
30579 free (t);
30580 }
30581 }
30582
30583 @*1 Commands.
30584 In the old days, \TeX\ was a \PASCAL\ program, and standard \PASCAL\
30585 did say nothing about a command line. So \TeX\ would open the terminal
30586 file for input and read all the information from the terminal.
30587 If you don't give \TeX\ command line arguments, this is still true today.
30588 In our present time, people got so much used to control the behavior
30589 of a program using command line arguments---especially when writing
30590 scripts---that \TeX\ Live allows the specification of commands on
30591 the command line which \TeX\ would normally expect on
30592 the first line of its terminal input.
30593
30594 So our next task is
30595 writing a function to add the remainder of the
30596 command line to \TeX's input buffer.
30597 The main job is done by the |input_add_str| function
30598 which duplicates part of the |input_ln| function.
30599 Further it skips initial spaces and replaces trailing spaces
30600 and line endings by a single space.
30601
30602 @<\TeX\ Live auxiliary functions@>=
30603 static void input_add_char(unsigned int c)
30604 {@+ if (last >= max_buf_stack)
30605 {@+max_buf_stack=last+1;
30606 if (max_buf_stack==buf_size)
30607 @<Report overflow of the input buffer, and abort@>;
30608 }
30609 buffer[last]=xord[c];incr(last);
30610 }
30611
30612 static void input_add_str(const char *str)
30613 {@+ int prev_last;
30614 while (*str==' ') str++;
30615 prev_last=last;
30616 while (*str!=0)
30617
30618 input_add_char(*str++);
30619 for (--last; last >= first ; --last)
30620 { char c =buffer[last];
30621 if ((c) != ' ' && (c) != '\r' && (c) != '\n') break;
30622 }
30623 last++;
30624 if (last>prev_last) input_add_char(' ');
30625 }
30626
30627 static int input_command_line(void)
30628 {@+
30629 last=first;
30630 while (optind < argc) input_add_str(argv[optind++]);
30631 loc=first;
30632 return (loc < last);
30633 @+ }
30634
30635 @ @<Forward declarations@>=
30636 static int input_command_line(void);
30637
30638
30639 @*1 Opening Files.
30640 When we open an output file, there is usually no searching necessary.
30641 In the best case, we have an absolute path and can open it.
30642 If the path is relative, we try in this order:
30643 the |file_name| prefixed by the |output_directory|,
30644 the |file_name| as is, and
30645 the |file_name| prefixed with the environment variable |TEXMFOUTPUT|.
30646
30647 If we were successful with one of the modified names, we update
30648 |name_of_file|.
30649
30650 @<\TeX\ Live functions@>=
30651 static FILE *open_out(const char *file_name, const char *file_mode)
30652 {@+ FILE *f=NULL;
30653 char *new_name=NULL;
30654 int absolute = kpse_absolute_p(file_name, false);
30655 if (absolute)
30656 { f=fopen(file_name,file_mode);
30657 if (f!=NULL) recorder_record_output (file_name);
30658 return f;
30659 }
30660 if (output_directory)
30661 { new_name = concat3(output_directory, DIR_SEP_STRING, file_name);
30662 f = fopen(new_name,file_mode);
30663 if (f==NULL) {@+ free(new_name); new_name=NULL;@+}
30664 }
30665 if (f==NULL)
30666 f = fopen(file_name,file_mode);
30667 if (f==NULL)
30668 { const char *texmfoutput = kpse_var_value("TEXMFOUTPUT");
30669 if (texmfoutput!=NULL && texmfoutput[0]!=0)
30670 { new_name = concat3(texmfoutput, DIR_SEP_STRING, file_name);@/
30671 f = fopen(new_name,file_mode);
30672 if (f==NULL) {@+ free(new_name); new_name=NULL; @+}
30673 }
30674 }
30675 if (f!=NULL && new_name!=NULL)
30676 update_name_of_file(new_name,(int)strlen(new_name));
30677 if (f!=NULL) recorder_record_output ((char*)name_of_file+1);
30678 if (new_name!=NULL) free(new_name);
30679 return f;
30680 }
30681
30682 static bool a_open_out(alpha_file *f) /*open a text file for output*/
30683 {@+f->f=open_out((char*)name_of_file+1,"w");
30684 return f->f!=NULL && ferror(f->f)==0;@+
30685 }
30686
30687 static bool b_open_out(byte_file *f) /*open a binary file for output*/
30688 {@+f->f=open_out((char *)name_of_file+1,"wb");
30689 return f->f!=NULL && ferror(f->f)==0;@+
30690 }
30691
30692 #ifdef @!INIT
30693 static bool w_open_out(word_file *f) /*open a word file for output*/
30694 {@+f->f=open_out((char *)name_of_file+1,"wb");
30695 return f->f!=NULL && ferror(f->f)==0;@+
30696 }
30697 #endif
30698
30699
30700 @ Format file names must be scanned
30701 before \TeX's string mechanism has been initialized.
30702 The function |update_name_of_file| will set |name_of_file| from
30703 a \CEE/ string.
30704
30705 We dare not give error messages here, since \TeX\ calls this routine before
30706 the |error| routine is ready to roll. Instead, we simply drop excess characters,
30707 since the error will be detected in another way when a strange file name
30708 isn't found.
30709 @^system dependencies@>
30710
30711 @<\TeX\ Live auxiliary functions@>=
30712 static void update_name_of_file(const char *@!s, int @!k)
30713 {@+ int j;
30714 if (k <= file_name_size) name_length=k;@+
30715 else name_length=file_name_size;
30716 for (j=0; j<name_length;j++) name_of_file[j+1]=xchr[(int)s[j]];
30717 name_of_file[name_length+1]=0;
30718 }
30719
30720 @ In standard \TeX, the |reset| macro is used to open input files.
30721 The \.{kpathsearch} library uses different search paths for
30722 different types of files and therefore different functions are needed to
30723 open these files. The common code is in the function |open_in|.
30724
30725 @<\TeX\ Live auxiliary functions@>=
30726 static FILE*open_in(char*filename,kpse_file_format_type t,const char*rwb)
30727 {@+ char *fname=NULL;
30728 FILE*f= NULL;
30729 fname= find_file(filename,t,true);
30730 if(fname!=NULL)
30731 {@+
30732 f= fopen(fname,rwb);
30733 if (f!=NULL) recorder_record_input(fname);
30734 if (full_name_of_file!=NULL) free(full_name_of_file);
30735 full_name_of_file=fname;@+
30736 }
30737 return f;
30738 }
30739
30740 static bool a_open_in(alpha_file *f) /*open a text file for input*/
30741 {@+f->f= open_in((char *)name_of_file+1,kpse_tex_format,"r");
30742 if (f->f!=NULL) get(*f);
30743 return f->f!=NULL && ferror(f->f)==0;
30744 }
30745
30746 static bool b_open_in(byte_file *f) /*open a binary file for input*/
30747 {@+f->f= open_in((char *)name_of_file+1,kpse_tfm_format,"rb");
30748 if (f->f!=NULL) get(*f);
30749 return f->f!=NULL && ferror(f->f)==0;
30750 }
30751
30752 static bool w_open_in(word_file *f) /*open a word file for input*/
30753 {@+
30754 f->f=NULL;
30755 if (name_of_file[1]!=0)
30756 f->f= open_in((char*)name_of_file+1,kpse_fmt_format,"rb");
30757 if (f->f!=NULL) get(*f);
30758 return f->f!=NULL && ferror(f->f)==0;
30759 }
30760
30761 @ \TeX's |open_fmt_file| function will call the following function
30762 either with the name of a format file as given with an ``\.{\AM}''
30763 prefix in the input or with |NULL| if no such name was specified.
30764 The function will try |dump_name| as a last resort before returning |NULL|.
30765
30766
30767
30768 @<\TeX\ Live functions@>=
30769 static bool open_fmt_file(void)
30770 {@+int j=loc;
30771 if (buffer[loc]=='&')
30772 {@+incr(loc);j=loc;buffer[last]=' ';
30773 while (buffer[j]!=' ') incr(j);
30774 update_name_of_file((char *)buffer+loc,j-loc);
30775 if (w_open_in(&fmt_file)) goto found;
30776 }
30777 update_name_of_file(dump_name,(int)strlen(dump_name));
30778 if (w_open_in(&fmt_file)) goto found;
30779 name_of_file[1]=0;
30780 wake_up_terminal;
30781 wterm_ln("I can't find a format file!");
30782 return false;
30783 found: loc=j;return true;
30784 }
30785
30786
30787 @ The \TeX\ Live infrastructure is able to generate format files,
30788 font metric files,
30789 and even some tex files, if required.
30790
30791 @<enable the generation of input files@>=
30792 kpse_set_program_enabled (kpse_tfm_format, MAKE_TEX_TFM_BY_DEFAULT,
30793 kpse_src_compile);@/
30794 kpse_set_program_enabled (kpse_tex_format, MAKE_TEX_TEX_BY_DEFAULT,
30795 kpse_src_compile);@/
30796 kpse_set_program_enabled (kpse_fmt_format, MAKE_TEX_FMT_BY_DEFAULT,
30797 kpse_src_compile);@/
30798
30799
30800
30801 @*1 Date and Time.
30802 We conclude this chapter using \.{time.h} to provide a function
30803 that is used to initialize
30804 \TeX's date and time information. Because |time| is one of \TeX's
30805 macros, we add the function |tl_now| before including \TeX's macros
30806 to wrap the call to the |time| function.
30807 It sets the variable |start_time| and returns a pointer to a |tm| structure
30808 to be used later in |fix_date_and_time|.
30809
30810 To support reproducible output, the environment variable |SOURCE_DATE_EPOCH|
30811 needs to be checked. If it is set, it is an ASCII representation of
30812 a UNIX timestamp, defined as the number
30813 of seconds, excluding leap seconds, since 01 Jan 1970 00:00:00 UTC.
30814 Its value is then used to initialize the |start_time| variable.
30815
30816 The \TeX\ Live conventions further require that setting the
30817 |FORCE_SOURCE_DATE| environment variable to $1$ will cause also \TeX's primitives
30818 \.{\\year}, \.{\\month}, \.{\\day}, and \.{\\time} to use this value
30819 as the current time. Looking at the \TeX\ Live code also reveals that
30820 these primitives use the local time instead of the GMT if this variable is
30821 not set to~1.
30822
30823 @<Header files and function declarations@>=
30824 #include <time.h>
30825 static time_t start_time = ((time_t)-1);
30826 static char *source_date_epoch,*force_source_date;
30827
30828 #if defined(_MSC_VER) && _MSC_VER < 1800
30829 #define strtoull _strtoui64
30830 #endif
30831
30832 static struct tm *tl_now(void)
30833 {@+struct tm *tp;
30834 time_t t;
30835 source_date_epoch= getenv("SOURCE_DATE_EPOCH");
30836 force_source_date= getenv("FORCE_SOURCE_DATE");
30837 if (force_source_date!=NULL &&
30838 (force_source_date[0]!='1' || force_source_date[1]!=0))
30839 force_source_date=NULL;
30840
30841 if (source_date_epoch!=NULL)
30842 { start_time= (time_t)strtoull(source_date_epoch, NULL, 10);
30843 if (force_source_date!=NULL)
30844 t=start_time;
30845 else
30846 t=time(NULL);
30847 }
30848 else
30849 t=start_time=time(NULL);
30850 if (force_source_date)
30851 tp=gmtime(&t);
30852 else
30853 tp=localtime(&t);
30854 return tp;
30855 }
30856
30857 @*1 Retrieving File Properties.
30858 To support \LaTeX, a few more time related functions are needed.
30859 @<Header files and function declarations@>=
30860 #define TIME_STR_SIZE 30
30861 static char time_str[TIME_STR_SIZE];
30862 static void get_creation_date(void);
30863 static void get_file_mod_date(void);
30864 static int get_file_size(void);
30865
30866 #include <md5.h>
30867 #define DIGEST_SIZE 16
30868 #define FILE_BUF_SIZE 1024
30869 static md5_byte_t md5_digest[DIGEST_SIZE];
30870
30871 static int get_md5_sum(int s, int file);
30872
30873 @ The code that follows was taken from the \.{texmfmp.c} file of
30874 the \TeX\ Live distribution and slightly modified.
30875
30876
30877 @<\TeX\ Live auxiliary functions@>=
30878
30879 static void
30880 make_time_str(time_t t, bool utc)
30881 {
30882 struct tm lt, gmt;
30883 size_t size;
30884 int off, off_hours, off_mins;
30885
30886 /* get the time */
30887 if (utc) {
30888 lt = *gmtime(&t);
30889 }
30890 else {
30891 lt = *localtime(&t);
30892 }
30893 size = strftime(time_str, TIME_STR_SIZE, "D:%Y%m%d%H%M%S", &lt);
30894 /* expected format: |"D:YYYYmmddHHMMSS"| */
30895 if (size == 0) {
30896 /* unexpected, contents of |time_str| is undefined */
30897 time_str[0] = '\0';
30898 return;
30899 }
30900
30901 /* correction for seconds: S can be in range 00 to 61,
30902 the PDF reference expects 00 to59,
30903 therefore we map |"60"| and |"61"| to |"59"| */
30904 if (time_str[14] == '6') {
30905 time_str[14] = '5';
30906 time_str[15] = '9';
30907 time_str[16] = '\0'; /* for safety */
30908 }
30909
30910 /* get the time zone offset */
30911 gmt = *gmtime(&t);
30912
30913 /* this calculation method was found in exim's tod.c */
30914 off = 60 * (lt.tm_hour - gmt.tm_hour) + lt.tm_min - gmt.tm_min;
30915 if (lt.tm_year != gmt.tm_year) {
30916 off += (lt.tm_year > gmt.tm_year) ? 1440 : -1440;
30917 } else if (lt.tm_yday != gmt.tm_yday) {
30918 off += (lt.tm_yday > gmt.tm_yday) ? 1440 : -1440;
30919 }
30920
30921 if (off == 0) {
30922 time_str[size++] = 'Z';
30923 time_str[size] = 0;
30924 } else {
30925 off_hours = off / 60;
30926 off_mins = abs(off - off_hours * 60);
30927 snprintf(&time_str[size], TIME_STR_SIZE-size, "%+03d'%02d'", off_hours, off_mins);
30928 }
30929 }
30930
30931 static void get_creation_date(void)
30932 { make_time_str(start_time,source_date_epoch!=NULL);
30933 }
30934
30935 /* static structure for file status set by |find_input_file| */
30936 #ifdef WIN32
30937 static struct _stat file_stat;
30938 #define GET_FILE_STAT _stat(fname,&file_stat)
30939 #else
30940 static struct stat file_stat;
30941 #define GET_FILE_STAT stat(fname,&file_stat)
30942 #endif
30943
30944
30945 static char* find_input_file(void)
30946 { char *fname;
30947 int r;
30948 if (output_directory&&!kpse_absolute_p((char*)name_of_file0, false))
30949 { int r=-1;
30950 fname = concat3(output_directory, DIR_SEP_STRING, (char*)name_of_file0);
30951 r=GET_FILE_STAT;
30952 if (r==0)
30953 return fname;
30954 free(fname);
30955 }
30956 fname = kpse_find_tex((char*)name_of_file0);
30957 if (fname!=NULL)
30958 { r=GET_FILE_STAT;
30959 if (r==0)
30960 return fname;
30961 free(fname);
30962 }
30963 fname=(char*)name_of_file0;
30964 r=GET_FILE_STAT;
30965 if (r==0)
30966 return strdup(fname);
30967 return NULL;
30968 }
30969
30970
30971 static void get_file_mod_date(void)
30972 { char *fname=NULL;
30973 fname= find_input_file();
30974 time_str[0]=0;
30975 if(fname!=NULL)
30976 { make_time_str(file_stat.st_mtime,source_date_epoch!=NULL && force_source_date!=NULL);
30977 free(fname);@+
30978 }
30979 }
30980
30981 static int get_file_size(void)
30982 { int s=-1;
30983 char *fname=NULL;
30984 fname= find_input_file();
30985 if(fname!=NULL)
30986 {s=file_stat.st_size;
30987 free(fname);@+
30988 }
30989 return s;
30990 }
30991
30992
30993 static int get_md5_sum(int s, int file)
30994 { md5_state_t st;
30995 memset(md5_digest,0,DIGEST_SIZE);
30996 if (file)
30997 { char *fname;
30998 pack_file_name(s,empty_string,empty_string,NULL);
30999 fname= find_input_file();
31000 if(fname!=NULL)
31001 { FILE *f;
31002 f = fopen(fname, "rb");
31003 if (f != NULL)
31004 { int r;
31005 char file_buf[FILE_BUF_SIZE];
31006 recorder_record_input(fname);
31007 md5_init(&st);
31008 while ((r = fread(&file_buf, 1, FILE_BUF_SIZE, f)) > 0)
31009 md5_append(&st, (const md5_byte_t *) file_buf, r);
31010 md5_finish(&st, md5_digest);
31011 fclose(f);
31012 }
31013 free(fname);
31014 }
31015 else
31016 return 0;
31017 }
31018 else
31019 { md5_init(&st);
31020 md5_append(&st,(md5_byte_t *)&str_pool[str_start[s]],
31021 str_start[s + 1] - str_start[s]);
31022 md5_finish(&st, md5_digest);
31023 }
31024 return DIGEST_SIZE;
31025 }
31026
31027 @* Profiling.
31028 If we want to find out where and how \TeX\ spends its time, we need
31029 a profiler. The common profilers, like {\tt gprof},
31030 examine the executable code of \TeX, then take some measurments at run time,
31031 and map this information to the functions or source lines of \TeX's code.
31032
31033 But \TeX\ is a programming language by itself, and when we program
31034 in \TeX, we want to map the timing information gathered at run time
31035 to the macros and source lines of \TeX's input files.
31036 The profiler implemented in the follwing code serves this purpose.
31037
31038 By default, profiling is initialy disabled.
31039 To enable profiling, you can use the {\tt -prof} option on the
31040 command line.
31041
31042 @<explain the options@>=
31043 " -prof "@/
31044 @t\qquad@>"\t enable profiling\n"@/
31045
31046 @ This option will set the |profile_on| variable, defined below, to true.
31047
31048 @<more options@>=
31049 { "prof", 0, &profile_on, 1 },
31050
31051 @ @<Global variables@>=
31052 static int @!profile_on=false;
31053
31054 @ To restrict profiling to selected parts of \TeX's input,
31055 we define two primitives for switching profiling on and off.
31056
31057 @d profile_on_code (eTeX_last_extension_cmd_mod+3) /* `\.{\\profileon}' */
31058 @d profile_off_code (eTeX_last_extension_cmd_mod+4) /* `\.{\\profileoff}' */
31059 @d pdftex_first_extension_code profile_off_code+1
31060
31061 @<Put each...@>=
31062 primitive("profileon", extension, profile_on_code);
31063 @!@:profileon\_}{\.{\\profileon} primitive@>
31064 primitive("profileoff", extension, profile_off_code);
31065 @!@:profileoff\_}{\.{\\profileoff} primitive@>
31066
31067 @ @<Cases of |extension| for |print_cmd_chr|@>=
31068 case profile_on_code: print_esc("profileon");@+break;
31069 case profile_off_code: print_esc("profileoff");@+break;
31070
31071 @ @<Cases for |do_extension|@>=
31072 case profile_on_code:
31073 if (!profile_on)
31074 { profile_on=true;
31075 @<record profiling on@>@;
31076 }
31077 break;
31078 case profile_off_code:
31079 if (profile_on)
31080 { @<record profiling off@>@;
31081 profile_on=false;
31082 }
31083 break;
31084
31085 @*1 Files and Lines.
31086 The ``instructions'' that drive the \TeX\ interpreter are called ``tokens''
31087 and we want to keep track of the files and the lines
31088 where the tokens come from.
31089 If a token comes from an external file, then \TeX's variable |line| will
31090 contain the correct line number, and |cur_file| contains the current file.
31091 |cur_file| is an abbreviation for |input_file[index]| with
31092 |index| being a short hand for |cur_input.index_field|.
31093 We can not use the |index| number to identify input files,
31094 because \TeX\ will reuse these numbers, possibly many times, after a file
31095 has been closed. Instead we make a new array |input_file_num| that
31096 runs in parallel to |input_file| and contains a unique current file number.
31097 Further we make a new |read_file_num| array that runs
31098 in parallel to |read_file|.
31099
31100 @d cur_file_num input_file_num[index] /*the current unique |alpha_file| number*/
31101
31102 @<Glob...@>=
31103 static uint8_t @!input_file_num0[max_in_open],
31104 *const @!input_file_num = @!input_file_num0-1;
31105 static uint8_t @! read_file_num[20];
31106
31107 @ To implement the association between unique file numbers and full
31108 file names, we use the array |file_num_name|. We will store file
31109 numbers with 8 bits and line numbers with 16 bits in a single 32 bit
31110 number. We do this because we will need to store this information
31111 together with the tokens in a token list. This representation will
31112 keep the most significant byte zero, so that we can later use it for
31113 the ``command'' value.
31114
31115 @<Global...@>=
31116 #define FILE_NUM_BITS 8
31117 #define MAX_FILE_NUM ((1<<FILE_NUM_BITS)-1)
31118 #define LINE_BITS 16
31119 #define MAX_LINE ((1<<LINE_BITS)-1)
31120 #define FILE_LINE(F,L) (((F)<<(LINE_BITS))|(L))
31121 #define FL_FILE(FL) ((FL)>>LINE_BITS)
31122 #define FL_LINE(FL) ((FL)&MAX_LINE)
31123 static char * @!file_num_name[MAX_FILE_NUM+1];
31124 static int file_from_cmd [MAX_FILE_NUM+1]; /* first command from the file */
31125 static int file_to_cmd [MAX_FILE_NUM+1]; /* last command from the file */
31126 static int file_num; /* the the last |file_num_name| allocated */
31127 static uint32_t cur_file_line=0; /* the file and line for |cur_tok| */
31128
31129 @ @<check |line| for overflow@>=
31130 if (line>=MAX_LINE) overflow("too many input lines", MAX_LINE);
31131
31132 @ Whenever we have a new |full_name_of_file|, we allocate
31133 a new unique file number.
31134
31135 @<Allocate a file number@>=
31136 if (file_num>=MAX_FILE_NUM) overflow("file number",file_num);
31137 else file_num++;
31138 file_num_name[file_num]=strdup(full_name_of_file);
31139 file_from_cmd[file_num]=cmd_count;
31140
31141 @ Whenever \TeX\ sets |cur_file| to a new value, we need to
31142 set |cur_file_num| as well.
31143
31144 @<Set new |cur_file_num|@>=
31145 @<Allocate a file number@>@;
31146 cur_file_num=file_num;
31147
31148 @ Whenever \TeX\ opens |read_file[n]| it needs to set the file count.
31149 @<Set new |read_file_num[n]|@>=
31150 @<Allocate a file number@>@;
31151 read_file_num[n]=file_num;
31152
31153 @ A few file numbers are predefined. Some tokens, for instance those
31154 that are loaded from a format file, have an unknown origin and are
31155 classified as comming from an |unknown_file|.
31156 We use |system_file| to assign time intervals to
31157 the system and use the command field to distinguish between different
31158 system events. There might also be tokens from the terminal, either
31159 typed in interactively (which will messup your timing values)
31160 or from the command line.
31161
31162 For the commands from the |system_file|, we use
31163 special line numbers to distinguish various cases.
31164
31165 @d unknown_file 0 /*tokens with unknown origin, usualy from a format file*/
31166 @d system_file 1 /*tokens generated by the system*/
31167 @d terminal_file 2 /*tokens read from the terminal*/
31168 @d system_unknown 0 /*should not happen*/
31169 @d system_start 1 /*startup of \TeX*/
31170 @d system_end 2 /*end of \TeX*/
31171 @d system_ship_out 3 /*time spent in |ship_out()|*/
31172 @d system_line_break 4 /*time spent in |line_break()|*/
31173 @d system_init_trie 5 /*time spent in |line_break()|*/
31174 @d system_build_page 6 /*time spent in |line_break()|*/
31175 @d system_input_ln 7 /*time spent in |line_break()|*/
31176 @d system_insert 8 /*time spent on tokens inserted by \TeX*/
31177
31178
31179 @<Set init...@>=
31180 file_num_name[unknown_file]="unknown";
31181 file_num_name[system_file]="system";
31182 file_num_name[terminal_file]="terminal";
31183 file_num=terminal_file;
31184
31185 @ When \TeX\ reads a token from an external file, it has to set
31186 |cur_file_line| based on the information in |cur_input|.
31187 This code is parallel to the code that is used to read the next line:
31188
31189 @<Set |cur_file_line| based on the information in |cur_input|@>=
31190 if (terminal_input)
31191 cur_file_line=FILE_LINE(terminal_file,0);
31192 else if (name<=19)
31193 cur_file_line=FILE_LINE(read_file_num[name-1],0); /* do I need the line? */
31194 else
31195 cur_file_line=FILE_LINE(cur_file_num,line);
31196
31197 @ When we end a \.{\\read} line, we set the current file and line.
31198 @<Set |cur_file_line| when a \.{\\read} line ends@>=
31199 cur_file_line=FILE_LINE(read_file_num[name-1],0);
31200
31201
31202 @ As described above, we store file and line numbers as 32 bit integers.
31203 When reading input from external files, we know the file and the line;
31204 but for token lists we need to store this information together
31205 with the tokens, when we create the token list.
31206 As a simple solution, we allocate a 32 bit integer for all pointers.
31207
31208 Whenever in \TeX's code a new token is generated, we know what file and
31209 line is responsible for what is going on. The newly generated token
31210 will then point to the same file and line.
31211
31212 @<Glob...@>=
31213 static uint32_t @!fl_mem0[mem_max-mem_min+1],
31214 *const @!fl_mem = @!fl_mem0-mem_min; /*the big dynamic file/line storage*/
31215
31216 @*1 Timing.
31217 When the interpreter of \TeX\ executes a command, we need to measure the
31218 time needed to execute it and record that information in a file.
31219 We call such a measurement a ``time stamp'' or ``stamp''
31220 for short.
31221 This process should be quick, in order not to disturb the measurements
31222 too much by the time needed for the measurement itself and its recording.
31223 So we keep the data in a large array, and postpone writing the output file
31224 until \TeX\ terminates.
31225
31226 Now let us consider the measurement of such a time stamp.
31227 As a general rule, the start of a new time interval is the end
31228 of the previous time interval. There is only a single look up
31229 of the current time for both. So all time intervals will add up
31230 to the total run time.
31231
31232 We keep the start time in two variables |start_sec| and |start_nsec|;
31233 the first counts the seconds, the other (roughly) the nano seconds.
31234 When we measure the end time, we should know the previous start time,
31235 and which command was executed and from which file and line this command
31236 was taken. The measured end time is the start time for the next command.
31237
31238
31239 @<Global variables@>=
31240 static long start_nsec, start_sec, diff_nsec;
31241 struct timespec ts;
31242 static int time_error;
31243
31244 @ To get timing information, we use the POSIX function |clock_gettime|.
31245 Depending on the operating system there are many different variations.
31246 The timer used for timing can be selected by defining |GETTIME| at
31247 compile time. If |GETTIME| is not set, we try to find a good default.
31248 Currently we use |timespec_get| under Windows and |clock_gettime|
31249 with a tread specific clock otherwise.
31250
31251 @<get current time@>=
31252 #ifdef GETTIME
31253 #if GETTIME==0
31254 time_error=clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts);
31255 #elif GETTIME==1
31256 time_error=clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
31257 #elif GETTIME==2
31258 time_error=clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
31259 #elif GETTIME==3
31260 time_error=clock_gettime(CLOCK_MONOTONIC, &ts);
31261 #else
31262 time_error=clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts);
31263 #endif
31264 #else
31265 /* guess a default */
31266 #ifdef _WIN32
31267 time_error=timespec_get(&ts, TIME_UTC);
31268 #else
31269 time_error=clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts);
31270 #endif
31271 #endif
31272
31273
31274 @ To record the timing information, we compute the time difference in
31275 nano seconds, assuming that it fits into unsigned 32 bit which means
31276 the difference should be less than about 4 seconds.
31277
31278 @<compute elapsed time@>=
31279 diff_nsec= (ts.tv_sec-start_sec)*1000000000+ (ts.tv_nsec-start_nsec);
31280 #if 0
31281 printf("time: %ld %ld %ld\n", diff_nsec, (ts.tv_sec), (ts.tv_nsec));
31282 #endif
31283
31284 start_nsec=ts.tv_nsec;
31285 start_sec=ts.tv_sec;
31286
31287 @*1 Commands.
31288 The fourth piece of information that we store with file, line, and time
31289 is the command that \TeX\ is executing.
31290 The elapsed time will fit into an four byte unsigned integer, and
31291 luckily also the command, the file and the line will do as well.
31292 When starting a new time interval, often we will not yet know the
31293 next command, its file, and its line.
31294 We keep the command, the file, the line, in a set of variables starting with
31295 |prof_|. These variables my change within a time interval, and the final
31296 values are written when the end time is known.
31297 There are also variables related to macro calls which are explainded later
31298 but are already defined here because we will initialize them together
31299 with the other variables.
31300
31301 @<Global variables@>=
31302 #define MAX_STAMPS 80000000
31303 #define MAX_MACRO_STACK 40000
31304 #define POP_BIT 0x80
31305
31306 static uint32_t stamp[MAX_STAMPS]; /*one chunk of profiling information*/
31307 static uint32_t st_count=0; /*the next available entry in the array above*/
31308 static uint32_t cmd_count=0; /*the number of time stamps in the array above*/
31309 static int prof_cmd=0; /*the command to be written */
31310 static uint32_t prof_file_line=0; /*the file and line to be written */
31311
31312 @ The code below initializes the variables. Note that we use the special
31313 command value |system_cmd|. The ``real'' command values
31314 are those that occur in the |big_switch| ranging from 0 (|escape|)
31315 to 100 (|max_command|), the values that are used when entering
31316 the |main_loop|(|letter|, |other_char|, |char_given|, and |char_num|)
31317 are a subset of these.
31318 The pseudo command |system_cmd| is just outside of this range.
31319 A few more pseudo commands are needed below and we define them here.
31320
31321 @d system_cmd (max_command+1) /*pseudo command value*/
31322 @d system_profile_on (system_cmd+1)
31323 @d system_profile_off (system_cmd+2)
31324 @d system_macro_push (system_cmd+3)
31325 @d system_macro_pop (system_cmd+4)
31326 @d system_macro_pop_small (system_cmd+5)
31327 @d system_macro_pop_0 (system_cmd+6)
31328
31329
31330 @<Initialize profiling@>=
31331 @<Initialize the macro call stack@>@;
31332 prof_cmd=system_cmd;
31333 prof_file_line=FILE_LINE(system_file,system_start);
31334 @<record macro call information if necessary@>@;
31335 #if 0
31336 clock_getres(CLOCK_MONOTONIC, &ts);
31337 printf("CLOCK_MONOTONIC: %ld %ld\n",ts.tv_sec,ts.tv_nsec);
31338
31339 clock_getres(CLOCK_MONOTONIC_RAW, &ts);
31340 printf("CLOCK_MONOTONIC_RAW: %ld %ld\n",ts.tv_sec,ts.tv_nsec);
31341
31342 clock_getres(CLOCK_PROCESS_CPUTIME_ID, &ts);
31343 printf("CLOCK_PROCESS_CPUTIME_ID: %ld %ld\n",ts.tv_sec,ts.tv_nsec);
31344
31345 clock_getres(CLOCK_THREAD_CPUTIME_ID, &ts);
31346 printf("CLOCK_THREAD_CPUTIME_ID: %ld %ld\n",ts.tv_sec,ts.tv_nsec);
31347 #endif
31348 @<get current time@>@;
31349 diff_nsec=0;
31350 start_nsec=ts.tv_nsec;
31351 start_sec=ts.tv_sec;
31352
31353 @ At the end of \TeX\ we check |last_depth| and clean the remaining
31354 macro stack if necessary. We end the record always with recording
31355 timing information.
31356
31357 @<pop the macro call stack at the end of \TeX@>=
31358 prof_cmd=cur_cmd; /* the stop command */
31359 prof_file_line=cur_file_line;
31360 prof_depth=0;
31361 profile_on=true;
31362 @<get current time@>@; /* advance the time */
31363 @<compute elapsed time@>@;
31364 @<record timing information@>@; /* pop to |prof_depth| */
31365
31366
31367 @ When we record the timing information,
31368 we first store command, file, and line, and then store
31369 the elapsed time.
31370
31371 @d SHOW_RECORD_TIMING 0
31372
31373 @<record timing information@>=
31374 if (profile_on)
31375 { if (st_count+3>MAX_STAMPS)
31376 overflow("profile data",MAX_STAMPS);
31377 @<record poping the macro stack if necessary@>@;
31378 stamp[st_count++]= (prof_cmd<<24) | prof_file_line;
31379 prof_cmd=prof_cmd&~POP_BIT; /*remove a possible |POP_BIT|*/
31380 #if SHOW_RECORD_TIMING
31381 print_char('<');print_int(cmd_count);
31382 print_char(':');
31383 if (prof_cmd&POP_BIT) print_char('-');
31384 print_int(prof_cmd&~POP_BIT);
31385 print_char(':');print_int(prof_depth);
31386 print_char('>');print_ln();
31387 #endif
31388 cmd_count++;
31389 @<get current time@>@;
31390 @<compute elapsed time@>@;
31391 stamp[st_count++]=diff_nsec;
31392 }
31393
31394
31395 @ To mark the execution of starting and ending profiling
31396 we use the system commands for the start and the end of profiling.
31397
31398 After switching profiling off, no more data is written to the output
31399 file. So we have to record the macro call and timing information
31400 explicitly before switching the profiling off.
31401
31402 @<record profiling off@>=
31403 prof_file_line=cur_file_line;
31404 prof_cmd=system_profile_off;
31405 prof_depth=cur_depth;
31406 @<record macro call information if necessary@>@;
31407 @<record timing information@>@;
31408
31409 @ When switching profiling on, we have to syncronize the start time
31410 with the current time and prepare everything for the recording
31411 of the timing before entering the main loop again.
31412 Setting the command, file and line information is simple.
31413 Since we can not assume that the macro call stack is unchanged,
31414 we record the necessary changes.
31415
31416 @<record profiling on@>=
31417 @<get current time@>@;
31418 diff_nsec=0;
31419 start_nsec=ts.tv_nsec;
31420 start_sec=ts.tv_sec;
31421 prof_file_line=cur_file_line;
31422 prof_cmd=system_profile_on;
31423 prof_depth=cur_depth;
31424 @<record macro call information if necessary@>@;
31425
31426 @ At the end of \TeX\ we record the timing for the |stop| command
31427 and pop the macro call stack.
31428
31429 @<record the end of \TeX@>=
31430 @<pop the macro call stack at the end of \TeX@>@;
31431
31432 @ There are two places where we regularly record the next command.
31433 The first one is when \TeX\ enters the big switch. Here
31434 we record the timing information before reading the next expanded token
31435 and set the current file, line, and command after reading the
31436 next expanded token.
31437 The other place is at the start of the main loop. Here both
31438 actions are done one after the other. Whenever we assiciate
31439 a command with the current time slot by setting |prof_cmd| and
31440 the profile data associated with it, we need to make sure that
31441 changes of entries in the macro call are reported to the profiler.
31442
31443 @<set current file, line, and command for the current time slot@>=
31444 if (profile_on)
31445 { prof_cmd=cur_cmd;
31446 prof_depth=cur_depth;
31447 prof_file_line=cur_file_line;
31448 @<record macro call information if necessary@>@;
31449 }
31450
31451 @ Some time expensive routines, |line_break| and |ship_out|, consume
31452 time that depends entirely on the output generated by \TeX\ but
31453 not on how that output is generated. So we charge the time spent in these
31454 routines on the system.
31455
31456 @<Local variables to save the profiling context@>=
31457 int tmp_cmd;
31458 int tmp_file_line;
31459 int tmp_depth;
31460
31461 @ @<Charge the time used here on |line_break|@>=
31462 if (profile_on)
31463 { @<record timing information@>@;
31464 tmp_file_line=prof_file_line;
31465 tmp_cmd=prof_cmd;
31466 tmp_depth=prof_depth;
31467 prof_file_line=FILE_LINE(system_file,system_line_break);
31468 prof_cmd=system_cmd;
31469 }
31470
31471
31472 @ @<restore the previous current file, line, and command@>=
31473 if (profile_on)
31474 { @<record timing information@>@;
31475 prof_file_line=tmp_file_line;
31476 prof_cmd=tmp_cmd;
31477 prof_depth=tmp_depth;
31478 }
31479
31480
31481
31482 @ @<Charge the time used here on |init_trie|@>=
31483 if (profile_on)
31484 { @<record timing information@>@;
31485 tmp_file_line=prof_file_line;
31486 tmp_cmd=prof_cmd;
31487 tmp_depth=prof_depth;
31488 prof_file_line=FILE_LINE(system_file,system_init_trie);
31489 prof_cmd=system_cmd;
31490 }
31491
31492
31493 @ @<Charge the time used here on |build_page|@>=
31494 if (profile_on)
31495 { @<record timing information@>@;
31496 tmp_file_line=prof_file_line;
31497 tmp_cmd=prof_cmd;
31498 tmp_depth=prof_depth;
31499 prof_file_line=FILE_LINE(system_file,system_build_page);
31500 prof_cmd=system_cmd;
31501 }
31502
31503
31504
31505 @ @<Charge the time used here on |ship_out|@>=
31506 if (profile_on)
31507 { @<record timing information@>@;
31508 tmp_file_line=prof_file_line;
31509 tmp_cmd=prof_cmd;
31510 tmp_depth=prof_depth;
31511 prof_file_line=FILE_LINE(system_file,system_ship_out);
31512 prof_cmd=system_cmd;
31513 }
31514
31515
31516 @*1 Macro Calls.
31517 Let's talk about collecting information about macro calls.
31518 Macro calls come in various flavours:
31519 There are active characters and single letter control sequences;
31520 both have their own region in the |eqtb| table of equivalents.
31521 Then there is an empty control sequence, and last there
31522 are lots of (currently up to 45000) multiletter control sequences.
31523 The plain format defines about 1000 and the \LaTeX\ format about 23000
31524 of them. When |get_next| finds a control sequence, it sets |cur_cs|
31525 to the index in the table of equivalents.
31526 It will further set |cur_cmd=eq_type(cur_cs)|, |cur_chr=equiv(cur_cs)|,
31527 and |cur_tok=cs_token_flag+cur_cs|.
31528
31529 The |get_x_token| or |expand| procedure will then notice the macro call
31530 and invoke |macro_call|.
31531 |macro_call| will inspect the call site and the parameter section
31532 of the macro and put the actual macro parameters on the parameter
31533 stack before pushing the macro body on the input stack.
31534
31535 But wait! |macro_call| will apply a technique called last call optimization
31536 before doing any of the above: It will remove all entries from
31537 the input stack that have no more tokens left for processing.
31538 This allows tail recursive macro calls in constant stack space and
31539 makes long recursive loops possible.
31540 For example building the \LaTeX\ format uses a loop to read the
31541 definition of UTF8 codes.
31542 This loop has more than 35000 iterations and a nesting depth
31543 of the same size. With last call optimization, the loop uses less than 3000
31544 entries on the input stack.
31545
31546 Popping the stack early makes it slightly more difficult
31547 to track who is calling whom---an information that we need if we want
31548 to give cumulative timing for a macro call. Cumulative timing is the time spent
31549 during that macro call including all the calls to sub-macros.
31550
31551 The timing information that we collected in the previous section
31552 assigned the time caused by the execution of \TeX's commands to the
31553 specific line and file that caused the execution of that command.
31554 As a consequnce, the time used for the expansion of a macro call
31555 is assigned to the file and line that contains the call site of the macro.
31556 The time that is spent on executing the commands in the macros body
31557 are assigned to the file and line containing the macro definition.
31558 But there is no information on the call graph that allows us to
31559 classify one command as comming from a lower level of expansion than
31560 the other.
31561
31562 In this section, we want to assign the time used for the execution
31563 of commands to a macro definition, with its name and the file and line
31564 that contains the definition of the macro.
31565 While the name of a macro is an important information, it is not
31566 sufficient to relate the time to the macros name, because
31567 the same name can be used for several different macros at various times.
31568
31569 So we collect for a macro call the following data:
31570
31571 \yskip\textindent{1)}The index |cur_cs| into the table of equivalents
31572 |eqtb|. Using |cur_cs| it is possible to access the macros name. For
31573 active characters and single letter control sequences, we obtain the
31574 character by subtracting |active_base| or |single_base| from |cur_cs|.
31575 For multi-letter control sequences, we find the index to |str_start|
31576 for the macro name in |text(cur_cs)|, the text field of the corresponding
31577 hash table entry. The association between |cur_cs| and the macro name
31578 is stored in a separate section of the profilers output file.
31579
31580 \yskip\textindent{2)}The line and file of the macro definition.
31581 We store this information in the |fl_mem| array using |equiv(cur_cs)|,
31582 the pointer to the reference count token of the macro.
31583
31584 \yskip\textindent{3)}The ``unoptimized'' nesting depth of the macro call.
31585
31586 We store this information in a 64 bit integer and define macros
31587 to assemble and disassemble this integer.
31588 From this information it is possible to reconstruct the call graph
31589 and compute cumulative timing information for macro calls.
31590 We keep the information for the whole ``unoptimized'' macro stack
31591 in the |macro_stack|.
31592 The varable |prof_depth| tells us the nesting depth of |prof_cmd|.
31593 The variable |last_depth| tells us the nesting depth
31594 of the last recorded time stamp and the variable |unchanged_depth|
31595 tells us which part of the macro stack is unchanged since then.
31596
31597
31598 @d CALL_DEPTH(A) ((A)>>48)
31599 @d CALL_EQTB(A) (((A)>>32)&0xFFFF)
31600 @d CALL_FILE(A) (((A)>>16)&0xFF)
31601 @d CALL_LINE(A) ((A)&0xFFFF)
31602 @d CALL_DE(A) ((A)>>32)
31603 @d CALL_CFL(A) ((A)&0xFFFFFFFF)
31604 @d CALL_INFO(D,C,FL) (((uint64_t)(D)<<48)|((uint64_t)(C)<<32)|
31605 (system_macro_push<<24)|FL)
31606
31607 @<Global variables@>=
31608 static uint64_t macro_stack[MAX_MACRO_STACK]={0}; /* the macro calls */
31609 static int prof_depth; /* the nesting depth of macros */
31610 static int last_depth; /* the nesting depth last report1ed*/
31611 static int unchanged_depth; /* up to here no change on |macro_stack|*/
31612 static int prof_max_depth;
31613
31614 @ @<Initialize the macro call stack@>=
31615 { int macro_depth=-1, macro_cs=0;
31616 uint32_t macro_fl=FILE_LINE(terminal_file,0);
31617 @<update the macro stack@>@;
31618 cmd_count++;
31619 stamp[st_count++]=CALL_CFL(macro_stack[0]);
31620 stamp[st_count++]=CALL_DE(macro_stack[0]);
31621 last_depth=unchanged_depth=prof_depth=0;
31622 }
31623
31624 @ We maintain the macro stack in the |macro_call| procedure
31625 by adding local variables that capture the information of
31626 the call token that cause the invocation of |macro_call|.
31627
31628 @<additional local variables for |macro_call|@>=
31629 uint32_t macro_fl=fl_mem[cur_chr];
31630 int macro_cs=cur_cs;
31631 int macro_depth=cur_depth;
31632
31633 @ At the end of |macro_call|, we use this information to
31634 update the |macro_stack| and related variables.
31635
31636 @<update the macro stack@>=
31637 macro_depth++;
31638 cur_depth=macro_depth;
31639 if (macro_depth>=MAX_MACRO_STACK)
31640 overflow("macro stack size", macro_depth);
31641 macro_stack[macro_depth]=CALL_INFO(macro_depth,macro_cs,macro_fl);
31642 if (macro_depth<=unchanged_depth)
31643 unchanged_depth=macro_depth-1;
31644
31645 @ We add files as part of the macro stack using the following code:
31646 @<additional local variables for |start_input|@>=
31647 uint32_t macro_fl=FILE_LINE(cur_file_num,0);
31648 int macro_cs=0;
31649 int macro_depth=cur_depth;
31650
31651 @ We add calls to the output routine and hook macros like \.{\\everypar}, \.{\\everymath}, etc. to the macro stack using tis code:
31652 @<additional local variables for |begin_token_list|@>=
31653 uint32_t macro_fl=fl_mem[p];
31654 int macro_cs=undefined_control_sequence+t;
31655 /*|undefined_control_sequence| is the last pointer in the hash table*/
31656 int macro_depth=cur_depth;
31657
31658
31659 @ As we have seen above, recording timing information consists
31660 of two steps:
31661 In the first step we set global variables like |prof_cmd| and |prof_depth|
31662 based on the current command. Then we wait until the command is executed,
31663 and in the second step we compute the elapsed time and store the
31664 information from the first step together with the time in the |stamp|
31665 array.
31666 Now we augment this process and store macro call related information.
31667
31668 The key value that guides this process is |prof_depth|:
31669 the macro nesting depth associated with |prof_cmd|.
31670 Using it we can get from the |macro_stack| information about
31671 all currently active macros at lower nesting levels.
31672 Two more variables |last_depth| and |unchanged_depth| are related to it:
31673 After recording macro call information for a command,
31674 we set |last_depth=unchanged_depth=prof_depth|.
31675 The next time we need to record macro call information,
31676 |unchanged_depth| and |prof_depth| may have changed, but
31677 |last_depth| should be unchanged. Because |unchanged_depth|
31678 can only decrease, we know that $|unchanged_depth|\le|last_depth|$.
31679 On the other hand, |prof_depth| can increase as well as decrease.
31680 This gives us the following cases:
31681
31682 \yskip\textindent{$|unchanged_depth|<|prof_depth|$}
31683 Record the new stack entries from $|unchanged_depth|+1$ up to |prof_depth|.
31684
31685 \yskip\textindent{$|prof_depth|=|unchanged_depth|=|last_depth|$:}
31686 No information on macro calls is necessary.
31687
31688 \yskip\textindent{$|prof_depth|<|unchanged_depth|=|last_depth|$:}
31689 Record that the stack was popped from |last_depth| down to |prof_depth|.
31690
31691 \yskip\textindent{$|prof_depth|\le|unchanged_depth|<|last_depth|$:}
31692 Record that the stack was popped from |last_depth| down to |prof_depth|.
31693
31694
31695 The common case that $|prof_dept|=|last_dept|-1$ asks for a more
31696 compact representation and we use the most significant bit of the
31697 command value to encode this case.
31698 Note that we count this as a separate command.
31699
31700 It would be nice if we could wait with recording the stack changes until
31701 the command is completely executed. The command however might read
31702 parameters which causes pops and pushes on the macro stack. So by the
31703 time the command has finished, the stack might have changed considerably.
31704 There is a further complication: the execusion of some commands does
31705 not end with a jump to |big_switch| but with a jump to |big_reswitch|.
31706 This will set a new value for |prof_cmd| and so will invalidate all our
31707 preparations.
31708 For this reason we need to make the recording of macro call information
31709 idempotent. Recording several pops and pushes explicitly does not harm
31710 (except for extra output) but setting the pop bit asks for trouble.
31711 Therefore we postpone the recording of poping the macro stack.
31712
31713
31714 @<record macro call information if necessary@>=
31715 if (unchanged_depth<prof_depth)
31716 @<record the new stack entries@>@;
31717
31718
31719 @ @<record poping the macro stack if necessary@>=
31720 if (last_depth>prof_depth)
31721 { if (last_depth==prof_depth+1)
31722 prof_cmd=prof_cmd|POP_BIT;
31723 else
31724 stamp[st_count++]=(system_macro_pop<<24)| (last_depth-prof_depth);
31725 #if SHOW_RECORD_TIMING
31726 print_char('{');print_int(cmd_count);
31727 print_char(':');print_int(system_macro_pop);
31728 print_char(':');print_int(last_depth);
31729 print_char('>');print_int(prof_depth);
31730 print_char('}');print_ln();
31731 #endif
31732 cmd_count++;
31733 last_depth=unchanged_depth=prof_depth;
31734 }
31735
31736
31737 @ The information about new stack entries are taken from the |macro_stack|.
31738
31739 @<record the new stack entries@>=
31740 { int i;
31741 if (last_depth>unchanged_depth)
31742 {
31743 #if SHOW_RECORD_TIMING
31744 print_char('{');print_int(cmd_count);
31745 print_char(':');print_int(system_macro_pop);
31746 print_char(':');print_int(last_depth);
31747 print_char('>');print_int(unchanged_depth);
31748 print_char('}');print_ln();
31749 #endif
31750 cmd_count++;
31751 }
31752 if (st_count+2*(prof_depth-unchanged_depth)>MAX_STAMPS)
31753 overflow("profile data",MAX_STAMPS);
31754 for (i=unchanged_depth+1;i<=prof_depth;i++)
31755 {
31756 #if SHOW_RECORD_TIMING
31757 print_char('[');print_int(cmd_count);
31758 print_char(':');print_int(i-1);
31759 print_char('<');print_int(CALL_DEPTH(macro_stack[i]));
31760 print_char(':'); print_cs(CALL_EQTB(macro_stack[i]));
31761 print_char(']');print_ln();
31762 #endif
31763 cmd_count++;
31764 stamp[st_count++]=CALL_CFL(macro_stack[i]);
31765 stamp[st_count++]=CALL_DE(macro_stack[i]);
31766 }
31767 last_depth=unchanged_depth=prof_depth;
31768 if (prof_depth>prof_max_depth) prof_max_depth=prof_depth;
31769 }
31770
31771
31772 @*1 Output the profile data.
31773 Here is the code that outputs the results.
31774 The format tries to be simple but flexible.
31775 The output file has four parts: size data, file names, macro names,
31776 and time stamps. To enable some error checking, the three file
31777 parts start and end with an output marker.
31778
31779 % we have typically from 1000 to 5000, in exteme cases up to 30000,
31780 % file/line entries
31781 % cut -d : -f 2,3 tmon.out | fgrep -v '.' | sort |uniq | wc -l
31782
31783 @<Finish the extensions@>=
31784 { FILE *prof;
31785 pack_job_name(".tprof");
31786 prof=fopen((char*)name_of_file0,"wb");
31787 if (prof==NULL) print_err("Unable to write the profile data\n");
31788 else {
31789 int i;
31790 prof_file_line=cur_file_line;
31791 @<output marker@>@;
31792 @<output size data@>@;
31793 @<output marker@>@;
31794 @<output file names@>@;
31795 @<output marker@>@;
31796 @<output macro names@>@;
31797 @<output marker@>@;
31798 @<output timing data@>@>
31799 @<output marker@>@;
31800 fclose(prof);
31801 }
31802 }
31803
31804 @ The output marker consists of eight byte: the ASCII codes of ``TEX PROF''.
31805
31806 @<output marker@>=
31807 fputs("TEX PROF",prof);
31808
31809
31810 @ The information necessary to process the file comes after the first
31811 marker. Here and in the following all numbers are written out in
31812 ``big-endian byte order''. We provide the following information:
31813
31814 The number of files (2 byte),
31815 the number of byte used for filenames
31816 including the zero bytes (2 byte),
31817 the number of time stamps (4 byte).
31818 The number of macro names (2 byte),
31819 the number of bytes used for macro names (4 byte),
31820 again including the zero bytes,
31821 and the maximum nesting depth used on the |macro_stack|.
31822
31823 We start with the macros to write multibyte integers in bigendian order.
31824
31825 @d PUT1(N) fputc((N)&0xFF,prof)
31826 @d PUT2(N) PUT1((N)>>8),PUT1(N)
31827 @d PUT4(N) PUT2((N)>>16),PUT2(N)
31828
31829
31830 @<output size data@>=
31831 PUT2(file_num+1); /* the number of files */
31832 { int n, m;
31833 m=0;
31834 for (i=0; i<=file_num; i++)
31835 { n=strlen(file_num_name[i]);
31836 m+=n+1;
31837 }
31838 PUT2(m); /* the number of byte used for file names */
31839 }
31840 PUT4(cmd_count); /* the number of commands */
31841 { int k, m;
31842 m=k=0;
31843 for (i=hash_base; i<undefined_control_sequence; i++)
31844 if (text(i)!=0)
31845 { k++;
31846 m+=(str_start[text(i)+1]-str_start[text(i)])+1;
31847 }
31848 PUT2(k); /* the number of macro names */
31849 PUT4(m); /* the number of byte for the macro names */
31850 PUT2(prof_max_depth); /*the maximum macro nesting depth*/
31851 }
31852
31853
31854 @ Writing the file names is simple.
31855
31856 @<output file names@>=
31857 for (i=0; i<=file_num; i++)
31858 { fputs(file_num_name[i], prof);
31859 PUT1(0);
31860 }
31861
31862 @ Here is the code to write the macro names to the output file.
31863 It traverses the |hash_table| from |hash_base| up to
31864 |undefined_control_sequence|. Each macro name is preceeded by
31865 its index in the hash table stored in two byte.
31866
31867 @<output macro names@>=
31868 for (i=hash_base; i<undefined_control_sequence; i++)
31869 if (text(i)!=0)
31870 { int k;
31871 PUT2(i);
31872 for (k=str_start[text(i)];k<str_start[text(i)+1];k++)
31873 PUT1(str_pool[k]);
31874 PUT1(0);
31875 }
31876
31877
31878 @ Next we output the time stamps. We use a variable format
31879 depending on the command value which is always in the top byte
31880 of the stamp. We optimize the output size slightly:
31881 For macro calls the |stamp| array contains the depth values.
31882 It is of course more efficient to write the relative changes
31883 into the output instead of the absolute values.
31884 A most common case is poping the stack by one. This is recorded
31885 in the |stamp| array by setting the |POP_BIT| in the command value
31886 and we simply keep this bit. Small relative values $n$ in the range
31887 $0 \le n \le 10$ are encoded using the command value
31888 $|system_macro_pop_0|+n$. Values in the range $11 \le n \le 255$
31889 encoded as single byte values following the commmand code
31890 |system_macro_pop_small|. All other values are encoded using
31891 two byte following the command code |system_macro_pop|.
31892 Encoding the pops separate from the calls, we need no longer
31893 store the depth values with the calls.
31894
31895 @<encode pop $n$@>=
31896 #if SHOW_WRITE_TIMING
31897 printf("!%d:%d:%d>%d\n",j++,i,last_depth,last_depth-n);
31898 #endif
31899 if (n<=10)
31900 PUT1(system_macro_pop_0+n);
31901 else if (n<=255)
31902 { PUT1(system_macro_pop_small);
31903 PUT1(n);
31904 }
31905 else
31906 { PUT1(system_macro_pop);
31907 PUT2(n);
31908 }
31909 last_depth=last_depth-n;
31910
31911 @ Now we can output the timing data.
31912
31913 @d SHOW_WRITE_TIMING 0
31914
31915 @<output timing data@>=
31916
31917 i=0;
31918 { int j=0;
31919 last_depth=-1;
31920 while (i< st_count)
31921 { int8_t c = stamp[i]>>24;
31922 if (c==system_macro_pop)
31923 { int n=stamp[i]&0xFFFF;
31924 @<encode pop $n$@>@;
31925 i++;
31926 }
31927 else if (c==system_macro_push)
31928 { int d=stamp[i+1]>>16;
31929 if (d<=last_depth)
31930 { int n=last_depth-d+1;
31931 @<encode pop $n$@>@;
31932 /* here I could optimize the case $n=1$ by setting the |POP_BIT|
31933 in |system_macro_push|*/
31934 }
31935 #if SHOW_WRITE_TIMING
31936 print_char('!');print_int(j++);
31937 print_char(':');print_int(i);
31938 print_char(':'); print_int(system_macro_push);
31939 print_char(':');print_int(d);
31940 print_char(':'); print_cs(stamp[i+1]&0xffff);
31941 print_char(']');print_ln();
31942 #endif
31943 PUT4(stamp[i]); i++;
31944 PUT2(stamp[i]); i++;
31945 last_depth=d;
31946 }
31947 else
31948 {
31949 if (c&POP_BIT)
31950 { last_depth--;
31951 #if SHOW_WRITE_TIMING
31952 printf("!%d:%d:%d>%d}\n",j++,i,last_depth+1,last_depth);
31953 #endif
31954 }
31955 #if SHOW_WRITE_TIMING
31956 printf("!%d:%d:%d:%d>\n",j++,i,stamp[i]>>24,last_depth);
31957 #endif
31958 PUT4(stamp[i]);i++;
31959 PUT4(stamp[i]);i++;
31960 }
31961 }
31962 }
31963
31964 @*1 Dumping the profiling information.
31965
31966 We dump the number of files first and then dump
31967 the file names including the
31968 terminating zero byte.
31969 We put eight byte into a memory word and dump them together.
31970 The last memory word is padded with zeros.
31971
31972 @<Dump the full file names@>=
31973 { two_halves hw;
31974 int i,j;
31975 hw.rh=file_num;
31976 i=0;
31977 for (k=0; k<=file_num; k++)
31978 { j=strlen(file_num_name[k]);
31979 if (j>i) i=j;
31980 }
31981 hw.lh=i;
31982 dump_hh(hw);
31983 }
31984 { memory_word m;
31985 int word_count=0;
31986 int byte_count=0;
31987 m.w=0;
31988 for (k=0;k<=file_num;k++)
31989 { char *s=file_num_name[k];
31990 do
31991 { m.w=(m.w<<8)|*s;
31992 byte_count++;
31993 if (byte_count==8)
31994 { dump_wd(m); word_count++;
31995 m.w=0; byte_count=0;
31996 }
31997 } while (*s++!=0);
31998 }
31999 if (byte_count >0)
32000 { while (byte_count<8)
32001 { m.w=(m.w<<8)|0;
32002 byte_count++;
32003 }
32004 dump_wd(m);word_count++;
32005 }
32006 print_ln();print_int(file_num);
32007 print(" file names dumped; total size "); print_int(word_count*8);
32008 }
32009
32010 @ @<Undump the full file names@>=
32011
32012 { two_halves hw;
32013 memory_word m;
32014 int byte_count=0;
32015 int i,j;
32016 char *buf;
32017 undump_hh(hw);
32018 file_num=hw.rh;
32019 if (file_num>MAX_FILE_NUM) overflow("file number",file_num);
32020 i=hw.lh;
32021 buf=malloc(i+1);
32022 if (buf==NULL)
32023 { print_err("Out of memory while reading filenames from format file");
32024 succumb;
32025 }
32026 for (k=0;k<=file_num;k++)
32027 { char *s=buf;
32028 do
32029 { if (byte_count==0)
32030 { undump_wd(m); byte_count=8; }
32031 *s=(m.w>>56)&0xFF; m.w=m.w<<8;
32032 byte_count--;
32033 } while (*s++!=0);
32034 file_num_name[k]=strdup(buf);
32035 if (file_num_name[k]==NULL)
32036 { print_err("Out of memory while reading filenames from format file");
32037 succumb;
32038 }
32039 }
32040 free(buf);
32041 }
32042
32043
32044 @
32045 Next we dump the file and line information from the |fl_mem| array.
32046 Because some formats leave many unallocated memory words in the |avail|
32047 list we dump only those memory words that are not on the avail list.
32048 We set the entry |fl_mem[p]| to zero if |p| is on the |avail| list
32049 while we traverse the list when dumping the memory words.
32050 Besides the unallocated entries also entries that specify the unknown
32051 file with line zero are completely zero. We do not dump these as well.
32052
32053 When dumping an entry we set the topmost bit of the entry to 1.
32054 An entry that has the topmost bit equal to zero contains the count
32055 of the following zero entries. We dump entries in pairs since
32056 the dump file is organized as a file of memory words
32057
32058 @<Dump the file and line information@>=
32059 { int word_count=0;
32060 k=hi_mem_min;
32061 while (k<=mem_end)
32062 { two_halves hw;
32063 halfword e;
32064 int word_count=0;
32065 @<compute the next file line entry@>@;
32066 hw.rh=e;
32067 if (k>mem_end) e=0;
32068 else
32069 { @<compute the next file line entry@>@; }
32070 hw.lh=e;
32071 dump_hh(hw); word_count++;
32072 }
32073 print_ln(); print_int(word_count);
32074 print(" words of file/line information dumped.");
32075 }
32076 @ @<compute the next file line entry@>=
32077 if (fl_mem[k]!=0) e=fl_mem[k++]|0x80000000;
32078 else
32079 { int i;
32080 i=1; k++;
32081 while (k<=mem_end && fl_mem[k]==0)
32082 { i++; k++; }
32083 e=i;
32084 }
32085
32086 @ @<Undump the file and line information@>=
32087 k=hi_mem_min;
32088 while (k<=mem_end)
32089 { two_halves hw;
32090 halfword e;
32091 undump_hh(hw);
32092 e=hw.rh;
32093 @<get the next file line entry@>@;
32094 if (k<=mem_end)
32095 { e=hw.lh;
32096 @<get the next file line entry@>@;
32097 }
32098 }
32099
32100 @ @<get the next file line entry@>=
32101 if (e&0x80000000)
32102 fl_mem[k++]=e&~0x80000000;
32103 else
32104 { int i;
32105 i=e;
32106 while (i>0)
32107 {i--; k++;}
32108 }
32109
32110 @*1 Profiling \.{PDF} Specific Macros.
32111 Macro packages providing \.{PDF} specific features typicaly test
32112 whether the current engine is generating \.{PDF} output
32113 before activating \.{PDF}-specific macros, and these macros
32114 then use \.{PDF}-specific primitives. To be able to profile
32115 these macros, the engine must provide (or at least pretend to provide)
32116 the necessary primitives to make the test for \.{PDF} output succeed
32117 and prevent the macros from failing because of undefined
32118 primitives or unexpected behaviour. Generating \.{PDF} ouput
32119 is usualy not required.
32120
32121 The {\tt -pdf} option is designed to provide the necessary behaviour
32122 by implementing replacements for the primitives of \pdfTeX.
32123
32124 @<explain the options@>=
32125 " -pdf "@/
32126 @t\qquad@>"\t pretend to be pdftex; requires -ini; implies -ltx\n"@/
32127
32128 @ This option will set the |pdf_on| variable, defined below, to true.
32129 The option requires the {\tt -ini} option because its effect is just
32130 the definition of additional primitives during initialization. It further
32131 implies the {\tt -ltx} option because the primitives necesary to
32132 run \LaTeX\ are part of \pdfTeX.
32133
32134 @<handle the options@>=
32135 else @+if (ARGUMENT_IS ("pdf")) @t\2@>
32136 if (iniversion) pdf_on=ltxp=true;
32137 else
32138 { fprintf(stderr,"-pdf requires -ini; try -ini -pdf\n");
32139 exit(1);
32140 }
32141
32142 @ @<more options@>=
32143 { "pdf", 0, 0, 0 },
32144
32145 @ @<Global variables@>=
32146 static int @!pdf_on=false;
32147
32148 @ Let us start with implementing the \.{PDF} version primitive.
32149 This primitive uses the |last_item| command with a special modifier
32150 \pdfTeX\ adds the codes for its extensions: |pdftex_version_code|, \dots
32151 between \TeX's |badness_code| and \eTeX's |eTeX_int| codes.
32152 Some codes like |elapsed_time_code| or |random_seed_code| are already defined above
32153 but we duplicate them here for simplicity.
32154 So here is the pdf version as well as all of PDF\TeX's command codes
32155 for the |last_item| command:
32156
32157 @d pdftex_version 140 /* \.{\\pdftexversion} */
32158 @d pdftex_revision "25" /* \.{\\pdftexrevision} */
32159 @d pdftex_version_string "-1.40.25" /*current \pdfTeX\ version*/
32160 @#
32161 @d pdftex_first_rint_code (badness_code+1) /*base for \pdfTeX's command codes*/
32162 @d pdftex_version_code (pdftex_first_rint_code+0) /*code for \.{\\pdftexversion}*/
32163 @d pdf_last_obj_code (pdftex_first_rint_code+1) /*code for \.{\\pdflastobj}*/
32164 @d pdf_last_xform_code (pdftex_first_rint_code+2) /*code for \.{\\pdflastxform}*/
32165 @d pdf_last_ximage_code (pdftex_first_rint_code+3) /*code for \.{\\pdflastximage}*/
32166 @d pdf_last_ximage_pages_code (pdftex_first_rint_code+4) /*code for \.{\\pdflastximagepages}*/
32167 @d pdf_last_annot_code (pdftex_first_rint_code+5) /*code for \.{\\pdflastannot}*/
32168 @d pdf_retval_code (pdftex_first_rint_code+6) /*global multi-purpose return value*/
32169 @d pdf_last_ximage_colordepth_code (pdftex_first_rint_code+7) /*code for \.{\\pdflastximagecolordepth}*/
32170 @d pdf_last_link_code (pdftex_first_rint_code+8) /*code for \.{\\pdflastlink}*/
32171 @d pdftex_last_item_codes (pdftex_first_rint_code+8) /*end of \pdfTeX's command codes*/
32172
32173 @ Using these codes we can add the primitives:
32174
32175 @<Put each...@>=
32176 if (pdf_on)
32177 {
32178 primitive("pdftexversion", last_item, pdftex_version_code);@/
32179 @!@:pdftex\_version\_}{\.{\\pdftexversion} primitive@>
32180 primitive("pdflastobj", last_item, pdf_last_obj_code);@/
32181 @!@:pdf\_last\_obj\_}{\.{\\pdflastobj} primitive@>
32182 primitive("pdflastxform", last_item, pdf_last_xform_code);@/
32183 @!@:pdf\_last\_xform\_}{\.{\\pdflastxform} primitive@>
32184 primitive("pdflastximage", last_item, pdf_last_ximage_code);@/
32185 @!@:pdf\_last\_ximage\_}{\.{\\pdflastximage} primitive@>
32186 primitive("pdflastximagepages", last_item, pdf_last_ximage_pages_code);@/
32187 @!@:pdf\_last\_ximage\_pages\_}{\.{\\pdflastximagepages} primitive@>
32188 primitive("pdflastannot", last_item, pdf_last_annot_code);@/
32189 @!@:pdf\_last\_annot\_}{\.{\\pdflastannot} primitive@>
32190 primitive("pdfretval", last_item, pdf_retval_code);@/
32191 @!@:pdf\_retval\_}{\.{\\pdfretval} primitive@>
32192 primitive("pdflastximagecolordepth", last_item, pdf_last_ximage_colordepth_code);@/
32193 @!@:pdf\_last\_ximage\_colordepth\_}{\.{\\pdflastximagecolordepth} primitive@>
32194 primitive("pdflastlink", last_item, pdf_last_link_code);@/
32195 @!@:pdf\_last\_link\_}{\.{\\pdflastlink} primitive@>
32196 }
32197
32198 @ Next we need to print the commands:
32199
32200 @<Cases of |last_item| for |print_cmd_chr|@>=
32201 case pdftex_version_code: print_esc("pdftexversion");@+break;
32202 case pdf_last_obj_code: print_esc("pdflastobj");@+break;
32203 case pdf_last_xform_code: print_esc("pdflastxform");@+break;
32204 case pdf_last_ximage_code: print_esc("pdflastximage");@+break;
32205 case pdf_last_ximage_pages_code: print_esc("pdflastximagepages");@+break;
32206 case pdf_last_annot_code: print_esc("pdflastannot");@+break;
32207 case pdf_retval_code: print_esc("pdfretval");@+break;
32208 case pdf_last_ximage_colordepth_code: print_esc("pdflastximagecolordepth");@+break;
32209 case pdf_last_link_code: print_esc("pdflastlink");@+break;
32210
32211 @ The implementation needs a few global variables.
32212
32213 @<Glob...@>=
32214 static int
32215 @!pdf_last_obj,
32216 @!pdf_last_xform,
32217 @!pdf_last_ximage,
32218 @!pdf_last_ximage_pages,
32219 @!pdf_last_annot,
32220 @!pdf_retval,
32221 @!pdf_last_ximage_colordepth,
32222 @!pdf_last_link;
32223
32224
32225 @ And this is sufficient to finish the implementation of this first batch of primitives:
32226 @<Cases for fetching an integer value@>=
32227 case pdftex_version_code: cur_val=pdftex_version;@+break;
32228 case pdf_last_obj_code: cur_val=pdf_last_obj;@+break;
32229 case pdf_last_xform_code: cur_val=pdf_last_xform;@+break;
32230 case pdf_last_ximage_code: cur_val=pdf_last_ximage;@+break;
32231 case pdf_last_ximage_pages_code: cur_val=pdf_last_ximage_pages;@+break;
32232 case pdf_last_annot_code: cur_val=pdf_last_annot;@+break;
32233 case pdf_retval_code: cur_val=pdf_retval;@+break;
32234 case pdf_last_ximage_colordepth_code: cur_val=pdf_last_ximage_colordepth;@+break;
32235 case pdf_last_link_code: cur_val=pdf_last_link;@+break;
32236
32237
32238 @ The next group of primitves uses the assignment commands. We start
32239 by defining the necessary command codes followed by the primitives.
32240
32241 @d pdftex_first_loc tex_toks /*base for \pdfTeX's token list parameters*/
32242 @d pdf_pages_attr_loc (pdftex_first_loc+0) /*points to token list for \.{\\pdfpagesattr}*/
32243 @d pdf_page_attr_loc (pdftex_first_loc+1) /*points to token list for \.{\\pdfpageattr}*/
32244 @d pdf_page_resources_loc (pdftex_first_loc+2) /*points to token list for \.{\\pdfpageresources}*/
32245 @d pdf_pk_mode_loc (pdftex_first_loc+3) /*points to token list for \.{\\pdfpkmode}*/
32246 @d pdf_toks (pdftex_first_loc+4) /*end of \pdfTeX's token list parameters*/
32247 @#
32248 @d pdftex_first_integer_code tex_int_pars /*base for \pdfTeX's integer parameters*/
32249 @d pdf_output_code (pdftex_first_integer_code+0) /*switch on PDF output if positive*/
32250 @d pdf_compress_level_code (pdftex_first_integer_code+1) /*compress level of streams*/
32251 @d pdf_decimal_digits_code (pdftex_first_integer_code+2) /*digits after the decimal point of numbers*/
32252 @d pdf_move_chars_code (pdftex_first_integer_code+3) /*move chars 0..31 to higher area if possible*/
32253 @d pdf_image_resolution_code (pdftex_first_integer_code+4) /*default image resolution*/
32254 @d pdf_pk_resolution_code (pdftex_first_integer_code+5) /*default resolution of PK font*/
32255 @d pdf_unique_resname_code (pdftex_first_integer_code+6) /*generate unique names for resouces*/
32256 @d pdf_option_always_use_pdfpagebox_code (pdftex_first_integer_code+7) /*if the PDF inclusion should always use a specific PDF page box*/
32257 @d pdf_option_pdf_inclusion_errorlevel_code (pdftex_first_integer_code+8) /*if the PDF inclusion should treat pdfs newer than |pdf_minor_version| as an error*/
32258 @d pdf_major_version_code (pdftex_first_integer_code+9) /*integer part of the PDF version produced*/
32259 @d pdf_minor_version_code (pdftex_first_integer_code+10) /*fractional part of the PDF version produced*/
32260 @d pdf_force_pagebox_code (pdftex_first_integer_code+11) /*if the PDF inclusion should always use a specific PDF page box*/
32261 @d pdf_pagebox_code (pdftex_first_integer_code+12) /*default pagebox to use for PDF inclusion*/
32262 @d pdf_inclusion_errorlevel_code (pdftex_first_integer_code+13) /*if the PDF inclusion should treat pdfs newer than |pdf_minor_version| as an error*/
32263 @d pdf_gamma_code (pdftex_first_integer_code+14)
32264 @d pdf_image_gamma_code (pdftex_first_integer_code+15)
32265 @d pdf_image_hicolor_code (pdftex_first_integer_code+16)
32266 @d pdf_image_apply_gamma_code (pdftex_first_integer_code+17)
32267 @d pdf_adjust_spacing_code (pdftex_first_integer_code+18) /*level of spacing adjusting*/
32268 @d pdf_protrude_chars_code (pdftex_first_integer_code+19) /*protrude chars at left/right edge of paragraphs*/
32269 @d pdf_tracing_fonts_code (pdftex_first_integer_code+20) /*level of font detail in log*/
32270 @d pdf_objcompresslevel_code (pdftex_first_integer_code+21) /*activate object streams*/
32271 @d pdf_adjust_interword_glue_code (pdftex_first_integer_code+22) /*adjust interword glue?*/
32272 @d pdf_prepend_kern_code (pdftex_first_integer_code+23) /*prepend kern before certain characters?*/
32273 @d pdf_append_kern_code (pdftex_first_integer_code+24) /*append kern before certain characters?*/
32274 @d pdf_gen_tounicode_code (pdftex_first_integer_code+25) /*generate ToUnicode for fonts?*/
32275 @d pdf_draftmode_code (pdftex_first_integer_code+26) /*switch on draftmode if positive*/
32276 @d pdf_inclusion_copy_font_code (pdftex_first_integer_code+27) /*generate ToUnicode for fonts?*/
32277 @d pdf_suppress_warning_dup_dest_code (pdftex_first_integer_code+28) /*suppress warning about duplicated destinations*/
32278 @d pdf_suppress_warning_dup_map_code (pdftex_first_integer_code+29) /*suppress warning about duplicated map lines*/
32279 @d pdf_suppress_warning_page_group_code (pdftex_first_integer_code+30) /*suppress warning about multiple pdfs with page group*/
32280 @d pdf_info_omit_date_code (pdftex_first_integer_code+31) /*omit generating CreationDate and ModDate*/
32281 @d pdf_suppress_ptex_info_code (pdftex_first_integer_code+32) /*suppress /PTEX.* entries in PDF dictionaries*/
32282 @d pdf_omit_charset_code (pdftex_first_integer_code+33) /*suppress /PTEX.* entries in PDF dictionaries*/
32283 @d pdf_omit_info_dict_code (pdftex_first_integer_code+34) /*suppress /PTEX.* entries in PDF dictionaries*/
32284 @d pdf_omit_procset_code (pdftex_first_integer_code+35) /*suppress /PTEX.* entries in PDF dictionaries*/
32285 @d pdf_int_pars (pdftex_first_integer_code+36) /*total number of \pdfTeX's integer parameters*/
32286 @#
32287 @d pdftex_first_dimen_code 23 /*first number defined in this section*/
32288 @d pdf_h_origin_code (pdftex_first_dimen_code+0) /*horigin of the PDF output*/
32289 @d pdf_v_origin_code (pdftex_first_dimen_code+1) /*vorigin of the PDF output*/
32290 @d pdf_link_margin_code (pdftex_first_dimen_code+2) /*link margin in the PDF output*/
32291 @d pdf_dest_margin_code (pdftex_first_dimen_code+3) /*dest margin in the PDF output*/
32292 @d pdf_thread_margin_code (pdftex_first_dimen_code+4) /*thread margin in the PDF output*/
32293 @d pdf_first_line_height_code (pdftex_first_dimen_code+5)
32294 @d pdf_last_line_depth_code (pdftex_first_dimen_code+6)
32295 @d pdf_each_line_height_code (pdftex_first_dimen_code+7)
32296 @d pdf_each_line_depth_code (pdftex_first_dimen_code+8)
32297 @d pdf_ignored_dimen_code (pdftex_first_dimen_code+9)
32298 @d pdf_px_dimen_code (pdftex_first_dimen_code+10)
32299 @d pdftex_last_dimen_code (pdftex_first_dimen_code+10) /*last number defined in this section*/
32300 @d dimen_pars (pdftex_last_dimen_code+1) /*total number of dimension parameters*/
32301
32302 @<Put each...@>=
32303 if (pdf_on)
32304 {
32305 primitive("pdfpagesattr", assign_toks, pdf_pages_attr_loc);
32306 @!@:pdf\_pages\_attr\_}{\.{\\pdfpagesattr} primitive@>
32307 primitive("pdfpageattr", assign_toks, pdf_page_attr_loc);
32308 @!@:pdf\_page\_attr\_}{\.{\\pdfpageattr} primitive@>
32309 primitive("pdfpageresources", assign_toks, pdf_page_resources_loc);
32310 @!@:pdf\_page\_resources\_}{\.{\\pdfpageresources} primitive@>
32311 primitive("pdfpkmode", assign_toks, pdf_pk_mode_loc);
32312 @!@:pdf\_pk\_mode\_}{\.{\\pdfpkmode} primitive@>
32313 @#
32314 primitive("pdfoutput", assign_int, int_base+pdf_output_code);@/
32315 @!@:pdf\_output\_}{\.{\\pdfoutput} primitive@>
32316 primitive("pdfcompresslevel", assign_int, int_base+pdf_compress_level_code);@/
32317 @!@:pdf\_compress\_level\_}{\.{\\pdfcompresslevel} primitive@>
32318 primitive("pdfobjcompresslevel", assign_int, int_base+pdf_objcompresslevel_code);@/
32319 @!@:pdf\_objcompresslevel\_}{\.{\\pdfobjcompresslevel} primitive@>
32320 primitive("pdfdecimaldigits", assign_int, int_base+pdf_decimal_digits_code);@/
32321 @!@:pdf\_decimal\_digits\_}{\.{\\pdfdecimaldigits} primitive@>
32322 primitive("pdfmovechars", assign_int, int_base+pdf_move_chars_code);@/
32323 @!@:pdf\_move\_chars\_}{\.{\\pdfmovechars} primitive@>
32324 primitive("pdfimageresolution", assign_int, int_base+pdf_image_resolution_code);@/
32325 @!@:pdf\_image\_resolution\_}{\.{\\pdfimageresolution} primitive@>
32326 primitive("pdfpkresolution", assign_int, int_base+pdf_pk_resolution_code);@/
32327 @!@:pdf\_pk\_resolution\_}{\.{\\pdfpkresolution} primitive@>
32328 primitive("pdfuniqueresname", assign_int, int_base+pdf_unique_resname_code);@/
32329 @!@:pdf\_unique\_resname\_}{\.{\\pdfuniqueresname} primitive@>
32330 primitive("pdfoptionpdfminorversion", assign_int, int_base+pdf_minor_version_code);@/
32331 @!@:pdf\_minor\_version\_}{\.{\\pdfoptionpdfminorversion} primitive@>
32332 primitive("pdfoptionalwaysusepdfpagebox", assign_int, int_base+pdf_option_always_use_pdfpagebox_code);@/
32333 @!@:pdf\_option\_always\_use\_pdfpagebox\_}{\.{\\pdfoptionalwaysusepdfpagebox} primitive@>
32334 primitive("pdfoptionpdfinclusionerrorlevel", assign_int, int_base+pdf_option_pdf_inclusion_errorlevel_code);@/
32335 @!@:pdf\_option\_pdf\_inclusion\_errorlevel\_}{\.{\\pdfoptionpdfinclusionerrorlevel} primitive@>
32336 primitive("pdfmajorversion", assign_int, int_base+pdf_major_version_code);@/
32337 @!@:pdf\_major\_version\_}{\.{\\pdfmajorversion} primitive@>
32338 primitive("pdfminorversion", assign_int, int_base+pdf_minor_version_code);@/
32339 @!@:pdf\_minor\_version\_}{\.{\\pdfminorversion} primitive@>
32340 primitive("pdfforcepagebox", assign_int, int_base+pdf_force_pagebox_code);@/
32341 @!@:pdf\_force\_pagebox\_}{\.{\\pdfforcepagebox} primitive@>
32342 primitive("pdfpagebox", assign_int, int_base+pdf_pagebox_code);@/
32343 @!@:pdf\_pagebox\_}{\.{\\pdfpagebox} primitive@>
32344 primitive("pdfinclusionerrorlevel", assign_int, int_base+pdf_inclusion_errorlevel_code);@/
32345 @!@:pdf\_inclusion\_errorlevel\_}{\.{\\pdfinclusionerrorlevel} primitive@>
32346 primitive("pdfgamma", assign_int, int_base+pdf_gamma_code);@/
32347 @!@:pdf\_gamma\_}{\.{\\pdfgamma} primitive@>
32348 @!@:pdf\_gamma\_}{\.{\\pdfgamma} primitive@>
32349 primitive("pdfimagegamma", assign_int, int_base+pdf_image_gamma_code);@/
32350 @!@:pdf\_image\_gamma\_}{\.{\\pdfimagegamma} primitive@>
32351 primitive("pdfimagehicolor", assign_int, int_base+pdf_image_hicolor_code);@/
32352 @!@:pdf\_image\_hicolor\_}{\.{\\pdfimagehicolor} primitive@>
32353 primitive("pdfimageapplygamma", assign_int, int_base+pdf_image_apply_gamma_code);@/
32354 @!@:pdf\_image\_apply\_gamma\_}{\.{\\pdfimageapplygamma} primitive@>
32355 primitive("pdfadjustspacing", assign_int, int_base+pdf_adjust_spacing_code);@/
32356 @!@:pdf\_adjust\_spacing\_}{\.{\\pdfadjustspacing} primitive@>
32357 primitive("pdfprotrudechars", assign_int, int_base+pdf_protrude_chars_code);@/
32358 @!@:pdf\_protrude\_chars\_}{\.{\\pdfprotrudechars} primitive@>
32359 primitive("pdftracingfonts", assign_int, int_base+pdf_tracing_fonts_code);@/
32360 @!@:pdf\_tracing\_fonts\_}{\.{\\pdftracingfonts} primitive@>
32361 primitive("pdfadjustinterwordglue", assign_int, int_base+pdf_adjust_interword_glue_code);@/
32362 @!@:pdf\_adjust\_interword\_glue\_}{\.{\\pdfadjustinterwordglue} primitive@>
32363 primitive("pdfprependkern", assign_int, int_base+pdf_prepend_kern_code);@/
32364 @!@:pdf\_prepend\_kern\_}{\.{\\pdfprependkern} primitive@>
32365 primitive("pdfappendkern", assign_int, int_base+pdf_append_kern_code);@/
32366 @!@:pdf\_append\_kern\_}{\.{\\pdfappendkern} primitive@>
32367 primitive("pdfgentounicode", assign_int, int_base+pdf_gen_tounicode_code);@/
32368 @!@:pdf\_gen\_tounicode\_}{\.{\\pdfgentounicode} primitive@>
32369 primitive("pdfdraftmode", assign_int, int_base+pdf_draftmode_code);@/
32370 @!@:pdf\_draftmode\_}{\.{\\pdfdraftmode} primitive@>
32371 primitive("pdfinclusioncopyfonts", assign_int, int_base+pdf_inclusion_copy_font_code);@/
32372 @!@:pdf\_inclusion\_copy\_font\_}{\.{\\pdfinclusioncopyfonts} primitive@>
32373 primitive("pdfsuppresswarningdupdest", assign_int, int_base+pdf_suppress_warning_dup_dest_code);@/
32374 @!@:pdf\_suppress\_warning\_dup\_dest\_}{\.{\\pdfsuppresswarningdupdest} primitive@>
32375 primitive("pdfsuppresswarningdupmap", assign_int, int_base+pdf_suppress_warning_dup_map_code);@/
32376 @!@:pdf\_suppress\_warning\_dup\_map\_}{\.{\\pdfsuppresswarningdupmap} primitive@>
32377 primitive("pdfsuppresswarningpagegroup", assign_int, int_base+pdf_suppress_warning_page_group_code);@/
32378 @!@:pdf\_suppress\_warning\_page\_group\_}{\.{\\pdfsuppresswarningpagegroup} primitive@>
32379 primitive("pdfinfoomitdate", assign_int, int_base+pdf_info_omit_date_code);@/
32380 @!@:pdf\_info\_omit\_date\_}{\.{\\pdfinfoomitdate} primitive@>
32381 primitive("pdfsuppressptexinfo", assign_int, int_base+pdf_suppress_ptex_info_code);@/
32382 @!@:pdf\_suppress\_ptex\_info\_}{\.{\\pdfsuppressptexinfo} primitive@>
32383 primitive("pdfomitcharset", assign_int, int_base+pdf_omit_charset_code);@/
32384 @!@:pdf\_omit\_charset}{\.{\\pdfomitcharset} primitive@>
32385 primitive("pdfomitinfodict", assign_int, int_base+pdf_omit_info_dict_code);@/
32386 @!@:pdf\_omit\_info\_dict}{\.{\\pdfomitinfodict} primitive@>
32387 primitive("pdfomitprocset", assign_int, int_base+pdf_omit_procset_code);@/
32388 @!@:pdf\_omit\_procset}{\.{\\pdfomitprocset} primitive@>
32389 @#
32390 primitive("pdfhorigin", assign_dimen, dimen_base+pdf_h_origin_code);@/
32391 @!@:pdf\_h\_origin\_}{\.{\\pdfhorigin} primitive@>
32392 primitive("pdfvorigin", assign_dimen, dimen_base+pdf_v_origin_code);@/
32393 @!@:pdf\_v\_origin\_}{\.{\\pdfvorigin} primitive@>
32394 primitive("pdflinkmargin", assign_dimen, dimen_base+pdf_link_margin_code);@/
32395 @!@:pdf\_link\_margin\_}{\.{\\pdflinkmargin} primitive@>
32396 primitive("pdfdestmargin", assign_dimen, dimen_base+pdf_dest_margin_code);@/
32397 @!@:pdf\_dest\_margin\_}{\.{\\pdfdestmargin} primitive@>
32398 primitive("pdfthreadmargin", assign_dimen, dimen_base+pdf_thread_margin_code);@/
32399 @!@:pdf\_thread\_margin\_}{\.{\\pdfthreadmargin} primitive@>
32400 primitive("pdffirstlineheight", assign_dimen, dimen_base+pdf_first_line_height_code);@/
32401 @!@:pdf\_first\_line\_height\_}{\.{\\pdffirstlineheight} primitive@>
32402 primitive("pdflastlinedepth", assign_dimen, dimen_base+pdf_last_line_depth_code);@/
32403 @!@:pdf\_last\_line\_depth\_}{\.{\\pdflastlinedepth} primitive@>
32404 primitive("pdfeachlineheight", assign_dimen, dimen_base+pdf_each_line_height_code);@/
32405 @!@:pdf\_each\_line\_height\_}{\.{\\pdfeachlineheight} primitive@>
32406 primitive("pdfeachlinedepth", assign_dimen, dimen_base+pdf_each_line_depth_code);@/
32407 @!@:pdf\_each\_line\_depth\_}{\.{\\pdfeachlinedepth} primitive@>
32408 primitive("pdfignoreddimen", assign_dimen, dimen_base+pdf_ignored_dimen_code);@/
32409 @!@:pdf\_ignored\_dimen\_}{\.{\\pdfignoreddimen} primitive@>
32410 primitive("pdfpxdimen", assign_dimen, dimen_base+pdf_px_dimen_code);@/
32411 @!@:pdf\_px\_dimen\_}{\.{\\pdfpxdimen} primitive@>
32412 primitive("ifpdfprimitive", if_test, if_primitive_code);
32413 @!@:if\_primitive\_}{\.{\\if} primitive@>
32414
32415
32416 }
32417
32418 @ As before we add cases to the printing routines.
32419
32420 @<Cases of |assign_toks| for |print_cmd_chr|@>=
32421 case pdf_pages_attr_loc: print_esc("pdfpagesattr");@+break;
32422 case pdf_page_attr_loc: print_esc("pdfpageattr");@+break;
32423 case pdf_page_resources_loc: print_esc("pdfpageresources");@+break;
32424 case pdf_pk_mode_loc: print_esc("pdfpkmode");@+break;
32425
32426 @ @<Cases for |print_param|@>=
32427 case pdf_output_code: print_esc("pdfoutput");@+break;
32428 case pdf_compress_level_code: print_esc("pdfcompresslevel");@+break;
32429 case pdf_objcompresslevel_code: print_esc("pdfobjcompresslevel");@+break;
32430 case pdf_decimal_digits_code: print_esc("pdfdecimaldigits");@+break;
32431 case pdf_move_chars_code: print_esc("pdfmovechars");@+break;
32432 case pdf_image_resolution_code: print_esc("pdfimageresolution");@+break;
32433 case pdf_pk_resolution_code: print_esc("pdfpkresolution");@+break;
32434 case pdf_unique_resname_code: print_esc("pdfuniqueresname");@+break;
32435 case pdf_option_always_use_pdfpagebox_code: print_esc("pdfoptionalwaysusepdfpagebox");@+break;
32436 case pdf_option_pdf_inclusion_errorlevel_code: print_esc("pdfoptionpdfinclusionerrorlevel");@+break;
32437 case pdf_major_version_code: print_esc("pdfmajorversion");@+break;
32438 case pdf_minor_version_code: print_esc("pdfminorversion");@+break;
32439 case pdf_force_pagebox_code: print_esc("pdfforcepagebox");@+break;
32440 case pdf_pagebox_code: print_esc("pdfpagebox");@+break;
32441 case pdf_inclusion_errorlevel_code: print_esc("pdfinclusionerrorlevel");@+break;
32442 case pdf_gamma_code: print_esc("pdfgamma");@+break;
32443 case pdf_image_gamma_code: print_esc("pdfimagegamma");@+break;
32444 case pdf_image_hicolor_code: print_esc("pdfimagehicolor");@+break;
32445 case pdf_image_apply_gamma_code: print_esc("pdfimageapplygamma");@+break;
32446 case pdf_adjust_spacing_code: print_esc("pdfadjustspacing");@+break;
32447 case pdf_protrude_chars_code: print_esc("pdfprotrudechars");@+break;
32448 case pdf_tracing_fonts_code: print_esc("pdftracingfonts");@+break;
32449 case pdf_adjust_interword_glue_code: print_esc("pdfadjustinterwordglue");@+break;
32450 case pdf_prepend_kern_code: print_esc("pdfprependkern");@+break;
32451 case pdf_append_kern_code: print_esc("pdfappendkern");@+break;
32452 case pdf_gen_tounicode_code: print_esc("pdfgentounicode");@+break;
32453 case pdf_draftmode_code: print_esc("pdfdraftmode");@+break;
32454 case pdf_inclusion_copy_font_code: print_esc("pdfinclusioncopyfonts");@+break;
32455 case pdf_suppress_warning_dup_dest_code: print_esc("pdfsuppresswarningdupdest");@+break;
32456 case pdf_suppress_warning_dup_map_code: print_esc("pdfsuppresswarningdupmap");@+break;
32457 case pdf_suppress_warning_page_group_code: print_esc("pdfsuppresswarningpagegroup");@+break;
32458 case pdf_info_omit_date_code: print_esc("pdfinfoomitdate");@+break;
32459 case pdf_suppress_ptex_info_code: print_esc("pdfsuppressptexinfo");@+break;
32460 case pdf_omit_charset_code: print_esc("pdfomitcharset");@+break;
32461 case pdf_omit_info_dict_code: print_esc("pdfomitinfodict");@+break;
32462 case pdf_omit_procset_code: print_esc("pdfomitprocset");@+break;
32463
32464 @ @<Cases for |print_lenght_param|@>=
32465 case pdf_h_origin_code: print_esc("pdfhorigin");@+break;
32466 case pdf_v_origin_code: print_esc("pdfvorigin");@+break;
32467 case pdf_link_margin_code: print_esc("pdflinkmargin");@+break;
32468 case pdf_dest_margin_code: print_esc("pdfdestmargin");@+break;
32469 case pdf_thread_margin_code: print_esc("pdfthreadmargin");@+break;
32470 case pdf_first_line_height_code: print_esc("pdffirstlineheight");@+break;
32471 case pdf_last_line_depth_code: print_esc("pdflastlinedepth");@+break;
32472 case pdf_each_line_height_code: print_esc("pdfeachlineheight");@+break;
32473 case pdf_each_line_depth_code: print_esc("pdfeachlinedepth");@+break;
32474 case pdf_ignored_dimen_code: print_esc("pdfignoreddimen");@+break;
32475 case pdf_px_dimen_code: print_esc("pdfpxdimen");@+break;
32476
32477 @ It remains to initialize some of these entries.
32478
32479 @<Initialize table entries...@>=
32480 dimen_par(pdf_h_origin_code)=4736287; /* 0.5 inch */
32481 dimen_par(pdf_v_origin_code)=4736287;
32482 int_par(pdf_compress_level_code)=9;
32483 int_par(pdf_objcompresslevel_code)=0;
32484 int_par(pdf_decimal_digits_code)=3;
32485 int_par(pdf_image_resolution_code)=72;
32486 int_par(pdf_major_version_code)=1;
32487 int_par(pdf_minor_version_code)=4;
32488 int_par(pdf_gamma_code)=1000;
32489 int_par(pdf_image_gamma_code)=2200;
32490 int_par(pdf_image_hicolor_code)=1;
32491 int_par(pdf_image_apply_gamma_code)=0;
32492 int_par(pdf_draftmode_code)=0;
32493 dimen_par(pdf_px_dimen_code)=65782; /* 1bp */
32494
32495 @ The next class of primitives extend the |convert| comand.
32496 These codes go in between |Prote_last_convert_code| and |job_name_code|.
32497
32498 @d pdftex_first_convert_code (Prote_last_convert_code+1) /*base for \pdfTeX's command codes*/
32499 @d pdftex_revision_code (pdftex_first_convert_code+0) /*command code for \.{\\pdftexrevision}*/
32500 @d pdftex_banner_code (pdftex_first_convert_code+1) /*command code for \.{\\pdftexbanner}*/
32501 @d pdf_font_name_code (pdftex_first_convert_code+2) /*command code for \.{\\pdffontname}*/
32502 @d pdf_font_objnum_code (pdftex_first_convert_code+3) /*command code for \.{\\pdffontobjnum}*/
32503 @d pdf_font_size_code (pdftex_first_convert_code+4) /*command code for \.{\\pdffontsize}*/
32504 @d pdf_page_ref_code (pdftex_first_convert_code+5) /*command code for \.{\\pdfpageref}*/
32505 @d pdf_xform_name_code (pdftex_first_convert_code+6) /*command code for \.{\\pdfxformname}*/
32506 @d pdf_escape_string_code (pdftex_first_convert_code+7) /*command code for \.{\\pdfescapestring}*/
32507 @d pdf_escape_name_code (pdftex_first_convert_code+8) /*command code for \.{\\pdfescapename}*/
32508 @d left_margin_kern_code (pdftex_first_convert_code+9) /*command code for \.{\\leftmarginkern}*/
32509 @d right_margin_kern_code (pdftex_first_convert_code+10) /*command code for \.{\\rightmarginkern}*/
32510 @d pdf_colorstack_init_code (pdftex_first_convert_code+11) /*command code for \.{\\pdfcolorstackinit}*/
32511 @d pdf_escape_hex_code (pdftex_first_convert_code+12) /*command code for \.{\\pdfescapehex}*/
32512 @d pdf_unescape_hex_code (pdftex_first_convert_code+13) /*command code for \.{\\pdfunescapehex}*/
32513 @d pdf_match_code (pdftex_first_convert_code+14) /*command code for \.{\\pdfmatch}*/
32514 @d pdf_last_match_code (pdftex_first_convert_code+15) /*command code for \.{\\pdflastmatch}*/
32515 @d pdf_insert_ht_code (pdftex_first_convert_code+16) /*command code for \.{\\pdfinsertht}*/
32516 @d pdf_ximage_bbox_code (pdftex_first_convert_code+17) /*command code for \.{\\pdfximagebbox}*/
32517 @d pdftex_convert_codes (pdftex_first_convert_code+18) /*end of \pdfTeX's command codes*/
32518
32519
32520 @<Put each...@>=
32521 if (pdf_on)
32522 {
32523 primitive("pdftexrevision", convert, pdftex_revision_code);@/
32524 @!@:pdftex\_revision\_}{\.{\\pdftexrevision} primitive@>
32525 primitive("pdftexbanner", convert, pdftex_banner_code);@/
32526 @!@:pdftex\_banner\_}{\.{\\pdftexbanner} primitive@>
32527 primitive("pdffontname", convert, pdf_font_name_code);@/
32528 @!@:pdf\_font\_name\_}{\.{\\pdffontname} primitive@>
32529 primitive("pdffontobjnum", convert, pdf_font_objnum_code);@/
32530 @!@:pdf\_font\_objnum\_}{\.{\\pdffontobjnum} primitive@>
32531 primitive("pdffontsize", convert, pdf_font_size_code);@/
32532 @!@:pdf\_font\_size\_}{\.{\\pdffontsize} primitive@>
32533 primitive("pdfpageref", convert, pdf_page_ref_code);@/
32534 @!@:pdf\_page\_ref\_}{\.{\\pdfpageref} primitive@>
32535 primitive("leftmarginkern", convert, left_margin_kern_code);@/
32536 @!@:left\_margin\_kern\_}{\.{\\leftmarginkern} primitive@>
32537 primitive("rightmarginkern", convert, right_margin_kern_code);@/
32538 @!@:right\_margin\_kern\_}{\.{\\rightmarginkern} primitive@>
32539 primitive("pdfxformname", convert, pdf_xform_name_code);@/
32540 @!@:pdf\_xform\_name\_}{\.{\\pdfxformname} primitive@>
32541 primitive("pdfescapestring", convert, pdf_escape_string_code);@/
32542 @!@:pdf\_escape\_string\_}{\.{\\pdfescapestring} primitive@>
32543 primitive("pdfescapename", convert, pdf_escape_name_code);@/
32544 @!@:pdf\_escape\_name\_}{\.{\\pdfescapename} primitive@>
32545 primitive("pdfescapehex", convert, pdf_escape_hex_code);@/
32546 @!@:pdf\_escape\_hex\_}{\.{\\pdfescapehex} primitive@>
32547 primitive("pdfunescapehex", convert, pdf_unescape_hex_code);@/
32548 @!@:pdf\_unescape\_hex\_}{\.{\\pdfunescapehex} primitive@>
32549 primitive("pdfmatch", convert, pdf_match_code);@/
32550 @!@:pdf\_match\_}{\.{\\pdfmatch} primitive@>
32551 primitive("pdflastmatch", convert, pdf_last_match_code);@/
32552 @!@:pdf\_last\_match\_}{\.{\\pdflastmatch} primitive@>
32553 primitive("pdfcolorstackinit", convert, pdf_colorstack_init_code);@/
32554 @!@:pdf\_colorstack\_init\_}{\.{\\pdfcolorstackinit} primitive@>
32555 }
32556
32557 @ The usual code for printing:
32558
32559 @<Cases of |convert| for |print_cmd_chr|@>=
32560 case pdftex_revision_code: print_esc("pdftexrevision");@+break;
32561 case pdftex_banner_code: print_esc("pdftexbanner");@+break;
32562 case pdf_font_name_code: print_esc("pdffontname");@+break;
32563 case pdf_font_objnum_code: print_esc("pdffontobjnum");@+break;
32564 case pdf_font_size_code: print_esc("pdffontsize");@+break;
32565 case pdf_page_ref_code: print_esc("pdfpageref");@+break;
32566 case left_margin_kern_code: print_esc("leftmarginkern");@+break;
32567 case right_margin_kern_code: print_esc("rightmarginkern");@+break;
32568 case pdf_xform_name_code: print_esc("pdfxformname");@+break;
32569 case pdf_escape_string_code: print_esc("pdfescapestring");@+break;
32570 case pdf_escape_name_code: print_esc("pdfescapename");@+break;
32571 case pdf_escape_hex_code: print_esc("pdfescapehex");@+break;
32572 case pdf_unescape_hex_code: print_esc("pdfunescapehex");@+break;
32573 case pdf_match_code: print_esc("pdfmatch");@+break;
32574 case pdf_last_match_code: print_esc("pdflastmatch");@+break;
32575 case pdf_colorstack_init_code: print_esc("pdfcolorstackinit");@+break;
32576 case pdf_insert_ht_code: print_esc("pdfinsertht");@+break;
32577 case pdf_ximage_bbox_code: print_esc("pdfximagebbox");@+break;
32578
32579 @ The following code is taken from pdftex. At this point, I should drop
32580 some of the primitives that I do not want to implement.
32581 To skip general text we use the following macro
32582
32583
32584 @<Cases of `Scan the argument for command |c|'@>=
32585 case pdftex_revision_code: do_nothing;@+break;
32586 case pdftex_banner_code: do_nothing;@+break;
32587 case pdf_font_name_code: case pdf_font_objnum_code:
32588 case pdf_font_size_code: {@+
32589 scan_font_ident();
32590 if (cur_val==null_font)
32591 pdf_error("font","invalid font identifier");
32592 } @+break;
32593 case pdf_page_ref_code: {@+
32594 scan_int();
32595 if (cur_val <= 0)
32596 pdf_error("pageref","invalid page number");
32597 } @+break;
32598 case left_margin_kern_code: case right_margin_kern_code: {@+
32599 pointer p;
32600 scan_register_num();
32601 fetch_box(p);
32602 if ((p==null)||(type(p)!=hlist_node))
32603 pdf_error("marginkern","a non-empty hbox expected");
32604 } @+break;
32605 case pdf_xform_name_code: {@+
32606 scan_int();
32607 } @+break;
32608 case pdf_escape_string_code:
32609 case pdf_escape_name_code:
32610 case pdf_escape_hex_code:
32611 case pdf_unescape_hex_code:
32612 scan_general_x_text(); /*the simplified version*/
32613 ins_list(link(link(garbage)));
32614 free_avail(link(garbage)); /*drop reference count*/
32615 return;
32616 case pdf_match_code:
32617 scan_keyword("icase");
32618 if (scan_keyword("subcount")) scan_int();
32619 scan_pdf_ext_toks(); /*the simplified version*/
32620 scan_pdf_ext_toks(); /*the simplified version*/
32621 break;
32622 case pdf_last_match_code:
32623 {@+pointer p,q;
32624 scan_int();
32625 /* always returning ``\.{-1->}''*/
32626 p=temp_head;link(p)=null;
32627 store_new_token(other_token+'-');
32628 store_new_token(other_token+'1');
32629 store_new_token(other_token+'-');
32630 store_new_token(other_token+'>');
32631 ins_list(link(temp_head));
32632 return;
32633 }
32634 case pdf_colorstack_init_code:
32635 {@+
32636 scan_keyword("page");
32637 if (!scan_keyword("direct"))
32638 scan_keyword("page");
32639 scan_pdf_ext_toks(); /*the simplified version*/
32640 cur_val=0;
32641 } @+break;
32642 case pdf_insert_ht_code: scan_register_num();@+break;
32643 case pdf_ximage_bbox_code: {@+
32644 scan_int();
32645 scan_int();
32646 }@+break;
32647
32648
32649 @ This is the ``dummy'' |scan_pdf_ext_toks| routine we used above
32650 and a variation of it which we need later.
32651
32652 @<Declare procedures needed in |do_ext...@>=
32653 static void scan_pdf_ext_toks(void)
32654 { scan_toks(false,true); /*like \.{\\special}*/
32655 flush_list(def_ref);
32656 }
32657 static void scan_pdf_ext_late_toks(void)
32658 { scan_toks(false, false); /*like \.{\\special}, but doesn't expand*/
32659 flush_list(def_ref);
32660 }
32661
32662
32663 @ The second part of handling conversion commands is the printing of the result.
32664
32665 @<Cases of `Print the result of command |c|'@>=
32666 case pdftex_revision_code: print(pdftex_revision);@+break;
32667 case pdftex_banner_code: print("This is pdfTeX, Version 3.141592653");@+break;
32668 case pdf_font_name_code: case pdf_font_objnum_code: print_int(cur_val);@+break;
32669 case pdf_font_size_code:
32670 print_scaled(font_size[cur_val]);
32671 print("pt");@+break;
32672 case pdf_page_ref_code: print_int(1);@+break;
32673 case pdf_xform_name_code: print_int(cur_val);@+break;
32674 case pdf_escape_string_code:
32675 case pdf_escape_name_code:
32676 case left_margin_kern_code: print("0pt");@+break;
32677 case right_margin_kern_code: print("0pt");@+break;
32678 case pdf_colorstack_init_code: print_int(cur_val);@+break;
32679 case pdf_escape_hex_code:
32680 case pdf_unescape_hex_code:
32681 case pdf_match_code:
32682 case pdf_last_match_code:
32683 case pdf_insert_ht_code: print("10pt");@+break;
32684 case pdf_ximage_bbox_code: print("10pt");@+break;
32685
32686
32687 @ A few functions are neede to complete the implementation of the \pdfTeX\ simulation.
32688
32689
32690 @<Error handling procedures@>=
32691 static void pdf_error(char *t, char *p)
32692 {@+
32693 normalize_selector();
32694 print_err("pdfTeX error");
32695 if (t!=0) {@+
32696 print(" (");
32697 print(t);
32698 print(")");
32699 }
32700 print(": ");print(p);
32701 succumb;
32702 }
32703
32704
32705 @ The last command we need to consider is the |extension| command.
32706
32707 @d pdf_literal_node (pdftex_first_extension_code+0)
32708
32709 @d pdf_lateliteral_node (pdftex_first_extension_code+1) /*Not needed*/
32710
32711 @d pdf_obj_code (pdftex_first_extension_code+2)
32712 @d pdf_refobj_node (pdftex_first_extension_code+3)
32713 @d pdf_xform_code (pdftex_first_extension_code+4)
32714 @d pdf_refxform_node (pdftex_first_extension_code+5)
32715 @d pdf_ximage_code (pdftex_first_extension_code+6)
32716 @d pdf_refximage_node (pdftex_first_extension_code+7)
32717 @d pdf_annot_node (pdftex_first_extension_code+8)
32718 @d pdf_start_link_node (pdftex_first_extension_code+9)
32719 @d pdf_end_link_node (pdftex_first_extension_code+10)
32720 @d pdf_outline_code (pdftex_first_extension_code+11)
32721 @d pdf_dest_node (pdftex_first_extension_code+12)
32722 @d pdf_thread_node (pdftex_first_extension_code+13)
32723 @d pdf_start_thread_node (pdftex_first_extension_code+14)
32724 @d pdf_end_thread_node (pdftex_first_extension_code+15)
32725
32726 @d pdf_info_code (pdftex_first_extension_code+16)
32727 @d pdf_catalog_code (pdftex_first_extension_code+17)
32728 @d pdf_names_code (pdftex_first_extension_code+18)
32729
32730 @d pdf_font_attr_code (pdftex_first_extension_code+19)
32731 @d pdf_include_chars_code (pdftex_first_extension_code+20)
32732 @d pdf_map_file_code (pdftex_first_extension_code+21)
32733 @d pdf_map_line_code (pdftex_first_extension_code+22)
32734 @d pdf_trailer_code (pdftex_first_extension_code+23)
32735 @d pdf_trailer_id_code (pdftex_first_extension_code+24)
32736
32737 @d pdf_font_expand_code (pdftex_first_extension_code+25)
32738
32739 @d pdf_snap_ref_point_node (pdftex_first_extension_code+26)
32740 @d pdf_snapy_node (pdftex_first_extension_code+27)
32741 @d pdf_snapy_comp_node (pdftex_first_extension_code+28)
32742 @d pdf_glyph_to_unicode_code (pdftex_first_extension_code+29)
32743 @d pdf_colorstack_node (pdftex_first_extension_code+30)
32744 @d pdf_setmatrix_node (pdftex_first_extension_code+31)
32745 @d pdf_save_node (pdftex_first_extension_code+32)
32746 @d pdf_restore_node (pdftex_first_extension_code+33)
32747 @d pdf_nobuiltin_tounicode_code (pdftex_first_extension_code+34)
32748 @d pdf_interword_space_on_node (pdftex_first_extension_code+35)
32749 @d pdf_interword_space_off_node (pdftex_first_extension_code+36)
32750 @d pdf_fake_space_node (pdftex_first_extension_code+37)
32751 @d pdf_running_link_off_node (pdftex_first_extension_code+38)
32752 @d pdf_running_link_on_node (pdftex_first_extension_code+39)
32753 @d pdf_space_font_code (pdftex_first_extension_code+40)
32754 @#
32755 @d tracing_stack_level_code (pdftex_first_extension_code+41)
32756 @d pdf_par_token_context_code (pdftex_first_extension_code+42)
32757 @d pdf_par_token_name_code (pdftex_first_extension_code+43)
32758 @d pdf_show_stream_code (pdftex_first_extension_code+44)
32759 @#
32760 @d pdftex_last_extension_code (pdftex_first_extension_code+44)
32761
32762 @<Put each...@>=
32763 if (pdf_on)
32764 {
32765 primitive("pdfliteral", extension, pdf_literal_node);@/
32766 @!@:pdf\_literal\_}{\.{\\pdfliteral} primitive@>
32767 primitive("pdfobj", extension, pdf_obj_code);@/
32768 @!@:pdf\_obj\_}{\.{\\pdfobj} primitive@>
32769 primitive("pdfrefobj", extension, pdf_refobj_node);@/
32770 @!@:pdf\_refobj\_}{\.{\\pdfrefobj} primitive@>
32771 primitive("pdfxform", extension, pdf_xform_code);@/
32772 @!@:pdf\_xform\_}{\.{\\pdfxform} primitive@>
32773 primitive("pdfrefxform", extension, pdf_refxform_node);@/
32774 @!@:pdf\_refxform\_}{\.{\\pdfrefxform} primitive@>
32775 primitive("pdfximage", extension, pdf_ximage_code);@/
32776 @!@:pdf\_ximage\_}{\.{\\pdfximage} primitive@>
32777 primitive("pdfrefximage", extension, pdf_refximage_node);@/
32778 @!@:pdf\_refximage\_}{\.{\\pdfrefximage} primitive@>
32779 primitive("pdfannot", extension, pdf_annot_node);@/
32780 @!@:pdf\_annot\_}{\.{\\pdfannot} primitive@>
32781 primitive("pdfstartlink", extension, pdf_start_link_node);@/
32782 @!@:pdf\_start\_link\_}{\.{\\pdfstartlink} primitive@>
32783 primitive("pdfendlink", extension, pdf_end_link_node);@/
32784 @!@:pdf\_end\_link\_}{\.{\\pdfendlink} primitive@>
32785 primitive("pdfoutline", extension, pdf_outline_code);@/
32786 @!@:pdf\_outline\_}{\.{\\pdfoutline} primitive@>
32787 primitive("pdfdest", extension, pdf_dest_node);@/
32788 @!@:pdf\_dest\_}{\.{\\pdfdest} primitive@>
32789 primitive("pdfthread", extension, pdf_thread_node);@/
32790 @!@:pdf\_thread\_}{\.{\\pdfthread} primitive@>
32791 primitive("pdfstartthread", extension, pdf_start_thread_node);@/
32792 @!@:pdf\_start\_thread\_}{\.{\\pdfstartthread} primitive@>
32793 primitive("pdfendthread", extension, pdf_end_thread_node);@/
32794 @!@:pdf\_end\_thread\_}{\.{\\pdfendthread} primitive@>
32795
32796 primitive("pdfinfo", extension, pdf_info_code);@/
32797 @!@:pdf\_info\_}{\.{\\pdfinfo} primitive@>
32798 primitive("pdfcatalog", extension, pdf_catalog_code);@/
32799 @!@:pdf\_catalog\_}{\.{\\pdfcatalog} primitive@>
32800 primitive("pdfnames", extension, pdf_names_code);@/
32801 @!@:pdf\_names\_}{\.{\\pdfnames} primitive@>
32802
32803 primitive("pdffontattr", extension, pdf_font_attr_code);@/
32804 @!@:pdf\_font\_attr\_}{\.{\\pdffontattr} primitive@>
32805 primitive("pdfincludechars", extension, pdf_include_chars_code);@/
32806 @!@:pdf\_include\_chars\_}{\.{\\pdfincludechars} primitive@>
32807 primitive("pdfmapfile", extension, pdf_map_file_code);@/
32808 @!@:pdf\_map\_file\_}{\.{\\pdfmapfile} primitive@>
32809 primitive("pdfmapline", extension, pdf_map_line_code);@/
32810 @!@:pdf\_map\_line\_}{\.{\\pdfmapline} primitive@>
32811 primitive("pdftrailer", extension, pdf_trailer_code);@/
32812 @!@:pdf\_trailer\_}{\.{\\pdftrailer} primitive@>
32813 primitive("pdftrailerid", extension, pdf_trailer_id_code);@/
32814 @!@:pdf\_trailer\_id\_}{\.{\\pdftrailerid} primitive@>
32815
32816 primitive("pdffontexpand", extension, pdf_font_expand_code);@/
32817 @!@:pdf\_font\_expand\_}{\.{\\pdffontexpand} primitive@>
32818
32819 primitive("pdfsnaprefpoint", extension, pdf_snap_ref_point_node);@/
32820 @!@:pdf\_snap\_ref\_point\_}{\.{\\pdfsnaprefpoint} primitive@>
32821 primitive("pdfsnapy", extension, pdf_snapy_node);@/
32822 @!@:pdf\_snapy\_}{\.{\\pdfsnapy} primitive@>
32823 primitive("pdfsnapycomp", extension, pdf_snapy_comp_node);@/
32824 @!@:pdf\_snapy\_comp\_}{\.{\\pdfsnapycomp} primitive@>
32825 primitive("pdfglyphtounicode", extension, pdf_glyph_to_unicode_code);@/
32826 @!@:pdf\_glyph\_to\_unicode\_}{\.{\\pdfglyphtounicode} primitive@>
32827 primitive("pdfcolorstack", extension, pdf_colorstack_node);@/
32828 @!@:pdf\_colorstack\_}{\.{\\pdfcolorstack} primitive@>
32829 primitive("pdfsetmatrix", extension, pdf_setmatrix_node);@/
32830 @!@:pdf\_setmatrix\_}{\.{\\pdfsetmatrix} primitive@>
32831 primitive("pdfsave", extension, pdf_save_node);@/
32832 @!@:pdf\_save\_}{\.{\\pdfsave} primitive@>
32833 primitive("pdfrestore", extension, pdf_restore_node);@/
32834 @!@:pdf\_restore\_}{\.{\\pdfrestore} primitive@>
32835 primitive("pdfnobuiltintounicode", extension, pdf_nobuiltin_tounicode_code);@/
32836 @!@:pdf\_nobuiltin\_tounicode\_}{\.{\\pdfnobuiltintounicode} primitive@>
32837 primitive("pdfinterwordspaceon", extension, pdf_interword_space_on_node);@/
32838 @!@:pdf\_interword\_space\_on\_}{\.{\\pdfinterwordspaceon} primitive@>
32839 primitive("pdfinterwordspaceoff", extension, pdf_interword_space_off_node);@/
32840 @!@:pdf\_interword\_space\_off\_}{\.{\\pdfinterwordspaceoff} primitive@>
32841 primitive("pdffakespace", extension, pdf_fake_space_node);@/
32842 @!@:pdf\_fake\_space\_}{\.{\\pdffakespace} primitive@>
32843 primitive("pdfrunninglinkoff", extension, pdf_running_link_off_node);@/
32844 @!@:pdf\_running\_link\_off\_}{\.{\\pdfrunninglinkoff} primitive@>
32845 primitive("pdfrunninglinkon", extension, pdf_running_link_on_node);@/
32846 @!@:pdf\_running\_link\_on\_}{\.{\\pdfrunninglinkon} primitive@>
32847 primitive("pdfspacefont", extension, pdf_space_font_code);@/
32848 @!@:pdf\_space\_font\_}{\.{\\pdfspacefont} primitive@>
32849 @#
32850 primitive("tracingstacklevels", extension, tracing_stack_level_code);@/
32851 @!@:tracingstacklevels\_}{\.{\\tracingstacklevels} primitive@>
32852 primitive("partokencontext", extension, pdf_par_token_context_code);@/
32853 @!@:\partokencontext}{\.{\\partokencontext} primitive@>
32854 primitive("partokenname", extension, pdf_par_token_name_code);@/
32855 @!@:partokenname\_}{\.{\\partokenname} primitive@>
32856 primitive("showstream", extension, pdf_show_stream_code);@/
32857 @!@:showstream\_}{\.{\\showstream} primitive@>
32858 }
32859
32860 @ After having defined the primitives, we arange for printing them.
32861
32862 @<Cases of |extension| for |print_cmd_chr|@>=
32863 case pdf_annot_node: print_esc("pdfannot");@+break;
32864 case pdf_catalog_code: print_esc("pdfcatalog");@+break;
32865 case pdf_dest_node: print_esc("pdfdest");@+break;
32866 case pdf_end_link_node: print_esc("pdfendlink");@+break;
32867 case pdf_end_thread_node: print_esc("pdfendthread");@+break;
32868 case pdf_font_attr_code: print_esc("pdffontattr");@+break;
32869 case pdf_font_expand_code: print_esc("pdffontexpand");@+break;
32870 case pdf_include_chars_code: print_esc("pdfincludechars");@+break;
32871 case pdf_info_code: print_esc("pdfinfo");@+break;
32872 case pdf_literal_node: print_esc("pdfliteral");@+break;
32873 case pdf_colorstack_node: print_esc("pdfcolorstack");@+break;
32874 case pdf_setmatrix_node: print_esc("pdfsetmatrix");@+break;
32875 case pdf_save_node: print_esc("pdfsave");@+break;
32876 case pdf_restore_node: print_esc("pdfrestore");@+break;
32877 case pdf_map_file_code: print_esc("pdfmapfile");@+break;
32878 case pdf_map_line_code: print_esc("pdfmapline");@+break;
32879 case pdf_names_code: print_esc("pdfnames");@+break;
32880 case pdf_obj_code: print_esc("pdfobj");@+break;
32881 case pdf_outline_code: print_esc("pdfoutline");@+break;
32882 case pdf_refobj_node: print_esc("pdfrefobj");@+break;
32883 case pdf_refxform_node: print_esc("pdfrefxform");@+break;
32884 case pdf_refximage_node: print_esc("pdfrefximage");@+break;
32885 case pdf_snap_ref_point_node: print_esc("pdfsnaprefpoint");@+break;
32886 case pdf_snapy_comp_node: print_esc("pdfsnapycomp");@+break;
32887 case pdf_snapy_node: print_esc("pdfsnapy");@+break;
32888 case pdf_start_link_node: print_esc("pdfstartlink");@+break;
32889 case pdf_start_thread_node: print_esc("pdfstartthread");@+break;
32890 case pdf_thread_node: print_esc("pdfthread");@+break;
32891 case pdf_trailer_code: print_esc("pdftrailer");@+break;
32892 case pdf_trailer_id_code: print_esc("pdftrailerid");@+break;
32893 case pdf_xform_code: print_esc("pdfxform");@+break;
32894 case pdf_ximage_code: print_esc("pdfximage");@+break;
32895 case pdf_nobuiltin_tounicode_code: print_esc("pdfnobuiltintounicode");@+break;
32896 case pdf_glyph_to_unicode_code: print_esc("pdfglyphtounicode");@+break;
32897 case pdf_interword_space_on_node: print_esc("pdfinterwordspaceon");@+break;
32898 case pdf_interword_space_off_node: print_esc("pdfinterwordspaceoff");@+break;
32899 case pdf_fake_space_node: print_esc("pdffakespace");@+break;
32900 case pdf_running_link_off_node: print_esc("pdfrunninglinkoff");@+break;
32901 case pdf_running_link_on_node: print_esc("pdfrunninglinkon");@+break;
32902 case pdf_space_font_code: print_esc("pdfspacefont");@+break;
32903 case tracing_stack_level_code: print_esc("tracingstacklevels");@+break;
32904 case pdf_par_token_context_code: print_esc("partokencontext");@+break;
32905 case pdf_par_token_name_code: print_esc("partokenname");@+break;
32906 case pdf_show_stream_code: print_esc("showstream");@+break;
32907
32908
32909 @ And last not least we have to implement the primitives.
32910
32911 @<Cases for |do_extension|@>=
32912 case pdf_annot_node: @<Implement \.{\\pdfannot}@>@;@+break;
32913 case pdf_catalog_code: @<Implement \.{\\pdfcatalog}@>@;@+break;
32914 case pdf_dest_node: @<Implement \.{\\pdfdest}@>@;@+break;
32915 case pdf_end_link_node: @+break;
32916 case pdf_end_thread_node: @+break;
32917 case pdf_font_attr_code: @<Implement \.{\\pdffontattr}@>@;@+break;
32918 case pdf_font_expand_code: read_expand_font();@+break;
32919 case pdf_include_chars_code: pdf_include_chars();@+break;
32920 case pdf_info_code: scan_pdf_ext_toks();@+break;
32921 case pdf_literal_node: @<Implement \.{\\pdfliteral}@>@;@+break;
32922 case pdf_colorstack_node: @<Implement \.{\\pdfcolorstack}@>@;@+break;
32923 case pdf_setmatrix_node: scan_pdf_ext_toks();@+break;
32924 case pdf_save_node: @+break;
32925 case pdf_restore_node: @+break;
32926 case pdf_map_file_code: scan_pdf_ext_toks();@+break;
32927 case pdf_map_line_code: scan_pdf_ext_toks();@+break;
32928 case pdf_names_code: scan_pdf_ext_toks();@+break;
32929 case pdf_obj_code: @<Implement \.{\\pdfobj}@>@;@+break;
32930 case pdf_outline_code: @<Implement \.{\\pdfoutline}@>@;@+break;
32931 case pdf_refobj_node: scan_int();@+break;
32932 case pdf_refxform_node: scan_int();@+break;
32933 case pdf_refximage_node: scan_int();@+break;
32934 case pdf_snap_ref_point_node: @+break;
32935 case pdf_snapy_comp_node: scan_int();@+break;
32936 case pdf_snapy_node: @+break;
32937 case pdf_start_link_node: scan_annot(); scan_action();@+break;
32938 case pdf_start_thread_node: scan_annot(); scan_thread_id();@+break;
32939 case pdf_thread_node: scan_annot(); scan_thread_id();@+break;
32940 case pdf_trailer_code: scan_pdf_ext_toks();@+break;
32941 case pdf_trailer_id_code: scan_pdf_ext_toks();@+break;
32942 case pdf_xform_code: @<Implement \.{\\pdfxform}@>@;@+break;
32943 case pdf_ximage_code: scan_image(); @+break;
32944 case pdf_glyph_to_unicode_code: scan_pdf_ext_toks();scan_pdf_ext_toks();@+break;
32945 case pdf_nobuiltin_tounicode_code: scan_font_ident();@+break;
32946 case pdf_interword_space_on_node: @+break;
32947 case pdf_interword_space_off_node: @+break;
32948 case pdf_fake_space_node: @+break;
32949 case pdf_running_link_off_node: @+break;
32950 case pdf_running_link_on_node: @+break;
32951 case pdf_space_font_code: scan_pdf_ext_toks(); @+break;
32952 case tracing_stack_level_code: scan_int();@+break;
32953 case pdf_par_token_context_code: scan_optional_equals();scan_int();@+break;
32954 case pdf_par_token_name_code: scan_optional_equals();get_token();@+break;
32955 case pdf_show_stream_code: scan_optional_equals();scan_int();@+break;
32956
32957
32958 @ @<Implement \.{\\pdfannot}@>=
32959 {@+ if (scan_keyword("reserveobjnum")) {@+@<Scan an optional space@>;}
32960 else{@+
32961 if (scan_keyword("useobjnum")) {@+scan_int();}
32962 scan_annot();
32963 scan_pdf_ext_toks();
32964 }
32965 }
32966
32967 @ @<Implement \.{\\pdfcatalog}@>=
32968 {@+ scan_pdf_ext_toks();
32969 if (scan_keyword("openaction")) scan_action();
32970 }
32971
32972 @ The |scan_action| routine is used not only here
32973 but also for links and outlines.
32974
32975
32976 @d pdf_action_page 0 /*GoTo action*/
32977 @d pdf_action_goto 1 /*GoTo action*/
32978 @d pdf_action_thread 2 /*Thread action*/
32979 @d pdf_action_user 3 /*user-defined action*/
32980
32981 @<Declare procedures needed in |do_ext...@>=
32982 static void scan_action(void) /*read an action specification*/
32983 {@+int pdf_action;
32984 int pdf_action_file=0;
32985 int pdf_action_new_window=0;
32986 if (scan_keyword("user"))
32987 pdf_action=pdf_action_user;
32988 else if (scan_keyword("goto"))
32989 pdf_action=pdf_action_goto;
32990 else if (scan_keyword("thread"))
32991 pdf_action=pdf_action_thread;
32992 else
32993 pdf_error("ext1","action type missing");
32994 if (pdf_action==pdf_action_user) {@+
32995 scan_pdf_ext_toks();
32996 return; }
32997 if (scan_keyword("file")) {@+
32998 scan_pdf_ext_toks();
32999 pdf_action_file=1;
33000 }
33001 if (scan_keyword("struct")) {@+
33002 if (pdf_action!=pdf_action_goto)
33003 pdf_error("ext1","only GoTo action can be used with `struct'");
33004 if (pdf_action_file!=0) {@+
33005 scan_pdf_ext_toks();
33006 }
33007 else if (scan_keyword("name")) {@+
33008 scan_pdf_ext_toks();
33009 }
33010 else if (scan_keyword("num")) {@+
33011 scan_int();
33012 if (cur_val <= 0)
33013 pdf_error("ext1","num identifier must be positive");
33014 }
33015 else
33016 pdf_error("ext1","identifier type missing");
33017 }
33018 if (scan_keyword("page")) {@+
33019 if (pdf_action!=pdf_action_goto)
33020 pdf_error("ext1","only GoTo action can be used with `page'");
33021 pdf_action=pdf_action_page;
33022 scan_int();
33023 if (cur_val <= 0)
33024 pdf_error("ext1","page number must be positive");
33025 scan_pdf_ext_toks();
33026 }
33027 else if (scan_keyword("name")) {@+
33028 scan_pdf_ext_toks();
33029 }
33030 else if (scan_keyword("num")) {@+
33031 if ((pdf_action==pdf_action_goto)&&
33032 (pdf_action_file!=0))
33033 pdf_error("ext1",
33034 "`goto' option cannot be used with both `file' and `num'");
33035 scan_int();
33036 if (cur_val <= 0)
33037 pdf_error("ext1","num identifier must be positive");
33038 }
33039 else
33040 pdf_error("ext1","identifier type missing");
33041 if (scan_keyword("newwindow")) {@+
33042 pdf_action_new_window=1;
33043 @<Scan an optional space@>;}
33044 else if (scan_keyword("nonewwindow")) {@+
33045 pdf_action_new_window=2;
33046 @<Scan an optional space@>;}
33047 else
33048 pdf_action_new_window=0;
33049 if ((pdf_action_new_window > 0)&&
33050 (((pdf_action!=pdf_action_goto)&&
33051 (pdf_action!=pdf_action_page))||
33052 (pdf_action_file==0)))
33053 pdf_error("ext1",
33054 "`newwindow'/`nonewwindow' must be used with `goto' and `file' option");
33055 }
33056
33057 @ Next we scan a destination.
33058
33059 @d pdf_dest_xyz 0
33060 @d pdf_dest_fit 1
33061 @d pdf_dest_fith 2
33062 @d pdf_dest_fitv 3
33063 @d pdf_dest_fitb 4
33064 @d pdf_dest_fitbh 5
33065 @d pdf_dest_fitbv 6
33066 @d pdf_dest_fitr 7
33067
33068 @<Implement \.{\\pdfdest}@>=
33069 {@+ int pdf_dest_type;
33070 if (scan_keyword("struct")) {@+
33071 scan_int();
33072 if (cur_val <= 0)
33073 pdf_error("ext1","struct identifier must be positive");
33074 }
33075 if (scan_keyword("num")) {@+
33076 scan_int();
33077 if (cur_val <= 0)
33078 pdf_error("ext1","num identifier must be positive");
33079 if (cur_val > max_halfword)
33080 pdf_error("ext1","number too big");
33081 }
33082 else if (scan_keyword("name")) {@+
33083 scan_pdf_ext_toks();
33084 }
33085 else
33086 pdf_error("ext1","identifier type missing");
33087 if (scan_keyword("xyz")) {@+
33088 pdf_dest_type=pdf_dest_xyz;
33089 if (scan_keyword("zoom")) {@+
33090 scan_int();
33091 if (cur_val > max_halfword)
33092 pdf_error("ext1","number too big");
33093 }
33094 }
33095 else if (scan_keyword("fitbh"))
33096 pdf_dest_type=pdf_dest_fitbh;
33097 else if (scan_keyword("fitbv"))
33098 pdf_dest_type=pdf_dest_fitbv;
33099 else if (scan_keyword("fitb"))
33100 pdf_dest_type=pdf_dest_fitb;
33101 else if (scan_keyword("fith"))
33102 pdf_dest_type=pdf_dest_fith;
33103 else if (scan_keyword("fitv"))
33104 pdf_dest_type=pdf_dest_fitv;
33105 else if (scan_keyword("fitr"))
33106 pdf_dest_type=pdf_dest_fitr;
33107 else if (scan_keyword("fit"))
33108 pdf_dest_type=pdf_dest_fit;
33109 else
33110 pdf_error("ext1","destination type missing");
33111 @<Scan an optional space@>;
33112 if (pdf_dest_type==pdf_dest_fitr) {@+
33113 scan_alt_rule(); /*scans | < rule spec > | to |alt_rule|*/
33114 }
33115 }
33116
33117
33118
33119 @ @<Declare procedures needed in |do_ext...@>=
33120 static void scan_alt_rule(void) /*scans rule spec to |alt_rule|*/
33121 {@+
33122 reswitch:
33123 if (scan_keyword("width")) {@+
33124 scan_normal_dimen;
33125 goto reswitch;
33126 }
33127 if (scan_keyword("height")) {@+
33128 scan_normal_dimen;
33129 goto reswitch;
33130 }
33131 if (scan_keyword("depth")) {@+
33132 scan_normal_dimen;
33133 goto reswitch;
33134 }
33135 }
33136
33137 static void scan_annot(void) /*scan an annotation*/
33138 {@+
33139 scan_alt_rule(); /*scans | < rule spec > |*/
33140 if (scan_keyword("attr"))
33141 scan_pdf_ext_toks();
33142 }
33143
33144
33145
33146 @ @<Implement \.{\\pdffontattr}@>=
33147 {@+
33148 scan_font_ident();
33149 if (cur_val==null_font)
33150 pdf_error("font","invalid font identifier");
33151 scan_pdf_ext_toks();
33152 }
33153
33154 @ To implement \.{\\pdffontexpand} we need the following routine:
33155
33156 @<Declare procedures needed in |do_ext...@>=
33157 static void read_expand_font(void) /*read font expansion spec*/
33158 {@+int shrink_limit, stretch_limit, font_step;
33159 internal_font_number f;
33160
33161 /*read font expansion parameters*/
33162 scan_font_ident();
33163 f=cur_val;
33164 if (f==null_font)
33165 pdf_error("font expansion","invalid font identifier");
33166 scan_optional_equals();
33167 scan_int();
33168 scan_int();
33169 scan_int();
33170 if (scan_keyword("autoexpand")) {@+
33171 @<Scan an optional space@>;
33172 }
33173 }
33174
33175 @ Do implement \.{\\pdfincludechars} we need the next function.
33176 @<Declare procedures needed in |do_ext...@>=
33177 static void pdf_include_chars(void)
33178 {@+str_number s;
33179 pool_pointer k; /*running indices*/
33180 internal_font_number f;
33181
33182 scan_font_ident();
33183 f=cur_val;
33184 if (f==null_font)
33185 pdf_error("font","invalid font identifier");
33186 scan_pdf_ext_toks();
33187 }
33188
33189 @ @<Implement \.{\\pdfliteral}@>=
33190 {@+ int k;
33191 if (scan_keyword("shipout")) k=pdf_lateliteral_node;
33192 else k=pdf_literal_node;
33193 if (scan_keyword("direct")) do_nothing;
33194 else if (scan_keyword("page")) do_nothing;
33195 else do_nothing;
33196 if (k==pdf_literal_node) scan_pdf_ext_toks();
33197 else scan_pdf_ext_late_toks();
33198 }
33199
33200 @
33201
33202 @d colorstack_set 0
33203 @d colorstack_push 1
33204 @d colorstack_data 1 /* last value where data field is set */
33205 @d colorstack_pop 2
33206 @d colorstack_current 3
33207
33208 @<Implement \.{\\pdfcolorstack}@>=
33209 {@+int i;
33210 scan_int();
33211 if (scan_keyword("set")) {@+
33212 i=colorstack_set;
33213 }
33214 else if (scan_keyword("push")) {@+
33215 i=colorstack_push;
33216 }
33217 else if (scan_keyword("pop")) {@+
33218 i=colorstack_pop;
33219 }
33220 else if (scan_keyword("current")) {@+
33221 i=colorstack_current;
33222 }
33223 else{@+
33224 i=-1; /*error*/
33225 }
33226 if (i >= 0) {@+
33227 if (i <= colorstack_data) {@+
33228 scan_pdf_ext_toks();
33229 }
33230 }
33231 }
33232
33233 @ @<Implement \.{\\pdfobj}@>=
33234 {@+
33235 if (scan_keyword("reserveobjnum")) {@+
33236 @<Scan an optional space@>;
33237 }
33238 else{@+
33239 if (scan_keyword("useobjnum")) scan_int();
33240 if (scan_keyword("stream")) {@+
33241 if (scan_keyword("attr")) scan_pdf_ext_toks();
33242 }
33243 if (scan_keyword("file")) do_nothing;
33244 scan_pdf_ext_toks();
33245 }
33246 }
33247
33248 @ @<Implement \.{\\pdfoutline}@>=
33249 {@+
33250 if (scan_keyword("attr")) scan_pdf_ext_toks();
33251 scan_action();
33252 if (scan_keyword("count")) scan_int();
33253 scan_pdf_ext_toks();
33254 }
33255
33256 @ @<Implement \.{\\pdfxform}@>=
33257 {@+
33258 if (scan_keyword("attr")) scan_pdf_ext_toks();
33259 if (scan_keyword("resources")) scan_pdf_ext_toks();
33260 scan_register_num();
33261 }
33262
33263 @ The next procedure is neede for \.{\\pdfthread} and \.{\\pdfstartthread}
33264
33265 @<Declare procedures needed in |do_ext...@>=
33266 static void scan_thread_id(void)
33267 {@+if (scan_keyword("num")) scan_int();
33268 else if (scan_keyword("name")) scan_pdf_ext_toks();
33269 }
33270
33271 @ The next functions are used to implement \.{\\pdfximage}.
33272 @<Declare procedures needed in |do_ext...@>=
33273 static void scan_pdf_box_spec(void) /*scans PDF pagebox specification*/
33274 {@+
33275 if (scan_keyword("mediabox")) return;
33276 else if (scan_keyword("cropbox")) return;
33277 else if (scan_keyword("bleedbox")) return;
33278 else if (scan_keyword("trimbox")) return;
33279 else if (scan_keyword("artbox")) return;
33280 }
33281
33282 static void scan_image(void)
33283 {@+ scan_alt_rule();
33284 if (scan_keyword("attr")) scan_pdf_ext_toks();
33285 if (scan_keyword("named")) scan_pdf_ext_toks();
33286 else if (scan_keyword("page")) scan_int();
33287 if (scan_keyword("colorspace")) scan_int();
33288 scan_pdf_box_spec();
33289 scan_pdf_ext_toks();
33290 }
33291
33292
33293 @ The current version of the {\tt -pdf} version does not implementa all \pdfTeX\ primitives.
33294 For example, the primitves \.{\\pdfcopyfont} and \.{\\letterspacefont} are not defined but
33295 dummy versions could be implemented with |scan_font_ident| and |scan_int|.
33296
33297
33298 @* Index.
33299 Here is where you can find all uses of each identifier in the program,
33300 with underlined entries pointing to where the identifier was defined.
33301 If the identifier is only one letter long, however, you get to see only
33302 the underlined entries. {\sl All references are to section numbers instead of
33303 page numbers.}
33304
33305 This index also lists error messages and other aspects of the program
33306 that you might want to look up some day. For example, the entry
33307 for ``system dependencies'' lists all sections that should receive
33308 special attention from people who are installing \TeX\ in a new
33309 operating environment. A list of various things that can't happen appears
33310 under ``this can't happen''. Approximately 40 sections are listed under
33311 ``inner loop''; these account for about 60\pct! of \TeX's running time,
33312 exclusive of input and output.