Debian Codegraph @

texk/web2c/hitexdir/hitex.w

raw
1 % This file is part of HINT
2 % Copyright 2017-2026 Martin Ruckert, Hochschule Muenchen, Lothstrasse 64, 80336 Muenchen
3 %
4 % Permission is hereby granted, free of charge, to any person obtaining a copy
5 % of this software and associated documentation files (the "Software"), to deal
6 % in the Software without restriction, including without limitation the rights
7 % to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 % copies of the Software, and to permit persons to whom the Software is
9 % furnished to do so, subject to the following conditions:
10 %
11 % The above copyright notice and this permission notice shall be
12 % included in all copies or substantial portions of the Software.
13 %
14 % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 % IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 % FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 % COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
18 % WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
19 % OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 % THE SOFTWARE.
21 %
22 % Except as contained in this notice, the name of the copyright holders shall
23 % not be used in advertising or otherwise to promote the sale, use or other
24 % dealings in this Software without prior written authorization from the
25 % copyright holders.
26
27 % The HINT program is derived from Donald E. Knuth's TeX and the
28 % subsequent e-TeX extension of TeX.
29
30 % Prote is copyright (C) 2021 by Thierry Laronde and put under
31 % the MIT/X11 license.
32 %
33 % As TeX and e-TeX are reserved names for the unchanged (except for the
34 % necessary implementation of system dependencies) instances of, resp.,
35 % Donald E. Knuth's program and the NTS team's e-TeX implementation, the
36 % name Prote is reserved for this kerTeX implementation.
37 %
38 % Hence, this is neither TeX (even if it is compatible at start) nor
39 % e-TeX (even if is compatible when entering the first set of
40 % extensions).
41
42 % Version 0 was released in September 1982 after it passed a variety of tests.
43 % Version 1 was released in November 1983 after thorough testing.
44 % Version 1.1 fixed ``disappearing font identifiers'' et alia (July 1984).
45 % Version 1.2 allowed `0' in response to an error, et alia (October 1984).
46 % Version 1.3 made memory allocation more flexible and local (November 1984).
47 % Version 1.4 fixed accents right after line breaks, et alia (April 1985).
48 % Version 1.5 fixed \the\toks after other expansion in \edefs (August 1985).
49 % Version 2.0 (almost identical to 1.5) corresponds to "Volume B" (April 1986).
50 % Version 2.1 corrected anomalies in discretionary breaks (January 1987).
51 % Version 2.2 corrected "(Please type...)" with null \endlinechar (April 1987).
52 % Version 2.3 avoided incomplete page in premature termination (August 1987).
53 % Version 2.4 fixed \noaligned rules in indented displays (August 1987).
54 % Version 2.5 saved cur_order when expanding tokens (September 1987).
55 % Version 2.6 added 10sp slop when shipping leaders (November 1987).
56 % Version 2.7 improved rounding of negative-width characters (November 1987).
57 % Version 2.8 fixed weird bug if no \patterns are used (December 1987).
58 % Version 2.9 made \csname\endcsname's "relax" local (December 1987).
59 % Version 2.91 fixed \outer\def\a0{}\a\a bug (April 1988).
60 % Version 2.92 fixed \patterns, also file names with complex macros (May 1988).
61 % Version 2.93 fixed negative halving in allocator when mem_min<0 (June 1988).
62 % Version 2.94 kept open_log_file from calling fatal_error (November 1988).
63 % Version 2.95 solved that problem a better way (December 1988).
64 % Version 2.96 corrected bug in "Infinite shrinkage" recovery (January 1989).
65 % Version 2.97 corrected blunder in creating 2.95 (February 1989).
66 % Version 2.98 omitted save_for_after at outer level (March 1989).
67 % Version 2.99 caught $$\begingroup\halign..$$ (June 1989).
68 % Version 2.991 caught .5\ifdim.6... (June 1989).
69 % Version 2.992 introduced major changes for 8-bit extensions (September 1989).
70 % Version 2.993 fixed a save_stack synchronization bug et alia (December 1989).
71 % Version 3.0 fixed unusual displays; was more \output robust (March 1990).
72 % Version 3.1 fixed nullfont, disabled \write{\the\prevgraf} (September 1990).
73 % Version 3.14 fixed unprintable font names and corrected typos (March 1991).
74 % Version 3.141 more of same; reconstituted ligatures better (March 1992).
75 % Version 3.1415 preserved nonexplicit kerns, tidied up (February 1993).
76 % Version 3.14159 allowed fontmemsize to change; bulletproofing (March 1995).
77 % Version 3.141592 fixed \xleaders, glueset, weird alignments (December 2002).
78 % Version 3.1415926 was a general cleanup with minor fixes (February 2008).
79 % Version 3.14159265 was similar (January 2014).
80 % Version 3.141592653 was similar but more extensive (January 2021).
81
82 % A reward of $327.68 will be paid to the first finder of any remaining bug.
83
84 % This is the 1.1 version of Prote, developed during August 2021,
85 % and corrected during September/October 2021 and amended in august 2023
86 % for file primitives behavior matching input behavior.
87 %
88 % 1.0: adds primitives needed by LaTeX as listed in ltnews31.
89 % - 2022-07-21: tidying formal fix: a spurious line was a left over
90 % of a removed paragraph (pointed by Martin Ruckert). Suppressed.
91 %
92 % 1.1: 2023-08-01: the new file primitives are used in LaTeX expecting
93 % the input behavior that ".tex" be appended if no extension. So
94 % modified to provide this.
95 %
96 % History towards 1.0 release:
97 % 0.99.4:
98 % - typos and style corrections provided by Martin Ruckert for
99 % clean translation in Pascal (forward declarations and underscores
100 % omitted);
101 % - adjustments against e-TeX 2.6 instead of 2.1 (T. Laronde).
102 % 0.99.7:
103 % - \expanded was using an e-TeX procedure not doing def handling
104 % => using scan_toks() now. Reported by Martin Ruckert and
105 % test code narrowed down by Phelype Oleinik.
106 % 0.99.8:
107 % - \expanded again: scan_toks() sets def_ref. But back_list()
108 % has to take not the reference count, but the first token.
109 % Passing def_ref, a next invocation of scan_toks() was inserting
110 % a missing left brace and then reading pass the end of the token
111 % list to find a matching right one. def_ref => link(def_ref).
112 % Test code narrowed down by Phelype Oleinik (a great help!).
113 % - The API for file related primitives has been changed: no error
114 % is reported on failure to find/open and nothing is returned
115 % (matches current other implementations).
116 % 0.99.9:
117 % - Fix typos in Pascal replacement text; xchg_buffer_length=0 =>
118 % xchg_buffer_length:=0 (caught by Martin Ruckert).
119 % 0.99.10:
120 % - KerTeX Public License -> X11/MIT license.
121 % 1.0:
122 % - Just naming the official release. No change.
123 %
124 % This work was done by Thierry Laronde and is under the MIT/X11
125 % license.
126 %
127 %
128
129 % Here is TeX material that gets inserted after \input webmac
130 \def\hang{\hangindent 3em\noindent\ignorespaces}
131 \def\hangg#1 {\hang\hbox{#1 }}
132 \def\textindent#1{\hangindent2.5em\noindent\hbox to2.5em{\hss#1 }\ignorespaces}
133 \font\ninerm=cmr9
134 \let\mc=\ninerm % medium caps for names like SAIL
135
136 \ifxetex
137 \def\XeTeX{X\kern-.125em\lower.5ex\hbox{\mirror{E}}\kern-.1667em\TeX}
138 \else
139 \def\XeTeX{X\kern-.125em\lower.5ex\hbox{E}\kern-.1667em\TeX}
140 \fi
141
142 \def\eTeX{$\varepsilon$-\TeX}
143
144 \def\Prote{{\tenrm P\kern-0.1em R\kern-0.15em\raise.11ex\hbox{o}%
145 \kern-0.22em T\kern-0.05em E}}
146 \ifpdftex
147 \sanitizecommand{\eTeX}{eTeX}
148 \sanitizecommand{\Prote}{PRoTE}
149 \fi
150 \font\tenlogo=logo10
151 \def\MP{{\tenlogo META}\-{\tenlogo POST}}
152 \def\eTeX{$\varepsilon$-\TeX}
153 \font\sf=cmss10 % used for the HINT name
154 \def\HINT{\leavevmode\hbox{\sf HINT\spacefactor1000}}
155 \ifpdftex\sanitizecommand{\HINT}{HINT}\fi
156 \font\revrm=xbmc10 % for right-to-left text
157 % to generate xbmc10 (i.e., reflected cmbx10) use a file
158 % xbmc10.mf containing:
159 %+++++++++++++++++++++++++++++++++++++++++++++++++
160 % if unknown cmbase: input cmbase fi
161 % extra_endchar := extra_endchar &
162 % "currentpicture:=currentpicture " &
163 % "reflectedabout((.5[l,r],0),(.5[l,r],1));";
164 % input cmbx10
165 %+++++++++++++++++++++++++++++++++++++++++++++++++
166 \ifx\beginL\undefined % this is TeX
167 \def\XeT{X\kern-.125em\lower.5ex\hbox{E}\kern-.1667emT}
168 \def\TeXeT{\TeX-\hbox{\revrm \XeT}} % for TeX-XeT
169 \def\TeXXeT{\TeX-\hbox{\revrm -\XeT}} % for TeX--XeT
170 \else
171 \ifx\eTeXversion\undefined % this is \TeXeT
172 \def\TeXeT{\TeX-{\revrm\beginR\TeX\endR}} % for TeX-XeT
173 \def\TeXXeT{\TeX-{\revrm\beginR\TeX-\endR}} % for TeX--XeT
174 \else % this is \eTeX
175 \def\TeXeT{\TeX-{\TeXXeTstate=1\revrm\beginR\TeX\endR}} % for TeX-XeT
176 \def\TeXXeT{\TeX-{\TeXXeTstate=1\revrm\beginR\TeX-\endR}} % for TeX--XeT
177 \fi
178 \fi
179 \def\PASCAL{Pascal}
180 \def\ph{\hbox{Pascal-H}}
181 \def\pct!{{\char`\%}} % percent sign in ordinary text
182 \def\grp{\.{\char'173...\char'175}}
183 \font\logo=logo10 % font used for the METAFONT logo
184 \def\MF{{\logo META}\-{\logo FONT}}
185 \def\<#1>{$\langle#1\rangle$}
186 \def\section{\mathhexbox278}
187
188 \def\(#1){} % this is used to make section names sort themselves better
189 \def\9#1{} % this is used for sort keys in the index via @@:sort key}{entry@@>
190
191 \let\@@=\relax % we want to be able to \write a \?
192
193 \def\HiTeX{Hi\TeX}
194 \def\LuaTeX{Lua\TeX}
195
196 \def\title{Hi\TeX}
197 \def\LaTeX{L\kern-.36em\raise.3ex\hbox{\sc A}\kern-.15em\TeX}%
198 % system dependent redefinitions of \title should come later
199 % and should use:
200 % \toks0=\expandafter{\title}
201 % \edef\title{...\the\toks0...}
202 %\let\maybe=\iffalse % print only changed modules
203 \def\topofcontents{\hsize 5.5in
204 \vglue 0pt plus 1fil minus 1.5in
205 \def\@@##1]{\hbox to 1in{\hfil##1.\ }}
206 }
207 \def\botofcontents{\vskip 0pt plus 1fil minus 1.5in}
208 \pageno=3
209 \def\glob{13} % this should be the section number of "<Global...>"
210 \def\gglob{20, 26} % this should be the next two sections of "<Global...>"
211
212 \def\.#1{\leavevmode\hbox{\tentex % typewriter type for strings
213 \let\\=\BS % backslash in a string
214 \let\'=\RQ % right quote in a string
215 \let\`=\LQ % left quote in a string
216 \let\{=\LB % left brace in a string
217 \let\}=\RB % right brace in a string
218 \let\~=\TL % tilde in a string
219 \let\ =\SP % space in a string
220 \let\_=\UL % underline in a string
221 \let\&=\AM % ampersand in a string
222 #1\kern.05em}}
223 \def\&#1{\leavevmode\hbox{\bf\def\_{\UL}%
224 #1\/\kern.05em}} % boldface type for reserved words
225 \def\\#1{\leavevmode\hbox{\it\def\_{\UL}%
226 #1\/\kern.05em}} % italic type for identifiers
227 \def\vb#1{{\rm #1}}
228 \def\^{\ifmmode\mathchar"222 \else\char`^ \fi} % pointer or hat
229 \def\LQ{{\tt\char'22}} % left quote in a string
230 \def\RQ{{\tt\char'23}} % right quote in a string
231 \def\UL{{\tt\char`\_}} % underline character in a C identifier
232 \def\dotdot{\mathrel{.\,.}} % double dot, used only in math mode
233 \setbox\MGbox=\hbox{\kern1pt$\rightarrow$\kern1pt} % C pointer to field
234 \def\MG{\copy\MGbox}
235 @s dotdot TeX
236 @s alpha_file int
237 @s byte_file int
238 @s word_file int
239 @s uint8_t int
240 @s int16_t int
241 @s uint16_t int
242 @s int32_t int
243 @s uint32_t int
244 @s halfword int
245 @s nonnegative_integer int
246 @s small_number int
247 @s glue_ratio double
248 @s Xdimen int
249 @s Kern int
250 @s Font int
251 @s Glue int
252 @s Disc int
253 @s Lig int
254 @s Rule int
255 @s List int
256 @s Kind int
257 @s Info int
258 @s kpse_file_format_type int
259 @s Stretch int
260 @s in TeX
261 @s line normal
262 @s to do
263
264 @* Introduction.
265 This is Hi\TeX, a program derived from \TeX, extending its capabilities
266 using \eTeX\ and \Prote, and adding functions common to other engines from
267 the \TeX\ Live distribution. Hi\TeX\ writes output files in
268 the \HINT\ file format. Like \TeX, it is
269 a document compiler intended to produce typesetting of high
270 quality.
271 The \PASCAL\ program that follows is the definition of \TeX82, a standard
272 @:PASCAL}{\PASCAL@>
273 @!@:TeX82}{\TeX82@>
274 version of \TeX\ that is designed to be highly portable so that identical output
275 will be obtainable on a great variety of computers.
276
277 The main purpose of the following program is to explain the algorithms of \TeX\
278 as clearly as possible. As a result, the program will not necessarily be very
279 efficient when a particular \PASCAL\ compiler has translated it into a
280 particular machine language. However, the program has been written so that it
281 can be tuned to run efficiently in a wide variety of operating environments
282 by making comparatively few changes. Such flexibility is possible because
283 the documentation that follows is written in the \.{WEB} language, which is
284 at a higher level than \PASCAL; the preprocessing step that converts \.{WEB}
285 to \PASCAL\ is able to introduce most of the necessary refinements.
286 Semi-automatic translation to other languages is also feasible, because the
287 program below does not make extensive use of features that are peculiar to
288 \PASCAL.
289
290 A large piece of software like \TeX\ has inherent complexity that cannot
291 be reduced below a certain level of difficulty, although each individual
292 part is fairly simple by itself. The \.{WEB} language is intended to make
293 the algorithms as readable as possible, by reflecting the way the
294 individual program pieces fit together and by providing the
295 cross-references that connect different parts. Detailed comments about
296 what is going on, and about why things were done in certain ways, have
297 been liberally sprinkled throughout the program. These comments explain
298 features of the implementation, but they rarely attempt to explain the
299 \TeX\ language itself, since the reader is supposed to be familiar with
300 {\sl The \TeX book}.
301 @.WEB@>
302 @:TeXbook}{\sl The \TeX book@>
303
304 @ The present implementation has a long ancestry, beginning in the summer
305 of~1977, when Michael~F. Plass and Frank~M. Liang designed and coded
306 a prototype
307 @^Plass, Michael Frederick@>
308 @^Liang, Franklin Mark@>
309 @^Knuth, Donald Ervin@>
310 based on some specifications that the author (in the following, unless
311 specified, ``the author'' refers to D.E.~Knuth) had made in May of that year.
312 This original proto\TeX\ included macro definitions and elementary
313 manipulations on boxes and glue, but it did not have line-breaking,
314 page-breaking, mathematical formulas, alignment routines, error recovery,
315 or the present semantic nest; furthermore,
316 it used character lists instead of token lists, so that a control sequence
317 like \.{\\halign} was represented by a list of seven characters. A
318 complete version of \TeX\ was designed and coded by the author in late
319 1977 and early 1978; that program, like its prototype, was written in the
320 {\mc SAIL} language, for which an excellent debugging system was
321 available. Preliminary plans to convert the {\mc SAIL} code into a form
322 somewhat like the present ``web'' were developed by Luis Trabb~Pardo and
323 @^Trabb Pardo, Luis Isidoro@>
324 the author at the beginning of 1979, and a complete implementation was
325 created by Ignacio~A. Zabala in 1979 and 1980. The \TeX82 program, which
326 @^Zabala Salelles, Ignacio Andr\'es@>
327 was written by the author during the latter part of 1981 and the early
328 part of 1982, also incorporates ideas from the 1979 implementation of
329 @^Guibas, Leonidas Ioannis@>
330 @^Sedgewick, Robert@>
331 @^Wyatt, Douglas Kirk@>
332 \TeX\ in {\mc MESA} that was written by Leonidas Guibas, Robert Sedgewick,
333 and Douglas Wyatt at the Xerox Palo Alto Research Center. Several hundred
334 refinements were introduced into \TeX82 based on the experiences gained with
335 the original implementations, so that essentially every part of the system
336 has been substantially improved. After the appearance of ``Version 0'' in
337 September 1982, this program benefited greatly from the comments of
338 many other people, notably David~R. Fuchs and Howard~W. Trickey.
339 A final revision in September 1989 extended the input character set to
340 eight-bit codes and introduced the ability to hyphenate words from
341 different languages, based on some ideas of Michael~J. Ferguson.
342 @^Fuchs, David Raymond@>
343 @^Trickey, Howard Wellington@>
344 @^Ferguson, Michael John@>
345
346 No doubt there still is plenty of room for improvement, but the author
347 is firmly committed to keeping \TeX82 ``frozen'' from now on; stability
348 and reliability are to be its main virtues.
349
350 On the other hand, the \.{WEB} description can be extended without changing
351 the core of \TeX82 itself, and the program has been designed so that such
352 extensions are not extremely difficult to make.
353 The |banner| string defined here should be changed whenever \TeX\
354 undergoes any modifications, so that it will be clear which version of
355 \TeX\ might be the guilty party when a problem arises.
356 @^extensions to \TeX@>
357 @^system dependencies@>
358
359 This program contains code for various features extending \TeX,
360 therefore this program is called `\Prote' and not
361 `\TeX'; the official name `\TeX' by itself is reserved
362 for software systems that are fully compatible with each other.
363 A special test suite called the ``\.{TRIP} test'' is available for
364 helping to determine whether a particular implementation deserves to be
365 known as `\TeX' [cf.~Stanford Computer Science report CS1027,
366 November 1984].
367
368 A similar test suite called the ``\.{SELLETTE} test'' is available for
369 helping to determine whether a particular implementation deserves to be
370 known as `\Prote'.
371
372 @d eTeX_version 2 /* \.{\\eTeXversion} */
373 @d eTeX_revision ".6" /* \.{\\eTeXrevision} */
374 @d eTeX_version_string "2.6" /*current \eTeX\ version*/
375 @#
376 @d TeX_banner "This is TeX, Version 3.141592653" /*printed when \TeX\ starts*/
377 @#
378 @#
379 @d TEX ETEX /*change program name into |ETEX|*/
380 @#
381 @d eTeX_states 1 /*number of \eTeX\ state variables in |eqtb|*/
382 @#
383 @d Prote_version_string "3.141592653-2.6-1.1.0" /*current \Prote\ version*/
384 @d Prote_version 1 /* \.{\\Proteversion} */
385 @d Prote_revision ".1.0" /* \.{\\Proterevision} */
386 @#
387 @d Prote_banner "This is Prote, Version " Prote_version_string
388 /*printed when \Prote\ starts*/
389 @#
390
391 @d HITEX_VERSION "2.0"
392
393 @d banner "This is HiTeX " HITEX_VERSION ", TeX version 3.141592653 "@|
394 TL_VERSION
395 /*printed when \TeX\ starts*/
396
397 @ Different \PASCAL s have slightly different conventions, and the present
398 @!@:PASCAL H}{\ph@>
399 program expresses \TeX\ in terms of the \PASCAL\ that was
400 available to the author in 1982. Constructions that apply to
401 this particular compiler, which we shall call \ph, should help the
402 reader see how to make an appropriate interface for other systems
403 if necessary. (\ph\ is Charles Hedrick's modification of a compiler
404 @^Hedrick, Charles Locke@>
405 for the DECsystem-10 that was originally developed at the University of
406 Hamburg; cf.\ {\sl Software---Practice and Experience \bf6} (1976),
407 29--42. The \TeX\ program below is intended to be adaptable, without
408 extensive changes, to most other versions of \PASCAL, so it does not fully
409 use the admirable features of \ph. Indeed, a conscious effort has been
410 made here to avoid using several idiosyncratic features of standard
411 \PASCAL\ itself, so that most of the code can be translated mechanically
412 into other high-level languages. For example, the `\&{with}' and `\\{new}'
413 features are not used, nor are pointer types, set types, or enumerated
414 scalar types; there are no `\&{var}' parameters, except in the case of files
415 --- \eTeX, however, does use `\&{var}' parameters for the |reverse| function;
416 there are no tag fields on variant records; there are no assignments
417 |double=int|; no procedures are declared local to other procedures.)
418
419 The portions of this program that involve system-dependent code, where
420 changes might be necessary because of differences between \PASCAL\ compilers
421 and/or differences between
422 operating systems, can be identified by looking at the sections whose
423 numbers are listed under `system dependencies' in the index. Furthermore,
424 the index entries for `dirty \PASCAL' list all places where the restrictions
425 of \PASCAL\ have not been followed perfectly, for one reason or another.
426 @!@^system dependencies@>
427 @!@^dirty \PASCAL@>
428
429 Incidentally, \PASCAL's standard |round| function can be problematical,
430 because it disagrees with the IEEE floating-point standard.
431 Many implementors have
432 therefore chosen to substitute their own home-grown rounding procedure.
433
434 @ The following is an outline of the program, whose
435 components will be filled in later, using the conventions of \.{cweb}.
436 @.WEB@>
437 For example, the portion of the program called `\X\glob:Global
438 variables\X' below will be replaced by a sequence of variable declarations
439 that starts in $\section\glob$ of this documentation. In this way, we are able
440 to define each individual global variable when we are prepared to
441 understand what it means; we do not have to define all of the globals at
442 once. Cross references in $\section\glob$, where it says ``See also
443 sections \gglob, \dots,'' also make it possible to look at the set of
444 all global variables, if desired. Similar remarks apply to the other
445 portions of the program.
446
447 The program starts with inserting header files and occasionally a function
448 must be placed before declaring \TeX's macros, because the function
449 uses identifiers that \TeX will declare as macros.
450
451 @p @<Header files and function declarations@>@;
452 @h
453 enum {@<Constants in the outer block@>@;
454 @!empty_string=256 /*the empty string follows after 256 characters*/
455 };
456 @<Types in the outer block@>@;
457 @<Forward declarations@>@;
458 @<Global variables@>@;
459 @#
460 static void initialize(void) /*this procedure gets things started properly*/
461 {@+@<Local variables for initialization@>@;
462 @<Initialize whatever \TeX\ might access@>;
463 } @#
464 @<Basic printing procedures@>@;
465 @<Error handling procedures@>@;
466
467 @ The overall \TeX\ program begins with the heading just shown, after which
468 comes a bunch of procedure declarations and function declarations.
469 Finally we will get to the main program, which begins with the
470 comment `|start_here|'. If you want to skip down to the
471 main program now, you can look up `|start_here|' in the index.
472 But the author suggests that the best way to understand this program
473 is to follow pretty much the order of \TeX's components as they appear in the
474 \.{WEB} description you are now reading, since the present ordering is
475 intended to combine the advantages of the ``bottom up'' and ``top down''
476 approaches to the problem of understanding a somewhat complicated system.
477
478 @ There is no need to declare labels in \CEE/.
479
480 @ Some of the code below is intended to be used only when diagnosing the
481 strange behavior that sometimes occurs when \TeX\ is being installed or
482 when system wizards are fooling around with \TeX\ without quite knowing
483 what they are doing. Such code will not normally be compiled; it is
484 delimited by the codewords `$|@t\#\&{ifdef} \.{DEBUG}@>|\ldots|@t\#\&{endif}@>|$', with apologies
485 to people who wish to preserve the purity of English.
486
487 Similarly, there is some conditional code delimited by
488 `$|@t\#\&{ifdef} \.{STAT}@>|\ldots|@t\#\&{endif}@>|$' that is intended for use when statistics are to be
489 kept about \TeX's memory usage. The |@t\#\&{ifdef} \.{STAT}@>| $\ldots$ |@t\#\&{endif}@>| code also
490 implements diagnostic information for \.{\\tracingparagraphs},
491 \.{\\tracingpages}, and \.{\\tracingrestores}.
492 @^debugging@>
493
494 @ This program has two important variations: (1) There is a long and slow
495 version called \.{INITEX}, which does the extra calculations needed to
496 @.INITEX@>
497 initialize \TeX's internal tables; and (2)~there is a shorter and faster
498 production version, which cuts the initialization to a bare minimum.
499 Parts of the program that are needed in (1) but not in (2) are delimited by
500 the codewords `$|@t\#\&{ifdef} \.{INIT}@>|\ldots|@t\#\&{endif}@>|$'.
501
502 \TeX\ Live has established the common practice
503 to select the initialization code at runtime
504 using the |iniversion| variable.
505
506 @<Initialize whatever...@>=
507 @<Set initial values of key variables@>@/
508 #ifdef @!INIT
509 if (iniversion) /* \TeX\ Live*/
510 {@+@<Initialize table entries (done by \.{INITEX} only)@>@;@+}
511 #endif
512
513 @ The declaration of all basic type definitions needed by Hi\TeX\ are
514 contained in a system dependent header file.
515
516
517 @<Header files and function declarations@>=
518 #include "hibasetypes.h"
519 #include <string.h>
520 #include <math.h>
521
522 @ Further it is necessary to define some build in primitives of
523 \PASCAL\ that are otherwise not available in~\CEE/.
524 @:PASCAL H}{\ph@>
525
526 @d odd(X) ((X)&1)
527 @d chr(X) ((unsigned char)(X))
528 @d ord(X) ((unsigned int)(X))
529 @d abs(X) ((X)>-(X)?(X):-(X))
530 @d round(X) ((int)((X)>=0.0?floor((X)+0.5):ceil((X)-0.5)))
531
532 @ The following parameters can be changed at compile time to extend or
533 reduce \TeX's capacity. They may have different values in \.{INITEX} and
534 in production versions of \TeX.
535 @.INITEX@>
536 @^system dependencies@>
537
538 @<Constants...@>=
539 @!mem_max=5000000, /*greatest index in \TeX's internal |mem| array;
540 must be strictly less than |max_halfword|;
541 must be equal to |mem_top| in \.{INITEX}, otherwise | >= mem_top|*/
542 @!mem_min=0, /*smallest index in \TeX's internal |mem| array;
543 must be |min_halfword| or more;
544 must be equal to |mem_bot| in \.{INITEX}, otherwise | <= mem_bot|*/
545 @!buf_size=2000000, /*maximum number of characters simultaneously present in
546 current lines of open files and in control sequences between
547 \.{\\csname} and \.{\\endcsname}; must not exceed |max_halfword|*/
548 @!error_line=79, /*width of context lines on terminal error messages*/
549 @!half_error_line=50, /*width of first lines of contexts in terminal
550 error messages; should be between 30 and |error_line-15|*/
551 @!max_print_line=79, /*width of longest text lines output; should be at least 60*/
552 @!stack_size=5000, /*maximum number of simultaneous input sources*/
553 @!max_in_open=15, /*maximum number of input files and error insertions that
554 can be going on simultaneously*/
555 @!font_max=255, /*maximum internal font number; must not exceed |max_quarterword|
556 and must be at most |font_base+256|*/
557 @!font_mem_size=8000000, /*number of words of |font_info| for all fonts*/
558 @!param_size=10000, /*maximum number of simultaneous macro parameters*/
559 @!nest_size=500, /*maximum number of semantic levels simultaneously active*/
560 @!max_strings=500000, /*maximum number of strings; must not exceed |max_halfword|*/
561 @!string_vacancies=90000, /*the minimum number of characters that should be
562 available for the user's control sequences and font names,
563 after \TeX's own error messages are stored*/
564 @!pool_size=6250000, /*maximum number of characters in strings, including all
565 error messages and help texts, and the names of all fonts and
566 control sequences; must exceed |string_vacancies| by the total
567 length of \TeX's own strings, which is currently about 23000*/
568 @!save_size=100000, /*space for saving values outside of current group; must be
569 at most |max_halfword|*/
570 @!trie_size=1500000, /*space for hyphenation patterns; should be larger for
571 \.{INITEX} than it is in production versions of \TeX*/
572 @!trie_op_size=35111, /*space for ``opcodes'' in the hyphenation patterns*/
573 @!file_name_size=1024, /*file names shouldn't be longer than this*/
574 @!xchg_buffer_size=64, /*must be at least 64*/
575 /*size of |eight_bits| buffer for exchange with system routines*/
576
577 @ Like the preceding parameters, the following quantities can be changed
578 at compile time to extend or reduce \TeX's capacity. But if they are changed,
579 it is necessary to rerun the initialization program \.{INITEX}
580 @.INITEX@>
581 to generate new tables for the production \TeX\ program.
582 One can't simply make helter-skelter changes to the following constants,
583 since certain rather complex initialization
584 numbers are computed from them. They are defined here using
585 \.{WEB} macros, instead of being put into the above |enum| list in order to
586 emphasize this distinction.
587
588 @d mem_bot 0 /*smallest index in the |mem| array dumped by \.{INITEX};
589 must not be less than |mem_min|*/
590 @d mem_top 5000000 /*largest index in the |mem| array dumped by \.{INITEX};
591 must be substantially larger than |mem_bot|
592 and not greater than |mem_max|*/
593 @d font_base 0 /*smallest internal font number; must not be less
594 than |min_quarterword|*/
595 @d hash_size 45000 /*maximum number of control sequences; it should be at most
596 about |(mem_max-mem_min)/(double)10|*/
597 @d hash_prime 35999 /*a prime number equal to about 85\pct! of |hash_size|*/
598 @d hyph_size 8191 /*another prime; the number of \.{\\hyphenation} exceptions*/
599 @^system dependencies@>
600
601 @ In case somebody has inadvertently made bad settings of the ``constants,''
602 \TeX\ checks them using a global variable called |bad|.
603
604 This is the first of many sections of \TeX\ where global variables are
605 defined.
606
607 @<Glob...@>=
608 static int @!bad; /*is some ``constant'' wrong?*/
609
610 @ Later on we will say `\ignorespaces|if (mem_max >= max_halfword) bad=14|',
611 or something similar. (We can't do that until |max_halfword| has been defined.)
612
613 @<Check the ``constant'' values for consistency@>=
614 bad=0;
615 if ((half_error_line < 30)||(half_error_line > error_line-15)) bad=1;
616 if (max_print_line < 60) bad=2;
617 if (mem_bot+1100 > mem_top) bad=4;
618 if (hash_prime > hash_size) bad=5;
619 if (max_in_open >= 128) bad=6;
620 if (mem_top < 256+11) bad=7; /*we will want |null_list > 255|*/
621
622 @ Labels are given symbolic names by the following definitions, so that
623 occasional |goto| statements will be meaningful. We insert the label
624 `|end|' just before the `\ignorespaces|} |\unskip' of a procedure in
625 which we have used the `|goto end|' statement defined below; the label
626 `|restart|' is occasionally used at the very beginning of a procedure; and
627 the label `|reswitch|' is occasionally used just prior to a |case|
628 statement in which some cases change the conditions and we wish to branch
629 to the newly applicable case. Loops that are set up with the |loop|
630 construction defined below are commonly exited by going to `|done|' or to
631 `|found|' or to `|not_found|', and they are sometimes repeated by going to
632 `|resume|'. If two or more parts of a subroutine start differently but
633 end up the same, the shared code may be gathered together at
634 `|common_ending|'.
635
636 Incidentally, this program never declares a label that isn't actually used,
637 because some fussy \PASCAL\ compilers will complain about redundant labels.
638
639 @ Here are some macros for common programming idioms.
640
641 @d incr(A) A=A+1 /*increase a variable by unity*/
642 @d decr(A) A=A-1 /*decrease a variable by unity*/
643 @d negate(A) A=-A /*change the sign of a variable*/
644 @d loop @+while (true) @+ /*repeat over and over until a |goto| happens*/
645 @f loop else
646 /*\.{WEB}'s |else| acts like `\ignorespaces|while true do|\unskip'*/
647 @d do_nothing /*empty statement*/
648 @d empty 0 /*symbolic name for a null constant*/
649
650 @* The character set.
651 In order to make \TeX\ readily portable to a wide variety of
652 computers, all of its input text is expected to be in UTF8 format.
653 It is converted to an internal twenty-one bit code,
654 This conversion is done immediately when each
655 character is read in. Conversely, characters are converted to UTF8
656 representation just before they are output to a text file.
657
658 Such an internal code is relevant to users of \TeX\ primarily because it
659 governs the positions of characters in the fonts. For example, the
660 character `\.A' has UTF code $65=0101$, and when \TeX\ typesets
661 this letter it specifies character number 65 in the current font.
662 If that font actually has `\.A' in a different position, \TeX\ doesn't
663 know what the real position is; the program that does the actual printing from
664 \TeX's device-independent files is responsible for converting from UTF to
665 a particular font encoding.
666 @^UTF code@>
667
668 \TeX's internal code also defines the value of constants
669 that begin with a reverse apostrophe; and it provides an index to the
670 \.{\\catcode}, \.{\\mathcode}, \.{\\uccode}, \.{\\lccode}, and \.{\\delcode}
671 tables.
672
673 @ Characters of text that have been converted to \TeX's internal form
674 are said to be of type |UTF_code|, which is a subrange of the integers.
675
676 @<Types...@>=
677 typedef unsigned char UTF8_code; /*eight-bit numbers*/
678 typedef uint32_t UTF_code; /*twenty-one-bit numbers*/
679
680 @ The original \PASCAL\ compiler was designed in the late 60s, when six-bit
681 character sets were common, so it did not make provision for lowercase
682 letters. Nowadays, of course, we need to deal with both capital and small
683 letters in a convenient way, especially in a program for typesetting;
684
685 @ Some of the ASCII codes without visible characters have been given symbolic
686 names in this program because they are used with a special meaning.
687
688 @d null_code 00 /*ASCII code that might disappear*/
689 @d carriage_return 015 /*ASCII code used at end of line*/
690 @d invalid_code 0177 /*ASCII code that many systems prohibit in text files*/
691
692
693 @* Input and output.
694 The bane of portability is the fact that different operating systems treat
695 input and output quite differently, perhaps because computer scientists
696 have not given sufficient attention to this problem. People have felt somehow
697 that input and output are not part of ``real'' programming. Well, it is true
698 that some kinds of programming are more fun than others. With existing
699 input/output conventions being so diverse and so messy, the only sources of
700 joy in such parts of the code are the rare occasions when one can find a
701 way to make the program a little less bad than it might have been. We have
702 two choices, either to attack I/O now and get it over with, or to postpone
703 I/O until near the end. Neither prospect is very attractive, so let's
704 get it over with.
705
706 The basic operations we need to do are (1)~inputting and outputting of
707 text, to or from a file or the user's terminal; (2)~inputting and
708 outputting of eight-bit bytes, to or from a file; (3)~instructing the
709 operating system to initiate (``open'') or to terminate (``close'') input or
710 output from a specified file; (4)~testing whether the end of an input
711 file has been reached.
712
713 \TeX\ needs to deal with two kinds of files.
714 We shall use the term |alpha_file| for a file that contains textual data,
715 and the term |byte_file| for a file that contains eight-bit binary information.
716 These two types turn out to be the same on many computers, but
717 sometimes there is a significant distinction, so we shall be careful to
718 distinguish between them. Standard protocols for transferring
719 such files from computer to computer, via high-speed networks, are
720 now becoming available to more and more communities of users.
721
722 The program actually makes use also of a third kind of file, called a
723 |word_file|, when dumping and reloading base information for its own
724 initialization. We shall define a word file later; but it will be possible
725 for us to specify simple operations on word files before they are defined.
726
727 @<Types...@>=
728 typedef uint8_t eight_bits; /*unsigned one-byte quantity*/
729 typedef struct {@+FILE *f;@+char@,d;@+} alpha_file; /*files that contain textual data*/
730 typedef struct {@+FILE *f;@+eight_bits@,d;@+} byte_file; /*files that contain binary data*/
731
732 @ Most of what we need to do with respect to input and output can be handled
733 by the I/O facilities that are standard in \PASCAL, i.e., the routines
734 called |get|, |put|, |eof|, and so on. But
735 standard \PASCAL\ does not allow file variables to be associated with file
736 names that are determined at run time, so it cannot be used to implement
737 \TeX; some sort of extension to \PASCAL's ordinary |reset| and |rewrite|
738 is crucial for our purposes. We shall assume that |name_of_file| is a variable
739 of an appropriate type such that the \PASCAL\ run-time system being used to
740 implement \TeX\ can open a file whose external name is specified by
741 |name_of_file|.
742 @^system dependencies@>
743
744 @<Glob...@>=
745 static unsigned char @!name_of_file0[file_name_size+1]={0},
746 *const @!name_of_file = @!name_of_file0-1;@;@/
747 /*on some systems this may be a \&{record} variable*/
748 static int @!name_length;@/ /*this many characters are actually
749 relevant in |name_of_file| (the rest are blank)*/
750
751 @ To open files, \TeX\ used \PASCAL's |reset| function.
752 We use the {\tt kpathsearch} library to implement new functions
753 in the section on \TeX\ Live Integration.
754 Here we give only the function prototypes.
755
756 \TeX's file-opening functions do not issue their own
757 error messages if something goes wrong. If a file identified by
758 |name_of_file| cannot be found,
759 or if such a file cannot be opened for some other reason
760 (e.g., someone may already be trying to write the same file)
761 \TeX's file-opening functions return |false|.
762 This allows \TeX\ to undertake appropriate corrective action.
763 @^system dependencies@>
764
765 @p
766 static FILE*open_in(char*filename,kpse_file_format_type t,const char*rwb); /* \TeX\ Live*/
767 static bool a_open_in(alpha_file *f); /*open a text file for input*/
768 static bool b_open_in(byte_file *f, char *path); /*open a binary file for input*/
769 static bool w_open_in(word_file *f); /*open a word file for input*/
770 static FILE *open_out(const char *file_name, const char *file_mode); /* \TeX\ Live*/
771 static bool a_open_out(alpha_file *f); /*open a text file for output*/
772 #ifdef @!INIT
773 static bool w_open_out(word_file *f); /*open a word file for output*/
774 #endif
775
776 @ Files can be closed with the \ph\ routine `|pascal_close(f)|', which
777 @:PASCAL H}{\ph@>
778 @^system dependencies@>
779 should be used when all input or output with respect to |f| has been completed.
780 This makes |f| available to be opened again, if desired; and if |f| was used for
781 output, the |pascal_close| operation makes the corresponding external file appear
782 on the user's area, ready to be read.
783
784 These procedures should not generate error messages if a file is
785 being closed before it has been successfully opened.
786
787 @p static void a_close(alpha_file *f) /*close a text file*/
788 {@+pascal_close((*f));
789 }
790 @#
791 static void b_close(byte_file *f) /*close a binary file*/
792 {@+pascal_close((*f));
793 }
794 @#
795 static void w_close(word_file *f) /*close a word file*/
796 {@+pascal_close((*f));
797 }
798
799 @ Binary input and output are done with \PASCAL's ordinary |get| and |put|
800 procedures, so we don't have to make any other special arrangements for
801 binary~I/O. Text output is also easy to do with standard \PASCAL\ routines.
802 The treatment of text input is more difficult, however, because
803 of the necessary translation to |ASCII_code| values.
804 \TeX's conventions should be efficient, and they should
805 blend nicely with the user's operating environment.
806
807 @ Input from text files is read one line at a time, using a routine called
808 |input_ln|. This function is defined in terms of global variables called
809 |buffer|, |first|, and |last| that will be described in detail later; for
810 now, it suffices for us to know that |buffer| is an array of |ASCII_code|
811 values, and that |first| and |last| are indices into this array
812 representing the beginning and ending of a line of text.
813
814 @<Glob...@>=
815 static UTF8_code @!buffer[buf_size+1]; /*lines of characters being read*/
816 static int @!first; /*the first unused position in |buffer|*/
817 static int @!last; /*end of the line just input to |buffer|*/
818 static int @!max_buf_stack; /*largest index used in |buffer|*/
819
820 @ The |input_ln| function brings the next line of input from the specified
821 file into available positions of the buffer array and returns the value
822 |true|, unless the file has already been entirely read, in which case it
823 returns |false| and sets |last=first|. In general, the |ASCII_code|
824 numbers that represent the next line of the file are input into
825 |buffer[first]|, |buffer[first+1]|, \dots, |buffer[last-1]|; and the
826 global variable |last| is set equal to |first| plus the length of the
827 line. Trailing blanks are removed from the line; thus, either |last==first|
828 (in which case the line was entirely blank) or |buffer[last-1]!=' '|.
829
830 An overflow error is given, however, if the normal actions of |input_ln|
831 would make |last >= buf_size|; this is done so that other parts of \TeX\
832 can safely look at the contents of |buffer[last+1]| without overstepping
833 the bounds of the |buffer| array. Upon entry to |input_ln|, the condition
834 |first < buf_size| will always hold, so that there is always room for an
835 ``empty'' line.
836
837 The variable |max_buf_stack|, which is used to keep track of how large
838 the |buf_size| parameter must be to accommodate the present job, is
839 also kept up to date by |input_ln|.
840
841 If the |bypass_eoln| parameter is |true|, |input_ln| will do a |get|
842 before looking at the first character of the line; this skips over
843 an |eoln| that was in |f.d|. The procedure does not do a |get| when it
844 reaches the end of the line; therefore it can be used to acquire input
845 from the user's terminal as well as from ordinary text files.
846
847 Standard \PASCAL\ says that a file should have |eoln| immediately
848 before |eof|, but \TeX\ needs only a weaker restriction: If |eof|
849 occurs in the middle of a line, the system function |eoln| should return
850 a |true| result (even though |f.d| will be undefined).
851
852 Since the inner loop of |input_ln| is part of \TeX's ``inner loop''---each
853 character of input comes in at this place---it is wise to reduce system
854 overhead by making use of special routines that read in an entire array
855 of characters at once, if such routines are available. The following
856 code uses standard \PASCAL\ to illustrate what needs to be done, but
857 finer tuning is often possible at well-developed \PASCAL\ sites.
858 @^inner loop@>
859
860 @p static bool input_ln(alpha_file *f, bool @!bypass_eoln)
861 /*inputs the next line or returns |false|*/
862 {@+int last_nonblank; /*|last| with trailing blanks removed*/
863 if (bypass_eoln) if (!eof((*f))) get((*f));
864 /*input the first character of the line into |f.d|*/
865 last=first; /*cf.\ Matthew 19\thinspace:\thinspace30*/
866 if (eof((*f))) return false;
867 else{@+last_nonblank=first;
868 while (!eoln((*f)))
869 {@+if (last >= max_buf_stack)
870 {@+max_buf_stack=last+1;
871 if (max_buf_stack==buf_size)
872 @<Report overflow of the input buffer, and abort@>;
873 }
874 buffer[last]=(*f).d;get((*f));incr(last);
875 if (buffer[last-1]!=' ') last_nonblank=last;
876 }
877 last=last_nonblank;return true;
878 }
879 }
880
881 @ The user's terminal acts essentially like other files of text, except
882 that it is used both for input and for output. When the terminal is
883 considered an input file, the file variable is called |term_in|, and when it
884 is considered an output file the file variable is |term_out|.
885 @^system dependencies@>
886
887 @<Glob...@>=
888 static alpha_file @!term_in; /*the terminal as an input file*/
889 static alpha_file @!term_out; /*the terminal as an output file*/
890
891 @ Here is how to open the terminal files
892 in \ph. The `\.{/I}' switch suppresses the first |get|.
893 @:PASCAL H}{\ph@>
894 @^system dependencies@>
895
896 @d t_open_in term_in.f=stdin /*open the terminal for text input*/
897 @d t_open_out term_out.f=stdout /*open the terminal for text output*/
898
899 @ Sometimes it is necessary to synchronize the input/output mixture that
900 happens on the user's terminal, and three system-dependent
901 procedures are used for this
902 purpose. The first of these, |update_terminal|, is called when we want
903 to make sure that everything we have output to the terminal so far has
904 actually left the computer's internal buffers and been sent.
905 The second, |clear_terminal|, is called when we wish to cancel any
906 input that the user may have typed ahead (since we are about to
907 issue an unexpected error message). The third, |wake_up_terminal|,
908 is supposed to revive the terminal if the user has disabled it by
909 some instruction to the operating system. The following macros show how
910 these operations can be specified in \ph:
911 @:PASCAL H}{\ph@>
912 @^system dependencies@>
913
914 @d update_terminal fflush(term_out.f) /*empty the terminal output buffer*/
915 @d clear_terminal fflush(term_in.f) /*clear the terminal input buffer*/
916 @d wake_up_terminal do_nothing /*cancel the user's cancellation of output*/
917
918 @ We need a special routine to read the first line of \TeX\ input from
919 the user's terminal. This line is different because it is read before we
920 have opened the transcript file; there is sort of a ``chicken and
921 egg'' problem here. If the user types `\.{\\input paper}' on the first
922 line, or if some macro invoked by that line does such an \.{\\input},
923 the transcript file will be named `\.{paper.log}'; but if no \.{\\input}
924 commands are performed during the first line of terminal input, the transcript
925 file will acquire its default name `\.{texput.log}'. (The transcript file
926 will not contain error messages generated by the first line before the
927 first \.{\\input} command.)
928 @.texput@>
929
930 The first line is even more special if we are lucky enough to have an operating
931 system that treats \TeX\ differently from a run-of-the-mill \PASCAL\ object
932 program. It's nice to let the user start running a \TeX\ job by typing
933 a command line like `\.{tex paper}'; in such a case, \TeX\ will operate
934 as if the first line of input were `\.{paper}', i.e., the first line will
935 consist of the remainder of the command line, after the part that invoked
936 \TeX.
937
938 The first line is special also because it may be read before \TeX\ has
939 input a format file. In such cases, normal error messages cannot yet
940 be given. The following code uses concepts that will be explained later.
941 (If the \PASCAL\ compiler does not support non-local |@!goto|\unskip, the
942 @^system dependencies@>
943 statement `|goto exit(0)|' should be replaced by something that
944 quietly terminates the program.)
945
946 @<Report overflow of the input buffer, and abort@>=
947 if (format_ident==0)
948 {@+write_ln(term_out,"Buffer size exceeded!");exit(0);
949 @.Buffer size exceeded@>
950 }
951 else{@+cur_input.loc_field=first;cur_input.limit_field=last-1;
952 overflow("buffer size", buf_size);
953 @:TeX capacity exceeded buffer size}{\quad buffer size@>
954 }
955
956 @ Different systems have different ways to get started. But regardless of
957 what conventions are adopted, the routine that initializes the terminal
958 should satisfy the following specifications:
959
960 \yskip\textindent{1)}It should open file |term_in| for input from the
961 terminal. (The file |term_out| will already be open for output to the
962 terminal.)
963
964 \textindent{2)}If the user has given a command line, this line should be
965 considered the first line of terminal input. Otherwise the
966 user should be prompted with `\.{**}', and the first line of input
967 should be whatever is typed in response.
968
969 \textindent{3)}The first line of input, which might or might not be a
970 command line, should appear in locations |first| to |last-1| of the
971 |buffer| array.
972
973 \textindent{4)}The global variable |loc| should be set so that the
974 character to be read next by \TeX\ is in |buffer[loc]|. This
975 character should not be blank, and we should have |loc < last|.
976
977 \yskip\noindent(It may be necessary to prompt the user several times
978 before a non-blank line comes in. The prompt is `\.{**}' instead of the
979 later `\.*' because the meaning is slightly different: `\.{\\input}' need
980 not be typed immediately after~`\.{**}'.)
981
982 @d loc cur_input.loc_field /*location of first unread character in |buffer|*/
983
984 @ The following routine calls |input_command_line|
985 to retrieve a possible command line.
986 @^system dependencies@>
987
988 @p static bool init_terminal(void) /*gets the terminal input started*/
989 {@+
990 t_open_in;
991 if (input_command_line()) return true; /* \TeX\ Live */
992 loop@+{@+wake_up_terminal;pascal_write(term_out,"**");update_terminal;
993 @.**@>
994 if (!input_ln(&term_in, true)) /*this shouldn't happen*/
995 {@+write_ln(term_out);
996 pascal_write(term_out,"! End of file on the terminal... why?");
997 @.End of file on the terminal@>
998 return false;
999 }
1000 loc=first;
1001 while ((loc < last)&&(buffer[loc]==' ')) incr(loc);
1002 if (loc < last)
1003 {@+return true;
1004 /*return unless the line was all blank*/
1005 }
1006 write_ln(term_out,"Please type the name of your input file.");
1007 }
1008 }
1009
1010 @* String handling.
1011 Control sequence names and diagnostic messages are variable-length strings
1012 of eight-bit characters. Since \PASCAL\ does not have a well-developed string
1013 mechanism, \TeX\ does all of its string processing by homegrown methods.
1014
1015 Elaborate facilities for dynamic strings are not needed, so all of the
1016 necessary operations can be handled with a simple data structure.
1017 The array |str_pool| contains all of the (eight-bit) ASCII codes in all
1018 of the strings, and the array |str_start| contains indices of the starting
1019 points of each string. Strings are referred to by integer numbers, so that
1020 string number |s| comprises the characters |str_pool[j]| for
1021 |str_start[s] <= j < str_start[s+1]|. Additional integer variables
1022 |pool_ptr| and |str_ptr| indicate the number of entries used so far
1023 in |str_pool| and |str_start|, respectively; locations
1024 |str_pool[pool_ptr]| and |str_start[str_ptr]| are
1025 ready for the next string to be allocated.
1026
1027 String numbers 0 to 255 are reserved for strings that correspond to single
1028 ASCII characters. This is in accordance with the conventions of \.{WEB},
1029 @.WEB@>
1030 which converts single-character strings into the ASCII code number of the
1031 single character involved, while it converts other strings into integers
1032 and builds a string pool file. Thus, when the string constant \.{"."} appears
1033 in the program below, \.{WEB} converts it into the integer 46, which is the
1034 ASCII code for a period, while \.{WEB} will convert a string like \.{"hello"}
1035 into some integer greater than~255. String number 46 will presumably be the
1036 single character `\..'; but some ASCII codes have no standard visible
1037 representation, and \TeX\ sometimes needs to be able to print an arbitrary
1038 ASCII character, so the first 256 strings are used to specify exactly what
1039 should be printed for each of the 256 possibilities.
1040
1041 @<Types...@>=
1042 typedef int32_t pool_pointer; /*for variables that point into |str_pool|*/
1043 typedef int32_t str_number; /*for variables that point into |str_start|*/
1044 typedef uint8_t packed_ASCII_code; /*elements of |str_pool| array*/
1045
1046 @ @<Glob...@>=
1047 static packed_ASCII_code @!str_pool[pool_size+1]; /*the characters*/
1048 static pool_pointer @!str_start[max_strings+1]; /*the starting pointers*/
1049 static pool_pointer @!pool_ptr; /*first unused position in |str_pool|*/
1050 static str_number @!str_ptr; /*number of the current string being created*/
1051 static pool_pointer @!init_pool_ptr; /*the starting value of |pool_ptr|*/
1052 static str_number @!init_str_ptr; /*the starting value of |str_ptr|*/
1053
1054 @ Several of the elementary string operations are performed using \.{WEB}
1055 macros instead of \PASCAL\ procedures, because many of the
1056 operations are done quite frequently and we want to avoid the
1057 overhead of procedure calls. For example, here is
1058 a simple macro that computes the length of a string.
1059 @.WEB@>
1060
1061 @d length(A) (str_start[A+1]-str_start[A]) /*the number of characters
1062 in string number \#*/
1063
1064 @ The length of the current string is called |cur_length|:
1065
1066 @d cur_length (pool_ptr-str_start[str_ptr])
1067
1068 @ Strings are created by appending character codes to |str_pool|.
1069 The |append_char| macro, defined here, does not check to see if the
1070 value of |pool_ptr| has gotten too high; this test is supposed to be
1071 made before |append_char| is used. There is also a |flush_char|
1072 macro, which erases the last character appended.
1073
1074 To test if there is room to append |l| more characters to |str_pool|,
1075 we shall write |str_room(l)|, which aborts \TeX\ and gives an
1076 apologetic error message if there isn't enough room.
1077
1078 @d append_char(A) /*put |ASCII_code| \# at the end of |str_pool|*/
1079 {@+str_pool[pool_ptr]=A;incr(pool_ptr);
1080 }
1081 @d flush_char decr(pool_ptr) /*forget the last character in the pool*/
1082 @d str_room(A) /*make sure that the pool hasn't overflowed*/
1083 {@+if (pool_ptr+A > pool_size)
1084 overflow("pool size", pool_size-init_pool_ptr);
1085 @:TeX capacity exceeded pool size}{\quad pool size@>
1086 }
1087
1088 @ Once a sequence of characters has been appended to |str_pool|, it
1089 officially becomes a string when the function |make_string| is called.
1090 This function returns the identification number of the new string as its
1091 value.
1092
1093 @p static str_number make_string(void) /*current string enters the pool*/
1094 {@+if (str_ptr==max_strings)
1095 overflow("number of strings", max_strings-init_str_ptr);
1096 @:TeX capacity exceeded number of strings}{\quad number of strings@>
1097 incr(str_ptr);str_start[str_ptr]=pool_ptr;
1098 return str_ptr-1;
1099 }
1100
1101 @ To destroy the most recently made string, we say |flush_string|.
1102
1103 @d flush_string {@+decr(str_ptr);pool_ptr=str_start[str_ptr];
1104 }
1105
1106 @ The following subroutine compares string |s| with another string of the
1107 same length that appears in |buf|;
1108 the result is |true| if and only if the strings are equal.
1109 Empirical tests indicate that |str_eq_buf| is used in such a way that
1110 it tends to return |true| about 80 percent of the time.
1111
1112 @p static bool str_eq_buf(str_number @!s, unsigned char *buf)
1113 /*test equality of strings*/
1114 {@+ /*loop exit*/
1115 pool_pointer j; /*running index*/
1116 j=str_start[s];
1117 while (j < str_start[s+1])
1118 {@+if (str_pool[j]!=*buf || *buf==0)
1119 return false;
1120 j++;buf++;
1121 }
1122 return true;
1123 }
1124
1125 @ Here is a similar routine, but it compares two strings in the string pool,
1126 and it does not assume that they have the same length.
1127
1128 @p static bool str_eq_str(str_number @!s, str_number @!t)
1129 /*test equality of strings*/
1130 {@+ /*loop exit*/
1131 pool_pointer j, @!k; /*running indices*/
1132 bool @!result; /*result of comparison*/
1133 result=false;
1134 if (length(s)!=length(t)) goto not_found;
1135 j=str_start[s];k=str_start[t];
1136 while (j < str_start[s+1])
1137 {@+if (str_pool[j]!=str_pool[k]) goto not_found;
1138 incr(j);incr(k);
1139 }
1140 result=true;
1141 not_found: return result;
1142 }
1143 @t\4@>@<Declare \Prote\ procedures for strings@>@;
1144
1145 @ The initial values of |str_pool|, |str_start|, |pool_ptr|,
1146 and |str_ptr| are computed by the \.{INITEX} program, based in part
1147 on the information that \.{WEB} has output while processing \TeX.
1148 @.INITEX@>
1149 @^string pool@>
1150
1151 @p
1152 static bool get_strings_started(void) /*initializes the string pool*/
1153 {@+
1154 int k, @!l; /*small indices or counters*/
1155 pool_ptr=0;str_ptr=0;str_start[0]=0;
1156 @<Make the first 256 strings@>;
1157 @<Add the empty string to the string pool@>;
1158 return true;
1159 }
1160
1161 @ @d app_lc_hex(A) l=A;
1162 if (l < 10) append_char(l+'0')@;@+else append_char(l-10+'a')
1163
1164 @<Make the first 256...@>=
1165 for (k=0; k<=255; k++)
1166 {@+if ((@<Character |k| cannot be printed@>))
1167 {@+append_char('^');append_char('^');
1168 if (k < 0100) append_char(k+0100)@;
1169 else if (k < 0200) append_char(k-0100)@;
1170 else{@+app_lc_hex(k/16);app_lc_hex(k%16);
1171 }
1172 }
1173 else append_utf8(k);
1174 make_string();
1175 }
1176
1177 @ The first 128 strings will contain 95 standard ASCII characters, and the
1178 other 33 characters will be printed in three-symbol form like `\.{\^\^A}'
1179 unless a system-dependent change is made here. Installations that have
1180 an extended character set
1181 would like string 032 to be the single character 032 instead of the
1182 three characters 0136, 0136, 0132 (\.{\^\^Z}). On the other hand,
1183 even people with an extended character set will want to represent string
1184 015 by \.{\^\^M}, since 015 is |carriage_return|; the idea is to
1185 produce visible strings instead of tabs or line-feeds or carriage-returns
1186 or bell-rings or characters that are treated anomalously in text files.
1187
1188 Unprintable characters of codes 128--255 are, similarly, rendered
1189 \.{\^\^80}--\.{\^\^ff}.
1190
1191 The boolean expression defined here should be |true| unless \TeX\
1192 internal code number~|k| corresponds to a non-troublesome visible
1193 symbol in the local character set. An appropriate formula for the
1194 extended character set recommended in {\sl The \TeX book\/} would, for
1195 example, be `|k in[0, 010 dotdot 012, 014, 015, 033, 0177 dotdot 0377]|'.
1196 If character |k| cannot be printed, and |k < 0200|, then character |k+0100| or
1197 |k-0100| must be printable; moreover, ASCII codes |[041 dotdot 046,
1198 060 dotdot 071, 0136, 0141 dotdot 0146, 0160 dotdot 0171]| must be printable.
1199 Thus, at least 80 printable characters are needed.
1200 @:TeXbook}{\sl The \TeX book@>
1201 @^character set dependencies@>
1202 @^system dependencies@>
1203
1204 @<Character |k| cannot be printed@>=
1205 (k < ' ')||(k > '~')
1206
1207 @ The |pool_file| variable is no longer needed and has been removed.
1208
1209 Instead of reading the other strings from the \.{TEX.POOL} file,
1210 it is sufficient here to add the empty string.
1211 @<Add the empty string to the string pool@>=
1212 make_string();
1213
1214 @ Without a string pool file there is no need for a pool check sum either.
1215 But this is a convenient place to define the function |s_no| that will
1216 add literal strings to the string pool at runtime, thereby obtaining their
1217 string number.
1218
1219 @p static int s_no(const char *str)
1220 {@+
1221 if (str[0]==0) return empty_string;
1222 if (str[1]==0) return str[0];
1223 str_room(strlen(str));
1224 while (*str!=0) append_char(*str++);
1225 return make_string();
1226 }
1227
1228 @ The function |s_no| is used in |initialize| and needs a forward
1229 declaration.
1230
1231 @<Forward declarations@>=
1232 static int s_no(const char *str);
1233
1234 @* On-line and off-line printing.
1235 Messages that are sent to a user's terminal and to the transcript-log file
1236 are produced by several `|print|' procedures. These procedures will
1237 direct their output to a variety of places, based on the setting of
1238 the global variable |selector|, which has the following possible
1239 values:
1240
1241 \yskip
1242 \hang |term_and_log|, the normal setting, prints on the terminal and on the
1243 transcript file.
1244
1245 \hang |log_only|, prints only on the transcript file.
1246
1247 \hang |term_only|, prints only on the terminal.
1248
1249 \hang |no_print|, doesn't print at all. This is used only in rare cases
1250 before the transcript file is open.
1251
1252 \hang |pseudo|, puts output into a cyclic buffer that is used
1253 by the |show_context| routine; when we get to that routine we shall discuss
1254 the reasoning behind this curious mode.
1255
1256 \hang |new_string|, appends the output to the current string in the
1257 string pool.
1258
1259 \hang 0 to 15, prints on one of the sixteen files for \.{\\write} output.
1260
1261 \yskip
1262 \noindent The symbolic names `|term_and_log|', etc., have been assigned
1263 numeric codes that satisfy the convenient relations |no_print+1==term_only|,
1264 |no_print+2==log_only|, |term_only+2==log_only+1==term_and_log|.
1265
1266 Three additional global variables, |tally| and |term_offset| and
1267 |file_offset|, record the number of characters that have been printed
1268 since they were most recently cleared to zero. We use |tally| to record
1269 the length of (possibly very long) stretches of printing; |term_offset|
1270 and |file_offset|, on the other hand, keep track of how many characters
1271 have appeared so far on the current line that has been output to the
1272 terminal or to the transcript file, respectively.
1273
1274 @d no_print 16 /*|selector| setting that makes data disappear*/
1275 @d term_only 17 /*printing is destined for the terminal only*/
1276 @d log_only 18 /*printing is destined for the transcript file only*/
1277 @d term_and_log 19 /*normal |selector| setting*/
1278 @d pseudo 20 /*special |selector| setting for |show_context|*/
1279 @d new_string 21 /*printing is deflected to the string pool*/
1280 @d max_selector 21 /*highest selector setting*/
1281
1282 @<Glob...@>=
1283 static alpha_file @!log_file; /*transcript of \TeX\ session*/
1284 static int @!selector; /*where to print a message*/
1285 static int8_t @!dig[23]; /*digits in a number being output*/
1286 static int @!tally; /*the number of characters recently printed*/
1287 static int @!term_offset;
1288 /*the number of characters on the current terminal line*/
1289 static int @!file_offset;
1290 /*the number of characters on the current file line*/
1291 static UTF8_code @!trick_buf[error_line+1]; /*circular buffer for
1292 pseudoprinting*/
1293 static int @!trick_count; /*threshold for pseudoprinting, explained later*/
1294 static int @!first_count; /*another variable for pseudoprinting*/
1295
1296 @ @<Initialize the output routines@>=
1297 selector=term_only;tally=0;term_offset=0;file_offset=0;
1298
1299 @ Macro abbreviations for output to the terminal and to the log file are
1300 defined here for convenience. Some systems need special conventions
1301 for terminal output, and it is possible to adhere to those conventions
1302 by changing |wterm|, |wterm_ln|, and |wterm_cr| in this section.
1303 @^system dependencies@>
1304
1305 @<Basic printing procedures@>=
1306 #define @[put(F)@] @[fwrite(&((F).d)@],@[sizeof((F).d),1,(F).f)@]@;
1307 #define @[get(F)@] @[(void)fread(&((F).d),sizeof((F).d),1,(F).f)@]
1308
1309 #define @[pascal_close(F)@] @[fclose((F).f),(F).f=NULL@]
1310 #define @[eof(F)@] @[feof((F).f)@]
1311 #define @[eoln(F)@] @[((F).d=='\n'||eof(F))@]
1312 #define @[erstat(F)@] @[((F).f==NULL?-1:ferror((F).f))@]
1313
1314 #define @[pascal_write(F, FMT,...)@] @[fprintf(F.f,FMT,## __VA_ARGS__)@]
1315 #define @[write_ln(F,...)@] @[pascal_write(F,__VA_ARGS__"\n")@]
1316
1317 #define @[wterm(FMT,...)@] @[pascal_write(term_out,FMT, ## __VA_ARGS__)@]
1318 #define @[wterm_ln(FMT,...)@] @[wterm(FMT "\n", ## __VA_ARGS__)@]
1319 #define wterm_cr @[pascal_write(term_out,"\n")@]
1320 #define @[wlog(FMT, ...)@] @[pascal_write(log_file,FMT, ## __VA_ARGS__)@]
1321 #define @[wlog_ln(FMT, ...)@] @[wlog(FMT "\n", ## __VA_ARGS__)@]
1322 #define wlog_cr @[pascal_write(log_file,"\n")@]
1323
1324 @ To end a line of text output, we call |print_ln|.
1325
1326 @<Basic print...@>=
1327 static void print_ln(void) /*prints an end-of-line*/
1328 {@+switch (selector) {
1329 case term_and_log: {@+wterm_cr;wlog_cr;
1330 term_offset=0;file_offset=0;
1331 } @+break;
1332 case log_only: {@+wlog_cr;file_offset=0;
1333 } @+break;
1334 case term_only: {@+wterm_cr;term_offset=0;
1335 } @+break;
1336 case no_print: case pseudo: case new_string: do_nothing;@+break;
1337 default:write_ln(write_file[selector]);
1338 } @/
1339 } /*|tally| is not affected*/
1340
1341 @ The |print_char| procedure sends one character to the desired destination.
1342 All printing comes through |print_ln| or |print_char|.
1343
1344 @<Basic printing...@>=
1345 static void print_char(UTF8_code @!s) /*prints a single character byte*/
1346 {@+
1347 if (@<Character |s| is the current new-line character@>)
1348 if (selector < pseudo)
1349 {@+print_ln();return;
1350 }
1351 switch (selector) {
1352 case term_and_log: {@+wterm("%c",s);wlog("%c",s);
1353 incr(term_offset);incr(file_offset);
1354 if (term_offset==max_print_line)
1355 {@+wterm_cr;term_offset=0;
1356 }
1357 if (file_offset==max_print_line)
1358 {@+wlog_cr;file_offset=0;
1359 }
1360 } @+break;
1361 case log_only: {@+wlog("%c",s);incr(file_offset);
1362 if (file_offset==max_print_line) print_ln();
1363 } @+break;
1364 case term_only: {@+wterm("%c",s);incr(term_offset);
1365 if (term_offset==max_print_line) print_ln();
1366 } @+break;
1367 case no_print: do_nothing;@+break;
1368 case pseudo: if (tally < trick_count) trick_buf[tally%error_line]=s;@+break;
1369 case new_string: {@+if (pool_ptr < pool_size) append_char(s);
1370 } @+break; /*we drop characters if the string space is full*/
1371 default:pascal_write(write_file[selector],"%c", s);
1372 } @/
1373 incr(tally);
1374 }
1375
1376 @ An entire string is output by calling |print|. Note that if we are outputting
1377 the single standard ASCII character \.c, we could call |print('c')|, since
1378 |'c'==99| is the number of a single-character string, as explained above. But
1379 |print_char('c')| is quicker, so \TeX\ goes directly to the |print_char|
1380 routine when it knows that this is safe. (The present implementation
1381 assumes that it is always safe to print a visible ASCII character.)
1382 @^system dependencies@>
1383
1384 @<Basic print...@>=
1385 static void print(char *s) /* the simple version */
1386 { @+if (s == NULL) s="???"; /*this can't happen*/
1387 while (*s!=0) print_char(*s++);@+
1388 }
1389
1390 static void printn(int @!s) /*prints string |s|*/
1391 {@+
1392 pool_pointer j; /*current character code position*/
1393 int @!nl; /*new-line character to restore*/
1394 if (s >= str_ptr) {print("???"); return;}/*this can't happen*/
1395 @.???@>
1396 else if (s < 0x80)
1397 if (s < 0) { print("???");return; } /*can't happen*/
1398 else{@+if (selector > pseudo)
1399 {@+print_char(s);return; /*internal strings are not expanded*/
1400 }
1401 if ((@<Character |s| is the current new-line character@>))
1402 if (selector < pseudo)
1403 {@+print_ln();return;
1404 }
1405 nl=new_line_char;new_line_char=-1;
1406 /*temporarily disable new-line character*/
1407 j=str_start[s];
1408 while (j < str_start[s+1])
1409 {@+print_char(str_pool[j]);incr(j);
1410 }
1411 new_line_char=nl;return;
1412 }
1413 j=str_start[s];
1414 while (j < str_start[s+1])
1415 {@+print_char(str_pool[j]);incr(j);
1416 }
1417 }
1418
1419 @ Control sequence names, file names, and strings constructed with
1420 \.{\\string} might contain |ASCII_code| values that can't
1421 be printed using |print_char|. Therefore we use |slow_print| for them:
1422
1423 @<Basic print...@>=
1424 static void slow_print(int @!s) /*prints string |s|*/
1425 {@+pool_pointer j; /*current character code position*/
1426 if ((s >= str_ptr)||(s < 0x80)) printn(s);
1427 else{@+j=str_start[s];
1428 while (j < str_start[s+1])
1429 {@+if (str_pool[j]<0x80)
1430 printn(str_pool[j]);
1431 else
1432 print_char(str_pool[j]);
1433 incr(j);
1434 }
1435 }
1436 }
1437
1438 @ Here is the very first thing that \TeX\ prints: a headline that identifies
1439 the version number and format package. The |term_offset| variable is temporarily
1440 incorrect, but the discrepancy is not serious since we assume that this
1441 part of the program is system dependent.
1442 @^system dependencies@>
1443
1444 According to the conventions of \TeX\ Live,
1445 we print the |dump_name| if no format identifier is known.
1446 @<Initialize the output...@>=
1447 wterm("%s",banner);
1448 if (format_ident==0) wterm_ln(" (preloaded format=%s)", dump_name);
1449 else{@+slow_print(format_ident);print_ln();
1450 }
1451 update_terminal;
1452
1453 @ The procedure |print_nl| is like |print|, but it makes sure that the
1454 string appears at the beginning of a new line.
1455
1456 @<Basic print...@>=
1457 static void print_nl(char *@!s) /*prints string |s| at beginning of line*/
1458 {@+if (((term_offset > 0)&&(odd(selector)))||@|
1459 ((file_offset > 0)&&(selector >= log_only))) print_ln();
1460 print(s);
1461 }
1462
1463 @ The procedure |print_esc| prints a string that is preceded by
1464 the user's escape character (which is usually a backslash).
1465
1466 @<Basic print...@>=
1467 static void printn_esc(str_number @!s) /*prints escape character, then |s|*/
1468 {@+int c; /*the escape character code*/
1469 @<Set variable |c| to the current escape character@>;
1470 if (c >= 0) if (c < 256) printn(c);
1471 slow_print(s);
1472 }
1473
1474 static void print_esc(char *@!s) /*the fast way*/
1475 {@+int c; /*the escape character code*/
1476 @<Set variable |c| to the current escape character@>;
1477 if (c >= 0) if (c < 256) printn(c);
1478 print(s);
1479 }
1480
1481 @ An array of digits in the range |0 dotdot 15| is printed by |print_the_digs|.
1482
1483 @<Basic print...@>=
1484 static void print_the_digs(eight_bits @!k)
1485 /*prints |dig[k-1]|$\,\ldots\,$|dig[0]|*/
1486 {@+while (k > 0)
1487 {@+decr(k);
1488 if (dig[k] < 10) print_char('0'+dig[k]);
1489 else print_char('A'-10+dig[k]);
1490 }
1491 }
1492
1493 @ The following procedure, which prints out the decimal representation of a
1494 given integer |n|, has been written carefully so that it works properly
1495 if |n==0| or if |(-n)| would cause overflow. It does not apply |%| or |/|
1496 to negative arguments, since such operations are not implemented consistently
1497 by all \PASCAL\ compilers.
1498
1499 @<Basic print...@>=
1500 static void print_int(int @!n) /*prints an integer in decimal form*/
1501 {@+int k; /*index to current digit; we assume that $\vert n\vert<10^{23}$*/
1502 int @!m; /*used to negate |n| in possibly dangerous cases*/
1503 k=0;
1504 if (n < 0)
1505 {@+print_char('-');
1506 if (n > -100000000) negate(n);
1507 else{@+m=-1-n;n=m/10;m=(m%10)+1;k=1;
1508 if (m < 10) dig[0]=m;
1509 else{@+dig[0]=0;incr(n);
1510 }
1511 }
1512 }
1513 @/do@+{dig[k]=n%10;n=n/10;incr(k);
1514 }@+ while (!(n==0));
1515 print_the_digs(k);
1516 }
1517
1518 @ Here is a trivial procedure to print two digits; it is usually called with
1519 a parameter in the range |0 <= n <= 99|.
1520
1521 @p static void print_two(int @!n) /*prints two least significant digits*/
1522 {@+n=abs(n)%100;print_char('0'+(n/10));
1523 print_char('0'+(n%10));
1524 }
1525
1526 @ Hexadecimal printing of nonnegative integers is accomplished by |print_hex|.
1527
1528 @p static void print_hex(int @!n)
1529 /*prints a positive integer in hexadecimal form*/
1530 {@+int k; /*index to current digit; we assume that $0\le n<16^{22}$*/
1531 k=0;print_char('"');
1532 @/do@+{dig[k]=n%16;n=n/16;incr(k);
1533 }@+ while (!(n==0));
1534 print_the_digs(k);
1535 }
1536
1537 @ Old versions of \TeX\ needed a procedure called |print_ASCII| whose function
1538 is now subsumed by |print|. We retain the old name here as a possible aid to
1539 future software arch\ae ologists.
1540
1541 @d print_ASCII printn
1542
1543 @ Roman numerals are produced by the |print_roman_int| routine. Readers
1544 who like puzzles might enjoy trying to figure out how this tricky code
1545 works; therefore no explanation will be given. Notice that 1990 yields
1546 \.{mcmxc}, not \.{mxm}.
1547
1548 @p static void print_roman_int(int @!n)
1549 {@+
1550 pool_pointer j, @!k; /*mysterious indices into |mystery|*/
1551 nonnegative_integer @!u, @!v; /*mysterious numbers*/
1552 const char mystery[] ="m2d5c2l5x2v5i";
1553 j=0;v=1000;
1554 loop@+{@+while (n >= v)
1555 {@+print_char(mystery[j]);n=n-v;
1556 }
1557 if (n <= 0) return; /*nonpositive input produces no output*/
1558 k=j+2;u=v/(mystery[k-1]-'0');
1559 if (mystery[k-1]=='2')
1560 {@+k=k+2;u=u/(mystery[k-1]-'0');
1561 }
1562 if (n+u >= v)
1563 {@+print_char(mystery[k]);n=n+u;
1564 }
1565 else{@+j=j+2;v=v/(mystery[j-1]-'0');
1566 }
1567 }
1568 }
1569
1570 @ The |print| subroutine will not print a string that is still being
1571 created. The following procedure will.
1572
1573 @p static void print_current_string(void) /*prints a yet-unmade string*/
1574 {@+pool_pointer j; /*points to current character code*/
1575 j=str_start[str_ptr];
1576 while (j < pool_ptr)
1577 {@+print_char(str_pool[j]);incr(j);
1578 }
1579 }
1580
1581 @ Here is a procedure that asks the user to type a line of input,
1582 assuming that the |selector| setting is either |term_only| or |term_and_log|.
1583 The input is placed into locations |first| through |last-1| of the
1584 |buffer| array, and echoed on the transcript file if appropriate.
1585
1586 This procedure is never called when |interaction < scroll_mode|.
1587
1588 @d prompt_input(A) {@+wake_up_terminal;print(A);term_input();
1589 } /*prints a string and gets a line of input*/
1590
1591 @p static void term_input(void) /*gets a line from the terminal*/
1592 {@+int k; /*index into |buffer|*/
1593 update_terminal; /*now the user sees the prompt for sure*/
1594 if (!input_ln(&term_in, true)) fatal_error("End of file on the terminal!");
1595 @.End of file on the terminal@>
1596 term_offset=0; /*the user's line ended with \<\rm return>*/
1597 decr(selector); /*prepare to echo the input*/
1598 if (last!=first) for (k=first; k<=last-1; k++) printn(buffer[k]);
1599 print_ln();incr(selector); /*restore previous status*/
1600 }
1601
1602 @* Reporting errors.
1603 When something anomalous is detected, \TeX\ typically does something like this:
1604 $$\vbox{\halign{#\hfil\cr
1605 |print_err("Something anomalous has been detected");|\cr
1606 |help3("This is the first line of my offer to help.")|\cr
1607 |("This is the second line. I'm trying to")|\cr
1608 |("explain the best way for you to proceed.");|\cr
1609 |error;|\cr}}$$
1610 A two-line help message would be given using |help2|, etc.; these informal
1611 helps should use simple vocabulary that complements the words used in the
1612 official error message that was printed. (Outside the U.S.A., the help
1613 messages should preferably be translated into the local vernacular. Each
1614 line of help is at most 60 characters long, in the present implementation,
1615 so that |max_print_line| will not be exceeded.)
1616
1617 The |print_err| procedure supplies a `\.!' before the official message,
1618 and makes sure that the terminal is awake if a stop is going to occur.
1619 The |error| procedure supplies a `\..' after the official message, then it
1620 shows the location of the error; and if |interaction==error_stop_mode|,
1621 it also enters into a dialog with the user, during which time the help
1622 message may be printed.
1623 @^system dependencies@>
1624
1625 Some of the errors in original \TeX\ should go only to the log file
1626 and without the word |"error"| in it because humans and
1627 software look for it. This behaviour is implemented here to match
1628 the behaviour of other \TeX\ engines.
1629
1630 @<Error handling...@>=
1631 static void print_ignored_err(char *s)
1632 {@+int old_selector_ignored_err = selector;
1633 selector = log_only;
1634 if (filelineerrorstylep) print_file_line(); /* \TeX\ Live */
1635 else print_nl("");
1636 print("ignored: "); print(s);
1637 selector = old_selector_ignored_err;
1638 }
1639
1640 static void print_err(char *s)
1641 {@+if (interaction==error_stop_mode) wake_up_terminal;
1642 if (filelineerrorstylep) print_file_line(); /* \TeX\ Live */
1643 else print_nl("! ");
1644 print(s);
1645 }
1646
1647 @ The global variable |interaction| has four settings, representing increasing
1648 amounts of user interaction:
1649
1650 @d batch_mode 0 /*omits all stops and omits terminal output*/
1651 @d nonstop_mode 1 /*omits all stops*/
1652 @d scroll_mode 2 /*omits error stops*/
1653 @d error_stop_mode 3 /*stops at every opportunity to interact*/
1654
1655 @<Glob...@>=
1656 static int @!interaction; /*current level of interaction*/
1657
1658 @ @<Set init...@>=
1659 if (interaction_option<0) interaction=error_stop_mode;
1660 else interaction=interaction_option; /* \TeX\ Live */
1661
1662 @ \TeX\ is careful not to call |error| when the print |selector| setting
1663 might be unusual. The only possible values of |selector| at the time of
1664 error messages are
1665
1666 \yskip\hang|no_print| (when |interaction==batch_mode|
1667 and |log_file| not yet open);
1668
1669 \hang|term_only| (when |interaction > batch_mode| and |log_file| not yet open);
1670
1671 \hang|log_only| (when |interaction==batch_mode| and |log_file| is open);
1672
1673 \hang|term_and_log| (when |interaction > batch_mode| and |log_file| is open).
1674
1675 @<Initialize the print |selector| based on |interaction|@>=
1676 if (interaction==batch_mode) selector=no_print;@+else selector=term_only
1677
1678 @ A global variable |deletions_allowed| is set |false| if the |get_next|
1679 routine is active when |error| is called; this ensures that |get_next|
1680 and related routines like |get_token| will never be called recursively.
1681 A similar interlock is provided by |set_box_allowed|.
1682 @^recursion@>
1683
1684 The global variable |history| records the worst level of error that
1685 has been detected. It has four possible values: |spotless|, |warning_issued|,
1686 |error_message_issued|, and |fatal_error_stop|.
1687
1688 Another global variable, |error_count|, is increased by one when an
1689 |error| occurs without an interactive dialog, and it is reset to zero at
1690 the end of every paragraph. If |error_count| reaches 100, \TeX\ decides
1691 that there is no point in continuing further.
1692
1693 @d spotless 0 /*|history| value when nothing has been amiss yet*/
1694 @d warning_issued 1 /*|history| value when |begin_diagnostic| has been called*/
1695 @d error_message_issued 2 /*|history| value when |error| has been called*/
1696 @d fatal_error_stop 3 /*|history| value when termination was premature*/
1697
1698 @<Glob...@>=
1699 static bool @!deletions_allowed; /*is it safe for |error| to call |get_token|?*/
1700 static bool @!set_box_allowed; /*is it safe to do a \.{\\setbox} assignment?*/
1701 static int @!history; /*has the source input been clean so far?*/
1702 static int @!error_count; /*the number of scrolled errors since the
1703 last paragraph ended*/
1704
1705 @ The value of |history| is initially |fatal_error_stop|, but it will
1706 be changed to |spotless| if \TeX\ survives the initialization process.
1707
1708 @<Set init...@>=
1709 deletions_allowed=true;set_box_allowed=true;
1710 error_count=0; /*|history| is initialized elsewhere*/
1711
1712 @ Since errors can be detected almost anywhere in \TeX, we want to declare the
1713 error procedures near the beginning of the program. But the error procedures
1714 in turn use some other procedures, which need to be declared |forward|
1715 before we get to |error| itself.
1716
1717 It is possible for |error| to be called recursively if some error arises
1718 when |get_token| is being used to delete a token, and/or if some fatal error
1719 occurs while \TeX\ is trying to fix a non-fatal one. But such recursion
1720 @^recursion@>
1721 is never more than two levels deep.
1722
1723 @<Error handling...@>=
1724 static void normalize_selector(void);@/
1725 static void get_token(void);@/
1726 static void term_input(void);@/
1727 static void show_context(void);@/
1728 static void begin_file_reading(void);@/
1729 static void open_log_file(void);@/
1730 static void close_files_and_terminate(void);@/
1731 static void clear_for_error_prompt(void);@/
1732 static void give_err_help(void);@/
1733 #ifdef @!DEBUG
1734 static void debug_help(void);
1735 #else
1736 #define debug_help() do_nothing
1737 #endif
1738
1739 @ Individual lines of help are recorded in the array |help_line|, which
1740 contains entries in positions |0 dotdot(help_ptr-1)|. They should be printed
1741 in reverse order, i.e., with |help_line[0]| appearing last.
1742
1743 @d hlp1(A) help_line[0]=A;@+}
1744 @d hlp2(A, B) help_line[1]=A;help_line[0]=B;@+}
1745 @d hlp3(A, B, C) help_line[2]=A;help_line[1]=B;help_line[0]=C;@+}
1746 @d hlp4(A, B, C, D) help_line[3]=A;help_line[2]=B;help_line[1]=C;help_line[0]=D;@+}
1747 @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;@+}
1748 @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;@+}
1749 @d help0 help_ptr=0 /*sometimes there might be no help*/
1750 @d help1(A) @+{@+help_ptr=1;hlp1(A) /*use this with one help line*/
1751 @d help2(A, B) @+{@+help_ptr=2;hlp2(A, B) /*use this with two help lines*/
1752 @d help3(A, B, C) @+{@+help_ptr=3;hlp3(A, B, C) /*use this with three help lines*/
1753 @d help4(A, B, C, D) @+{@+help_ptr=4;hlp4(A, B, C, D) /*use this with four help lines*/
1754 @d help5(A, B, C, D, E) @+{@+help_ptr=5;hlp5(A, B, C, D, E) /*use this with five help lines*/
1755 @d help6(A, B, C, D, E, F) @+{@+help_ptr=6;hlp6(A, B, C, D, E, F) /*use this with six help lines*/
1756
1757 @<Glob...@>=
1758 static char *@!help_line[6]; /*helps for the next |error|*/
1759 static int @!help_ptr; /*the number of help lines present*/
1760 static bool @!use_err_help; /*should the |err_help| list be shown?*/
1761
1762 @ @<Set init...@>=
1763 help_ptr=0;use_err_help=false;
1764
1765 @ The |jump_out| procedure just cuts across all active procedure levels and
1766 goes to |end_of_TEX|. This is the only nontrivial |@!goto| statement in the
1767 whole program. It is used when there is no recovery from a particular error.
1768
1769 Some \PASCAL\ compilers do not implement non-local |goto| statements.
1770 @^system dependencies@>
1771 In such cases the body of |jump_out| should simply be
1772 `|close_files_and_terminate|;\thinspace' followed by a call on some system
1773 procedure that quietly terminates the program.
1774
1775 @<Error hand...@>=
1776 static void jump_out(void)
1777 {@+ close_files_and_terminate(); exit(0);
1778 }
1779
1780 @ Here now is the general |error| routine.
1781
1782 @<Error hand...@>=
1783 static void error(void) /*completes the job of error reporting*/
1784 {@+
1785 UTF8_code c; /*what the user types*/
1786 int @!s1, @!s2, @!s3, @!s4;
1787 /*used to save global variables when deleting tokens*/
1788 if (history < error_message_issued) history=error_message_issued;
1789 print_char('.');show_context();
1790 if (interaction==error_stop_mode)
1791 @<Get user's advice and |return|@>;
1792 incr(error_count);
1793 if (error_count==100)
1794 {@+print_nl("(That makes 100 errors; please try again.)");
1795 @.That makes 100 errors...@>
1796 history=fatal_error_stop;jump_out();
1797 }
1798 @<Put help message on the transcript file@>;
1799 }
1800
1801 @ @<Get user's advice...@>=
1802 loop@+{@+resume: if (interaction!=error_stop_mode) return;
1803 clear_for_error_prompt();prompt_input("? ");
1804 @.?\relax@>
1805 if (last==first) return;
1806 c=buffer[first];
1807 if (c >= 'a') c=c+'A'-'a'; /*convert to uppercase*/
1808 @<Interpret code |c| and |return| if done@>;
1809 }
1810
1811 @ It is desirable to provide an `\.E' option here that gives the user
1812 an easy way to return from \TeX\ to the system editor, with the offending
1813 line ready to be edited. But such an extension requires some system
1814 wizardry, so the present implementation simply types out the name of the
1815 file that should be
1816 edited and the relevant line number.
1817 @^system dependencies@>
1818
1819 There is a secret `\.D' option available when the debugging routines haven't
1820 been commented~out.
1821 @^debugging@>
1822
1823 @<Interpret code |c| and |return| if done@>=
1824 switch (c) {
1825 case '0': case '1': case '2': case '3':
1826 case '4': case '5': case '6': case '7':
1827 case '8': case '9': if (deletions_allowed)
1828 @<Delete \(c)|c-"0"| tokens and |goto resume|@>@;@+break;
1829 @t\4\4@>@;
1830 #ifdef @!DEBUG
1831 case 'D': {@+debug_help();goto resume;@+}
1832 #endif
1833 case 'E': if (base_ptr > 0) if (input_stack[base_ptr].name_field >= 256)
1834 {@+print_nl("You want to edit file ");
1835 @.You want to edit file x@>
1836 slow_print(input_stack[base_ptr].name_field);
1837 print(" at line ");print_int(line);
1838 interaction=scroll_mode;jump_out();
1839 } @+break;
1840 case 'H': @<Print the help information and |goto resume|@>@;
1841 case 'I': @<Introduce new material from the terminal and |return|@>@;
1842 case 'Q': case 'R': case 'S': @<Change the interaction level and |return|@>@;
1843 case 'X': {@+interaction=scroll_mode;jump_out();
1844 } @+break;
1845 default:do_nothing;
1846 } @/
1847 @<Print the menu of available options@>@;
1848
1849 @ @<Print the menu...@>=
1850 {@+print("Type <return> to proceed, S to scroll future error messages,");@/
1851 @.Type <return> to proceed...@>
1852 print_nl("R to run without stopping, Q to run quietly,");@/
1853 print_nl("I to insert something, ");
1854 if (base_ptr > 0) if (input_stack[base_ptr].name_field >= 256)
1855 print("E to edit your file,");
1856 if (deletions_allowed)
1857 print_nl("1 or ... or 9 to ignore the next 1 to 9 tokens of input,");
1858 print_nl("H for help, X to quit.");
1859 }
1860
1861 @ Here the author of \TeX\ apologizes for making use of the numerical
1862 relation between |'Q'|, |'R'|, |'S'|, and the desired interaction settings
1863 |batch_mode|, |nonstop_mode|, |scroll_mode|.
1864 @^Knuth, Donald Ervin@>
1865
1866 @<Change the interaction...@>=
1867 {@+error_count=0;interaction=batch_mode+c-'Q';
1868 print("OK, entering ");
1869 switch (c) {
1870 case 'Q': {@+print_esc("batchmode");decr(selector);
1871 } @+break;
1872 case 'R': print_esc("nonstopmode");@+break;
1873 case 'S': print_esc("scrollmode");
1874 } /*there are no other cases*/
1875 print("...");print_ln();update_terminal;return;
1876 }
1877
1878 @ When the following code is executed, |buffer[(first+1)dotdot(last-1)]| may
1879 contain the material inserted by the user; otherwise another prompt will
1880 be given. In order to understand this part of the program fully, you need
1881 to be familiar with \TeX's input stacks.
1882
1883 @<Introduce new material...@>=
1884 {@+begin_file_reading(); /*enter a new syntactic level for terminal input*/
1885 /*now |state==mid_line|, so an initial blank space will count as a blank*/
1886 if (last > first+1)
1887 {@+loc=first+1;buffer[first]=' ';
1888 }
1889 else{@+prompt_input("insert>");loc=first;
1890 @.insert>@>
1891 }
1892 first=last;
1893 cur_input.limit_field=last-1; /*no |end_line_char| ends this line*/
1894 return;
1895 }
1896
1897 @ We allow deletion of up to 99 tokens at a time.
1898
1899 @<Delete \(c)|c-"0"| tokens...@>=
1900 {@+s1=cur_tok;s2=cur_cmd;s3=cur_chr;s4=align_state;
1901 align_state=1000000;OK_to_interrupt=false;
1902 if ((last > first+1)&&(buffer[first+1] >= '0')&&(buffer[first+1] <= '9'))
1903 c=c*10+buffer[first+1]-'0'*11;
1904 else c=c-'0';
1905 while (c > 0)
1906 {@+get_token(); /*one-level recursive call of |error| is possible*/
1907 decr(c);
1908 }
1909 cur_tok=s1;cur_cmd=s2;cur_chr=s3;align_state=s4;OK_to_interrupt=true;
1910 help2("I have just deleted some text, as you asked.",@/
1911 "You can now delete more, or insert, or whatever.");
1912 show_context();goto resume;
1913 }
1914
1915 @ @<Print the help info...@>=
1916 {@+if (use_err_help)
1917 {@+give_err_help();use_err_help=false;
1918 }
1919 else{@+if (help_ptr==0)
1920 help2("Sorry, I don't know how to help in this situation.",@/
1921 @t\kern1em@>"Maybe you should try asking a human?");
1922 @/do@+{decr(help_ptr);print(help_line[help_ptr]);print_ln();
1923 }@+ while (!(help_ptr==0));
1924 }
1925 help4("Sorry, I already gave what help I could...",@/
1926 "Maybe you should try asking a human?",@/
1927 "An error might have occurred before I noticed any problems.",@/
1928 "``If all else fails, read the instructions.'");@/
1929 goto resume;
1930 }
1931
1932 @ @<Put help message on the transcript file@>=
1933 if (interaction > batch_mode) decr(selector); /*avoid terminal output*/
1934 if (use_err_help)
1935 {@+print_ln();give_err_help();
1936 }
1937 else while (help_ptr > 0)
1938 {@+decr(help_ptr);print_nl(help_line[help_ptr]);
1939 }
1940 print_ln();
1941 if (interaction > batch_mode) incr(selector); /*re-enable terminal output*/
1942 print_ln()
1943
1944 @ A dozen or so error messages end with a parenthesized integer, so we
1945 save a teeny bit of program space by declaring the following procedure:
1946
1947 @p static void int_error(int @!n)
1948 {@+print(" (");print_int(n);print_char(')');error();
1949 }
1950
1951 @ In anomalous cases, the print selector might be in an unknown state;
1952 the following subroutine is called to fix things just enough to keep
1953 running a bit longer.
1954
1955 @p static void normalize_selector(void)
1956 {@+if (log_opened) selector=term_and_log;
1957 else selector=term_only;
1958 if (job_name==0) open_log_file();
1959 if (interaction==batch_mode) decr(selector);
1960 }
1961
1962 @ The following procedure prints \TeX's last words before dying.
1963
1964 @d succumb {@+if (interaction==error_stop_mode)
1965 interaction=scroll_mode; /*no more interaction*/
1966 if (log_opened) error();
1967 if (interaction > batch_mode) debug_help();
1968 history=fatal_error_stop;jump_out(); /*irrecoverable error*/
1969 }
1970
1971 @<Error hand...@>=
1972 static void fatal_error(char *@!s) /*prints |s|, and that's it*/
1973 {@+normalize_selector();@/
1974 print_err("Emergency stop");help1(s);succumb;
1975 @.Emergency stop@>
1976 }
1977
1978 @ Here is the most dreaded error message.
1979
1980 @<Error hand...@>=
1981 static void overflow(char *@!s, int @!n) /*stop due to finiteness*/
1982 {@+normalize_selector();
1983 print_err("TeX capacity exceeded, sorry [");
1984 @.TeX capacity exceeded ...@>
1985 print(s);print_char('=');print_int(n);print_char(']');
1986 help2("If you really absolutely need more capacity,",@/
1987 "you can ask a wizard to enlarge me.");
1988 succumb;
1989 }
1990
1991 @ The program might sometime run completely amok, at which point there is
1992 no choice but to stop. If no previous error has been detected, that's bad
1993 news; a message is printed that is really intended for the \TeX\
1994 maintenance person instead of the user (unless the user has been
1995 particularly diabolical). The index entries for `this can't happen' may
1996 help to pinpoint the problem.
1997 @^dry rot@>
1998
1999 @<Error hand...@>=
2000 static void confusion(char *@!s)
2001 /*consistency check violated; |s| tells where*/
2002 {@+normalize_selector();
2003 if (history < error_message_issued)
2004 {@+print_err("This can't happen (");print(s);print_char(')');
2005 @.This can't happen@>
2006 help1("I'm broken. Please show this to someone who can fix can fix");
2007 }
2008 else{@+print_err("I can't go on meeting you like this");
2009 @.I can't go on...@>
2010 help2("One of your faux pas seems to have wounded me deeply...",@/
2011 "in fact, I'm barely conscious. Please fix it and try again.");
2012 }
2013 succumb;
2014 }
2015
2016 @ Users occasionally want to interrupt \TeX\ while it's running.
2017 If the \PASCAL\ runtime system allows this, one can implement
2018 a routine that sets the global variable |interrupt| to some nonzero value
2019 when such an interrupt is signalled. Otherwise there is probably at least
2020 a way to make |interrupt| nonzero using the \PASCAL\ debugger.
2021 @^system dependencies@>
2022 @^debugging@>
2023
2024 @d check_interrupt {@+if (interrupt!=0) pause_for_instructions();
2025 }
2026
2027 @<Global...@>=
2028 static int @!interrupt; /*should \TeX\ pause for instructions?*/
2029 static bool @!OK_to_interrupt; /*should interrupts be observed?*/
2030
2031 @ @<Set init...@>=
2032 interrupt=0;OK_to_interrupt=true;
2033
2034 @ When an interrupt has been detected, the program goes into its
2035 highest interaction level and lets the user have nearly the full flexibility of
2036 the |error| routine. \TeX\ checks for interrupts only at times when it is
2037 safe to do this.
2038
2039 @p static void pause_for_instructions(void)
2040 {@+if (OK_to_interrupt)
2041 {@+interaction=error_stop_mode;
2042 if ((selector==log_only)||(selector==no_print))
2043 incr(selector);
2044 print_err("Interruption");
2045 @.Interruption@>
2046 help3("You rang?",@/
2047 "Try to insert an instruction for me (e.g., `I\\showlists'),",@/
2048 "unless you just want to quit by typing `X'.");
2049 deletions_allowed=false;error();deletions_allowed=true;
2050 interrupt=0;
2051 }
2052 }
2053
2054 @* Arithmetic with scaled dimensions.
2055 The principal computations performed by \TeX\ are done entirely in terms of
2056 integers less than $2^{31}$ in magnitude; and divisions are done only when both
2057 dividend and divisor are nonnegative. Thus, the arithmetic specified in this
2058 program can be carried out in exactly the same way on a wide variety of
2059 computers, including some small ones. Why? Because the arithmetic
2060 calculations need to be spelled out precisely in order to guarantee that
2061 \TeX\ will produce identical output on different machines. If some
2062 quantities were rounded differently in different implementations, we would
2063 find that line breaks and even page breaks might occur in different places.
2064 Hence the arithmetic of \TeX\ has been designed with care, and systems that
2065 claim to be implementations of \TeX82 should follow precisely the
2066 @:TeX82}{\TeX82@>
2067 calculations as they appear in the present program.
2068
2069 (Actually there are three places where \TeX\ uses |/| with a possibly negative
2070 numerator. These are harmless; see |/| in the index. Also if the user
2071 sets the \.{\\time} or the \.{\\year} to a negative value, some diagnostic
2072 information will involve negative-numerator division. The same remarks
2073 apply for |%| as well as for |/|.)
2074
2075 @ Here is a routine that calculates half of an integer, using an
2076 unambiguous convention with respect to signed odd numbers.
2077
2078 @p static int half(int @!x)
2079 {@+if (odd(x)) return(x+1)/2;
2080 else return x/2;
2081 }
2082
2083 @ Fixed-point arithmetic is done on {\sl scaled integers\/} that are multiples
2084 of $2^{-16}$. In other words, a binary point is assumed to be sixteen bit
2085 positions from the right end of a binary computer word.
2086
2087 @d unity 0200000 /*$2^{16}$, represents 1.00000*/
2088 @d two 0400000 /*$2^{17}$, represents 2.00000*/
2089
2090 @<Types...@>=
2091 typedef int scaled; /*this type is used for scaled integers*/
2092 typedef int32_t nonnegative_integer; /*$0\le x<2^{31}$*/
2093 typedef int8_t small_number; /*this type is self-explanatory*/
2094
2095 @ The following function is used to create a scaled integer from a given decimal
2096 fraction $(.d_0d_1\ldots d_{k-1})$, where |0 <= k <= 17|. The digit $d_i$ is
2097 given in |dig[i]|, and the calculation produces a correctly rounded result.
2098
2099 @p static scaled round_decimals(small_number @!k)
2100 /*converts a decimal fraction*/
2101 {@+int a; /*the accumulator*/
2102 a=0;
2103 while (k > 0)
2104 {@+decr(k);a=(a+dig[k]*two)/10;
2105 }
2106 return(a+1)/2;
2107 }
2108
2109 @ Conversely, here is a procedure analogous to |print_int|. If the output
2110 of this procedure is subsequently read by \TeX\ and converted by the
2111 |round_decimals| routine above, it turns out that the original value will
2112 be reproduced exactly; the ``simplest'' such decimal number is output,
2113 but there is always at least one digit following the decimal point.
2114
2115 The invariant relation in the \&{repeat} loop is that a sequence of
2116 decimal digits yet to be printed will yield the original number if and only if
2117 they form a fraction~$f$ in the range $s-\delta\le 10\cdot2^{16}f<s$.
2118 We can stop if and only if $f=0$ satisfies this condition; the loop will
2119 terminate before $s$ can possibly become zero.
2120
2121 @p static void print_scaled(scaled @!s) /*prints scaled real, rounded to five
2122 digits*/
2123 {@+scaled delta; /*amount of allowable inaccuracy*/
2124 if (s < 0)
2125 {@+print_char('-');negate(s); /*print the sign, if negative*/
2126 }
2127 print_int(s/unity); /*print the integer part*/
2128 print_char('.');
2129 s=10*(s%unity)+5;delta=10;
2130 @/do@+{if (delta > unity) s=s+0100000-50000; /*round the last digit*/
2131 print_char('0'+(s/unity));s=10*(s%unity);delta=delta*10;
2132 }@+ while (!(s <= delta));
2133 }
2134
2135 @ Physical sizes that a \TeX\ user specifies for portions of documents are
2136 represented internally as scaled points. Thus, if we define an `sp' (scaled
2137 @^sp@>
2138 point) as a unit equal to $2^{-16}$ printer's points, every dimension
2139 inside of \TeX\ is an integer number of sp. There are exactly
2140 4,736,286.72 sp per inch. Users are not allowed to specify dimensions
2141 larger than $2^{30}-1$ sp, which is a distance of about 18.892 feet (5.7583
2142 meters); two such quantities can be added without overflow on a 32-bit
2143 computer.
2144
2145 The present implementation of \TeX\ does not check for overflow when
2146 @^overflow in arithmetic@>
2147 dimensions are added or subtracted. This could be done by inserting a
2148 few dozen tests of the form `\ignorespaces|if (x >= 010000000000)|
2149 \\{report\_overflow}', but the chance of overflow is so remote that
2150 such tests do not seem worthwhile.
2151
2152 \TeX\ needs to do only a few arithmetic operations on scaled quantities,
2153 other than addition and subtraction, and the following subroutines do most of
2154 the work. A single computation might use several subroutine calls, and it is
2155 desirable to avoid producing multiple error messages in case of arithmetic
2156 overflow; so the routines set the global variable |arith_error| to |true|
2157 instead of reporting errors directly to the user. Another global variable,
2158 |rem|, holds the remainder after a division.
2159
2160 @<Glob...@>=
2161 static bool @!arith_error; /*has arithmetic overflow occurred recently?*/
2162 static scaled @!rem; /*amount subtracted to get an exact division*/
2163
2164 @ The first arithmetical subroutine we need computes $nx+y$, where |x|
2165 and~|y| are |scaled| and |n| is an integer. We will also use it to
2166 multiply integers.
2167
2168 @d nx_plus_y(A, B, C) mult_and_add(A, B, C, 07777777777)
2169 @d mult_integers(A, B) mult_and_add(A, B, 0, 017777777777)
2170
2171 @p static scaled mult_and_add(int @!n, scaled @!x, scaled @!y, scaled @!max_answer)
2172 {@+if (n < 0)
2173 {@+negate(x);negate(n);
2174 }
2175 if (n==0) return y;
2176 else if (((x <= (max_answer-y)/n)&&(-x <= (max_answer+y)/n)))
2177 return n*x+y;
2178 else{@+arith_error=true;return 0;
2179 }
2180 }
2181
2182 @ We also need to divide scaled dimensions by integers.
2183
2184 @p static scaled x_over_n(scaled @!x, int @!n)
2185 {@+bool negative; /*should |rem| be negated?*/
2186 scaled x_over_n;
2187 negative=false;
2188 if (n==0)
2189 {@+arith_error=true;x_over_n=0;rem=x;
2190 }
2191 else{@+if (n < 0)
2192 {@+negate(x);negate(n);negative=true;
2193 }
2194 if (x >= 0)
2195 {@+x_over_n=x/n;rem=x%n;
2196 }
2197 else{@+x_over_n=-((-x)/n);rem=-((-x)%n);
2198 }
2199 }
2200 if (negative) negate(rem);
2201 return x_over_n;}
2202
2203 @ Then comes the multiplication of a scaled number by a fraction |n/(double)d|,
2204 where |n| and |d| are nonnegative integers | <= @t$2^{16}$@>| and |d| is
2205 positive. It would be too dangerous to multiply by~|n| and then divide
2206 by~|d|, in separate operations, since overflow might well occur; and it
2207 would be too inaccurate to divide by |d| and then multiply by |n|. Hence
2208 this subroutine simulates 1.5-precision arithmetic.
2209
2210 @p static scaled xn_over_d(scaled @!x, int @!n, int @!d)
2211 {@+bool positive; /*was |x >= 0|?*/
2212 nonnegative_integer @!t, @!u, @!v; /*intermediate quantities*/
2213 scaled xn_over_d;
2214 if (x >= 0) positive=true;
2215 else{@+negate(x);positive=false;
2216 }
2217 t=(x%0100000)*n;
2218 u=(x/0100000)*n+(t/0100000);
2219 v=(u%d)*0100000+(t%0100000);
2220 if (u/d >= 0100000) arith_error=true;
2221 else u=0100000*(u/d)+(v/d);
2222 if (positive)
2223 {@+xn_over_d=u;rem=v%d;
2224 }
2225 else{@+xn_over_d=-u;rem=-(v%d);
2226 }
2227 return xn_over_d;}
2228
2229 @ The next subroutine is used to compute the ``badness'' of glue, when a
2230 total~|t| is supposed to be made from amounts that sum to~|s|. According
2231 to {\sl The \TeX book}, the badness of this situation is $100(t/s)^3$;
2232 however, badness is simply a heuristic, so we need not squeeze out the
2233 last drop of accuracy when computing it. All we really want is an
2234 approximation that has similar properties.
2235 @:TeXbook}{\sl The \TeX book@>
2236
2237 The actual method used to compute the badness is easier to read from the
2238 program than to describe in words. It produces an integer value that is a
2239 reasonably close approximation to $100(t/s)^3$, and all implementations
2240 of \TeX\ should use precisely this method. Any badness of $2^{13}$ or more is
2241 treated as infinitely bad, and represented by 10000.
2242
2243 It is not difficult to prove that $$\hbox{|badness(t+1, s) >= badness(t, s)
2244 >= badness(t, s+1)|}.$$ The badness function defined here is capable of
2245 computing at most 1095 distinct values, but that is plenty.
2246
2247 @d inf_bad 10000 /*infinitely bad value*/
2248
2249 @p @<Declare \Prote\ arithmetic routines@>@/
2250 static halfword badness(scaled @!t, scaled @!s) /*compute badness, given |t >= 0|*/
2251 {@+int r; /*approximation to $\alpha t/s$, where $\alpha^3\approx
2252 100\cdot2^{18}$*/
2253 if (t==0) return 0;
2254 else if (s <= 0) return inf_bad;
2255 else{@+if (t <= 7230584) r=(t*297)/s; /*$297^3=99.94\times2^{18}$*/
2256 else if (s >= 1663497) r=t/(s/297);
2257 else r=t;
2258 if (r > 1290) return inf_bad; /*$1290^3<2^{31}<1291^3$*/
2259 else return(r*r*r+0400000)/01000000;
2260 } /*that was $r^3/2^{18}$, rounded to the nearest integer*/
2261 }
2262
2263 @ When \TeX\ ``packages'' a list into a box, it needs to calculate the
2264 proportionality ratio by which the glue inside the box should stretch
2265 or shrink. This calculation does not affect \TeX's decision making,
2266 so the precise details of rounding, etc., in the glue calculation are not
2267 of critical importance for the consistency of results on different computers.
2268
2269 We shall use the type |glue_ratio| for such proportionality ratios.
2270 A glue ratio should take the same amount of memory as an
2271 |int| (usually 32 bits) if it is to blend smoothly with \TeX's
2272 other data structures. Thus |glue_ratio| should be equivalent to
2273 |short_real| in some implementations of \PASCAL. Alternatively,
2274 it is possible to deal with glue ratios using nothing but fixed-point
2275 arithmetic; see {\sl TUGboat \bf3},1 (March 1982), 10--27. (But the
2276 routines cited there must be modified to allow negative glue ratios.)
2277 @^system dependencies@>
2278
2279 @d set_glue_ratio_zero(A) A=0.0 /*store the representation of zero ratio*/
2280 @d set_glue_ratio_one(A) A=1.0 /*store the representation of unit ratio*/
2281 @d unfix(A) ((double)(A)) /*convert from |glue_ratio| to type |double|*/
2282 @d fix(A) ((glue_ratio)(A)) /*convert from |double| to type |glue_ratio|*/
2283 @d float_constant(A) ((double)(A)) /*convert |int| constant to |double|*/
2284
2285 @<Types...@>=
2286 #if __SIZEOF_FLOAT__==4
2287 typedef float float32_t;
2288 #else
2289 #error @=float type must have size 4@>
2290 #endif
2291 typedef float @!glue_ratio; /*one-word representation of a glue expansion factor*/
2292
2293 @* Packed data.
2294 In order to make efficient use of storage space, \TeX\ bases its major data
2295 structures on a |memory_word|, which contains either a (signed) integer,
2296 possibly scaled, or a (signed) |glue_ratio|, or a small number of
2297 fields that are one half or one quarter of the size used for storing
2298 integers.
2299
2300 If |x| is a variable of type |memory_word|, it contains up to four
2301 fields that can be referred to as follows:
2302 $$\vbox{\halign{\hfil#&#\hfil&#\hfil\cr
2303 |x|&.|i|&(an |int|)\cr
2304 |x|&.|sc|\qquad&(a |scaled| integer)\cr
2305 |x|&.|gr|&(a |glue_ratio|)\cr
2306 |x.hh.lh|, |x.hh|&.|rh|&(two halfword fields)\cr
2307 |x.hh.b0|, |x.hh.b1|, |x.hh|&.|rh|&(two quarterword fields, one halfword
2308 field)\cr
2309 |x.qqqq.b0|, |x.qqqq.b1|, |x.qqqq|&.|b2|, |x.qqqq.b3|\hskip-100pt
2310 &\qquad\qquad\qquad(four quarterword fields)\cr}}$$
2311 This is somewhat cumbersome to write, and not very readable either, but
2312 macros will be used to make the notation shorter and more transparent.
2313 The \PASCAL\ code below gives a formal definition of |memory_word| and
2314 its subsidiary types, using packed variant records. \TeX\ makes no
2315 assumptions about the relative positions of the fields within a word.
2316
2317 Since we are assuming 32-bit integers, a halfword must contain at least
2318 16 bits, and a quarterword must contain at least 8 bits.
2319 @^system dependencies@>
2320 But it doesn't hurt to have more bits; for example, with enough 36-bit
2321 words you might be able to have |mem_max| as large as 262142, which is
2322 eight times as much memory as anybody had during the first four years of
2323 \TeX's existence.
2324
2325 N.B.: Valuable memory space will be dreadfully wasted unless \TeX\ is compiled
2326 by a \PASCAL\ that packs all of the |memory_word| variants into
2327 the space of a single integer. This means, for example, that |glue_ratio|
2328 words should be |short_real| instead of |double| on some computers. Some
2329 \PASCAL\ compilers will pack an integer whose subrange is `|0 dotdot 255|' into
2330 an eight-bit field, but others insist on allocating space for an additional
2331 sign bit; on such systems you can get 256 values into a quarterword only
2332 if the subrange is `|-128 dotdot 127|'.
2333
2334 The present implementation tries to accommodate as many variations as possible,
2335 so it makes few assumptions. If integers having the subrange
2336 `|min_quarterword dotdot max_quarterword|' can be packed into a quarterword,
2337 and if integers having the subrange `|min_halfword dotdot max_halfword|'
2338 can be packed into a halfword, everything should work satisfactorily.
2339
2340 It is usually most efficient to have |min_quarterword==min_halfword==0|,
2341 so one should try to achieve this unless it causes a severe problem.
2342 The values defined here are recommended for most 64-bit computers.
2343
2344 @d min_quarterword 0 /*smallest allowable value in a |quarterword|*/
2345 @d max_quarterword 65535 /*largest allowable value in a |quarterword|*/
2346 @d min_halfword 0 /*smallest allowable value in a |halfword|*/
2347 @d max_halfword 0x3FFFFFFF /*largest allowable value in a |halfword|*/
2348
2349 @ Here are the inequalities that the quarterword and halfword values
2350 must satisfy (or rather, the inequalities that they mustn't satisfy):
2351
2352 @<Check the ``constant''...@>=
2353 #ifdef @!INIT
2354 if ((mem_min!=mem_bot)||(mem_max!=mem_top)) bad=10;
2355 #endif
2356 @;@/
2357 if ((mem_min > mem_bot)||(mem_max < mem_top)) bad=10;
2358 if ((min_quarterword > 0)||(max_quarterword < 127)) bad=11;
2359 if ((min_halfword > 0)||(max_halfword < 32767)) bad=12;
2360 if ((min_quarterword < min_halfword)||@|
2361 (max_quarterword > max_halfword)) bad=13;
2362 if ((mem_min < min_halfword)||(mem_max >= max_halfword)||@|
2363 (mem_bot-mem_min-1 > max_halfword)) bad=14;
2364 if ((font_base < min_quarterword)||(font_max > max_quarterword)) bad=15;
2365 if (font_max > font_base+256) bad=16;
2366 if ((save_size > max_halfword)||(max_strings > max_halfword)) bad=17;
2367 if (buf_size > max_halfword) bad=18;
2368 if (max_quarterword-min_quarterword < 255) bad=19;
2369
2370 @ The operation of adding or subtracting |min_quarterword| occurs quite
2371 frequently in \TeX, so it is convenient to abbreviate this operation
2372 by using the macros |qi| and |qo| for input and output to and from
2373 quarterword format.
2374
2375 The inner loop of \TeX\ will run faster with respect to compilers
2376 that don't optimize expressions like `|x+0|' and `|x-0|', if these
2377 macros are simplified in the obvious way when |min_quarterword==0|.
2378 @^inner loop@>@^system dependencies@>
2379
2380 @d qi(A) A+min_quarterword
2381 /*to put an |eight_bits| item into a quarterword*/
2382 @d qo(A) A-min_quarterword
2383 /*to take an |eight_bits| item out of a quarterword*/
2384 @d hi(A) A+min_halfword
2385 /*to put a sixteen-bit item into a halfword*/
2386 @d ho(A) A-min_halfword
2387 /*to take a sixteen-bit item from a halfword*/
2388
2389 @ The reader should study the following definitions closely:
2390 @^system dependencies@>
2391
2392 @d sc i /*|scaled| data is equivalent to |int|*/
2393
2394 @<Types...@>=
2395 typedef uint16_t quarterword; /*1/4 of a word*/
2396 typedef int32_t halfword; /*1/2 of a word*/
2397 typedef int8_t two_choices; /*used when there are two variants in a record*/
2398 typedef int8_t four_choices; /*used when there are four variants in a record*/
2399 typedef struct { @;@/
2400 halfword @!rh;
2401 union {
2402 halfword @!lh;
2403 struct { quarterword @!b0;quarterword @!b1;} ;
2404 struct { unsigned int b8:8; unsigned int b24:24;} ;
2405 };} two_halves;
2406 typedef struct { @;@/
2407 quarterword @!b0;
2408 quarterword @!b1;
2409 quarterword @!b2;
2410 quarterword @!b3;
2411 } four_quarters;
2412 typedef struct { @;@/
2413 union {
2414 int @!i;
2415 glue_ratio @!gr;
2416 two_halves @!hh;
2417 four_quarters @!qqqq;
2418 };} memory_word;
2419 typedef struct {@+FILE *f;@+memory_word@,d;@+} word_file;
2420
2421 @ When debugging, we may want to print a |memory_word| without knowing
2422 what type it is; so we print it in all modes.
2423 @^dirty \PASCAL@>@^debugging@>
2424
2425 @p
2426 #ifdef @!DEBUG
2427 static void print_word(memory_word @!w)
2428 /*prints |w| in all ways*/
2429 {@+print_int(w.i);print_char(' ');@/
2430 print_scaled(w.sc);print_char(' ');@/
2431 print_scaled(round(unity*unfix(w.gr)));print_ln();@/
2432 @^real multiplication@>
2433 print_int(w.hh.lh);print_char('=');print_int(w.hh.b0);print_char(':');
2434 print_int(w.hh.b1);print_char(';');print_int(w.hh.rh);print_char(' ');@/
2435 print_int(w.qqqq.b0);print_char(':');print_int(w.qqqq.b1);print_char(':');
2436 print_int(w.qqqq.b2);print_char(':');print_int(w.qqqq.b3);
2437 }
2438 #endif
2439
2440 @* Dynamic memory allocation.
2441 The \TeX\ system does nearly all of its own memory allocation, so that it
2442 can readily be transported into environments that do not have automatic
2443 facilities for strings, garbage collection, etc., and so that it can be in
2444 control of what error messages the user receives. The dynamic storage
2445 requirements of \TeX\ are handled by providing a large array |mem| in
2446 which consecutive blocks of words are used as nodes by the \TeX\ routines.
2447
2448 Pointer variables are indices into this array, or into another array
2449 called |eqtb| that will be explained later. A pointer variable might
2450 also be a special flag that lies outside the bounds of |mem|, so we
2451 allow pointers to assume any |halfword| value. The minimum halfword
2452 value represents a null pointer. \TeX\ does not assume that |mem[null]| exists.
2453
2454 @s pointer int
2455 @d pointer halfword /*a flag or a location in |mem| or |eqtb|*/
2456 @d null min_halfword /*the null pointer*/
2457
2458 @<Glob...@>=
2459 static pointer @!temp_ptr; /*a pointer variable for occasional emergency use*/
2460
2461 @ The |mem| array is divided into two regions that are allocated separately,
2462 but the dividing line between these two regions is not fixed; they grow
2463 together until finding their ``natural'' size in a particular job.
2464 Locations less than or equal to |lo_mem_max| are used for storing
2465 variable-length records consisting of two or more words each. This region
2466 is maintained using an algorithm similar to the one described in exercise
2467 2.5--19 of {\sl The Art of Computer Programming}. However, no size field
2468 appears in the allocated nodes; the program is responsible for knowing the
2469 relevant size when a node is freed. Locations greater than or equal to
2470 |hi_mem_min| are used for storing one-word records; a conventional
2471 \.{AVAIL} stack is used for allocation in this region.
2472
2473 Locations of |mem| between |mem_bot| and |mem_top| may be dumped as part
2474 of preloaded format files, by the \.{INITEX} preprocessor.
2475 @.INITEX@>
2476 Production versions of \TeX\ may extend the memory at both ends in order to
2477 provide more space; locations between |mem_min| and |mem_bot| are always
2478 used for variable-size nodes, and locations between |mem_top| and |mem_max|
2479 are always used for single-word nodes.
2480
2481 The key pointers that govern |mem| allocation have a prescribed order:
2482 $$\advance\thickmuskip-2mu
2483 \hbox{|null <= mem_min <= mem_bot < lo_mem_max <
2484 hi_mem_min < mem_top <= mem_end <= mem_max|.}$$
2485
2486 Empirical tests show that the present implementation of \TeX\ tends to
2487 spend about 9\pct! of its running time allocating nodes, and about 6\pct!
2488 deallocating them after their use.
2489
2490 @<Glob...@>=
2491 static memory_word @!mem0[mem_max-mem_min+1],
2492 *const @!mem = @!mem0-mem_min; /*the big dynamic storage area*/
2493 static pointer @!lo_mem_max; /*the largest location of variable-size memory in use*/
2494 static pointer @!hi_mem_min; /*the smallest location of one-word memory in use*/
2495
2496 @ In order to study the memory requirements of particular applications, it
2497 is possible to prepare a version of \TeX\ that keeps track of current and
2498 maximum memory usage. When code between the delimiters |
2499 #ifdef @!STAT
2500 | $\ldots$
2501 |@t\#\&{endif}@>| is not ``commented out,'' \TeX\ will run a bit slower but it will
2502 report these statistics when |tracing_stats| is sufficiently large.
2503
2504 @<Glob...@>=
2505 static int @!var_used, @!dyn_used; /*how much memory is in use*/
2506 #ifdef @!STAT
2507 #define incr_dyn_used @[incr(dyn_used)@]
2508 #define decr_dyn_used @[decr(dyn_used)@]
2509 #else
2510 #define incr_dyn_used
2511 #define decr_dyn_used
2512 #endif
2513
2514 @ Let's consider the one-word memory region first, since it's the
2515 simplest. The pointer variable |mem_end| holds the highest-numbered location
2516 of |mem| that has ever been used. The free locations of |mem| that
2517 occur between |hi_mem_min| and |mem_end|, inclusive, are of type
2518 |two_halves|, and we write |info(p)| and |link(p)| for the |lh|
2519 and |rh| fields of |mem[p]| when it is of this type. The single-word
2520 free locations form a linked list
2521 $$|avail|,\;\hbox{|link(avail)|},\;\hbox{|link(link(avail))|},\;\ldots$$
2522 terminated by |null|.
2523
2524 @d link(A) mem[A].hh.rh /*the |link| field of a memory word*/
2525 @d info(A) mem[A].hh.lh /*the |info| field of a memory word*/
2526
2527 @<Glob...@>=
2528 static pointer @!avail; /*head of the list of available one-word nodes*/
2529 static pointer @!mem_end; /*the last one-word node used in |mem|*/
2530
2531 @ If memory is exhausted, it might mean that the user has forgotten
2532 a right brace. We will define some procedures later that try to help
2533 pinpoint the trouble.
2534
2535 @p @<Declare the procedure called |show_token_list|@>@/
2536 @<Declare the procedure called |runaway|@>@;
2537
2538 @ The function |get_avail| returns a pointer to a new one-word node whose
2539 |link| field is null. However, \TeX\ will halt if there is no more room left.
2540 @^inner loop@>
2541
2542 If the available-space list is empty, i.e., if |avail==null|,
2543 we try first to increase |mem_end|. If that cannot be done, i.e., if
2544 |mem_end==mem_max|, we try to decrease |hi_mem_min|. If that cannot be
2545 done, i.e., if |hi_mem_min==lo_mem_max+1|, we have to quit.
2546
2547 @p static pointer get_avail(void) /*single-word node allocation*/
2548 {@+pointer p; /*the new node being got*/
2549 p=avail; /*get top location in the |avail| stack*/
2550 if (p!=null) avail=link(avail); /*and pop it off*/
2551 else if (mem_end < mem_max) /*or go into virgin territory*/
2552 {@+incr(mem_end);p=mem_end;
2553 }
2554 else{@+decr(hi_mem_min);p=hi_mem_min;
2555 if (hi_mem_min <= lo_mem_max)
2556 {@+runaway(); /*if memory is exhausted, display possible runaway text*/
2557 overflow("main memory size", mem_max+1-mem_min);
2558 /*quit; all one-word nodes are busy*/
2559 @:TeX capacity exceeded main memory size}{\quad main memory size@>
2560 }
2561 }
2562 link(p)=null; /*provide an oft-desired initialization of the new node*/
2563 #ifdef @!STAT
2564 incr(dyn_used);
2565 #endif
2566 @; /*maintain statistics*/
2567 return p;
2568 }
2569
2570 @ Conversely, a one-word node is recycled by calling |free_avail|.
2571 This routine is part of \TeX's ``inner loop,'' so we want it to be fast.
2572 @^inner loop@>
2573
2574 @d free_avail(A) /*single-word node liberation*/
2575 {@+link(A)=avail;avail=A;
2576 decr_dyn_used;
2577 }
2578
2579 @ There's also a |fast_get_avail| routine, which saves the procedure-call
2580 overhead at the expense of extra programming. This routine is used in
2581 the places that would otherwise account for the most calls of |get_avail|.
2582 @^inner loop@>
2583
2584 @d fast_get_avail(A) @t@>@;@/
2585 {@+A=avail; /*avoid |get_avail| if possible, to save time*/
2586 if (A==null) A=get_avail();
2587 else{@+avail=link(A);link(A)=null;
2588 incr_dyn_used;
2589 }
2590 }
2591
2592 @ The procedure |flush_list(p)| frees an entire linked list of
2593 one-word nodes that starts at position |p|.
2594 @^inner loop@>
2595
2596 @p static void flush_list(pointer @!p) /*makes list of single-word nodes
2597 available*/
2598 {@+pointer @!q, @!r; /*list traversers*/
2599 if (p!=null)
2600 {@+r=p;
2601 @/do@+{q=r;r=link(r);
2602 #ifdef @!STAT
2603 decr(dyn_used);
2604 #endif
2605 }@+ while (!(r==null)); /*now |q| is the last node on the list*/
2606 link(q)=avail;avail=p;
2607 }
2608 }
2609
2610 @ The available-space list that keeps track of the variable-size portion
2611 of |mem| is a nonempty, doubly-linked circular list of empty nodes,
2612 pointed to by the roving pointer |rover|.
2613
2614 Each empty node has size 2 or more; the first word contains the special
2615 value |max_halfword| in its |link| field and the size in its |info| field;
2616 the second word contains the two pointers for double linking.
2617
2618 Each nonempty node also has size 2 or more. Its first word is of type
2619 |two_halves|\kern-1pt, and its |link| field is never equal to |max_halfword|.
2620 Otherwise there is complete flexibility with respect to the contents
2621 of its other fields and its other words.
2622
2623 (We require |mem_max < max_halfword| because terrible things can happen
2624 when |max_halfword| appears in the |link| field of a nonempty node.)
2625
2626 @d empty_flag max_halfword /*the |link| of an empty variable-size node*/
2627 @d is_empty(A) (link(A)==empty_flag) /*tests for empty node*/
2628 @d node_size(A) info(A) /*the size field in empty variable-size nodes*/
2629 @d llink(A) info(A+1) /*left link in doubly-linked list of empty nodes*/
2630 @d rlink(A) link(A+1) /*right link in doubly-linked list of empty nodes*/
2631
2632 @<Glob...@>=
2633 static pointer @!rover; /*points to some node in the list of empties*/
2634
2635 @ A call to |get_node| with argument |s| returns a pointer to a new node
2636 of size~|s|, which must be 2~or more. The |link| field of the first word
2637 of this new node is set to null. An overflow stop occurs if no suitable
2638 space exists.
2639
2640 If |get_node| is called with $s=2^{30}$, it simply merges adjacent free
2641 areas and returns the value |max_halfword|.
2642
2643 @p static pointer get_node(int @!s) /*variable-size node allocation*/
2644 {@+
2645 pointer p; /*the node currently under inspection*/
2646 pointer @!q; /*the node physically after node |p|*/
2647 int @!r; /*the newly allocated node, or a candidate for this honor*/
2648 int @!t; /*temporary register*/
2649 restart: p=rover; /*start at some free node in the ring*/
2650 @/do@+{@<Try to allocate within node |p| and its physical successors, and
2651 |goto found| if allocation was possible@>;
2652 @^inner loop@>
2653 p=rlink(p); /*move to the next node in the ring*/
2654 }@+ while (!(p==rover)); /*repeat until the whole list has been traversed*/
2655 if (s==010000000000)
2656 {@+return max_halfword;
2657 }
2658 if (lo_mem_max+2 < hi_mem_min) if (lo_mem_max+2 <= mem_bot+max_halfword)
2659 @<Grow more variable-size memory and |goto restart|@>;
2660 overflow("main memory size", mem_max+1-mem_min);
2661 /*sorry, nothing satisfactory is left*/
2662 @:TeX capacity exceeded main memory size}{\quad main memory size@>
2663 found: link(r)=null; /*this node is now nonempty*/
2664 #ifdef @!STAT
2665 var_used=var_used+s; /*maintain usage statistics*/
2666 #endif
2667 @;@/
2668 return r;
2669 }
2670
2671 @ The lower part of |mem| grows by 1000 words at a time, unless
2672 we are very close to going under. When it grows, we simply link
2673 a new node into the available-space list. This method of controlled
2674 growth helps to keep the |mem| usage consecutive when \TeX\ is
2675 implemented on ``virtual memory'' systems.
2676 @^virtual memory@>
2677
2678 @<Grow more variable-size memory and |goto restart|@>=
2679 {@+if (hi_mem_min-lo_mem_max >= 1998) t=lo_mem_max+1000;
2680 else t=lo_mem_max+1+(hi_mem_min-lo_mem_max)/2;
2681 /*|lo_mem_max+2 <= t < hi_mem_min|*/
2682 p=llink(rover);q=lo_mem_max;rlink(p)=q;llink(rover)=q;@/
2683 if (t > mem_bot+max_halfword) t=mem_bot+max_halfword;
2684 rlink(q)=rover;llink(q)=p;link(q)=empty_flag;node_size(q)=t-lo_mem_max;@/
2685 lo_mem_max=t;link(lo_mem_max)=null;info(lo_mem_max)=null;
2686 rover=q;goto restart;
2687 }
2688
2689 @ Empirical tests show that the routine in this section performs a
2690 node-merging operation about 0.75 times per allocation, on the average,
2691 after which it finds that |r > p+1| about 95\pct! of the time.
2692
2693 @<Try to allocate...@>=
2694 q=p+node_size(p); /*find the physical successor*/
2695 @^inner loop@>
2696 while (is_empty(q)) /*merge node |p| with node |q|*/
2697 {@+t=rlink(q);
2698 if (q==rover) rover=t;
2699 llink(t)=llink(q);rlink(llink(q))=t;@/
2700 q=q+node_size(q);
2701 }
2702 r=q-s;
2703 if (r > p+1) @<Allocate from the top of node |p| and |goto found|@>;
2704 if (r==p) if (rlink(p)!=p)
2705 @<Allocate entire node |p| and |goto found|@>;
2706 node_size(p)=q-p /*reset the size in case it grew*/
2707
2708 @ @<Allocate from the top...@>=
2709 {@+node_size(p)=r-p; /*store the remaining size*/
2710 @^inner loop@>
2711 rover=p; /*start searching here next time*/
2712 goto found;
2713 }
2714
2715 @ Here we delete node |p| from the ring, and let |rover| rove around.
2716
2717 @<Allocate entire...@>=
2718 {@+rover=rlink(p);t=llink(p);
2719 llink(rover)=t;rlink(t)=rover;
2720 goto found;
2721 }
2722
2723 @ Conversely, when some variable-size node |p| of size |s| is no longer needed,
2724 the operation |free_node(p, s)| will make its words available, by inserting
2725 |p| as a new empty node just before where |rover| now points.
2726 @^inner loop@>
2727
2728 @p static void free_node(pointer @!p, halfword @!s) /*variable-size node
2729 liberation*/
2730 {@+pointer q; /*|llink(rover)|*/
2731 node_size(p)=s;link(p)=empty_flag;
2732 q=llink(rover);llink(p)=q;rlink(p)=rover; /*set both links*/
2733 llink(rover)=p;rlink(q)=p; /*insert |p| into the ring*/
2734 #ifdef @!STAT
2735 var_used=var_used-s;
2736 #endif
2737 @; /*maintain statistics*/
2738 }
2739
2740 @ Just before \.{INITEX} writes out the memory, it sorts the doubly linked
2741 available space list. The list is probably very short at such times, so a
2742 simple insertion sort is used. The smallest available location will be
2743 pointed to by |rover|, the next-smallest by |rlink(rover)|, etc.
2744
2745 @p
2746 #ifdef @!INIT
2747 static void sort_avail(void) /*sorts the available variable-size nodes
2748 by location*/
2749 {@+pointer p, @!q, @!r; /*indices into |mem|*/
2750 pointer @!old_rover; /*initial |rover| setting*/
2751 p=get_node(010000000000); /*merge adjacent free areas*/
2752 p=rlink(rover);rlink(rover)=max_halfword;old_rover=rover;
2753 while (p!=old_rover) @<Sort \(p)|p| into the list starting at |rover| and
2754 advance |p| to |rlink(p)|@>;
2755 p=rover;
2756 while (rlink(p)!=max_halfword)
2757 {@+llink(rlink(p))=p;p=rlink(p);
2758 }
2759 rlink(p)=rover;llink(rover)=p;
2760 }
2761 #endif
2762
2763 @ The following |while | loop is guaranteed to
2764 terminate, since the list that starts at
2765 |rover| ends with |max_halfword| during the sorting procedure.
2766
2767 @<Sort \(p)|p|...@>=
2768 if (p < rover)
2769 {@+q=p;p=rlink(q);rlink(q)=rover;rover=q;
2770 }
2771 else{@+q=rover;
2772 while (rlink(q) < p) q=rlink(q);
2773 r=rlink(p);rlink(p)=rlink(q);rlink(q)=p;p=r;
2774 }
2775
2776 @* Data structures for boxes and their friends.
2777 From the computer's standpoint, \TeX's chief mission is to create
2778 horizontal and vertical lists. We shall now investigate how the elements
2779 of these lists are represented internally as nodes in the dynamic memory.
2780
2781 A horizontal or vertical list is linked together by |link| fields in
2782 the first word of each node. Individual nodes represent boxes, glue,
2783 penalties, or special things like discretionary hyphens; because of this
2784 variety, some nodes are longer than others, and we must distinguish different
2785 kinds of nodes. We do this by putting a `|type|' field in the first word,
2786 together with the link and an optional `|subtype|'.
2787
2788 @d type(A) mem[A].hh.b0 /*identifies what kind of node this is*/
2789 @d subtype(A) mem[A].hh.b1 /*secondary identification in some cases*/
2790
2791 @ A |@!char_node|, which represents a single character, is the most important
2792 kind of node because it accounts for the vast majority of all boxes.
2793 Special precautions are therefore taken to ensure that a |char_node| does
2794 not take up much memory space. Every such node is one word long, and in fact
2795 it is identifiable by this property, since other kinds of nodes have at least
2796 two words, and they appear in |mem| locations less than |hi_mem_min|.
2797 This makes it possible to omit the |type| field in a |char_node|, leaving
2798 us room for two bytes that identify a |font| and a |character| within
2799 that font.
2800
2801 Note that the format of a |char_node| allows for up to 256 different
2802 fonts and up to 256 characters per font; but most implementations will
2803 probably limit the total number of fonts to fewer than 75 per job,
2804 and most fonts will stick to characters whose codes are
2805 less than 128 (since higher codes
2806 are more difficult to access on most keyboards).
2807
2808 Extensions of \TeX\ intended for oriental languages will need even more
2809 than $256\times256$ possible characters, when we consider different sizes
2810 @^oriental characters@>@^Chinese characters@>@^Japanese characters@>
2811 and styles of type. It is suggested that Chinese and Japanese fonts be
2812 handled by representing such characters in two consecutive |char_node|
2813 entries: The first of these has |font==font_base|, and its |link| points
2814 to the second;
2815 the second identifies the font and the character dimensions.
2816 The saving feature about oriental characters is that most of them have
2817 the same box dimensions. The |character| field of the first |char_node|
2818 is a ``\\{charext}'' that distinguishes between graphic symbols whose
2819 dimensions are identical for typesetting purposes. (See the \MF\ manual.)
2820 Such an extension of \TeX\ would not be difficult; further details are
2821 left to the reader.
2822
2823 In order to make sure that the |character| code fits in a quarterword,
2824 \TeX\ adds the quantity |min_quarterword| to the actual code.
2825
2826 Character nodes appear only in horizontal lists, never in vertical lists.
2827
2828 @d is_char_node(A) (A >= hi_mem_min)
2829 /*does the argument point to a |char_node|?*/
2830 @d font(A) mem[A].hh.b8 /*the font code in a |char_node|*/
2831 @d character(A) mem[A].hh.b24 /*the character code in a |char_node|*/
2832
2833 @ An |hlist_node| stands for a box that was made from a horizontal list.
2834 Each |hlist_node| is seven words long, and contains the following fields
2835 (in addition to the mandatory |type| and |link|, which we shall not
2836 mention explicitly when discussing the other node types): The |height| and
2837 |width| and |depth| are scaled integers denoting the dimensions of the
2838 box. There is also a |shift_amount| field, a scaled integer indicating
2839 how much this box should be lowered (if it appears in a horizontal list),
2840 or how much it should be moved to the right (if it appears in a vertical
2841 list). There is a |list_ptr| field, which points to the beginning of the
2842 list from which this box was fabricated; if |list_ptr| is |null|, the box
2843 is empty. Finally, there are three fields that represent the setting of
2844 the glue: |glue_set(p)| is a word of type |glue_ratio| that represents
2845 the proportionality constant for glue setting; |glue_sign(p)| is
2846 |stretching| or |shrinking| or |normal| depending on whether or not the
2847 glue should stretch or shrink or remain rigid; and |glue_order(p)|
2848 specifies the order of infinity to which glue setting applies (|normal|,
2849 |fil|, |fill|, or |filll|). The |subtype| field is not used.
2850
2851 @d hlist_node 0 /*|type| of hlist nodes*/
2852 @d box_node_size 9 /*number of words to allocate for a box, set, or pack node*/
2853 @d width_offset 1 /*position of |width| field in a box node*/
2854 @d depth_offset 2 /*position of |depth| field in a box node*/
2855 @d height_offset 3 /*position of |height| field in a box node*/
2856 @d width(A) mem[A+width_offset].sc /*width of the box, in sp*/
2857 @d depth(A) mem[A+depth_offset].sc /*depth of the box, in sp*/
2858 @d height(A) mem[A+height_offset].sc /*height of the box, in sp*/
2859 @d shift_amount(A) mem[A+4].sc /*repositioning distance, in sp*/
2860 @d list_offset 5 /*position of |list_ptr| field in a box node*/
2861 @d list_ptr(A) link(A+list_offset) /*beginning of the list inside the box*/
2862 @d glue_order(A) subtype(A+list_offset) /*applicable order of infinity*/
2863 @d glue_sign(A) type(A+list_offset) /*stretching or shrinking*/
2864 @d normal 0 /*the most common case when several cases are named*/
2865 @d stretching 1 /*glue setting applies to the stretch components*/
2866 @d shrinking 2 /*glue setting applies to the shrink components*/
2867 @d glue_offset 6 /*position of |glue_set| in a box node*/
2868 @d glue_set(A) mem[A+glue_offset].gr
2869 /*a word of type |glue_ratio| for glue setting*/
2870
2871 @ The |new_null_box| function returns a pointer to an |hlist_node| in
2872 which all subfields have the values corresponding to `\.{\\hbox\{\}}'.
2873 (The |subtype| field is set to |min_quarterword|, for historic reasons
2874 that are no longer relevant.)
2875
2876 @p static pointer new_null_box(void) /*creates a new box node*/
2877 {@+pointer p; /*the new node*/
2878 p=get_node(box_node_size);type(p)=hlist_node;
2879 subtype(p)=min_quarterword;
2880 width(p)=0;depth(p)=0;height(p)=0;shift_amount(p)=0;list_ptr(p)=null;
2881 glue_sign(p)=normal;glue_order(p)=normal;set_glue_ratio_zero(glue_set(p));
2882 return p;
2883 }
2884
2885 @ A |vlist_node| is like an |hlist_node| in all respects except that it
2886 contains a vertical list.
2887
2888 @d vlist_node 1 /*|type| of vlist nodes*/
2889
2890 @ A |rule_node| stands for a solid black rectangle; it has |width|,
2891 |depth|, and |height| fields just as in an |hlist_node|. However, if
2892 any of these dimensions is $-2^{30}$, the actual value will be determined
2893 by running the rule up to the boundary of the innermost enclosing box.
2894 This is called a ``running dimension.'' The |width| is never running in
2895 an hlist; the |height| and |depth| are never running in a~vlist.
2896
2897 @d rule_node 2 /*|type| of rule nodes*/
2898 @d rule_node_size 4 /*number of words to allocate for a rule node*/
2899 @d null_flag -010000000000 /*$-2^{30}$, signifies a missing item*/
2900 @d is_running(A) (A==null_flag) /*tests for a running dimension*/
2901
2902 @ A new rule node is delivered by the |new_rule| function. It
2903 makes all the dimensions ``running,'' so you have to change the
2904 ones that are not allowed to run.
2905
2906 @p static pointer new_rule(void)
2907 {@+pointer p; /*the new node*/
2908 p=get_node(rule_node_size);type(p)=rule_node;
2909 subtype(p)=0; /*the |subtype| is not used*/
2910 width(p)=null_flag;depth(p)=null_flag;height(p)=null_flag;
2911 return p;
2912 }
2913
2914 @ Insertions are represented by |ins_node| records, where the |subtype|
2915 indicates the corresponding box number. For example, `\.{\\insert 250}'
2916 leads to an |ins_node| whose |subtype| is |250+min_quarterword|.
2917 The |height| field of an |ins_node| is slightly misnamed; it actually holds
2918 the natural height plus depth of the vertical list being inserted.
2919 The |depth| field holds the |split_max_depth| to be used in case this
2920 insertion is split, and the |split_top_ptr| points to the corresponding
2921 |split_top_skip|. The |float_cost| field holds the |floating_penalty| that
2922 will be used if this insertion floats to a subsequent page after a
2923 split insertion of the same class. There is one more field, the
2924 |ins_ptr|, which points to the beginning of the vlist for the insertion.
2925
2926 @d ins_node 3 /*|type| of insertion nodes*/
2927 @d ins_node_size 5 /*number of words to allocate for an insertion*/
2928 @d float_cost(A) mem[A+1].i /*the |floating_penalty| to be used*/
2929 @d ins_ptr(A) info(A+4) /*the vertical list to be inserted*/
2930 @d split_top_ptr(A) link(A+4) /*the |split_top_skip| to be used*/
2931
2932 @ A |mark_node| has a |mark_ptr| field that points to the reference count
2933 of a token list that contains the user's \.{\\mark} text.
2934 In addition there is a |mark_class| field that contains the mark class.
2935
2936 @d mark_node 4 /*|type| of a mark node*/
2937 @d small_node_size 2 /*number of words to allocate for most node types*/
2938 @d mark_ptr(A) link(A+1) /*head of the token list for a mark*/
2939 @d mark_class(A) info(A+1) /*the mark class*/
2940
2941 @ An |adjust_node|, which occurs only in horizontal lists,
2942 specifies material that will be moved out into the surrounding
2943 vertical list; i.e., it is used to implement \TeX's `\.{\\vadjust}'
2944 operation. The |adjust_ptr| field points to the vlist containing this
2945 material.
2946
2947 @d adjust_node 5 /*|type| of an adjust node*/
2948 @d adjust_ptr(A) mem[A+1].i
2949 /*vertical list to be moved out of horizontal list*/
2950
2951 @ A |ligature_node|, which occurs only in horizontal lists, specifies
2952 a character that was fabricated from the interaction of two or more
2953 actual characters. The second word of the node, which is called the
2954 |lig_char| word, contains |font| and |character| fields just as in a
2955 |char_node|. The characters that generated the ligature have not been
2956 forgotten, since they are needed for diagnostic messages and for
2957 hyphenation; the |lig_ptr| field points to a linked list of character
2958 nodes for all original characters that have been deleted. (This list
2959 might be empty if the characters that generated the ligature were
2960 retained in other nodes.)
2961
2962 The |subtype| field is 0, plus 2 and/or 1 if the original source of the
2963 ligature included implicit left and/or right boundaries.
2964
2965 @d ligature_node 6 /*|type| of a ligature node*/
2966 @d lig_char(A) A+1 /*the word where the ligature is to be found*/
2967 @d lig_ptr(A) link(lig_char(A)) /*the list of characters*/
2968
2969 @ The |new_ligature| function creates a ligature node having given
2970 contents of the |font|, |character|, and |lig_ptr| fields. We also have
2971 a |new_lig_item| function, which returns a two-word node having a given
2972 |character| field. Such nodes are used for temporary processing as ligatures
2973 are being created.
2974
2975 @p static pointer new_ligature(quarterword @!f, quarterword @!c, pointer @!q)
2976 {@+pointer p; /*the new node*/
2977 p=get_node(small_node_size);type(p)=ligature_node;
2978 font(lig_char(p))=f;character(lig_char(p))=c;lig_ptr(p)=q;
2979 subtype(p)=0;return p;
2980 }
2981 @#
2982 static pointer new_lig_item(quarterword @!c)
2983 {@+pointer p; /*the new node*/
2984 p=get_node(small_node_size);character(p)=c;lig_ptr(p)=null;
2985 return p;
2986 }
2987
2988 @ A |disc_node|, which occurs only in horizontal lists, specifies a
2989 ``dis\-cretion\-ary'' line break. If such a break occurs at node |p|, the text
2990 that starts at |pre_break(p)| will precede the break, the text that starts at
2991 |post_break(p)| will follow the break, and text that appears in the next
2992 |replace_count(p)| nodes will be ignored. For example, an ordinary
2993 discretionary hyphen, indicated by `\.{\\-}', yields a |disc_node| with
2994 |pre_break| pointing to a |char_node| containing a hyphen, |post_break==null|,
2995 and |replace_count==0|. All three of the discretionary texts must be
2996 lists that consist entirely of character, kern, box, rule, and ligature nodes.
2997
2998 If |pre_break(p)==null|, the |ex_hyphen_penalty| will be charged for this
2999 break. Otherwise the |hyphen_penalty| will be charged. The texts will
3000 actually be substituted into the list by the line-breaking algorithm if it
3001 decides to make the break, and the discretionary node will disappear at
3002 that time; thus, the output routine sees only discretionaries that were
3003 not chosen.
3004
3005 @d disc_node 7 /*|type| of a discretionary node*/
3006 @d replace_count(A) (subtype(A)&0x7F) /*how many subsequent nodes to replace*/
3007 @d set_replace_count(A,B) (subtype(A)=(B)&0x7F)
3008 @d set_auto_disc(A) (subtype(A)|=0x80)
3009 @d is_auto_disc(A) (subtype(A)&0x80)
3010 @d pre_break(A) llink(A) /*text that precedes a discretionary break*/
3011 @d post_break(A) rlink(A) /*text that follows a discretionary break*/
3012
3013 @p static pointer new_disc(void) /*creates an empty |disc_node|*/
3014 {@+pointer p; /*the new node*/
3015 p=get_node(small_node_size);type(p)=disc_node;
3016 set_replace_count(p,0);pre_break(p)=null;post_break(p)=null;
3017 return p;
3018 }
3019
3020 @ A |whatsit_node| is a wild card reserved for extensions to \TeX. The
3021 |subtype| field in its first word says what `\\{whatsit}' it is, and
3022 implicitly determines the node size (which must be 2 or more) and the
3023 format of the remaining words. When a |whatsit_node| is encountered
3024 in a list, special actions are invoked; knowledgeable people who are
3025 careful not to mess up the rest of \TeX\ are able to make \TeX\ do new
3026 things by adding code at the end of the program. For example, there
3027 might be a `\TeX nicolor' extension to specify different colors of ink,
3028 @^extensions to \TeX@>
3029 and the whatsit node might contain the desired parameters.
3030
3031 The present implementation of \TeX\ treats the features associated with
3032 `\.{\\write}' and `\.{\\special}' as if they were extensions, in order to
3033 illustrate how such routines might be coded. We shall defer further
3034 discussion of extensions until the end of this program.
3035
3036 @d whatsit_node 8 /*|type| of special extension nodes*/
3037
3038 @ A |math_node|, which occurs only in horizontal lists, appears before and
3039 after mathematical formulas. The |subtype| field is |before| before the
3040 formula and |after| after it. There is a |width| field, which represents
3041 the amount of surrounding space inserted by \.{\\mathsurround}.
3042
3043 @d math_node 9 /*|type| of a math node*/
3044 @d before 0 /*|subtype| for math node that introduces a formula*/
3045 @d after 1 /*|subtype| for math node that winds up a formula*/
3046
3047 @p static pointer new_math(scaled @!w, small_number @!s)
3048 {@+pointer p; /*the new node*/
3049 p=get_node(small_node_size);type(p)=math_node;
3050 subtype(p)=s;width(p)=w;return p;
3051 }
3052
3053 @ \TeX\ makes use of the fact that |hlist_node|, |vlist_node|,
3054 |rule_node|, |ins_node|, |mark_node|, |adjust_node|, |ligature_node|,
3055 |disc_node|, |whatsit_node|, and |math_node| are at the low end of the
3056 type codes, by permitting a break at glue in a list if and only if the
3057 |type| of the previous node is less than |math_node|. Furthermore, a
3058 node is discarded after a break if its type is |math_node| or~more.
3059
3060 @d precedes_break(A) (type(A) < math_node)
3061 @d non_discardable(A) (type(A) < math_node)
3062
3063 @ A |glue_node| represents glue in a list. However, it is really only
3064 a pointer to a separate glue specification, since \TeX\ makes use of the
3065 fact that many essentially identical nodes of glue are usually present.
3066 If |p| points to a |glue_node|, |glue_ptr(p)| points to
3067 another packet of words that specify the stretch and shrink components, etc.
3068
3069 Glue nodes also serve to represent leaders; the |subtype| is used to
3070 distinguish between ordinary glue (which is called |normal|) and the three
3071 kinds of leaders (which are called |a_leaders|, |c_leaders|, and |x_leaders|).
3072 The |leader_ptr| field points to a rule node or to a box node containing the
3073 leaders; it is set to |null| in ordinary glue nodes.
3074
3075 Many kinds of glue are computed from \TeX's ``skip'' parameters, and
3076 it is helpful to know which parameter has led to a particular glue node.
3077 Therefore the |subtype| is set to indicate the source of glue, whenever
3078 it originated as a parameter. We will be defining symbolic names for the
3079 parameter numbers later (e.g., |line_skip_code==0|, |baseline_skip_code==1|,
3080 etc.); it suffices for now to say that the |subtype| of parametric glue
3081 will be the same as the parameter number, plus~one.
3082
3083 In math formulas there are two more possibilities for the |subtype| in a
3084 glue node: |mu_glue| denotes an \.{\\mskip} (where the units are scaled \.{mu}
3085 instead of scaled \.{pt}); and |cond_math_glue| denotes the `\.{\\nonscript}'
3086 feature that cancels the glue node immediately following if it appears
3087 in a subscript.
3088
3089 @d glue_node 10 /*|type| of node that points to a glue specification*/
3090 @d cond_math_glue 98 /*special |subtype| to suppress glue in the next node*/
3091 @d mu_glue 99 /*|subtype| for math glue*/
3092 @d a_leaders 100 /*|subtype| for aligned leaders*/
3093 @d c_leaders 101 /*|subtype| for centered leaders*/
3094 @d x_leaders 102 /*|subtype| for expanded leaders*/
3095 @d glue_ptr(A) llink(A) /*pointer to a glue specification*/
3096 @d leader_ptr(A) rlink(A) /*pointer to box or rule node for leaders*/
3097
3098 @ A glue specification has a halfword reference count in its first word,
3099 @^reference counts@>
3100 representing |null| plus the number of glue nodes that point to it (less one).
3101 Note that the reference count appears in the same position as
3102 the |link| field in list nodes; this is the field that is initialized
3103 to |null| when a node is allocated, and it is also the field that is flagged
3104 by |empty_flag| in empty nodes.
3105
3106 Glue specifications also contain three |scaled| fields, for the |width|,
3107 |stretch|, and |shrink| dimensions. Finally, there are two one-byte
3108 fields called |stretch_order| and |shrink_order|; these contain the
3109 orders of infinity (|normal|, |fil|, |fill|, or |filll|)
3110 corresponding to the stretch and shrink values.
3111
3112 @d glue_spec_size 4 /*number of words to allocate for a glue specification*/
3113 @d glue_ref_count(A) link(A) /*reference count of a glue specification*/
3114 @d stretch(A) mem[A+2].sc /*the stretchability of this glob of glue*/
3115 @d shrink(A) mem[A+3].sc /*the shrinkability of this glob of glue*/
3116 @d stretch_order(A) type(A) /*order of infinity for stretching*/
3117 @d shrink_order(A) subtype(A) /*order of infinity for shrinking*/
3118 @d fil 1 /*first-order infinity*/
3119 @d fill 2 /*second-order infinity*/
3120 @d filll 3 /*third-order infinity*/
3121
3122 @<Types...@>=
3123 typedef int8_t glue_ord; /*infinity to the 0, 1, 2, or 3 power*/
3124
3125 @ Here is a function that returns a pointer to a copy of a glue spec.
3126 The reference count in the copy is |null|, because there is assumed
3127 to be exactly one reference to the new specification.
3128
3129 @p static pointer new_spec(pointer @!p) /*duplicates a glue specification*/
3130 {@+pointer q; /*the new spec*/
3131 q=get_node(glue_spec_size);@/
3132 mem[q]=mem[p];glue_ref_count(q)=null;@/
3133 width(q)=width(p);stretch(q)=stretch(p);shrink(q)=shrink(p);
3134 return q;
3135 }
3136
3137 @ And here's a function that creates a glue node for a given parameter
3138 identified by its code number; for example,
3139 |new_param_glue(line_skip_code)| returns a pointer to a glue node for the
3140 current \.{\\lineskip}.
3141
3142 @p static pointer new_param_glue(small_number @!n)
3143 {@+pointer p; /*the new node*/
3144 pointer @!q; /*the glue specification*/
3145 p=get_node(small_node_size);type(p)=glue_node;subtype(p)=n+1;
3146 leader_ptr(p)=null;@/
3147 q=@<Current |mem| equivalent of glue parameter number |n|@>@t@>;
3148 glue_ptr(p)=q;incr(glue_ref_count(q));
3149 return p;
3150 }
3151
3152 @ Glue nodes that are more or less anonymous are created by |new_glue|,
3153 whose argument points to a glue specification.
3154
3155 @p static pointer new_glue(pointer @!q)
3156 {@+pointer p; /*the new node*/
3157 p=get_node(small_node_size);type(p)=glue_node;subtype(p)=normal;
3158 leader_ptr(p)=null;glue_ptr(p)=q;incr(glue_ref_count(q));
3159 return p;
3160 }
3161
3162 @ Still another subroutine is needed: This one is sort of a combination
3163 of |new_param_glue| and |new_glue|. It creates a glue node for one of
3164 the current glue parameters, but it makes a fresh copy of the glue
3165 specification, since that specification will probably be subject to change,
3166 while the parameter will stay put. The global variable |temp_ptr| is
3167 set to the address of the new spec.
3168
3169 @p static pointer new_skip_param(small_number @!n)
3170 {@+pointer p; /*the new node*/
3171 temp_ptr=new_spec(@<Current |mem| equivalent of glue parameter...@>);
3172 p=new_glue(temp_ptr);glue_ref_count(temp_ptr)=null;subtype(p)=n+1;
3173 return p;
3174 }
3175
3176 @ A |kern_node| has a |width| field to specify a (normally negative)
3177 amount of spacing. This spacing correction appears in horizontal lists
3178 between letters like A and V when the font designer said that it looks
3179 better to move them closer together or further apart. A kern node can
3180 also appear in a vertical list, when its `|width|' denotes additional
3181 spacing in the vertical direction. The |subtype| is either |normal| (for
3182 kerns inserted from font information or math mode calculations) or |explicit|
3183 (for kerns inserted from \.{\\kern} and \.{\\/} commands) or |acc_kern|
3184 (for kerns inserted from non-math accents) or |mu_glue| (for kerns
3185 inserted from \.{\\mkern} specifications in math formulas).
3186
3187 @d kern_node 11 /*|type| of a kern node*/
3188 @d explicit 1 /*|subtype| of kern nodes from \.{\\kern} and \.{\\/}*/
3189 @d acc_kern 2 /*|subtype| of kern nodes from accents*/
3190
3191 @ The |new_kern| function creates a kern node having a given width.
3192
3193 @p static pointer new_kern(scaled @!w)
3194 {@+pointer p; /*the new node*/
3195 p=get_node(small_node_size);type(p)=kern_node;
3196 subtype(p)=normal;
3197 width(p)=w;
3198 return p;
3199 }
3200
3201 @ A |penalty_node| specifies the penalty associated with line or page
3202 breaking, in its |penalty| field. This field is a fullword integer, but
3203 the full range of integer values is not used: Any penalty | >= 10000| is
3204 treated as infinity, and no break will be allowed for such high values.
3205 Similarly, any penalty | <= -10000| is treated as negative infinity, and a
3206 break will be forced.
3207
3208 @d penalty_node 12 /*|type| of a penalty node*/
3209 @d inf_penalty inf_bad /*``infinite'' penalty value*/
3210 @d eject_penalty (-inf_penalty) /*``negatively infinite'' penalty value*/
3211 @d penalty(A) mem[A+1].i /*the added cost of breaking a list here*/
3212
3213 @ Anyone who has been reading the last few sections of the program will
3214 be able to guess what comes next.
3215
3216 @p static pointer new_penalty(int @!m)
3217 {@+pointer p; /*the new node*/
3218 p=get_node(small_node_size);type(p)=penalty_node;
3219 subtype(p)=0; /*the |subtype| is not used*/
3220 penalty(p)=m;return p;
3221 }
3222
3223 @ You might think that we have introduced enough node types by now. Well,
3224 almost, but there is one more: An |unset_node| has nearly the same format
3225 as an |hlist_node| or |vlist_node|; it is used for entries in \.{\\halign}
3226 or \.{\\valign} that are not yet in their final form, since the box
3227 dimensions are their ``natural'' sizes before any glue adjustment has been
3228 made. The |glue_set| word is not present; instead, we have a |glue_stretch|
3229 field, which contains the total stretch of order |glue_order| that is
3230 present in the hlist or vlist being boxed.
3231 Similarly, the |shift_amount| field is replaced by a |glue_shrink| field,
3232 containing the total shrink of order |glue_sign| that is present.
3233 The |subtype| field is called |span_count|; an unset box typically
3234 contains the data for |qo(span_count)+1| columns.
3235 Unset nodes will be changed to box nodes when alignment is completed.
3236
3237 @d unset_node 13 /*|type| for an unset node*/
3238 @d unset_set_node 32 /*|type| for an unset |set_node|*/
3239 @d unset_pack_node 33 /*|type| for an unset |pack_node|*/
3240 @d glue_stretch(A) mem[A+glue_offset].sc /*total stretch in an unset node*/
3241 @d glue_shrink(A) shift_amount(A) /*total shrink in an unset node*/
3242 @d span_count(A) subtype(A) /*indicates the number of spanned columns*/
3243
3244 @ In fact, there are still more types coming. When we get to math formula
3245 processing we will see that a |style_node| has |type==14|; and a number
3246 of larger type codes will also be defined, for use in math mode only.
3247
3248 @ Warning: If any changes are made to these data structure layouts, such as
3249 changing any of the node sizes or even reordering the words of nodes,
3250 the |copy_node_list| procedure and the memory initialization code
3251 below may have to be changed. Such potentially dangerous parts of the
3252 program are listed in the index under `data structure assumptions'.
3253 @!@^data structure assumptions@>
3254 However, other references to the nodes are made symbolically in terms of
3255 the \.{WEB} macro definitions above, so that format changes will leave
3256 \TeX's other algorithms intact.
3257 @^system dependencies@>
3258
3259 @* Memory layout.
3260 Some areas of |mem| are dedicated to fixed usage, since static allocation is
3261 more efficient than dynamic allocation when we can get away with it. For
3262 example, locations |mem_bot| to |mem_bot+3| are always used to store the
3263 specification for glue that is `\.{0pt plus 0pt minus 0pt}'. The
3264 following macro definitions accomplish the static allocation by giving
3265 symbolic names to the fixed positions. Static variable-size nodes appear
3266 in locations |mem_bot| through |lo_mem_stat_max|, and static single-word nodes
3267 appear in locations |hi_mem_stat_min| through |mem_top|, inclusive. It is
3268 harmless to let |lig_trick| and |garbage| share the same location of |mem|.
3269
3270 @d zero_glue mem_bot /*specification for \.{0pt plus 0pt minus 0pt}*/
3271 @d fil_glue zero_glue+glue_spec_size /*\.{0pt plus 1fil minus 0pt}*/
3272 @d fill_glue fil_glue+glue_spec_size /*\.{0pt plus 1fill minus 0pt}*/
3273 @d ss_glue fill_glue+glue_spec_size /*\.{0pt plus 1fil minus 1fil}*/
3274 @d fil_neg_glue ss_glue+glue_spec_size /*\.{0pt plus -1fil minus 0pt}*/
3275 @d lo_mem_stat_max fil_neg_glue+glue_spec_size-1 /*largest statically
3276 allocated word in the variable-size |mem|*/
3277 @#
3278 @d page_ins_head mem_top /*list of insertion data for current page*/
3279 @d contrib_head mem_top-1 /*vlist of items not yet on current page*/
3280 @d page_head mem_top-2 /*vlist for current page*/
3281 @d temp_head mem_top-3 /*head of a temporary list of some kind*/
3282 @d hold_head mem_top-4 /*head of a temporary list of another kind*/
3283 @d adjust_head mem_top-5 /*head of adjustment list returned by |hpack|*/
3284 @d active mem_top-7 /*head of active list in |line_break|, needs two words*/
3285 @d align_head mem_top-8 /*head of preamble list for alignments*/
3286 @d end_span mem_top-9 /*tail of spanned-width lists*/
3287 @d omit_template mem_top-10 /*a constant token list*/
3288 @d null_list mem_top-11 /*permanently empty list*/
3289 @d lig_trick mem_top-12 /*a ligature masquerading as a |char_node|*/
3290 @d garbage mem_top-12 /*used for scrap information*/
3291 @d backup_head mem_top-13 /*head of token list built by |scan_keyword|*/
3292 @d setpage_head mem_top-14 /*head of page template list build by |new_setpage_node|*/
3293 @d max_page type(setpage_head) /* maximum page template number */
3294 @d max_stream subtype(setpage_head) /* maximum stream number */
3295 @d hi_mem_stat_min mem_top-14 /*smallest statically allocated word in
3296 the one-word |mem|*/
3297 @d hi_mem_stat_usage 15 /*the number of one-word nodes always present*/
3298
3299 @ The following code gets |mem| off to a good start, when \TeX\ is
3300 initializing itself the slow~way.
3301
3302 @<Local variables for init...@>=
3303 int i;
3304 int @!k; /*index into |mem|, |eqtb|, etc.*/
3305
3306 @ @<Initialize table entries...@>=
3307 for (k=mem_bot+1; k<=lo_mem_stat_max; k++) mem[k].sc=0;
3308 /*all glue dimensions are zeroed*/
3309 @^data structure assumptions@>
3310 k=mem_bot;@+while (k <= lo_mem_stat_max)
3311 /*set first words of glue specifications*/
3312 {@+glue_ref_count(k)=null+1;
3313 stretch_order(k)=normal;shrink_order(k)=normal;
3314 k=k+glue_spec_size;
3315 }
3316 stretch(fil_glue)=unity;stretch_order(fil_glue)=fil;@/
3317 stretch(fill_glue)=unity;stretch_order(fill_glue)=fill;@/
3318 stretch(ss_glue)=unity;stretch_order(ss_glue)=fil;@/
3319 shrink(ss_glue)=unity;shrink_order(ss_glue)=fil;@/
3320 stretch(fil_neg_glue)=-unity;stretch_order(fil_neg_glue)=fil;@/
3321 rover=lo_mem_stat_max+1;
3322 link(rover)=empty_flag; /*now initialize the dynamic memory*/
3323 node_size(rover)=1000; /*which is a 1000-word available node*/
3324 llink(rover)=rover;rlink(rover)=rover;@/
3325 lo_mem_max=rover+1000;link(lo_mem_max)=null;info(lo_mem_max)=null;@/
3326 for (k=hi_mem_stat_min; k<=mem_top; k++)
3327 mem[k]=mem[lo_mem_max]; /*clear list heads*/
3328 @<Initialize the special list heads and constant nodes@>;
3329 avail=null;mem_end=mem_top;
3330 hi_mem_min=hi_mem_stat_min; /*initialize the one-word memory*/
3331 var_used=lo_mem_stat_max+1-mem_bot;dyn_used=hi_mem_stat_usage;
3332 /*initialize statistics*/
3333
3334 @ If \TeX\ is extended improperly, the |mem| array might get screwed up.
3335 For example, some pointers might be wrong, or some ``dead'' nodes might not
3336 have been freed when the last reference to them disappeared. Procedures
3337 |check_mem| and |search_mem| are available to help diagnose such
3338 problems. These procedures make use of two arrays called |is_free| and
3339 |was_free| that are present only if \TeX's debugging routines have
3340 been included. (You may want to decrease the size of |mem| while you
3341 @^debugging@>
3342 are debugging.)
3343
3344 @<Glob...@>=
3345 #ifdef @!DEBUG
3346 static bool @!is_free0[mem_max-mem_min+1],
3347 *const @!is_free = @!is_free0-mem_min; /*free cells*/
3348 @t\hskip10pt@>static bool @!was_free0[mem_max-mem_min+1],
3349 *const @!was_free = @!was_free0-mem_min;
3350 /*previously free cells*/
3351 @t\hskip10pt@>static pointer @!was_mem_end, @!was_lo_max, @!was_hi_min;
3352 /*previous |mem_end|, |lo_mem_max|, and |hi_mem_min|*/
3353 @t\hskip10pt@>static bool @!panicking; /*do we want to check memory constantly?*/
3354 #endif
3355
3356 @ @<Set initial...@>=
3357 #ifdef @!DEBUG
3358 was_mem_end=mem_min; /*indicate that everything was previously free*/
3359 was_lo_max=mem_min;was_hi_min=mem_max;
3360 panicking=false;
3361 #endif
3362
3363 @ Procedure |check_mem| makes sure that the available space lists of
3364 |mem| are well formed, and it optionally prints out all locations
3365 that are reserved now but were free the last time this procedure was called.
3366
3367 @p
3368 #ifdef @!DEBUG
3369 static void check_mem(bool @!print_locs)
3370 {@+ /*loop exits*/
3371 int p, @!q; /*current locations of interest in |mem|*/
3372 bool @!clobbered; /*is something amiss?*/
3373 for (p=mem_min; p<=lo_mem_max; p++) is_free[p]=false; /*you can probably
3374 do this faster*/
3375 for (p=hi_mem_min; p<=mem_end; p++) is_free[p]=false; /*ditto*/
3376 @<Check single-word |avail| list@>;
3377 @<Check variable-size |avail| list@>;
3378 @<Check flags of unavailable nodes@>;
3379 if (print_locs) @<Print newly busy locations@>;
3380 for (p=mem_min; p<=lo_mem_max; p++) was_free[p]=is_free[p];
3381 for (p=hi_mem_min; p<=mem_end; p++) was_free[p]=is_free[p];
3382 /*|was_free=is_free| might be faster*/
3383 was_mem_end=mem_end;was_lo_max=lo_mem_max;was_hi_min=hi_mem_min;
3384 }
3385 #endif
3386
3387 @ @<Check single-word...@>=
3388 p=avail;q=null;clobbered=false;
3389 while (p!=null)
3390 {@+if ((p > mem_end)||(p < hi_mem_min)) clobbered=true;
3391 else if (is_free[p]) clobbered=true;
3392 if (clobbered)
3393 {@+print_nl("AVAIL list clobbered at ");
3394 @.AVAIL list clobbered...@>
3395 print_int(q);goto done1;
3396 }
3397 is_free[p]=true;q=p;p=link(q);
3398 }
3399 done1:
3400
3401 @ @<Check variable-size...@>=
3402 p=rover;q=null;clobbered=false;
3403 @/do@+{if ((p >= lo_mem_max)||(p < mem_min)) clobbered=true;
3404 else if ((rlink(p) >= lo_mem_max)||(rlink(p) < mem_min)) clobbered=true;
3405 else if (!(is_empty(p))||(node_size(p) < 2)||@|
3406 (p+node_size(p) > lo_mem_max)||@|(llink(rlink(p))!=p)) clobbered=true;
3407 if (clobbered)
3408 {@+print_nl("Double-AVAIL list clobbered at ");
3409 print_int(q);goto done2;
3410 }
3411 for (q=p; q<=p+node_size(p)-1; q++) /*mark all locations free*/
3412 {@+if (is_free[q])
3413 {@+print_nl("Doubly free location at ");
3414 @.Doubly free location...@>
3415 print_int(q);goto done2;
3416 }
3417 is_free[q]=true;
3418 }
3419 q=p;p=rlink(p);
3420 }@+ while (!(p==rover));
3421 done2:
3422
3423 @ @<Check flags...@>=
3424 p=mem_min;
3425 while (p <= lo_mem_max) /*node |p| should not be empty*/
3426 {@+if (is_empty(p))
3427 {@+print_nl("Bad flag at ");print_int(p);
3428 @.Bad flag...@>
3429 }
3430 while ((p <= lo_mem_max)&&!is_free[p]) incr(p);
3431 while ((p <= lo_mem_max)&&is_free[p]) incr(p);
3432 }
3433
3434 @ @<Print newly busy...@>=
3435 {@+print_nl("New busy locs:");
3436 for (p=mem_min; p<=lo_mem_max; p++)
3437 if (!is_free[p]&&((p > was_lo_max)||was_free[p]))
3438 {@+print_char(' ');print_int(p);
3439 }
3440 for (p=hi_mem_min; p<=mem_end; p++)
3441 if (!is_free[p]&&
3442 ((p < was_hi_min)||(p > was_mem_end)||was_free[p]))
3443 {@+print_char(' ');print_int(p);
3444 }
3445 }
3446
3447 @ The |search_mem| procedure attempts to answer the question ``Who points
3448 to node~|p|?'' In doing so, it fetches |link| and |info| fields of |mem|
3449 that might not be of type |two_halves|. Strictly speaking, this is
3450 @^dirty \PASCAL@>
3451 undefined in \PASCAL, and it can lead to ``false drops'' (words that seem to
3452 point to |p| purely by coincidence). But for debugging purposes, we want
3453 to rule out the places that do {\sl not\/} point to |p|, so a few false
3454 drops are tolerable.
3455
3456 @p
3457 #ifdef @!DEBUG
3458 static void search_mem(pointer @!p) /*look for pointers to |p|*/
3459 {@+int q; /*current position being searched*/
3460 for (q=mem_min; q<=lo_mem_max; q++)
3461 {@+if (link(q)==p)
3462 {@+print_nl("LINK(");print_int(q);print_char(')');
3463 }
3464 if (info(q)==p)
3465 {@+print_nl("INFO(");print_int(q);print_char(')');
3466 }
3467 }
3468 for (q=hi_mem_min; q<=mem_end; q++)
3469 {@+if (link(q)==p)
3470 {@+print_nl("LINK(");print_int(q);print_char(')');
3471 }
3472 if (info(q)==p)
3473 {@+print_nl("INFO(");print_int(q);print_char(')');
3474 }
3475 }
3476 @<Search |eqtb| for equivalents equal to |p|@>;
3477 @<Search |save_stack| for equivalents that point to |p|@>;
3478 @<Search |hyph_list| for pointers to |p|@>;
3479 }
3480 #endif
3481
3482 @* Displaying boxes.
3483 We can reinforce our knowledge of the data structures just introduced
3484 by considering two procedures that display a list in symbolic form.
3485 The first of these, called |short_display|, is used in ``overfull box''
3486 messages to give the top-level description of a list. The other one,
3487 called |show_node_list|, prints a detailed description of exactly what
3488 is in the data structure.
3489
3490 The philosophy of |short_display| is to ignore the fine points about exactly
3491 what is inside boxes, except that ligatures and discretionary breaks are
3492 expanded. As a result, |short_display| is a recursive procedure, but the
3493 recursion is never more than one level deep.
3494 @^recursion@>
3495
3496 A global variable |font_in_short_display| keeps track of the font code that
3497 is assumed to be present when |short_display| begins; deviations from this
3498 font will be printed.
3499
3500 @<Glob...@>=
3501 static int @!font_in_short_display; /*an internal font number*/
3502
3503 @ Boxes, rules, inserts, whatsits, marks, and things in general that are
3504 sort of ``complicated'' are indicated only by printing `\.{[]}'.
3505
3506 @p static void short_display(int @!p) /*prints highlights of list |p|*/
3507 {@+int n; /*for replacement counts*/
3508 while (p > mem_min)
3509 {@+if (is_char_node(p))
3510 {@+if (p <= mem_end)
3511 {@+if (font(p)!=font_in_short_display)
3512 {@+if ((font(p) < font_base)||(font(p) > font_max))
3513 print_char('*');
3514 @.*\relax@>
3515 else@<Print the font identifier for |font(p)|@>;
3516 print_char(' ');font_in_short_display=font(p);
3517 }
3518 if (character(p)<0x80)
3519 print_ASCII(character(p));
3520 else
3521 print_utf8(character(p));
3522 }
3523 }
3524 else@<Print a short indication of the contents of node |p|@>;
3525 p=link(p);
3526 }
3527 }
3528
3529 @ @<Print a short indication of the contents of node |p|@>=
3530 switch (type(p)) {
3531 case hlist_node: case vlist_node: case ins_node:
3532 case whatsit_node: case mark_node: case adjust_node:
3533 case unset_node: case unset_set_node: case unset_pack_node: print("[]");@+break;
3534 case rule_node: print_char('|');@+break;
3535 case glue_node: if (glue_ptr(p)!=zero_glue) print_char(' ');@+break;
3536 case math_node: print_char('$');@+break;
3537 case ligature_node: short_display(lig_ptr(p));@+break;
3538 case disc_node: {@+short_display(pre_break(p));
3539 short_display(post_break(p));@/
3540 n=replace_count(p);
3541 while (n > 0)
3542 {@+if (link(p)!=null) p=link(p);
3543 decr(n);
3544 }
3545 } @+break;
3546 default:do_nothing;
3547 }
3548
3549 @ The |show_node_list| routine requires some auxiliary subroutines: one to
3550 print a font-and-character combination, one to print a token list without
3551 its reference count, and one to print a rule dimension.
3552
3553 @p static void print_font_and_char(int @!p) /*prints |char_node| data*/
3554 {@+if (p > mem_end) print_esc("CLOBBERED.");
3555 else{@+if ((font(p) < font_base)||(font(p) > font_max)) print_char('*');
3556 @.*\relax@>
3557 else@<Print the font identifier for |font(p)|@>;
3558 print_char(' ');print_ASCII(qo(character(p)));
3559 }
3560 }
3561 @#
3562 static void print_mark(int @!p) /*prints token list data in braces*/
3563 {@+print_char('{');
3564 if ((p < hi_mem_min)||(p > mem_end)) print_esc("CLOBBERED.");
3565 else show_token_list(link(p), null, max_print_line-10);
3566 print_char('}');
3567 }
3568 @#
3569 static void print_rule_dimen(scaled @!d) /*prints dimension in rule node*/
3570 {@+if (is_running(d)) print_char('*');else print_scaled(d);
3571 @.*\relax@>
3572 }
3573
3574 @ Then there is a subroutine that prints glue stretch and shrink, possibly
3575 followed by the name of finite units:
3576
3577 @p static void print_glue(scaled @!d, int @!order, char *@!s)
3578 /*prints a glue component*/
3579 {@+print_scaled(d);
3580 if ((order < normal)||(order > filll)) print("foul");
3581 else if (order > normal)
3582 {@+print("fil");
3583 while (order > fil)
3584 {@+print_char('l');decr(order);
3585 }
3586 }
3587 else if (s!=0) print(s);
3588 }
3589
3590 @ The next subroutine prints a whole glue specification.
3591
3592 @p static void print_spec(int @!p, char *@!s)
3593 /*prints a glue specification*/
3594 {@+if ((p < mem_min)||(p >= lo_mem_max)) print_char('*');
3595 @.*\relax@>
3596 else{@+print_scaled(width(p));
3597 if (s!=0) print(s);
3598 if (stretch(p)!=0)
3599 {@+print(" plus ");print_glue(stretch(p), stretch_order(p), s);
3600 }
3601 if (shrink(p)!=0)
3602 {@+print(" minus ");print_glue(shrink(p), shrink_order(p), s);
3603 }
3604 }
3605 }
3606
3607 @ We also need to declare some procedures that appear later in this
3608 documentation.
3609
3610 @p @<Declare procedures needed for displaying the elements of mlists@>@;
3611 @<Declare the procedure called |print_skip_param|@>@;
3612 static void print_xdimen(pointer p)
3613 { if (p==null) { print_scaled(0); return; }
3614 print_scaled(xdimen_width(p));
3615 if (xdimen_hfactor(p)!=0)
3616 { print_char('+');print_scaled(xdimen_hfactor(p));print("*hsize");}
3617 if (xdimen_vfactor(p)!=0)
3618 { print_char('+');print_scaled(xdimen_vfactor(p));print("*vsize");}
3619 }
3620
3621 @ Since boxes can be inside of boxes, |show_node_list| is inherently recursive,
3622 @^recursion@>
3623 up to a given maximum number of levels. The history of nesting is indicated
3624 by the current string, which will be printed at the beginning of each line;
3625 the length of this string, namely |cur_length|, is the depth of nesting.
3626
3627 Recursive calls on |show_node_list| therefore use the following pattern:
3628
3629 @d node_list_display(A)
3630 {@+append_char('.');show_node_list(A);flush_char;
3631 } /*|str_room| need not be checked; see |show_box| below*/
3632
3633 @ A global variable called |depth_threshold| is used to record the maximum
3634 depth of nesting for which |show_node_list| will show information. If we
3635 have |depth_threshold==0|, for example, only the top level information will
3636 be given and no sublists will be traversed. Another global variable, called
3637 |breadth_max|, tells the maximum number of items to show at each level;
3638 |breadth_max| had better be positive, or you won't see anything.
3639
3640 @<Glob...@>=
3641 static int @!depth_threshold; /*maximum nesting depth in box displays*/
3642 static int @!breadth_max; /*maximum number of items shown at the same list level*/
3643
3644 @ Now we are ready for |show_node_list| itself. This procedure has been
3645 written to be ``extra robust'' in the sense that it should not crash or get
3646 into a loop even if the data structures have been messed up by bugs in
3647 the rest of the program. You can safely call its parent routine
3648 |show_box(p)| for arbitrary values of |p| when you are debugging \TeX.
3649 However, in the presence of bad data, the procedure may
3650 @^dirty \PASCAL@>@^debugging@>
3651 fetch a |memory_word| whose variant is different from the way it was stored;
3652 for example, it might try to read |mem[p].hh| when |mem[p]|
3653 contains a scaled integer, if |p| is a pointer that has been
3654 clobbered or chosen at random.
3655
3656 @p static void show_node_list(int @!p) /*prints a node list symbolically*/
3657 {@+
3658 int n; /*the number of items already printed at this level*/
3659 double @!g; /*a glue ratio, as a floating point number*/
3660 if (cur_length > depth_threshold)
3661 {@+if (p > null) print(" []");
3662 /*indicate that there's been some truncation*/
3663 return;
3664 }
3665 n=0;
3666 while (p > mem_min)
3667 {@+print_ln();print_current_string(); /*display the nesting history*/
3668 if (p > mem_end) /*pointer out of range*/
3669 {@+print("Bad link, display aborted.");return;
3670 @.Bad link...@>
3671 }
3672 incr(n);if (n > breadth_max) /*time to stop*/
3673 {@+print("etc.");return;
3674 @.etc@>
3675 }
3676 @<Display node |p|@>;
3677 p=link(p);
3678 }
3679
3680 }
3681
3682 @ @<Display node |p|@>=
3683 if (is_char_node(p)) print_font_and_char(p);
3684 else switch (type(p)) {
3685 case hlist_node: case vlist_node: case unset_node: case unset_set_node: case unset_pack_node: @<Display box |p|@>@;@+break;
3686 case rule_node: @<Display rule |p|@>@;@+break;
3687 case ins_node: @<Display insertion |p|@>@;@+break;
3688 case whatsit_node: @<Display the whatsit node |p|@>@;@+break;
3689 case glue_node: @<Display glue |p|@>@;@+break;
3690 case kern_node: @<Display kern |p|@>@;@+break;
3691 case math_node: @<Display math node |p|@>@;@+break;
3692 case ligature_node: @<Display ligature |p|@>@;@+break;
3693 case penalty_node: @<Display penalty |p|@>@;@+break;
3694 case disc_node: @<Display discretionary |p|@>@;@+break;
3695 case mark_node: @<Display mark |p|@>@;@+break;
3696 case adjust_node: @<Display adjustment |p|@>@;@+break;
3697 @t\4@>@<Cases of |show_node_list| that arise in mlists only@>@;
3698 default:print("Unknown node type!");
3699 }
3700
3701 @ @<Display box |p|@>=
3702 {@+if (type(p)==hlist_node) print_esc("h");
3703 else if (type(p)==vlist_node) print_esc("v");
3704 else print_esc("unset");
3705 print("box(");print_scaled(height(p));print_char('+');
3706 print_scaled(depth(p));print(")x");print_scaled(width(p));
3707 if (type(p)==unset_set_node) print(" set");
3708 else if (type(p)==unset_pack_node) print(" pack");
3709 else if (type(p)==unset_node)
3710 @<Display special fields of the unset node |p|@>@;
3711 else{@+@<Display the value of |glue_set(p)|@>;
3712 if (shift_amount(p)!=0)
3713 {@+print(", shifted ");print_scaled(shift_amount(p));
3714 }
3715 }
3716 node_list_display(list_ptr(p)); /*recursive call*/
3717 }
3718
3719 @ @<Display special fields of the unset node |p|@>=
3720 {@+if (span_count(p)!=min_quarterword)
3721 {@+print(" (");print_int(qo(span_count(p))+1);
3722 print(" columns)");
3723 }
3724 if (glue_stretch(p)!=0)
3725 {@+print(", stretch ");print_glue(glue_stretch(p), glue_order(p), 0);
3726 }
3727 if (glue_shrink(p)!=0)
3728 {@+print(", shrink ");print_glue(glue_shrink(p), glue_sign(p), 0);
3729 }
3730 }
3731
3732 @ The code will have to change in this place if |glue_ratio| is
3733 a structured type instead of an ordinary |double|. Note that this routine
3734 should avoid arithmetic errors even if the |glue_set| field holds an
3735 arbitrary random value. The following code assumes that a properly
3736 formed nonzero |double| number has absolute value $2^{20}$ or more when
3737 it is regarded as an integer; this precaution was adequate to prevent
3738 floating point underflow on the author's computer.
3739 @^system dependencies@>
3740 @^dirty \PASCAL@>
3741
3742 @<Display the value of |glue_set(p)|@>=
3743 g=unfix(glue_set(p));
3744 if ((g!=float_constant(0))&&(glue_sign(p)!=normal))
3745 {@+print(", glue set ");
3746 if (glue_sign(p)==shrinking) print("- ");
3747 if (abs(mem[p+glue_offset].i) < 04000000) print("?.?");
3748 else if (abs(g) > float_constant(20000))
3749 {@+if (g > float_constant(0)) print_char('>');
3750 else print("< -");
3751 print_glue(20000*unity, glue_order(p), 0);
3752 }
3753 else print_glue(round(unity*g), glue_order(p), 0);
3754 @^real multiplication@>
3755 }
3756
3757 @ @<Display rule |p|@>=
3758 {@+print_esc("rule(");print_rule_dimen(height(p));print_char('+');
3759 print_rule_dimen(depth(p));print(")x");print_rule_dimen(width(p));
3760 }
3761
3762 @ @<Display insertion |p|@>=
3763 {@+print_esc("insert");print_int(qo(subtype(p)));
3764 print("; split(");print_spec(split_top_ptr(p), 0);
3765 print_char(',');print_scaled(depth(p));
3766 print("); float cost ");print_int(float_cost(p));
3767 node_list_display(ins_ptr(p)); /*recursive call*/
3768 }
3769
3770 @ @<Display glue |p|@>=
3771 if (subtype(p) >= a_leaders) @<Display leaders |p|@>@;
3772 else{@+print_esc("glue");
3773 if (subtype(p)!=normal)
3774 {@+print_char('(');
3775 if (subtype(p) < cond_math_glue)
3776 print_skip_param(subtype(p)-1);
3777 else if (subtype(p)==cond_math_glue) print_esc("nonscript");
3778 else print_esc("mskip");
3779 print_char(')');
3780 }
3781 if (subtype(p)!=cond_math_glue)
3782 {@+print_char(' ');
3783 if (subtype(p) < cond_math_glue) print_spec(glue_ptr(p), 0);
3784 else print_spec(glue_ptr(p),"mu");
3785 }
3786 }
3787
3788 @ @<Display leaders |p|@>=
3789 {@+print_esc("");
3790 if (subtype(p)==c_leaders) print_char('c');
3791 else if (subtype(p)==x_leaders) print_char('x');
3792 print("leaders ");print_spec(glue_ptr(p), 0);
3793 node_list_display(leader_ptr(p)); /*recursive call*/
3794 }
3795
3796 @ An ``explicit'' kern value is indicated implicitly by an explicit space.
3797
3798 @<Display kern |p|@>=
3799 if (subtype(p)!=mu_glue)
3800 {@+print_esc("kern");
3801 if (subtype(p)!=normal) print_char(' ');
3802 print_scaled(width(p));
3803 if (subtype(p)==acc_kern) print(" (for accent)");
3804 @.for accent@>
3805 }
3806 else{@+print_esc("mkern");print_scaled(width(p));print("mu");
3807 }
3808
3809 @ @<Display math node |p|@>=
3810 {@+print_esc("math");
3811 if (subtype(p)==before) print("on");
3812 else print("off");
3813 if (width(p)!=0)
3814 {@+print(", surrounded ");print_scaled(width(p));
3815 }
3816 }
3817
3818 @ @<Display ligature |p|@>=
3819 {@+print_font_and_char(lig_char(p));print(" (ligature ");
3820 if (subtype(p) > 1) print_char('|');
3821 font_in_short_display=font(lig_char(p));short_display(lig_ptr(p));
3822 if (odd(subtype(p))) print_char('|');
3823 print_char(')');
3824 }
3825
3826 @ @<Display penalty |p|@>=
3827 {@+print_esc("penalty ");print_int(penalty(p));
3828 }
3829
3830 @ The |post_break| list of a discretionary node is indicated by a prefixed
3831 `\.{\char'174}' instead of the `\..' before the |pre_break| list.
3832
3833 @<Display discretionary |p|@>=
3834 {@+print_esc("discretionary");
3835 if (replace_count(p) > 0)
3836 {@+print(" replacing ");print_int(replace_count(p));
3837 }
3838 node_list_display(pre_break(p)); /*recursive call*/
3839 append_char('|');show_node_list(post_break(p));flush_char; /*recursive call*/
3840 }
3841
3842 @ @<Display mark |p|@>=
3843 {@+print_esc("mark");
3844 if (mark_class(p)!=0)
3845 {@+print_char('s');print_int(mark_class(p));
3846 }
3847 print_mark(mark_ptr(p));
3848 }
3849
3850 @ @<Display adjustment |p|@>=
3851 {@+print_esc("vadjust");node_list_display(adjust_ptr(p)); /*recursive call*/
3852 }
3853
3854 @ The recursive machinery is started by calling |show_box|.
3855 @^recursion@>
3856
3857 @p static void show_box(pointer @!p)
3858 {@+@<Assign the values |depth_threshold:=show_box_depth| and |breadth_max:=show_box_breadth|@>;
3859 if (breadth_max <= 0) breadth_max=5;
3860 if (pool_ptr+depth_threshold >= pool_size)
3861 depth_threshold=pool_size-pool_ptr-1;
3862 /*now there's enough room for prefix string*/
3863 show_node_list(p); /*the show starts at |p|*/
3864 print_ln();
3865 }
3866
3867 @* Destroying boxes.
3868 When we are done with a node list, we are obliged to return it to free
3869 storage, including all of its sublists. The recursive procedure
3870 |flush_node_list| does this for us.
3871
3872 @ First, however, we shall consider two non-recursive procedures that do
3873 simpler tasks. The first of these, |delete_token_ref|, is called when
3874 a pointer to a token list's reference count is being removed. This means
3875 that the token list should disappear if the reference count was |null|,
3876 otherwise the count should be decreased by one.
3877 @^reference counts@>
3878
3879 @d token_ref_count(A) info(A) /*reference count preceding a token list*/
3880
3881 @p static void delete_token_ref(pointer @!p) /*|p| points to the reference count
3882 of a token list that is losing one reference*/
3883 {@+if (token_ref_count(p)==null) flush_list(p);
3884 else decr(token_ref_count(p));
3885 }
3886
3887 @ Similarly, |delete_glue_ref| is called when a pointer to a glue
3888 specification is being withdrawn.
3889 @^reference counts@>
3890 @d fast_delete_glue_ref(A) @t@>@;@/
3891 {@+if (glue_ref_count(A)==null) free_node(A, glue_spec_size);
3892 else decr(glue_ref_count(A));
3893 }
3894
3895 @p static void delete_glue_ref(pointer @!p) /*|p| points to a glue specification*/
3896 fast_delete_glue_ref(p)
3897 static void delete_xdimen_ref(pointer @!p) /*|p| points to a xdimen specification*/
3898 {@+if (p==null) return;
3899 if (xdimen_ref_count(p)==null) free_node(p, xdimen_node_size);
3900 else decr(xdimen_ref_count(p));
3901 }
3902
3903 @ Now we are ready to delete any node list, recursively.
3904 In practice, the nodes deleted are usually charnodes (about 2/3 of the time),
3905 and they are glue nodes in about half of the remaining cases.
3906 @^recursion@>
3907
3908 @p static void flush_node_list(pointer @!p) /*erase list of nodes starting at |p|*/
3909 {@+ /*go here when node |p| has been freed*/
3910 pointer q; /*successor to node |p|*/
3911 while (p!=null)
3912 @^inner loop@>
3913 {@+q=link(p);
3914 if (is_char_node(p)) free_avail(p)@;
3915 else{@+switch (type(p)) {
3916 case hlist_node: case vlist_node: case unset_node:
3917 case unset_set_node: case unset_pack_node: {@+flush_node_list(list_ptr(p));
3918 free_node(p, box_node_size);goto done;
3919 }
3920 case rule_node: {@+free_node(p, rule_node_size);goto done;
3921 }
3922 case ins_node: {@+flush_node_list(ins_ptr(p));
3923 delete_glue_ref(split_top_ptr(p));
3924 free_node(p, ins_node_size);goto done;
3925 }
3926 case whatsit_node: @<Wipe out the whatsit node |p| and |goto done|@>@;
3927 case glue_node: {@+fast_delete_glue_ref(glue_ptr(p));
3928 if (leader_ptr(p)!=null) flush_node_list(leader_ptr(p));
3929 } @+break;
3930 case kern_node: case math_node: case penalty_node: do_nothing;@+break;
3931 case ligature_node: flush_node_list(lig_ptr(p));@+break;
3932 case mark_node: delete_token_ref(mark_ptr(p));@+break;
3933 case disc_node: {@+flush_node_list(pre_break(p));
3934 flush_node_list(post_break(p));
3935 } @+break;
3936 case adjust_node: flush_node_list(adjust_ptr(p));@+break;
3937 @t\4@>@<Cases of |flush_node_list| that arise in mlists only@>@;
3938 default:confusion("flushing");
3939 @:this can't happen flushing}{\quad flushing@>
3940 } @/
3941 free_node(p, small_node_size);
3942 done: ;}
3943 p=q;
3944 }
3945 }
3946
3947 @* Copying boxes.
3948 Another recursive operation that acts on boxes is sometimes needed: The
3949 procedure |copy_node_list| returns a pointer to another node list that has
3950 the same structure and meaning as the original. Note that since glue
3951 specifications and token lists have reference counts, we need not make
3952 copies of them. Reference counts can never get too large to fit in a
3953 halfword, since each pointer to a node is in a different memory address,
3954 and the total number of memory addresses fits in a halfword.
3955 @^recursion@>
3956 @^reference counts@>
3957
3958 (Well, there actually are also references from outside |mem|; if the
3959 |save_stack| is made arbitrarily large, it would theoretically be possible
3960 to break \TeX\ by overflowing a reference count. But who would want to do that?)
3961
3962 @d add_token_ref(A) incr(token_ref_count(A)) /*new reference to a token list*/
3963 @d add_glue_ref(A) incr(glue_ref_count(A)) /*new reference to a glue spec*/
3964 @d add_xdimen_ref(A) if (A!=null) incr(xdimen_ref_count(A)) /*new reference to an xdimen*/
3965
3966 @ The copying procedure copies words en masse without bothering
3967 to look at their individual fields. If the node format changes---for
3968 example, if the size is altered, or if some link field is moved to another
3969 relative position---then this code may need to be changed too.
3970 @^data structure assumptions@>
3971
3972 @p static pointer copy_node_list(pointer @!p) /*makes a duplicate of the
3973 node list that starts at |p| and returns a pointer to the new list*/
3974 {@+pointer h; /*temporary head of copied list*/
3975 pointer @!q; /*previous position in new list*/
3976 pointer @!r; /*current node being fabricated for new list*/
3977 int @!words; /*number of words remaining to be copied*/
3978 h=get_avail();q=h;
3979 while (p!=null)
3980 {@+@<Make a copy of node |p| in node |r|@>;
3981 link(q)=r;q=r;p=link(p);
3982 }
3983 link(q)=null;q=link(h);free_avail(h);
3984 return q;
3985 }
3986
3987 @ @<Make a copy of node |p|...@>=
3988 words=1; /*this setting occurs in more branches than any other*/
3989 if (is_char_node(p)) r=get_avail();
3990 else@<Case statement to copy different types and set |words| to the number
3991 of initial words not yet copied@>;
3992 while (words > 0)
3993 {@+decr(words);mem[r+words]=mem[p+words];
3994 }
3995
3996 @ @<Case statement to copy...@>=
3997 switch (type(p)) {
3998 case hlist_node: case vlist_node: case unset_node:
3999 case unset_set_node: case unset_pack_node: {@+r=get_node(box_node_size);
4000 mem[r+6]=mem[p+6];mem[r+5]=mem[p+5]; /*copy the last two words*/
4001 list_ptr(r)=copy_node_list(list_ptr(p)); /*this affects |mem[r+5]|*/
4002 words=5;
4003 } @+break;
4004 case rule_node: {@+r=get_node(rule_node_size);words=rule_node_size;
4005 } @+break;
4006 case ins_node: {@+r=get_node(ins_node_size);mem[r+4]=mem[p+4];
4007 add_glue_ref(split_top_ptr(p));
4008 ins_ptr(r)=copy_node_list(ins_ptr(p)); /*this affects |mem[r+4]|*/
4009 words=ins_node_size-1;
4010 } @+break;
4011 case whatsit_node: @<Make a partial copy of the whatsit node |p| and make
4012 |r| point to it; set |words| to the number of initial words not yet copied@>@;@+break;
4013 case glue_node: {@+r=get_node(small_node_size);add_glue_ref(glue_ptr(p));
4014 glue_ptr(r)=glue_ptr(p);leader_ptr(r)=copy_node_list(leader_ptr(p));
4015 } @+break;
4016 case kern_node: case math_node: case penalty_node: {@+r=get_node(small_node_size);
4017 words=small_node_size;
4018 } @+break;
4019 case ligature_node: {@+r=get_node(small_node_size);
4020 mem[lig_char(r)]=mem[lig_char(p)]; /*copy |font| and |character|*/
4021 lig_ptr(r)=copy_node_list(lig_ptr(p));
4022 } @+break;
4023 case disc_node: {@+r=get_node(small_node_size);
4024 pre_break(r)=copy_node_list(pre_break(p));
4025 post_break(r)=copy_node_list(post_break(p));
4026 } @+break;
4027 case mark_node: {@+r=get_node(small_node_size);add_token_ref(mark_ptr(p));
4028 words=small_node_size;
4029 } @+break;
4030 case adjust_node: {@+r=get_node(small_node_size);
4031 adjust_ptr(r)=copy_node_list(adjust_ptr(p));
4032 } @+break; /*|words==1==small_node_size-1|*/
4033 default:confusion("copying");
4034 @:this can't happen copying}{\quad copying@>
4035 }
4036
4037 @* The command codes.
4038 Before we can go any further, we need to define symbolic names for the internal
4039 code numbers that represent the various commands obeyed by \TeX. These codes
4040 are somewhat arbitrary, but not completely so. For example, the command
4041 codes for character types are fixed by the language, since a user says,
4042 e.g., `\.{\\catcode \`\\\${} = 3}' to make \.{\char'44} a math delimiter,
4043 and the command code |math_shift| is equal to~3. Some other codes have
4044 been made adjacent so that |case| statements in the program need not consider
4045 cases that are widely spaced, or so that |case| statements can be replaced
4046 by |if| statements.
4047
4048 At any rate, here is the list, for future reference. First come the
4049 ``catcode'' commands, several of which share their numeric codes with
4050 ordinary commands when the catcode cannot emerge from \TeX's scanning routine.
4051
4052 @d escape 0 /*escape delimiter (called \.\\ in {\sl The \TeX book\/})*/
4053 @:TeXbook}{\sl The \TeX book@>
4054 @d relax 0 /*do nothing ( \.{\\relax} )*/
4055 @d left_brace 1 /*beginning of a group ( \.\{ )*/
4056 @d right_brace 2 /*ending of a group ( \.\} )*/
4057 @d math_shift 3 /*mathematics shift character ( \.\$ )*/
4058 @d tab_mark 4 /*alignment delimiter ( \.\&, \.{\\span} )*/
4059 @d car_ret 5 /*end of line ( |carriage_return|, \.{\\cr}, \.{\\crcr} )*/
4060 @d out_param 5 /*output a macro parameter*/
4061 @d mac_param 6 /*macro parameter symbol ( \.\# )*/
4062 @d sup_mark 7 /*superscript ( \.{\char'136} )*/
4063 @d sub_mark 8 /*subscript ( \.{\char'137} )*/
4064 @d ignore 9 /*characters to ignore ( \.{\^\^@@} )*/
4065 @d endv 9 /*end of \<v_j> list in alignment template*/
4066 @d spacer 10 /*characters equivalent to blank space ( \.{\ } )*/
4067 @d letter 11 /*characters regarded as letters ( \.{A..Z}, \.{a..z} )*/
4068 @d other_char 12 /*none of the special character types*/
4069 @d active_char 13 /*characters that invoke macros ( \.{\char`\~} )*/
4070 @d par_end 13 /*end of paragraph ( \.{\\par} )*/
4071 @d match 13 /*match a macro parameter*/
4072 @d comment 14 /*characters that introduce comments ( \.\% )*/
4073 @d end_match 14 /*end of parameters to macro*/
4074 @d stop 14 /*end of job ( \.{\\end}, \.{\\dump} )*/
4075 @d invalid_char 15 /*characters that shouldn't appear ( \.{\^\^?} )*/
4076 @d delim_num 15 /*specify delimiter numerically ( \.{\\delimiter} )*/
4077 @d max_char_code 15 /*largest catcode for individual characters*/
4078
4079 @ Next are the ordinary run-of-the-mill command codes. Codes that are
4080 |min_internal| or more represent internal quantities that might be
4081 expanded by `\.{\\the}'.
4082
4083 @d char_num 16 /*character specified numerically ( \.{\\char} )*/
4084 @d math_char_num 17 /*explicit math code ( \.{\\mathchar} )*/
4085 @d mark 18 /*mark definition ( \.{\\mark} )*/
4086 @d xray 19 /*peek inside of \TeX\ ( \.{\\show}, \.{\\showbox}, etc.~)*/
4087 @d make_box 20 /*make a box ( \.{\\box}, \.{\\copy}, \.{\\hbox}, etc.~)*/
4088 @d hmove 21 /*horizontal motion ( \.{\\moveleft}, \.{\\moveright} )*/
4089 @d vmove 22 /*vertical motion ( \.{\\raise}, \.{\\lower} )*/
4090 @d un_hbox 23 /*unglue a box ( \.{\\unhbox}, \.{\\unhcopy} )*/
4091 @d un_vbox 24 /*unglue a box ( \.{\\unvbox}, \.{\\unvcopy} )*/
4092 /*( or \.{\\pagediscards}, \.{\\splitdiscards} )*/
4093 @d remove_item 25 /*nullify last item ( \.{\\unpenalty},
4094 \.{\\unkern}, \.{\\unskip} )*/
4095 @d hskip 26 /*horizontal glue ( \.{\\hskip}, \.{\\hfil}, etc.~)*/
4096 @d vskip 27 /*vertical glue ( \.{\\vskip}, \.{\\vfil}, etc.~)*/
4097 @d mskip 28 /*math glue ( \.{\\mskip} )*/
4098 @d kern 29 /*fixed space ( \.{\\kern} )*/
4099 @d mkern 30 /*math kern ( \.{\\mkern} )*/
4100 @d leader_ship 31 /*use a box ( \.{\\shipout}, \.{\\leaders}, etc.~)*/
4101 @d halign 32 /*horizontal table alignment ( \.{\\halign} )*/
4102 @d valign 33 /*vertical table alignment ( \.{\\valign} )*/
4103 @d no_align 34 /*temporary escape from alignment ( \.{\\noalign} )*/
4104 @d vrule 35 /*vertical rule ( \.{\\vrule} )*/
4105 @d hrule 36 /*horizontal rule ( \.{\\hrule} )*/
4106 @d insert 37 /*vlist inserted in box ( \.{\\insert} )*/
4107 @d vadjust 38 /*vlist inserted in enclosing paragraph ( \.{\\vadjust} )*/
4108 @d ignore_spaces 39 /*gobble |spacer| tokens ( \.{\\ignorespaces} )*/
4109 @d after_assignment 40 /*save till assignment is done ( \.{\\afterassignment} )*/
4110 @d after_group 41 /*save till group is done ( \.{\\aftergroup} )*/
4111 @d break_penalty 42 /*additional badness ( \.{\\penalty} )*/
4112 @d start_par 43 /*begin paragraph ( \.{\\indent}, \.{\\noindent} )*/
4113 @d ital_corr 44 /*italic correction ( \.{\\/} )*/
4114 @d accent 45 /*attach accent in text ( \.{\\accent} )*/
4115 @d math_accent 46 /*attach accent in math ( \.{\\mathaccent} )*/
4116 @d discretionary 47 /*discretionary texts ( \.{\\-}, \.{\\discretionary} )*/
4117 @d eq_no 48 /*equation number ( \.{\\eqno}, \.{\\leqno} )*/
4118 @d left_right 49 /*variable delimiter ( \.{\\left}, \.{\\right} )*/
4119 /*( or \.{\\middle} )*/
4120 @d math_comp 50 /*component of formula ( \.{\\mathbin}, etc.~)*/
4121 @d limit_switch 51 /*diddle limit conventions ( \.{\\displaylimits}, etc.~)*/
4122 @d above 52 /*generalized fraction ( \.{\\above}, \.{\\atop}, etc.~)*/
4123 @d math_style 53 /*style specification ( \.{\\displaystyle}, etc.~)*/
4124 @d math_choice 54 /*choice specification ( \.{\\mathchoice} )*/
4125 @d non_script 55 /*conditional math glue ( \.{\\nonscript} )*/
4126 @d vcenter 56 /*vertically center a vbox ( \.{\\vcenter} )*/
4127 @d case_shift 57 /*force specific case ( \.{\\lowercase}, \.{\\uppercase}~)*/
4128 @d message 58 /*send to user ( \.{\\message}, \.{\\errmessage} )*/
4129 @d extension 59 /*extensions to \TeX\ ( \.{\\write}, \.{\\special}, etc.~)*/
4130 @d in_stream 60 /*files for reading ( \.{\\openin}, \.{\\closein} )*/
4131 @d begin_group 61 /*begin local grouping ( \.{\\begingroup} )*/
4132 @d end_group 62 /*end local grouping ( \.{\\endgroup} )*/
4133 @d omit 63 /*omit alignment template ( \.{\\omit} )*/
4134 @d ex_space 64 /*explicit space ( \.{\\\ } )*/
4135 @d no_boundary 65 /*suppress boundary ligatures ( \.{\\noboundary} )*/
4136 @d radical 66 /*square root and similar signs ( \.{\\radical} )*/
4137 @d end_cs_name 67 /*end control sequence ( \.{\\endcsname} )*/
4138 @d min_internal 68 /*the smallest code that can follow \.{\\the}*/
4139 @d char_given 68 /*character code defined by \.{\\chardef}*/
4140 @d math_given 69 /*math code defined by \.{\\mathchardef}*/
4141 @d last_item 70 /*most recent item ( \.{\\lastpenalty},
4142 \.{\\lastkern}, \.{\\lastskip} )*/
4143 @d max_non_prefixed_command 70 /*largest command code that can't be \.{\\global}*/
4144
4145 @ The next codes are special; they all relate to mode-independent
4146 assignment of values to \TeX's internal registers or tables.
4147 Codes that are |max_internal| or less represent internal quantities
4148 that might be expanded by `\.{\\the}'.
4149
4150 @d toks_register 71 /*token list register ( \.{\\toks} )*/
4151 @d assign_toks 72 /*special token list ( \.{\\output}, \.{\\everypar}, etc.~)*/
4152 @d assign_int 73 /*user-defined integer ( \.{\\tolerance}, \.{\\day}, etc.~)*/
4153 @d assign_dimen 74 /*user-defined length ( \.{\\hsize}, etc.~)*/
4154 @d assign_glue 75 /*user-defined glue ( \.{\\baselineskip}, etc.~)*/
4155 @d assign_mu_glue 76 /*user-defined muglue ( \.{\\thinmuskip}, etc.~)*/
4156 @d assign_font_dimen 77 /*user-defined font dimension ( \.{\\fontdimen} )*/
4157 @d assign_font_int 78 /*user-defined font integer ( \.{\\hyphenchar},
4158 \.{\\skewchar} )*/
4159 @d set_aux 79 /*specify state info ( \.{\\spacefactor}, \.{\\prevdepth} )*/
4160 @d set_prev_graf 80 /*specify state info ( \.{\\prevgraf} )*/
4161 @d set_page_dimen 81 /*specify state info ( \.{\\pagegoal}, etc.~)*/
4162 @d set_page_int 82 /*specify state info ( \.{\\deadcycles},
4163 \.{\\insertpenalties} )*/
4164 /*( or \.{\\interactionmode} )*/
4165 @d set_box_dimen 83 /*change dimension of box ( \.{\\wd}, \.{\\ht}, \.{\\dp} )*/
4166 @d set_shape 84 /*specify fancy paragraph shape ( \.{\\parshape} )*/
4167 /*(or \.{\\interlinepenalties}, etc.~)*/
4168 @d def_code 85 /*define a character code ( \.{\\catcode}, etc.~)*/
4169 @d def_family 86 /*declare math fonts ( \.{\\textfont}, etc.~)*/
4170 @d set_font 87 /*set current font ( font identifiers )*/
4171 @d def_font 88 /*define a font file ( \.{\\font} )*/
4172 @d internal_register 89 /*internal register ( \.{\\count}, \.{\\dimen}, etc.~)*/
4173 @d max_internal 89 /*the largest code that can follow \.{\\the}*/
4174 @d advance 90 /*advance a register or parameter ( \.{\\advance} )*/
4175 @d multiply 91 /*multiply a register or parameter ( \.{\\multiply} )*/
4176 @d divide 92 /*divide a register or parameter ( \.{\\divide} )*/
4177 @d prefix 93 /*qualify a definition ( \.{\\global}, \.{\\long}, \.{\\outer} )*/
4178 /*( or \.{\\protected} )*/
4179 @d let 94 /*assign a command code ( \.{\\let}, \.{\\futurelet} )*/
4180 @d shorthand_def 95 /*code definition ( \.{\\chardef}, \.{\\countdef}, etc.~)*/
4181 @d read_to_cs 96 /*read into a control sequence ( \.{\\read} )*/
4182 /*( or \.{\\readline} )*/
4183 @d def 97 /*macro definition ( \.{\\def}, \.{\\gdef}, \.{\\xdef}, \.{\\edef} )*/
4184 @d set_box 98 /*set a box ( \.{\\setbox} )*/
4185 @d hyph_data 99 /*hyphenation data ( \.{\\hyphenation}, \.{\\patterns} )*/
4186 @d set_interaction 100 /*define level of interaction ( \.{\\batchmode}, etc.~)*/
4187 @d max_command 100 /*the largest command code seen at |big_switch|*/
4188
4189 @ The remaining command codes are extra special, since they cannot get through
4190 \TeX's scanner to the main control routine. They have been given values higher
4191 than |max_command| so that their special nature is easily discernible.
4192 The ``expandable'' commands come first.
4193
4194 @d undefined_cs (max_command+1) /*initial state of most |eq_type| fields*/
4195 @d expand_after (max_command+2) /*special expansion ( \.{\\expandafter} )*/
4196 @d no_expand (max_command+3) /*special nonexpansion ( \.{\\noexpand} )*/
4197 @d input (max_command+4) /*input a source file ( \.{\\input}, \.{\\endinput} )*/
4198 /*( or \.{\\scantokens} )*/
4199 @d if_test (max_command+5) /*conditional text ( \.{\\if}, \.{\\ifcase}, etc.~)*/
4200 @d fi_or_else (max_command+6) /*delimiters for conditionals ( \.{\\else}, etc.~)*/
4201 @d cs_name (max_command+7) /*make a control sequence from tokens ( \.{\\csname} )*/
4202 @d convert (max_command+8) /*convert to text ( \.{\\number}, \.{\\string}, etc.~)*/
4203 @d the (max_command+9) /*expand an internal quantity ( \.{\\the} )*/
4204 /*( or \.{\\unexpanded}, \.{\\detokenize} )*/
4205 @d top_bot_mark (max_command+10) /*inserted mark ( \.{\\topmark}, etc.~)*/
4206 @d call (max_command+11) /*non-long, non-outer control sequence*/
4207 @d long_call (max_command+12) /*long, non-outer control sequence*/
4208 @d outer_call (max_command+13) /*non-long, outer control sequence*/
4209 @d long_outer_call (max_command+14) /*long, outer control sequence*/
4210 @d end_template (max_command+15) /*end of an alignment template*/
4211 @d dont_expand (max_command+16) /*the following token was marked by \.{\\noexpand}*/
4212 @d glue_ref (max_command+17) /*the equivalent points to a glue specification*/
4213 @d shape_ref (max_command+18) /*the equivalent points to a parshape specification*/
4214 @d box_ref (max_command+19) /*the equivalent points to a box node, or is |null|*/
4215 @d data (max_command+20) /*the equivalent is simply a halfword number*/
4216
4217 @* The semantic nest.
4218 \TeX\ is typically in the midst of building many lists at once. For example,
4219 when a math formula is being processed, \TeX\ is in math mode and
4220 working on an mlist; this formula has temporarily interrupted \TeX\ from
4221 being in horizontal mode and building the hlist of a paragraph; and this
4222 paragraph has temporarily interrupted \TeX\ from being in vertical mode
4223 and building the vlist for the next page of a document. Similarly, when a
4224 \.{\\vbox} occurs inside of an \.{\\hbox}, \TeX\ is temporarily
4225 interrupted from working in restricted horizontal mode, and it enters
4226 internal vertical mode. The ``semantic nest'' is a stack that
4227 keeps track of what lists and modes are currently suspended.
4228
4229 At each level of processing we are in one of six modes:
4230
4231 \yskip\hang|vmode| stands for vertical mode (the page builder);
4232
4233 \hang|hmode| stands for horizontal mode (the paragraph builder);
4234
4235 \hang|mmode| stands for displayed formula mode;
4236
4237 \hang|-vmode| stands for internal vertical mode (e.g., in a \.{\\vbox});
4238
4239 \hang|-hmode| stands for restricted horizontal mode (e.g., in an \.{\\hbox});
4240
4241 \hang|-mmode| stands for math formula mode (not displayed).
4242
4243 \yskip\noindent The mode is temporarily set to zero while processing \.{\\write}
4244 texts.
4245
4246 Numeric values are assigned to |vmode|, |hmode|, and |mmode| so that
4247 \TeX's ``big semantic switch'' can select the appropriate thing to
4248 do by computing the value |abs(mode)+cur_cmd|, where |mode| is the current
4249 mode and |cur_cmd| is the current command code.
4250
4251 @d vmode 1 /*vertical mode*/
4252 @d hmode (vmode+max_command+1) /*horizontal mode*/
4253 @d mmode (hmode+max_command+1) /*math mode*/
4254
4255 @p static void print_mode(int @!m) /*prints the mode represented by |m|*/
4256 {@+if (m > 0)
4257 switch (m/(max_command+1)) {
4258 case 0: print("vertical");@+break;
4259 case 1: print("horizontal");@+break;
4260 case 2: print("display math");
4261 }
4262 else if (m==0) print("no");
4263 else switch ((-m)/(max_command+1)) {
4264 case 0: print("internal vertical");@+break;
4265 case 1: print("restricted horizontal");@+break;
4266 case 2: print("math");
4267 }
4268 print(" mode");
4269 }
4270
4271 @ The state of affairs at any semantic level can be represented by
4272 five values:
4273
4274 \yskip\hang|mode| is the number representing the semantic mode, as
4275 just explained.
4276
4277 \yskip\hang|head| is a |pointer| to a list head for the list being built;
4278 |link(head)| therefore points to the first element of the list, or
4279 to |null| if the list is empty.
4280
4281 \yskip\hang|tail| is a |pointer| to the final node of the list being
4282 built; thus, |tail==head| if and only if the list is empty.
4283
4284 \yskip\hang|prev_graf| is the number of lines of the current paragraph that
4285 have already been put into the present vertical list.
4286
4287 \yskip\hang|aux| is an auxiliary |memory_word| that gives further information
4288 that is needed to characterize the situation.
4289
4290 \yskip\noindent
4291 In vertical mode, |aux| is also known as |prev_depth|; it is the scaled
4292 value representing the depth of the previous box, for use in baseline
4293 calculations, or it is | <= -1000|pt if the next box on the vertical list is to
4294 be exempt from baseline calculations. In horizontal mode, |aux| is also
4295 known as |space_factor| and |clang|; it holds the current space factor used in
4296 spacing calculations, and the current language used for hyphenation.
4297 (The value of |clang| is undefined in restricted horizontal mode.)
4298 In math mode, |aux| is also known as |incompleat_noad|; if
4299 not |null|, it points to a record that represents the numerator of a
4300 generalized fraction for which the denominator is currently being formed
4301 in the current list.
4302
4303 There is also a sixth quantity, |mode_line|, which correlates
4304 the semantic nest with the user's input; |mode_line| contains the source
4305 line number at which the current level of nesting was entered. The negative
4306 of this line number is the |mode_line| at the level of the
4307 user's output routine.
4308
4309 A seventh quantity, |eTeX_aux|, is used by the extended features \eTeX.
4310 In vertical modes it is known as |LR_save| and holds the LR stack when a
4311 paragraph is interrupted by a displayed formula. In display math mode
4312 it is known as |LR_box| and holds a pointer to a prototype box for the
4313 display. In math mode it is known as |delim_ptr| and points to the most
4314 recent |left_noad| or |middle_noad| of a |math_left_group|.
4315
4316 In horizontal mode, the |prev_graf| field is used for initial language data.
4317
4318 The semantic nest is an array called |nest| that holds the |mode|, |head|,
4319 |tail|, |prev_graf|, |aux|, and |mode_line| values for all semantic levels
4320 below the currently active one. Information about the currently active
4321 level is kept in the global quantities |mode|, |head|, |tail|, |prev_graf|,
4322 |aux|, and |mode_line|, which live in a \PASCAL\ record that is ready to
4323 be pushed onto |nest| if necessary.
4324
4325 @d ignore_depth (-1000*unity) /*|prev_depth| value that is ignored*/
4326 @d unknown_depth (-2000*unity) /*|prev_depth| value that is unknown*/
4327
4328 @<Types...@>=
4329 typedef struct { int16_t @!mode_field;@+
4330 pointer @!head_field, @!tail_field;
4331 pointer @!eTeX_aux_field;
4332 int @!pg_field, @!ml_field;@+
4333 memory_word @!aux_field;
4334 } list_state_record;
4335
4336 @ @d mode cur_list.mode_field /*current mode*/
4337 @d head cur_list.head_field /*header node of current list*/
4338 @d tail cur_list.tail_field /*final node on current list*/
4339 @d eTeX_aux cur_list.eTeX_aux_field /*auxiliary data for \eTeX*/
4340 @d delim_ptr eTeX_aux /*most recent left or right noad of a math left group*/
4341 @d prev_graf cur_list.pg_field /*number of paragraph lines accumulated*/
4342 @d aux cur_list.aux_field /*auxiliary data about the current list*/
4343 @d prev_depth aux.sc /*the name of |aux| in vertical mode*/
4344 @d space_factor aux.hh.lh /*part of |aux| in horizontal mode*/
4345 @d clang aux.hh.rh /*the other part of |aux| in horizontal mode*/
4346 @d incompleat_noad aux.i /*the name of |aux| in math mode*/
4347 @d mode_line cur_list.ml_field /*source file line number at beginning of list*/
4348
4349 @<Glob...@>=
4350 static list_state_record @!nest[nest_size+1];
4351 static int @!nest_ptr; /*first unused location of |nest|*/
4352 static int @!max_nest_stack; /*maximum of |nest_ptr| when pushing*/
4353 static list_state_record @!cur_list; /*the ``top'' semantic state*/
4354 static int @!shown_mode; /*most recent mode shown by \.{\\tracingcommands}*/
4355
4356 @ Here is a common way to make the current list grow:
4357
4358 @d tail_append(A) {@+link(tail)=A;tail=link(tail);
4359 }
4360
4361 @ We will see later that the vertical list at the bottom semantic level is split
4362 into two parts; the ``current page'' runs from |page_head| to |page_tail|,
4363 and the ``contribution list'' runs from |contrib_head| to |tail| of
4364 semantic level zero. The idea is that contributions are first formed in
4365 vertical mode, then ``contributed'' to the current page (during which time
4366 the page-breaking decisions are made). For now, we don't need to know
4367 any more details about the page-building process.
4368
4369 @<Set init...@>=
4370 nest_ptr=0;max_nest_stack=0;
4371 mode=vmode;head=contrib_head;tail=contrib_head;
4372 eTeX_aux=null;
4373 prev_depth=ignore_depth;mode_line=0;
4374 prev_graf=0;shown_mode=0;
4375 @<Start a new current page@>;
4376
4377 @ When \TeX's work on one level is interrupted, the state is saved by
4378 calling |push_nest|. This routine changes |head| and |tail| so that
4379 a new (empty) list is begun; it does not change |mode| or |aux|.
4380
4381 @p static void push_nest(void) /*enter a new semantic level, save the old*/
4382 {@+if (nest_ptr > max_nest_stack)
4383 {@+max_nest_stack=nest_ptr;
4384 if (nest_ptr==nest_size) overflow("semantic nest size", nest_size);
4385 @:TeX capacity exceeded semantic nest size}{\quad semantic nest size@>
4386 }
4387 nest[nest_ptr]=cur_list; /*stack the record*/
4388 incr(nest_ptr);head=get_avail();tail=head;prev_graf=0;mode_line=line;
4389 eTeX_aux=null;
4390 }
4391
4392 @ Conversely, when \TeX\ is finished on the current level, the former
4393 state is restored by calling |pop_nest|. This routine will never be
4394 called at the lowest semantic level, nor will it be called unless |head|
4395 is a node that should be returned to free memory.
4396
4397 @p static void pop_nest(void) /*leave a semantic level, re-enter the old*/
4398 {@+free_avail(head);decr(nest_ptr);cur_list=nest[nest_ptr];
4399 }
4400
4401 @ Here is a procedure that displays what \TeX\ is working on, at all levels.
4402
4403 @p static void print_totals(void);
4404 static void show_activities(void)
4405 {@+int p; /*index into |nest|*/
4406 int @!m; /*mode*/
4407 memory_word @!a; /*auxiliary*/
4408 pointer @!q, @!r; /*for showing the current page*/
4409 int @!t; /*ditto*/
4410 nest[nest_ptr]=cur_list; /*put the top level into the array*/
4411 print_nl("");print_ln();
4412 for (p=nest_ptr; p>=0; p--)
4413 {@+m=nest[p].mode_field;a=nest[p].aux_field;
4414 print_nl("### ");print_mode(m);
4415 print(" entered at line ");print_int(abs(nest[p].ml_field));
4416 if (m==hmode) if (nest[p].pg_field!=040600000)
4417 {@+print(" (language");print_int(nest[p].pg_field%0200000);
4418 print(":hyphenmin");print_int(nest[p].pg_field/020000000);
4419 print_char(',');print_int((nest[p].pg_field/0200000)%0100);
4420 print_char(')');
4421 }
4422 if (nest[p].ml_field < 0) print(" (\\output routine)");
4423 if (p==0)
4424 {@+@<Show the status of the current page@>;
4425 if (link(contrib_head)!=null)
4426 print_nl("### recent contributions:");
4427 }
4428 show_box(link(nest[p].head_field));
4429 @<Show the auxiliary field, |a|@>;
4430 }
4431 }
4432
4433 @ @<Show the auxiliary...@>=
4434 switch (abs(m)/(max_command+1)) {
4435 case 0: {@+print_nl("prevdepth ");
4436 if (a.sc <= ignore_depth)
4437 { if (a.sc <= unknown_depth) print("unknown"); else print("ignored"); }
4438 else print_scaled(a.sc);
4439 if (nest[p].pg_field!=0)
4440 {@+print(", prevgraf ");
4441 print_int(nest[p].pg_field);print(" line");
4442 if (nest[p].pg_field!=1) print_char('s');
4443 }
4444 } @+break;
4445 case 1: {@+print_nl("spacefactor ");print_int(a.hh.lh);
4446 if (m > 0) @+if (a.hh.rh > 0)
4447 {@+print(", current language ");print_int(a.hh.rh);@+
4448 }
4449 } @+break;
4450 case 2: if (a.i!=null)
4451 {@+print("this will begin denominator of:");show_box(a.i);@+
4452 }
4453 } /*there are no other cases*/
4454
4455 @* The table of equivalents.
4456 Now that we have studied the data structures for \TeX's semantic routines,
4457 we ought to consider the data structures used by its syntactic routines. In
4458 other words, our next concern will be
4459 the tables that \TeX\ looks at when it is scanning
4460 what the user has written.
4461
4462 The biggest and most important such table is called |eqtb|. It holds the
4463 current ``equivalents'' of things; i.e., it explains what things mean
4464 or what their current values are, for all quantities that are subject to
4465 the nesting structure provided by \TeX's grouping mechanism. There are six
4466 parts to |eqtb|:
4467
4468 \yskip\hangg 1) |eqtb[active_base dotdot(hash_base-1)]| holds the current
4469 equivalents of single-character control sequences.
4470
4471 \yskip\hangg 2) |eqtb[hash_base dotdot(glue_base-1)]| holds the current
4472 equivalents of multiletter control sequences.
4473
4474 \yskip\hangg 3) |eqtb[glue_base dotdot(local_base-1)]| holds the current
4475 equivalents of glue parameters like the current baselineskip.
4476
4477 \yskip\hangg 4) |eqtb[local_base dotdot(int_base-1)]| holds the current
4478 equivalents of local halfword quantities like the current box registers,
4479 the current ``catcodes,'' the current font, and a pointer to the current
4480 paragraph shape.
4481
4482 \yskip\hangg 5) |eqtb[int_base dotdot(dimen_base-1)]| holds the current
4483 equivalents of fullword integer parameters like the current hyphenation
4484 penalty.
4485
4486 \yskip\hangg 6) |eqtb[dimen_base dotdot eqtb_size]| holds the current equivalents
4487 of fullword dimension parameters like the current hsize or amount of
4488 hanging indentation.
4489
4490 \yskip\noindent Note that, for example, the current amount of
4491 baselineskip glue is determined by the setting of a particular location
4492 in region~3 of |eqtb|, while the current meaning of the control sequence
4493 `\.{\\baselineskip}' (which might have been changed by \.{\\def} or
4494 \.{\\let}) appears in region~2.
4495
4496 @ Each entry in |eqtb| is a |memory_word|. Most of these words are of type
4497 |two_halves|, and subdivided into three fields:
4498
4499 \yskip\hangg 1) The |eq_level| (a quarterword) is the level of grouping at
4500 which this equivalent was defined. If the level is |level_zero|, the
4501 equivalent has never been defined; |level_one| refers to the outer level
4502 (outside of all groups), and this level is also used for global
4503 definitions that never go away. Higher levels are for equivalents that
4504 will disappear at the end of their group. @^global definitions@>
4505
4506 \yskip\hangg 2) The |eq_type| (another quarterword) specifies what kind of
4507 entry this is. There are many types, since each \TeX\ primitive like
4508 \.{\\hbox}, \.{\\def}, etc., has its own special code. The list of
4509 command codes above includes all possible settings of the |eq_type| field.
4510
4511 \yskip\hangg 3) The |equiv| (a halfword) is the current equivalent value.
4512 This may be a font number, a pointer into |mem|, or a variety of other
4513 things.
4514
4515 @d eq_level_field(A) A.hh.b1
4516 @d eq_type_field(A) A.hh.b0
4517 @d equiv_field(A) A.hh.rh
4518 @d eq_level(A) eq_level_field(eqtb[A]) /*level of definition*/
4519 @d eq_type(A) eq_type_field(eqtb[A]) /*command code for equivalent*/
4520 @d equiv(A) equiv_field(eqtb[A]) /*equivalent value*/
4521 @d level_zero min_quarterword /*level for undefined quantities*/
4522 @d level_one (level_zero+1) /*outermost level for defined quantities*/
4523
4524 @ Many locations in |eqtb| have symbolic names. The purpose of the next
4525 paragraphs is to define these names, and to set up the initial values of the
4526 equivalents.
4527
4528 In the first region we have 256 equivalents for ``active characters'' that
4529 act as control sequences, followed by 256 equivalents for single-character
4530 control sequences.
4531
4532 Then comes region~2, which corresponds to the hash table that we will
4533 define later. The maximum address in this region is used for a dummy
4534 control sequence that is perpetually undefined. There also are several
4535 locations for control sequences that are perpetually defined
4536 (since they are used in error recovery).
4537
4538 @d active_base 1 /*beginning of region 1, for active character equivalents*/
4539 @d utf8_single_size 0x80 /*|0x80| UTF8 characters (|0|--|0x7F|), fit in a single byte*/
4540 @d active_hash_base (active_base+utf8_single_size)
4541 @d active_hash_bits 8
4542 @d active_hash_size (1<<active_hash_bits) /*other active characters share this region*/
4543 @d single_base (active_hash_base+active_hash_size) /*equivalents of one-character control sequences*/
4544 @d null_cs (single_base+utf8_single_size) /*equivalent of \.{\\csname\\endcsname}*/
4545 @d hash_base (null_cs+1) /*beginning of region 2, for the hash table*/
4546 @d frozen_control_sequence (hash_base+hash_size) /*for error recovery*/
4547 @d frozen_protection frozen_control_sequence /*inaccessible but definable*/
4548 @d frozen_cr (frozen_control_sequence+1) /*permanent `\.{\\cr}'*/
4549 @d frozen_end_group (frozen_control_sequence+2) /*permanent `\.{\\endgroup}'*/
4550 @d frozen_right (frozen_control_sequence+3) /*permanent `\.{\\right}'*/
4551 @d frozen_fi (frozen_control_sequence+4) /*permanent `\.{\\fi}'*/
4552 @d frozen_end_template (frozen_control_sequence+5) /*permanent `\.{\\endtemplate}'*/
4553 @d frozen_endv (frozen_control_sequence+6) /*second permanent `\.{\\endtemplate}'*/
4554 @d frozen_relax (frozen_control_sequence+7) /*permanent `\.{\\relax}'*/
4555 @d end_write (frozen_control_sequence+8) /*permanent `\.{\\endwrite}'*/
4556 @d frozen_dont_expand (frozen_control_sequence+9)
4557 /*permanent `\.{\\notexpanded:}'*/
4558 @d frozen_primitive (frozen_control_sequence+10)
4559 /*permanent `\.{\\primitive:}'*/
4560 @d frozen_null_font (frozen_control_sequence+11)
4561 /*permanent `\.{\\nullfont}'*/
4562 @d font_id_base (frozen_null_font-font_base)
4563 /*begins table of 257 permanent font identifiers*/
4564 @d undefined_control_sequence (frozen_null_font+257) /*dummy location*/
4565 @d glue_base (undefined_control_sequence+1) /*beginning of region 3*/
4566
4567 @<Initialize table entries...@>=
4568 eq_type(undefined_control_sequence)=undefined_cs;
4569 equiv(undefined_control_sequence)=null;
4570 eq_level(undefined_control_sequence)=level_zero;
4571 for (k=active_base; k<=undefined_control_sequence-1; k++)
4572 eqtb[k]=eqtb[undefined_control_sequence];
4573
4574 @ Here is a routine that displays the current meaning of an |eqtb| entry
4575 in region 1 or~2. (Similar routines for the other regions will appear
4576 below.)
4577
4578 @<Show equivalent |n|, in region 1 or 2@>=
4579 {@+sprint_cs(n);print_char('=');print_cmd_chr(eq_type(n), equiv(n));
4580 if (eq_type(n) >= call)
4581 {@+print_char(':');show_token_list(link(equiv(n)), null, 32);
4582 }
4583 }
4584
4585 @ Region 3 of |eqtb| contains the 256 \.{\\skip} registers, as well as the
4586 glue parameters defined here. It is important that the ``muskip''
4587 parameters have larger numbers than the others.
4588
4589 @d line_skip_code 0 /*interline glue if |baseline_skip| is infeasible*/
4590 @d baseline_skip_code 1 /*desired glue between baselines*/
4591 @d par_skip_code 2 /*extra glue just above a paragraph*/
4592 @d above_display_skip_code 3 /*extra glue just above displayed math*/
4593 @d below_display_skip_code 4 /*extra glue just below displayed math*/
4594 @d above_display_short_skip_code 5
4595 /*glue above displayed math following short lines*/
4596 @d below_display_short_skip_code 6
4597 /*glue below displayed math following short lines*/
4598 @d left_skip_code 7 /*glue at left of justified lines*/
4599 @d right_skip_code 8 /*glue at right of justified lines*/
4600 @d top_skip_code 9 /*glue at top of main pages*/
4601 @d split_top_skip_code 10 /*glue at top of split pages*/
4602 @d tab_skip_code 11 /*glue between aligned entries*/
4603 @d space_skip_code 12 /*glue between words (if not |zero_glue|)*/
4604 @d xspace_skip_code 13 /*glue after sentences (if not |zero_glue|)*/
4605 @d par_fill_skip_code 14 /*glue on last line of paragraph*/
4606 @d thin_mu_skip_code 15 /*thin space in math formula*/
4607 @d med_mu_skip_code 16 /*medium space in math formula*/
4608 @d thick_mu_skip_code 17 /*thick space in math formula*/
4609 @d glue_pars 18 /*total number of glue parameters*/
4610 @d skip_base (glue_base+glue_pars) /*table of 256 ``skip'' registers*/
4611 @d mu_skip_base (skip_base+256) /*table of 256 ``muskip'' registers*/
4612 @d local_base (mu_skip_base+256) /*beginning of region 4*/
4613 @#
4614 @d skip(A) equiv(skip_base+A) /*|mem| location of glue specification*/
4615 @d mu_skip(A) equiv(mu_skip_base+A) /*|mem| location of math glue spec*/
4616 @d glue_par(A) equiv(glue_base+A) /*|mem| location of glue specification*/
4617 @d line_skip glue_par(line_skip_code)
4618 @d baseline_skip glue_par(baseline_skip_code)
4619 @d par_skip glue_par(par_skip_code)
4620 @d above_display_skip glue_par(above_display_skip_code)
4621 @d below_display_skip glue_par(below_display_skip_code)
4622 @d above_display_short_skip glue_par(above_display_short_skip_code)
4623 @d below_display_short_skip glue_par(below_display_short_skip_code)
4624 @d left_skip glue_par(left_skip_code)
4625 @d right_skip glue_par(right_skip_code)
4626 @d top_skip glue_par(top_skip_code)
4627 @d split_top_skip glue_par(split_top_skip_code)
4628 @d tab_skip glue_par(tab_skip_code)
4629 @d space_skip glue_par(space_skip_code)
4630 @d xspace_skip glue_par(xspace_skip_code)
4631 @d par_fill_skip glue_par(par_fill_skip_code)
4632 @d thin_mu_skip glue_par(thin_mu_skip_code)
4633 @d med_mu_skip glue_par(med_mu_skip_code)
4634 @d thick_mu_skip glue_par(thick_mu_skip_code)
4635
4636 @<Current |mem| equivalent of glue parameter number |n|@>=glue_par(n)
4637
4638 @ Sometimes we need to convert \TeX's internal code numbers into symbolic
4639 form. The |print_skip_param| routine gives the symbolic name of a glue
4640 parameter.
4641
4642 @<Declare the procedure called |print_skip_param|@>=
4643 static void print_skip_param(int @!n)
4644 {@+switch (n) {
4645 case line_skip_code: print_esc("lineskip");@+break;
4646 case baseline_skip_code: print_esc("baselineskip");@+break;
4647 case par_skip_code: print_esc("parskip");@+break;
4648 case above_display_skip_code: print_esc("abovedisplayskip");@+break;
4649 case below_display_skip_code: print_esc("belowdisplayskip");@+break;
4650 case above_display_short_skip_code: print_esc("abovedisplayshortskip");@+break;
4651 case below_display_short_skip_code: print_esc("belowdisplayshortskip");@+break;
4652 case left_skip_code: print_esc("leftskip");@+break;
4653 case right_skip_code: print_esc("rightskip");@+break;
4654 case top_skip_code: print_esc("topskip");@+break;
4655 case split_top_skip_code: print_esc("splittopskip");@+break;
4656 case tab_skip_code: print_esc("tabskip");@+break;
4657 case space_skip_code: print_esc("spaceskip");@+break;
4658 case xspace_skip_code: print_esc("xspaceskip");@+break;
4659 case par_fill_skip_code: print_esc("parfillskip");@+break;
4660 case thin_mu_skip_code: print_esc("thinmuskip");@+break;
4661 case med_mu_skip_code: print_esc("medmuskip");@+break;
4662 case thick_mu_skip_code: print_esc("thickmuskip");@+break;
4663 default:print("[unknown glue parameter!]");
4664 }
4665 }
4666
4667 @ The symbolic names for glue parameters are put into \TeX's hash table
4668 by using the routine called |primitive|, defined below. Let us enter them
4669 now, so that we don't have to list all those parameter names anywhere else.
4670
4671 @<Put each of \TeX's primitives into the hash table@>=
4672 primitive("lineskip", assign_glue, glue_base+line_skip_code);@/
4673 @!@:line\_skip\_}{\.{\\lineskip} primitive@>
4674 primitive("baselineskip", assign_glue, glue_base+baseline_skip_code);@/
4675 @!@:baseline\_skip\_}{\.{\\baselineskip} primitive@>
4676 primitive("parskip", assign_glue, glue_base+par_skip_code);@/
4677 @!@:par\_skip\_}{\.{\\parskip} primitive@>
4678 primitive("abovedisplayskip", assign_glue, glue_base+above_display_skip_code);@/
4679 @!@:above\_display\_skip\_}{\.{\\abovedisplayskip} primitive@>
4680 primitive("belowdisplayskip", assign_glue, glue_base+below_display_skip_code);@/
4681 @!@:below\_display\_skip\_}{\.{\\belowdisplayskip} primitive@>
4682 primitive("abovedisplayshortskip",
4683 assign_glue, glue_base+above_display_short_skip_code);@/
4684 @!@:above\_display\_short\_skip\_}{\.{\\abovedisplayshortskip} primitive@>
4685 primitive("belowdisplayshortskip",
4686 assign_glue, glue_base+below_display_short_skip_code);@/
4687 @!@:below\_display\_short\_skip\_}{\.{\\belowdisplayshortskip} primitive@>
4688 primitive("leftskip", assign_glue, glue_base+left_skip_code);@/
4689 @!@:left\_skip\_}{\.{\\leftskip} primitive@>
4690 primitive("rightskip", assign_glue, glue_base+right_skip_code);@/
4691 @!@:right\_skip\_}{\.{\\rightskip} primitive@>
4692 primitive("topskip", assign_glue, glue_base+top_skip_code);@/
4693 @!@:top\_skip\_}{\.{\\topskip} primitive@>
4694 primitive("splittopskip", assign_glue, glue_base+split_top_skip_code);@/
4695 @!@:split\_top\_skip\_}{\.{\\splittopskip} primitive@>
4696 primitive("tabskip", assign_glue, glue_base+tab_skip_code);@/
4697 @!@:tab\_skip\_}{\.{\\tabskip} primitive@>
4698 primitive("spaceskip", assign_glue, glue_base+space_skip_code);@/
4699 @!@:space\_skip\_}{\.{\\spaceskip} primitive@>
4700 primitive("xspaceskip", assign_glue, glue_base+xspace_skip_code);@/
4701 @!@:xspace\_skip\_}{\.{\\xspaceskip} primitive@>
4702 primitive("parfillskip", assign_glue, glue_base+par_fill_skip_code);@/
4703 @!@:par\_fill\_skip\_}{\.{\\parfillskip} primitive@>
4704 primitive("thinmuskip", assign_mu_glue, glue_base+thin_mu_skip_code);@/
4705 @!@:thin\_mu\_skip\_}{\.{\\thinmuskip} primitive@>
4706 primitive("medmuskip", assign_mu_glue, glue_base+med_mu_skip_code);@/
4707 @!@:med\_mu\_skip\_}{\.{\\medmuskip} primitive@>
4708 primitive("thickmuskip", assign_mu_glue, glue_base+thick_mu_skip_code);@/
4709 @!@:thick\_mu\_skip\_}{\.{\\thickmuskip} primitive@>
4710
4711 @ @<Cases of |print_cmd_chr| for symbolic printing of primitives@>=
4712 case assign_glue: case assign_mu_glue: if (chr_code < skip_base)
4713 print_skip_param(chr_code-glue_base);
4714 else if (chr_code < mu_skip_base)
4715 {@+print_esc("skip");print_int(chr_code-skip_base);
4716 }
4717 else{@+print_esc("muskip");print_int(chr_code-mu_skip_base);
4718 } @+break;
4719
4720 @ All glue parameters and registers are initially `\.{0pt plus0pt minus0pt}'.
4721
4722 @<Initialize table entries...@>=
4723 equiv(glue_base)=zero_glue;eq_level(glue_base)=level_one;
4724 eq_type(glue_base)=glue_ref;
4725 for (k=glue_base+1; k<=local_base-1; k++) eqtb[k]=eqtb[glue_base];
4726 glue_ref_count(zero_glue)=glue_ref_count(zero_glue)+local_base-glue_base;
4727
4728 @ @<Show equivalent |n|, in region 3@>=
4729 if (n < skip_base)
4730 {@+print_skip_param(n-glue_base);print_char('=');
4731 if (n < glue_base+thin_mu_skip_code) print_spec(equiv(n),"pt");
4732 else print_spec(equiv(n),"mu");
4733 }
4734 else if (n < mu_skip_base)
4735 {@+print_esc("skip");print_int(n-skip_base);print_char('=');
4736 print_spec(equiv(n),"pt");
4737 }
4738 else{@+print_esc("muskip");print_int(n-mu_skip_base);print_char('=');
4739 print_spec(equiv(n),"mu");
4740 }
4741
4742 @ Region 4 of |eqtb| contains the local quantities defined here. The
4743 bulk of this region is taken up by five tables that are indexed by eight-bit
4744 characters; these tables are important to both the syntactic and semantic
4745 portions of \TeX. There are also a bunch of special things like font and
4746 token parameters, as well as the tables of \.{\\toks} and \.{\\box}
4747 registers.
4748
4749 @d par_shape_loc local_base /*specifies paragraph shape*/
4750 @d output_routine_loc (local_base+1) /*points to token list for \.{\\output}*/
4751 @d every_par_loc (local_base+2) /*points to token list for \.{\\everypar}*/
4752 @d every_math_loc (local_base+3) /*points to token list for \.{\\everymath}*/
4753 @d every_display_loc (local_base+4) /*points to token list for \.{\\everydisplay}*/
4754 @d every_hbox_loc (local_base+5) /*points to token list for \.{\\everyhbox}*/
4755 @d every_vbox_loc (local_base+6) /*points to token list for \.{\\everyvbox}*/
4756 @d every_job_loc (local_base+7) /*points to token list for \.{\\everyjob}*/
4757 @d every_cr_loc (local_base+8) /*points to token list for \.{\\everycr}*/
4758 @d err_help_loc (local_base+9) /*points to token list for \.{\\errhelp}*/
4759 @d tex_toks (local_base+10) /*end of \TeX's token list parameters*/
4760 @#
4761 @d etex_toks_base tex_toks /*base for \eTeX's token list parameters*/
4762 @d every_eof_loc etex_toks_base /*points to token list for \.{\\everyeof}*/
4763 @d etex_toks (etex_toks_base+1) /*end of \eTeX's token list parameters*/
4764 @#
4765 @d toks_base etex_toks /*table of 256 token list registers*/
4766 @#
4767 @d etex_pen_base (toks_base+256) /*start of table of \eTeX's penalties*/
4768 @d inter_line_penalties_loc etex_pen_base /*additional penalties between lines*/
4769 @d club_penalties_loc (etex_pen_base+1) /*penalties for creating club lines*/
4770 @d widow_penalties_loc (etex_pen_base+2) /*penalties for creating widow lines*/
4771 @d display_widow_penalties_loc (etex_pen_base+3) /*ditto, just before a display*/
4772 @d etex_pens (etex_pen_base+4) /*end of table of \eTeX's penalties*/
4773 @#
4774 @d box_base etex_pens /*table of 256 box registers*/
4775 @d cur_font_loc (box_base+256) /*internal font number outside math mode*/
4776 @d math_font_base (cur_font_loc+1) /*table of 48 math font numbers*/
4777 @d cat_code_base (math_font_base+48) /*table of 256 command codes (the ``catcodes'')*/
4778 @d sf_code_base (cat_code_base+256) /*table of 256 spacefactor mappings*/
4779 @d math_code_base (sf_code_base+256) /*table of 256 math mode mappings*/
4780 @d int_base (math_code_base+256) /*beginning of region 5*/
4781 @#
4782 @d utf_base_skip 0x200000 /*distance of utf bases, $\hbox{power of 2} > |0x10FFFF|$*/
4783 @d utf_cp_mask (utf_base_skip-1)
4784 @d utf_base_mask (~utf_cp_mask)
4785 @d utf_first_base ((eqtb_size+1+utf_cp_mask)&utf_base_mask) /*$\hbox{first multiple of |utf_base_skip|} > |eqtb_size|$*/
4786 @d utf_cat_code_base utf_first_base /*0x110000 command codes (the ``catcodes'')*/
4787 @d utf_sf_code_base (utf_cat_code_base+utf_base_skip) /*0x110000 spacefactor mappings*/
4788 @d utf_del_code_base (utf_sf_code_base+utf_base_skip) /*0x110000 delimiter mappings*/
4789 @d utf_math_code_base (utf_del_code_base+utf_base_skip) /*0x110000 mathcode mappings*/
4790 @d utf_math_codenum_base (utf_math_code_base+utf_base_skip) /*0x110000 mathcodenum mappings*/
4791 @d utf_lc_code_base (utf_math_codenum_base+utf_base_skip) /*0x110000 lowercase mappings*/
4792 @d utf_uc_code_base (utf_lc_code_base+utf_base_skip) /*0x110000 uppercase mappings*/
4793 @d utf_code_limit (utf_uc_code_base+utf_base_skip) /*upper bound*/
4794 @#
4795 @d par_shape_ptr equiv(par_shape_loc)
4796 @d output_routine equiv(output_routine_loc)
4797 @d every_par equiv(every_par_loc)
4798 @d every_math equiv(every_math_loc)
4799 @d every_display equiv(every_display_loc)
4800 @d every_hbox equiv(every_hbox_loc)
4801 @d every_vbox equiv(every_vbox_loc)
4802 @d every_job equiv(every_job_loc)
4803 @d every_cr equiv(every_cr_loc)
4804 @d err_help equiv(err_help_loc)
4805 @d toks(X) equiv(toks_base+X)
4806 @d box(A) equiv(box_base+A)
4807 @d cur_font equiv(cur_font_loc)
4808 @d fam_fnt(A) equiv(math_font_base+A)
4809 @d cat_code(A) ((A)<0x100?equiv(cat_code_base+A):utf_catcode(A))
4810 @d lc_code(A) utf_lccode(A)
4811 @d uc_code(A) utf_uccode(A)
4812 @d sf_code(A) ((A)<0x100?equiv(sf_code_base+A):utf_sfcode(A))
4813 @d math_code(A) ((A)<0x100?equiv(math_code_base+A):utf_mathcode(A))
4814 /*Note: |math_code(c)| is the true math code plus |min_halfword|*/
4815
4816 @<Put each...@>=
4817 primitive("output", assign_toks, output_routine_loc);
4818 @!@:output\_}{\.{\\output} primitive@>
4819 primitive("everypar", assign_toks, every_par_loc);
4820 @!@:every\_par\_}{\.{\\everypar} primitive@>
4821 primitive("everymath", assign_toks, every_math_loc);
4822 @!@:every\_math\_}{\.{\\everymath} primitive@>
4823 primitive("everydisplay", assign_toks, every_display_loc);
4824 @!@:every\_display\_}{\.{\\everydisplay} primitive@>
4825 primitive("everyhbox", assign_toks, every_hbox_loc);
4826 @!@:every\_hbox\_}{\.{\\everyhbox} primitive@>
4827 primitive("everyvbox", assign_toks, every_vbox_loc);
4828 @!@:every\_vbox\_}{\.{\\everyvbox} primitive@>
4829 primitive("everyjob", assign_toks, every_job_loc);
4830 @!@:every\_job\_}{\.{\\everyjob} primitive@>
4831 primitive("everycr", assign_toks, every_cr_loc);
4832 @!@:every\_cr\_}{\.{\\everycr} primitive@>
4833 primitive("errhelp", assign_toks, err_help_loc);
4834 @!@:err\_help\_}{\.{\\errhelp} primitive@>
4835
4836 @ @<Cases of |print_cmd_chr|...@>=
4837 case assign_toks: if (chr_code >= toks_base)
4838 {@+print_esc("toks");print_int(chr_code-toks_base);
4839 }
4840 else switch (chr_code) {
4841 case output_routine_loc: print_esc("output");@+break;
4842 case every_par_loc: print_esc("everypar");@+break;
4843 case every_math_loc: print_esc("everymath");@+break;
4844 case every_display_loc: print_esc("everydisplay");@+break;
4845 case every_hbox_loc: print_esc("everyhbox");@+break;
4846 case every_vbox_loc: print_esc("everyvbox");@+break;
4847 case every_job_loc: print_esc("everyjob");@+break;
4848 case every_cr_loc: print_esc("everycr");@+break;
4849 @/@<Cases of |assign_toks| for |print_cmd_chr|@>@/
4850 default:print_esc("errhelp");
4851 } @+break;
4852
4853 @ We initialize most things to null or undefined values. An undefined font
4854 is represented by the internal code |font_base|.
4855
4856 However, the character code tables are given initial values based on the
4857 conventional interpretation of ASCII code. These initial values should
4858 not be changed when \TeX\ is adapted for use with non-English languages;
4859 all changes to the initialization conventions should be made in format
4860 packages, not in \TeX\ itself, so that global interchange of formats is
4861 possible.
4862
4863 @d null_font font_base
4864 @d utf_var_code (7<<21) /*new utf math code meaning ``use the current family''*/
4865
4866 @<Initialize table entries...@>=
4867 par_shape_ptr=null;eq_type(par_shape_loc)=shape_ref;
4868 eq_level(par_shape_loc)=level_one;@/
4869 for (k=etex_pen_base; k<=etex_pens-1; k++)
4870 eqtb[k]=eqtb[par_shape_loc];
4871 for (k=output_routine_loc; k<=toks_base+255; k++)
4872 eqtb[k]=eqtb[undefined_control_sequence];
4873 box(0)=null;eq_type(box_base)=box_ref;eq_level(box_base)=level_one;
4874 for (k=box_base+1; k<=box_base+255; k++) eqtb[k]=eqtb[box_base];
4875 cur_font=null_font;eq_type(cur_font_loc)=data;
4876 eq_level(cur_font_loc)=level_one;@/
4877 for (k=math_font_base; k<=math_font_base+47; k++) eqtb[k]=eqtb[cur_font_loc];
4878 equiv(cat_code_base)=0;eq_type(cat_code_base)=data;
4879 eq_level(cat_code_base)=level_one;@/
4880 for (k=cat_code_base+1; k<=int_base-1; k++) eqtb[k]=eqtb[cat_code_base];
4881 for (k=0; k<=255; k++)
4882 {@+equiv(cat_code_base+k)=other_char;equiv(math_code_base+k)=hi(k);
4883 equiv(sf_code_base+k)=1000;
4884 }
4885 equiv(cat_code_base+carriage_return)=car_ret;equiv(cat_code_base+' ')=spacer;
4886 equiv(cat_code_base+'\\')=escape;equiv(cat_code_base+'%')=comment;
4887 equiv(cat_code_base+invalid_code)=invalid_char;equiv(cat_code_base+null_code)=ignore;
4888 for (k='0'; k<='9'; k++) equiv(math_code_base+k)=hi(k+utf_var_code);
4889 for (k='A'; k<='Z'; k++)
4890 {@+equiv(cat_code_base+k)=letter;equiv(cat_code_base+k+'a'-'A')=letter;@/
4891 equiv(math_code_base+k)=k+utf_var_code+(1<<24);
4892 equiv(math_code_base+k+'a'-'A')=hi(k+'a'-'A'+utf_var_code+(1<<24));@/
4893 equiv(sf_code_base+k)=999;
4894 #if 0
4895 lc_code(k)=k+'a'-'A';lc_code(k+'a'-'A')=k+'a'-'A';@/
4896 uc_code(k)=k;uc_code(k+'a'-'A')=k;@/
4897 #endif
4898 }
4899 @<Fix some character code assignments for UTF@>@;
4900
4901 @ @<Show equivalent |n|, in region 4@>=
4902 if ((n==par_shape_loc)||((n >= etex_pen_base)&&(n < etex_pens)))
4903 {@+print_cmd_chr(set_shape, n);print_char('=');
4904 if (equiv(n)==null) print_char('0');
4905 else if (n > par_shape_loc)
4906 {@+print_int(penalty(equiv(n)));print_char(' ');
4907 print_int(penalty(equiv(n)+1));
4908 if (penalty(equiv(n)) > 1) print_esc("ETC.");
4909 }
4910 else print_int(info(par_shape_ptr));
4911 }
4912 else if (n < toks_base)
4913 {@+print_cmd_chr(assign_toks, n);print_char('=');
4914 if (equiv(n)!=null) show_token_list(link(equiv(n)), null, 32);
4915 }
4916 else if (n < box_base)
4917 {@+print_esc("toks");print_int(n-toks_base);print_char('=');
4918 if (equiv(n)!=null) show_token_list(link(equiv(n)), null, 32);
4919 }
4920 else if (n < cur_font_loc)
4921 {@+print_esc("box");print_int(n-box_base);print_char('=');
4922 if (equiv(n)==null) print("void");
4923 else{@+depth_threshold=0;breadth_max=1;show_node_list(equiv(n));
4924 }
4925 }
4926 else if (n < cat_code_base) @<Show the font identifier in |eqtb[n]|@>@;
4927 else@<Show the halfword code in |eqtb[n]|@>@;
4928
4929 @ @<Show the font identifier in |eqtb[n]|@>=
4930 {@+if (n==cur_font_loc) print("current font");
4931 else if (n < math_font_base+16)
4932 {@+print_esc("textfont");print_int(n-math_font_base);
4933 }
4934 else if (n < math_font_base+32)
4935 {@+print_esc("scriptfont");print_int(n-math_font_base-16);
4936 }
4937 else{@+print_esc("scriptscriptfont");print_int(n-math_font_base-32);
4938 }
4939 print_char('=');@/
4940 printn_esc(hash[font_id_base+equiv(n)].rh);
4941 /*that's |font_id_text(equiv(n))|*/
4942 }
4943
4944 @ @<Show the halfword code in |eqtb[n]|@>=
4945 if (n < math_code_base)
4946 {@+if (n < math_code_base)
4947 {@+print_esc("catcode");print_int(n-cat_code_base);
4948 print_char('=');print_int(equiv(n));
4949 }
4950 else
4951 {@+print("This information should be in the utf tables");
4952 }
4953 }
4954 else{@+print_esc("mathcode");print_int(n-math_code_base);
4955 print_char('=');print_int(ho(equiv(n)));
4956 }
4957
4958 @ Region 5 of |eqtb| contains the integer parameters and registers defined
4959 here, as well as the |del_code| table. The latter table differs from the
4960 |cat_code dotdot math_code| tables that precede it, since delimiter codes are
4961 fullword integers while the other kinds of codes occupy at most a
4962 halfword. This is what makes region~5 different from region~4. We will
4963 store the |eq_level| information in an auxiliary array of quarterwords
4964 that will be defined later.
4965
4966 @d pretolerance_code 0 /*badness tolerance before hyphenation*/
4967 @d tolerance_code 1 /*badness tolerance after hyphenation*/
4968 @d line_penalty_code 2 /*added to the badness of every line*/
4969 @d hyphen_penalty_code 3 /*penalty for break after discretionary hyphen*/
4970 @d ex_hyphen_penalty_code 4 /*penalty for break after explicit hyphen*/
4971 @d club_penalty_code 5 /*penalty for creating a club line*/
4972 @d widow_penalty_code 6 /*penalty for creating a widow line*/
4973 @d display_widow_penalty_code 7 /*ditto, just before a display*/
4974 @d broken_penalty_code 8 /*penalty for breaking a page at a broken line*/
4975 @d bin_op_penalty_code 9 /*penalty for breaking after a binary operation*/
4976 @d rel_penalty_code 10 /*penalty for breaking after a relation*/
4977 @d pre_display_penalty_code 11
4978 /*penalty for breaking just before a displayed formula*/
4979 @d post_display_penalty_code 12
4980 /*penalty for breaking just after a displayed formula*/
4981 @d inter_line_penalty_code 13 /*additional penalty between lines*/
4982 @d double_hyphen_demerits_code 14 /*demerits for double hyphen break*/
4983 @d final_hyphen_demerits_code 15 /*demerits for final hyphen break*/
4984 @d adj_demerits_code 16 /*demerits for adjacent incompatible lines*/
4985 @d mag_code 17 /*magnification ratio*/
4986 @d delimiter_factor_code 18 /*ratio for variable-size delimiters*/
4987 @d looseness_code 19 /*change in number of lines for a paragraph*/
4988 @d time_code 20 /*current time of day*/
4989 @d day_code 21 /*current day of the month*/
4990 @d month_code 22 /*current month of the year*/
4991 @d year_code 23 /*current year of our Lord*/
4992 @d show_box_breadth_code 24 /*nodes per level in |show_box|*/
4993 @d show_box_depth_code 25 /*maximum level in |show_box|*/
4994 @d hbadness_code 26 /*hboxes exceeding this badness will be shown by |hpack|*/
4995 @d vbadness_code 27 /*vboxes exceeding this badness will be shown by |vpack|*/
4996 @d pausing_code 28 /*pause after each line is read from a file*/
4997 @d tracing_online_code 29 /*show diagnostic output on terminal*/
4998 @d tracing_macros_code 30 /*show macros as they are being expanded*/
4999 @d tracing_stats_code 31 /*show memory usage if \TeX\ knows it*/
5000 @d tracing_paragraphs_code 32 /*show line-break calculations*/
5001 @d tracing_pages_code 33 /*show page-break calculations*/
5002 @d tracing_output_code 34 /*show boxes when they are shipped out*/
5003 @d tracing_lost_chars_code 35 /*show characters that aren't in the font*/
5004 @d tracing_commands_code 36 /*show command codes at |big_switch|*/
5005 @d tracing_restores_code 37 /*show equivalents when they are restored*/
5006 @d uc_hyph_code 38 /*hyphenate words beginning with a capital letter*/
5007 @d output_penalty_code 39 /*penalty found at current page break*/
5008 @d max_dead_cycles_code 40 /*bound on consecutive dead cycles of output*/
5009 @d hang_after_code 41 /*hanging indentation changes after this many lines*/
5010 @d floating_penalty_code 42 /*penalty for insertions held over after a split*/
5011 @d global_defs_code 43 /*override \.{\\global} specifications*/
5012 @d cur_fam_code 44 /*current family*/
5013 @d escape_char_code 45 /*escape character for token output*/
5014 @d default_hyphen_char_code 46 /*value of \.{\\hyphenchar} when a font is loaded*/
5015 @d default_skew_char_code 47 /*value of \.{\\skewchar} when a font is loaded*/
5016 @d end_line_char_code 48 /*character placed at the right end of the buffer*/
5017 @d new_line_char_code 49 /*character that prints as |print_ln|*/
5018 @d language_code 50 /*current hyphenation table*/
5019 @d left_hyphen_min_code 51 /*minimum left hyphenation fragment size*/
5020 @d right_hyphen_min_code 52 /*minimum right hyphenation fragment size*/
5021 @d holding_inserts_code 53 /*do not remove insertion nodes from \.{\\box255}*/
5022 @d error_context_lines_code 54 /*maximum intermediate line pairs shown*/
5023 @d tracing_stack_levels_code 55 /*tracing |input_stack| level if |tracingmacros| positive*/
5024 @d tracing_fonts_code 56 /*tracing specification, finding, and loading of fonts*/
5025 @d tex_int_pars 57 /*total number of \TeX's integer parameters*/
5026 @#
5027 @d etex_int_base tex_int_pars /*base for \eTeX's integer parameters*/
5028 @d tracing_assigns_code etex_int_base /*show assignments*/
5029 @d tracing_groups_code (etex_int_base+1) /*show save/restore groups*/
5030 @d tracing_ifs_code (etex_int_base+2) /*show conditionals*/
5031 @d tracing_scan_tokens_code (etex_int_base+3) /*show pseudo file open and close*/
5032 @d tracing_nesting_code (etex_int_base+4) /*show incomplete groups and ifs within files*/
5033 @d saving_vdiscards_code (etex_int_base+5) /*save items discarded from vlists*/
5034 @d saving_hyph_codes_code (etex_int_base+6) /*save hyphenation codes for languages*/
5035 @d expand_depth_code (etex_int_base+7) /*maximum depth for expansion---\eTeX*/
5036 @d ignore_primitive_error_code (etex_int_base+8) /*ignore some primitive/engine errors*/
5037 @d eTeX_state_code (etex_int_base+9) /*\eTeX\ state variables*/
5038 @d etex_int_pars (eTeX_state_code+eTeX_states) /*total number of \eTeX's integer parameters*/
5039 @#
5040 @d int_pars etex_int_pars /*total number of integer parameters*/
5041 @d count_base (int_base+int_pars) /*256 user \.{\\count} registers*/
5042 @d del_code_base (count_base+256) /*256 delimiter code mappings*/
5043 @d dimen_base (del_code_base+256) /*beginning of region 6*/
5044 @#
5045 @d del_code(A) ((A)<0x100?eqtb[del_code_base+A].i:utf_delcode(A))
5046 @d count(A) eqtb[count_base+A].i
5047 @d int_par(A) eqtb[int_base+A].i /*an integer parameter*/
5048 @d pretolerance int_par(pretolerance_code)
5049 @d tolerance int_par(tolerance_code)
5050 @d line_penalty int_par(line_penalty_code)
5051 @d hyphen_penalty int_par(hyphen_penalty_code)
5052 @d ex_hyphen_penalty int_par(ex_hyphen_penalty_code)
5053 @d club_penalty int_par(club_penalty_code)
5054 @d widow_penalty int_par(widow_penalty_code)
5055 @d display_widow_penalty int_par(display_widow_penalty_code)
5056 @d broken_penalty int_par(broken_penalty_code)
5057 @d bin_op_penalty int_par(bin_op_penalty_code)
5058 @d rel_penalty int_par(rel_penalty_code)
5059 @d pre_display_penalty int_par(pre_display_penalty_code)
5060 @d post_display_penalty int_par(post_display_penalty_code)
5061 @d inter_line_penalty int_par(inter_line_penalty_code)
5062 @d double_hyphen_demerits int_par(double_hyphen_demerits_code)
5063 @d final_hyphen_demerits int_par(final_hyphen_demerits_code)
5064 @d adj_demerits int_par(adj_demerits_code)
5065 @d mag int_par(mag_code)
5066 @d delimiter_factor int_par(delimiter_factor_code)
5067 @d looseness int_par(looseness_code)
5068 @d time int_par(time_code)
5069 @d day int_par(day_code)
5070 @d month int_par(month_code)
5071 @d year int_par(year_code)
5072 @d show_box_breadth int_par(show_box_breadth_code)
5073 @d show_box_depth int_par(show_box_depth_code)
5074 @d hbadness int_par(hbadness_code)
5075 @d vbadness int_par(vbadness_code)
5076 @d pausing int_par(pausing_code)
5077 @d tracing_online int_par(tracing_online_code)
5078 @d tracing_macros int_par(tracing_macros_code)
5079 @d tracing_stats int_par(tracing_stats_code)
5080 @d tracing_paragraphs int_par(tracing_paragraphs_code)
5081 @d tracing_pages int_par(tracing_pages_code)
5082 @d tracing_output int_par(tracing_output_code)
5083 @d tracing_lost_chars int_par(tracing_lost_chars_code)
5084 @d tracing_commands int_par(tracing_commands_code)
5085 @d tracing_restores int_par(tracing_restores_code)
5086 @d uc_hyph int_par(uc_hyph_code)
5087 @d output_penalty int_par(output_penalty_code)
5088 @d max_dead_cycles int_par(max_dead_cycles_code)
5089 @d hang_after int_par(hang_after_code)
5090 @d floating_penalty int_par(floating_penalty_code)
5091 @d global_defs int_par(global_defs_code)
5092 @d cur_fam int_par(cur_fam_code)
5093 @d escape_char int_par(escape_char_code)
5094 @d default_hyphen_char int_par(default_hyphen_char_code)
5095 @d default_skew_char int_par(default_skew_char_code)
5096 @d end_line_char int_par(end_line_char_code)
5097 @d new_line_char int_par(new_line_char_code)
5098 @d language int_par(language_code)
5099 @d left_hyphen_min int_par(left_hyphen_min_code)
5100 @d right_hyphen_min int_par(right_hyphen_min_code)
5101 @d holding_inserts int_par(holding_inserts_code)
5102 @d error_context_lines int_par(error_context_lines_code)
5103 @d tracing_stack_levels int_par(tracing_stack_levels_code)
5104 @d tracing_fonts int_par(tracing_fonts_code)
5105 @#
5106 @d tracing_assigns int_par(tracing_assigns_code)
5107 @d tracing_groups int_par(tracing_groups_code)
5108 @d tracing_ifs int_par(tracing_ifs_code)
5109 @d tracing_scan_tokens int_par(tracing_scan_tokens_code)
5110 @d tracing_nesting int_par(tracing_nesting_code)
5111 @d saving_vdiscards int_par(saving_vdiscards_code)
5112 @d saving_hyph_codes int_par(saving_hyph_codes_code)
5113 @d expand_depth int_par(expand_depth_code)
5114 @d ignore_primitive_error int_par(ignore_primitive_error_code)
5115 @d ignore_infinite_glue_shrinkage_bit 1
5116
5117 @<Assign the values |depth_threshold:=show_box_depth|...@>=
5118 depth_threshold=show_box_depth;
5119 breadth_max=show_box_breadth
5120
5121 @ We can print the symbolic name of an integer parameter as follows.
5122
5123 @p static void print_param(int @!n)
5124 {@+switch (n) {
5125 case pretolerance_code: print_esc("pretolerance");@+break;
5126 case tolerance_code: print_esc("tolerance");@+break;
5127 case line_penalty_code: print_esc("linepenalty");@+break;
5128 case hyphen_penalty_code: print_esc("hyphenpenalty");@+break;
5129 case ex_hyphen_penalty_code: print_esc("exhyphenpenalty");@+break;
5130 case club_penalty_code: print_esc("clubpenalty");@+break;
5131 case widow_penalty_code: print_esc("widowpenalty");@+break;
5132 case display_widow_penalty_code: print_esc("displaywidowpenalty");@+break;
5133 case broken_penalty_code: print_esc("brokenpenalty");@+break;
5134 case bin_op_penalty_code: print_esc("binoppenalty");@+break;
5135 case rel_penalty_code: print_esc("relpenalty");@+break;
5136 case pre_display_penalty_code: print_esc("predisplaypenalty");@+break;
5137 case post_display_penalty_code: print_esc("postdisplaypenalty");@+break;
5138 case inter_line_penalty_code: print_esc("interlinepenalty");@+break;
5139 case double_hyphen_demerits_code: print_esc("doublehyphendemerits");@+break;
5140 case final_hyphen_demerits_code: print_esc("finalhyphendemerits");@+break;
5141 case adj_demerits_code: print_esc("adjdemerits");@+break;
5142 case mag_code: print_esc("mag");@+break;
5143 case delimiter_factor_code: print_esc("delimiterfactor");@+break;
5144 case looseness_code: print_esc("looseness");@+break;
5145 case time_code: print_esc("time");@+break;
5146 case day_code: print_esc("day");@+break;
5147 case month_code: print_esc("month");@+break;
5148 case year_code: print_esc("year");@+break;
5149 case show_box_breadth_code: print_esc("showboxbreadth");@+break;
5150 case show_box_depth_code: print_esc("showboxdepth");@+break;
5151 case hbadness_code: print_esc("hbadness");@+break;
5152 case vbadness_code: print_esc("vbadness");@+break;
5153 case pausing_code: print_esc("pausing");@+break;
5154 case tracing_online_code: print_esc("tracingonline");@+break;
5155 case tracing_macros_code: print_esc("tracingmacros");@+break;
5156 case tracing_stats_code: print_esc("tracingstats");@+break;
5157 case tracing_paragraphs_code: print_esc("tracingparagraphs");@+break;
5158 case tracing_pages_code: print_esc("tracingpages");@+break;
5159 case tracing_output_code: print_esc("tracingoutput");@+break;
5160 case tracing_lost_chars_code: print_esc("tracinglostchars");@+break;
5161 case tracing_commands_code: print_esc("tracingcommands");@+break;
5162 case tracing_restores_code: print_esc("tracingrestores");@+break;
5163 case uc_hyph_code: print_esc("uchyph");@+break;
5164 case output_penalty_code: print_esc("outputpenalty");@+break;
5165 case max_dead_cycles_code: print_esc("maxdeadcycles");@+break;
5166 case hang_after_code: print_esc("hangafter");@+break;
5167 case floating_penalty_code: print_esc("floatingpenalty");@+break;
5168 case global_defs_code: print_esc("globaldefs");@+break;
5169 case cur_fam_code: print_esc("fam");@+break;
5170 case escape_char_code: print_esc("escapechar");@+break;
5171 case default_hyphen_char_code: print_esc("defaulthyphenchar");@+break;
5172 case default_skew_char_code: print_esc("defaultskewchar");@+break;
5173 case end_line_char_code: print_esc("endlinechar");@+break;
5174 case new_line_char_code: print_esc("newlinechar");@+break;
5175 case language_code: print_esc("language");@+break;
5176 case left_hyphen_min_code: print_esc("lefthyphenmin");@+break;
5177 case right_hyphen_min_code: print_esc("righthyphenmin");@+break;
5178 case holding_inserts_code: print_esc("holdinginserts");@+break;
5179 case error_context_lines_code: print_esc("errorcontextlines");@+break;
5180 case tracing_stack_levels_code: print_esc("tracingstacklevels");@+break;
5181 case tracing_fonts_code: print_esc("tracingfonts");@+break;
5182 @/@<Cases for |print_param|@>@/
5183 default:print("[unknown integer parameter!]");
5184 }
5185 }
5186
5187 @ The integer parameter names must be entered into the hash table.
5188
5189 @<Put each...@>=
5190 primitive("pretolerance", assign_int, int_base+pretolerance_code);@/
5191 @!@:pretolerance\_}{\.{\\pretolerance} primitive@>
5192 primitive("tolerance", assign_int, int_base+tolerance_code);@/
5193 @!@:tolerance\_}{\.{\\tolerance} primitive@>
5194 primitive("linepenalty", assign_int, int_base+line_penalty_code);@/
5195 @!@:line\_penalty\_}{\.{\\linepenalty} primitive@>
5196 primitive("hyphenpenalty", assign_int, int_base+hyphen_penalty_code);@/
5197 @!@:hyphen\_penalty\_}{\.{\\hyphenpenalty} primitive@>
5198 primitive("exhyphenpenalty", assign_int, int_base+ex_hyphen_penalty_code);@/
5199 @!@:ex\_hyphen\_penalty\_}{\.{\\exhyphenpenalty} primitive@>
5200 primitive("clubpenalty", assign_int, int_base+club_penalty_code);@/
5201 @!@:club\_penalty\_}{\.{\\clubpenalty} primitive@>
5202 primitive("widowpenalty", assign_int, int_base+widow_penalty_code);@/
5203 @!@:widow\_penalty\_}{\.{\\widowpenalty} primitive@>
5204 primitive("displaywidowpenalty",
5205 assign_int, int_base+display_widow_penalty_code);@/
5206 @!@:display\_widow\_penalty\_}{\.{\\displaywidowpenalty} primitive@>
5207 primitive("brokenpenalty", assign_int, int_base+broken_penalty_code);@/
5208 @!@:broken\_penalty\_}{\.{\\brokenpenalty} primitive@>
5209 primitive("binoppenalty", assign_int, int_base+bin_op_penalty_code);@/
5210 @!@:bin\_op\_penalty\_}{\.{\\binoppenalty} primitive@>
5211 primitive("relpenalty", assign_int, int_base+rel_penalty_code);@/
5212 @!@:rel\_penalty\_}{\.{\\relpenalty} primitive@>
5213 primitive("predisplaypenalty", assign_int, int_base+pre_display_penalty_code);@/
5214 @!@:pre\_display\_penalty\_}{\.{\\predisplaypenalty} primitive@>
5215 primitive("postdisplaypenalty", assign_int, int_base+post_display_penalty_code);@/
5216 @!@:post\_display\_penalty\_}{\.{\\postdisplaypenalty} primitive@>
5217 primitive("interlinepenalty", assign_int, int_base+inter_line_penalty_code);@/
5218 @!@:inter\_line\_penalty\_}{\.{\\interlinepenalty} primitive@>
5219 primitive("doublehyphendemerits",
5220 assign_int, int_base+double_hyphen_demerits_code);@/
5221 @!@:double\_hyphen\_demerits\_}{\.{\\doublehyphendemerits} primitive@>
5222 primitive("finalhyphendemerits",
5223 assign_int, int_base+final_hyphen_demerits_code);@/
5224 @!@:final\_hyphen\_demerits\_}{\.{\\finalhyphendemerits} primitive@>
5225 primitive("adjdemerits", assign_int, int_base+adj_demerits_code);@/
5226 @!@:adj\_demerits\_}{\.{\\adjdemerits} primitive@>
5227 primitive("mag", assign_int, int_base+mag_code);@/
5228 @!@:mag\_}{\.{\\mag} primitive@>
5229 primitive("delimiterfactor", assign_int, int_base+delimiter_factor_code);@/
5230 @!@:delimiter\_factor\_}{\.{\\delimiterfactor} primitive@>
5231 primitive("looseness", assign_int, int_base+looseness_code);@/
5232 @!@:looseness\_}{\.{\\looseness} primitive@>
5233 primitive("time", assign_int, int_base+time_code);@/
5234 @!@:time\_}{\.{\\time} primitive@>
5235 primitive("day", assign_int, int_base+day_code);@/
5236 @!@:day\_}{\.{\\day} primitive@>
5237 primitive("month", assign_int, int_base+month_code);@/
5238 @!@:month\_}{\.{\\month} primitive@>
5239 primitive("year", assign_int, int_base+year_code);@/
5240 @!@:year\_}{\.{\\year} primitive@>
5241 primitive("showboxbreadth", assign_int, int_base+show_box_breadth_code);@/
5242 @!@:show\_box\_breadth\_}{\.{\\showboxbreadth} primitive@>
5243 primitive("showboxdepth", assign_int, int_base+show_box_depth_code);@/
5244 @!@:show\_box\_depth\_}{\.{\\showboxdepth} primitive@>
5245 primitive("hbadness", assign_int, int_base+hbadness_code);@/
5246 @!@:hbadness\_}{\.{\\hbadness} primitive@>
5247 primitive("vbadness", assign_int, int_base+vbadness_code);@/
5248 @!@:vbadness\_}{\.{\\vbadness} primitive@>
5249 primitive("pausing", assign_int, int_base+pausing_code);@/
5250 @!@:pausing\_}{\.{\\pausing} primitive@>
5251 primitive("tracingonline", assign_int, int_base+tracing_online_code);@/
5252 @!@:tracing\_online\_}{\.{\\tracingonline} primitive@>
5253 primitive("tracingmacros", assign_int, int_base+tracing_macros_code);@/
5254 @!@:tracing\_macros\_}{\.{\\tracingmacros} primitive@>
5255 primitive("tracingstats", assign_int, int_base+tracing_stats_code);@/
5256 @!@:tracing\_stats\_}{\.{\\tracingstats} primitive@>
5257 primitive("tracingparagraphs", assign_int, int_base+tracing_paragraphs_code);@/
5258 @!@:tracing\_paragraphs\_}{\.{\\tracingparagraphs} primitive@>
5259 primitive("tracingpages", assign_int, int_base+tracing_pages_code);@/
5260 @!@:tracing\_pages\_}{\.{\\tracingpages} primitive@>
5261 primitive("tracingoutput", assign_int, int_base+tracing_output_code);@/
5262 @!@:tracing\_output\_}{\.{\\tracingoutput} primitive@>
5263 primitive("tracinglostchars", assign_int, int_base+tracing_lost_chars_code);@/
5264 @!@:tracing\_lost\_chars\_}{\.{\\tracinglostchars} primitive@>
5265 primitive("tracingcommands", assign_int, int_base+tracing_commands_code);@/
5266 @!@:tracing\_commands\_}{\.{\\tracingcommands} primitive@>
5267 primitive("tracingrestores", assign_int, int_base+tracing_restores_code);@/
5268 @!@:tracing\_restores\_}{\.{\\tracingrestores} primitive@>
5269 primitive("uchyph", assign_int, int_base+uc_hyph_code);@/
5270 @!@:uc\_hyph\_}{\.{\\uchyph} primitive@>
5271 primitive("outputpenalty", assign_int, int_base+output_penalty_code);@/
5272 @!@:output\_penalty\_}{\.{\\outputpenalty} primitive@>
5273 primitive("maxdeadcycles", assign_int, int_base+max_dead_cycles_code);@/
5274 @!@:max\_dead\_cycles\_}{\.{\\maxdeadcycles} primitive@>
5275 primitive("hangafter", assign_int, int_base+hang_after_code);@/
5276 @!@:hang\_after\_}{\.{\\hangafter} primitive@>
5277 primitive("floatingpenalty", assign_int, int_base+floating_penalty_code);@/
5278 @!@:floating\_penalty\_}{\.{\\floatingpenalty} primitive@>
5279 primitive("globaldefs", assign_int, int_base+global_defs_code);@/
5280 @!@:global\_defs\_}{\.{\\globaldefs} primitive@>
5281 primitive("fam", assign_int, int_base+cur_fam_code);@/
5282 @!@:fam\_}{\.{\\fam} primitive@>
5283 primitive("escapechar", assign_int, int_base+escape_char_code);@/
5284 @!@:escape\_char\_}{\.{\\escapechar} primitive@>
5285 primitive("defaulthyphenchar", assign_int, int_base+default_hyphen_char_code);@/
5286 @!@:default\_hyphen\_char\_}{\.{\\defaulthyphenchar} primitive@>
5287 primitive("defaultskewchar", assign_int, int_base+default_skew_char_code);@/
5288 @!@:default\_skew\_char\_}{\.{\\defaultskewchar} primitive@>
5289 primitive("endlinechar", assign_int, int_base+end_line_char_code);@/
5290 @!@:end\_line\_char\_}{\.{\\endlinechar} primitive@>
5291 primitive("newlinechar", assign_int, int_base+new_line_char_code);@/
5292 @!@:new\_line\_char\_}{\.{\\newlinechar} primitive@>
5293 primitive("language", assign_int, int_base+language_code);@/
5294 @!@:language\_}{\.{\\language} primitive@>
5295 primitive("lefthyphenmin", assign_int, int_base+left_hyphen_min_code);@/
5296 @!@:left\_hyphen\_min\_}{\.{\\lefthyphenmin} primitive@>
5297 primitive("righthyphenmin", assign_int, int_base+right_hyphen_min_code);@/
5298 @!@:right\_hyphen\_min\_}{\.{\\righthyphenmin} primitive@>
5299 primitive("holdinginserts", assign_int, int_base+holding_inserts_code);@/
5300 @!@:holding\_inserts\_}{\.{\\holdinginserts} primitive@>
5301 primitive("errorcontextlines", assign_int, int_base+error_context_lines_code);@/
5302 @!@:error\_context\_lines\_}{\.{\\errorcontextlines} primitive@>
5303 primitive("tracingstacklevels", assign_int, int_base+tracing_stack_levels_code);@/
5304 @!@:tracing\_stack\_levels_}{\.{\\tracingstacklevels} primitive@>
5305 primitive("tracingfonts", assign_int, int_base+tracing_fonts_code);@/
5306 @!@:tracing\_fonts_}{\.{\\tracingfonts} primitive@>
5307
5308 @ @<Cases of |print_cmd_chr|...@>=
5309 case assign_int: if (chr_code < count_base) print_param(chr_code-int_base);
5310 else{@+print_esc("count");print_int(chr_code-count_base);
5311 } @+break;
5312
5313 @ The integer parameters should really be initialized by a macro package;
5314 the following initialization does the minimum to keep \TeX\ from
5315 complete failure.
5316 @^null delimiter@>
5317
5318 @<Initialize table entries...@>=
5319 for (k=int_base; k<=del_code_base-1; k++) eqtb[k].i=0;
5320 mag=1000;tolerance=10000;hang_after=1;max_dead_cycles=25;
5321 escape_char='\\';end_line_char=carriage_return;
5322 for (k=0; k<=255; k++) equiv(del_code_base+k)=-1;
5323 equiv(del_code_base+'.')=0; /*this null delimiter is used in error recovery*/
5324
5325 @ The following procedure, which is called just before \TeX\ initializes its
5326 input and output, establishes the initial values of the date and time.
5327 This does include too, for system integrators, the creation date and
5328 the reference moment for the timer---\Prote\ extensions. If the system
5329 supports environment variables, if |FORCE_SOURCE_DATE| is set to $1$ and
5330 |SOURCE_DATE_EPOCH| is set, the date related values: year, month, day
5331 and time, including creation date, will be taken relative from the value
5332 defined by |SOURCE_DATE_EPOCH|.
5333 @^creation date@>
5334 @^reference time@>
5335 @^system dependencies@>
5336 \TeX\ Live calls |tl_now| to obtain the current time as a |tm| structure.
5337 @p static void fix_date_and_time(void)
5338 {@+ struct tm *t=tl_now();
5339 time=sys_time= t->tm_hour*60+t->tm_min;/*minutes since midnight*/
5340 day=sys_day= t->tm_mday;/*day of the month*/
5341 month=sys_month=t->tm_mon+1;/*month of the year*/
5342 year=sys_year=t->tm_year+1900;/*Anno Domini*/
5343 }
5344
5345 @ @<Show equivalent |n|, in region 5@>=
5346 {@+if (n < count_base) print_param(n-int_base);
5347 else if (n < del_code_base)
5348 {@+print_esc("count");print_int(n-count_base);
5349 }
5350 else{@+print_esc("delcode");print_int(n-del_code_base);
5351 }
5352 print_char('=');print_int(eqtb[n].i);
5353 }
5354
5355 @ @<Set variable |c| to the current escape character@>=c=escape_char
5356
5357 @ @<Character |s| is the current new-line character@>=s==new_line_char
5358
5359 @ \TeX\ is occasionally supposed to print diagnostic information that
5360 goes only into the transcript file, unless |tracing_online| is positive.
5361 Here are two routines that adjust the destination of print commands:
5362
5363 @p static void begin_diagnostic(void) /*prepare to do some tracing*/
5364 {@+old_setting=selector;
5365 if ((tracing_online <= 0)&&(selector==term_and_log))
5366 {@+decr(selector);
5367 if (history==spotless) history=warning_issued;
5368 }
5369 }
5370 @#
5371 static void end_diagnostic(bool @!blank_line)
5372 /*restore proper conditions after tracing*/
5373 {@+print_nl("");
5374 if (blank_line) print_ln();
5375 selector=old_setting;
5376 }
5377
5378 @ Of course we had better declare a few more global variables, if the previous
5379 routines are going to work.
5380
5381 @<Glob...@>=
5382 static int @!old_setting;
5383 static int @!sys_time, @!sys_day, @!sys_month, @!sys_year;
5384 /*date and time supplied by external system*/
5385
5386 @ The final region of |eqtb| contains the dimension parameters defined
5387 here, and the 256 \.{\\dimen} registers.
5388
5389 @d par_indent_code 0 /*indentation of paragraphs*/
5390 @d math_surround_code 1 /*space around math in text*/
5391 @d line_skip_limit_code 2 /*threshold for |line_skip| instead of |baseline_skip|*/
5392 @d hsize_code 3 /*line width in horizontal mode*/
5393 @d vsize_code 4 /*page height in vertical mode*/
5394 @d max_depth_code 5 /*maximum depth of boxes on main pages*/
5395 @d split_max_depth_code 6 /*maximum depth of boxes on split pages*/
5396 @d box_max_depth_code 7 /*maximum depth of explicit vboxes*/
5397 @d hfuzz_code 8 /*tolerance for overfull hbox messages*/
5398 @d vfuzz_code 9 /*tolerance for overfull vbox messages*/
5399 @d delimiter_shortfall_code 10 /*maximum amount uncovered by variable delimiters*/
5400 @d null_delimiter_space_code 11 /*blank space in null delimiters*/
5401 @d script_space_code 12 /*extra space after subscript or superscript*/
5402 @d pre_display_size_code 13 /*length of text preceding a display*/
5403 @d display_width_code 14 /*length of line for displayed equation*/
5404 @d display_indent_code 15 /*indentation of line for displayed equation*/
5405 @d overfull_rule_code 16 /*width of rule that identifies overfull hboxes*/
5406 @d hang_indent_code 17 /*amount of hanging indentation*/
5407 @d h_offset_code 18 /*amount of horizontal offset when shipping pages out*/
5408 @d v_offset_code 19 /*amount of vertical offset when shipping pages out*/
5409 @d emergency_stretch_code 20 /*reduces badnesses on final pass of line-breaking*/
5410 @d page_width_code 21 /*current paper page width*/
5411 @d page_height_code 22 /*current paper page height*/
5412 @d dimen_pars 23 /*total number of dimension parameters*/
5413 @d scaled_base (dimen_base+dimen_pars)
5414 /*table of 256 user-defined \.{\\dimen} registers*/
5415 @d eqtb_size (scaled_base+255) /*largest subscript of |eqtb|*/
5416 @#
5417 @d dimen(A) eqtb[scaled_base+A].sc
5418 @d dimen_par(A) eqtb[dimen_base+A].sc /*a scaled quantity*/
5419 @d dimen_hfactor(A) hfactor_eqtb[scaled_base+A].sc
5420 @d dimen_vfactor(A) vfactor_eqtb[scaled_base+A].sc
5421 @d dimen_par_hfactor(A) hfactor_eqtb[dimen_base+A].sc
5422 @d dimen_par_vfactor(A) vfactor_eqtb[dimen_base+A].sc
5423 @d par_indent dimen_par(par_indent_code)
5424 @d math_surround dimen_par(math_surround_code)
5425 @d line_skip_limit dimen_par(line_skip_limit_code)
5426 @d hsize dimen_par(hsize_code)
5427 @d vsize dimen_par(vsize_code)
5428 @d max_depth dimen_par(max_depth_code)
5429 @d split_max_depth dimen_par(split_max_depth_code)
5430 @d box_max_depth dimen_par(box_max_depth_code)
5431 @d hfuzz dimen_par(hfuzz_code)
5432 @d vfuzz dimen_par(vfuzz_code)
5433 @d delimiter_shortfall dimen_par(delimiter_shortfall_code)
5434 @d null_delimiter_space dimen_par(null_delimiter_space_code)
5435 @d script_space dimen_par(script_space_code)
5436 @d pre_display_size dimen_par(pre_display_size_code)
5437 @d display_width dimen_par(display_width_code)
5438 @d display_indent dimen_par(display_indent_code)
5439 @d overfull_rule dimen_par(overfull_rule_code)
5440 @d hang_indent dimen_par(hang_indent_code)
5441 @d h_offset dimen_par(h_offset_code)
5442 @d v_offset dimen_par(v_offset_code)
5443 @d emergency_stretch dimen_par(emergency_stretch_code)
5444 @d page_height dimen_par(page_height_code)
5445
5446 @p static void print_length_param(int @!n)
5447 {@+switch (n) {
5448 case par_indent_code: print_esc("parindent");@+break;
5449 case math_surround_code: print_esc("mathsurround");@+break;
5450 case line_skip_limit_code: print_esc("lineskiplimit");@+break;
5451 case hsize_code: print_esc("hsize");@+break;
5452 case vsize_code: print_esc("vsize");@+break;
5453 case max_depth_code: print_esc("maxdepth");@+break;
5454 case split_max_depth_code: print_esc("splitmaxdepth");@+break;
5455 case box_max_depth_code: print_esc("boxmaxdepth");@+break;
5456 case hfuzz_code: print_esc("hfuzz");@+break;
5457 case vfuzz_code: print_esc("vfuzz");@+break;
5458 case delimiter_shortfall_code: print_esc("delimitershortfall");@+break;
5459 case null_delimiter_space_code: print_esc("nulldelimiterspace");@+break;
5460 case script_space_code: print_esc("scriptspace");@+break;
5461 case pre_display_size_code: print_esc("predisplaysize");@+break;
5462 case display_width_code: print_esc("displaywidth");@+break;
5463 case display_indent_code: print_esc("displayindent");@+break;
5464 case overfull_rule_code: print_esc("overfullrule");@+break;
5465 case hang_indent_code: print_esc("hangindent");@+break;
5466 case h_offset_code: print_esc("hoffset");@+break;
5467 case v_offset_code: print_esc("voffset");@+break;
5468 case emergency_stretch_code: print_esc("emergencystretch");@+break;
5469 case page_width_code: print_esc("pagewidth");@+break;
5470 case page_height_code: print_esc("pageheight");@+break;
5471 default:print("[unknown dimen parameter!]");
5472 }
5473 }
5474
5475 @ @<Put each...@>=
5476 primitive("parindent", assign_dimen, dimen_base+par_indent_code);@/
5477 @!@:par\_indent\_}{\.{\\parindent} primitive@>
5478 primitive("mathsurround", assign_dimen, dimen_base+math_surround_code);@/
5479 @!@:math\_surround\_}{\.{\\mathsurround} primitive@>
5480 primitive("lineskiplimit", assign_dimen, dimen_base+line_skip_limit_code);@/
5481 @!@:line\_skip\_limit\_}{\.{\\lineskiplimit} primitive@>
5482 primitive("hsize", assign_dimen, dimen_base+hsize_code);@/
5483 @!@:hsize\_}{\.{\\hsize} primitive@>
5484 primitive("vsize", assign_dimen, dimen_base+vsize_code);@/
5485 @!@:vsize\_}{\.{\\vsize} primitive@>
5486 primitive("maxdepth", assign_dimen, dimen_base+max_depth_code);@/
5487 @!@:max\_depth\_}{\.{\\maxdepth} primitive@>
5488 primitive("splitmaxdepth", assign_dimen, dimen_base+split_max_depth_code);@/
5489 @!@:split\_max\_depth\_}{\.{\\splitmaxdepth} primitive@>
5490 primitive("boxmaxdepth", assign_dimen, dimen_base+box_max_depth_code);@/
5491 @!@:box\_max\_depth\_}{\.{\\boxmaxdepth} primitive@>
5492 primitive("hfuzz", assign_dimen, dimen_base+hfuzz_code);@/
5493 @!@:hfuzz\_}{\.{\\hfuzz} primitive@>
5494 primitive("vfuzz", assign_dimen, dimen_base+vfuzz_code);@/
5495 @!@:vfuzz\_}{\.{\\vfuzz} primitive@>
5496 primitive("delimitershortfall",
5497 assign_dimen, dimen_base+delimiter_shortfall_code);@/
5498 @!@:delimiter\_shortfall\_}{\.{\\delimitershortfall} primitive@>
5499 primitive("nulldelimiterspace",
5500 assign_dimen, dimen_base+null_delimiter_space_code);@/
5501 @!@:null\_delimiter\_space\_}{\.{\\nulldelimiterspace} primitive@>
5502 primitive("scriptspace", assign_dimen, dimen_base+script_space_code);@/
5503 @!@:script\_space\_}{\.{\\scriptspace} primitive@>
5504 primitive("predisplaysize", assign_dimen, dimen_base+pre_display_size_code);@/
5505 @!@:pre\_display\_size\_}{\.{\\predisplaysize} primitive@>
5506 primitive("displaywidth", assign_dimen, dimen_base+display_width_code);@/
5507 @!@:display\_width\_}{\.{\\displaywidth} primitive@>
5508 primitive("displayindent", assign_dimen, dimen_base+display_indent_code);@/
5509 @!@:display\_indent\_}{\.{\\displayindent} primitive@>
5510 primitive("overfullrule", assign_dimen, dimen_base+overfull_rule_code);@/
5511 @!@:overfull\_rule\_}{\.{\\overfullrule} primitive@>
5512 primitive("hangindent", assign_dimen, dimen_base+hang_indent_code);@/
5513 @!@:hang\_indent\_}{\.{\\hangindent} primitive@>
5514 primitive("hoffset", assign_dimen, dimen_base+h_offset_code);@/
5515 @!@:h\_offset\_}{\.{\\hoffset} primitive@>
5516 primitive("voffset", assign_dimen, dimen_base+v_offset_code);@/
5517 @!@:v\_offset\_}{\.{\\voffset} primitive@>
5518 primitive("emergencystretch", assign_dimen, dimen_base+emergency_stretch_code);@/
5519 @!@:emergency\_stretch\_}{\.{\\emergencystretch} primitive@>
5520
5521 @ @<Cases of |print_cmd_chr|...@>=
5522 case assign_dimen: if (chr_code < scaled_base)
5523 print_length_param(chr_code-dimen_base);
5524 else{@+print_esc("dimen");print_int(chr_code-scaled_base);
5525 } @+break;
5526
5527 @ @<Initialize table entries...@>=
5528 for (k=dimen_base; k<=eqtb_size; k++) hfactor_eqtb[k].sc=vfactor_eqtb[k].sc=eqtb[k].sc=0;
5529
5530 @ @<Show equivalent |n|, in region 6@>=
5531 {@+if (n < scaled_base) print_length_param(n-dimen_base);
5532 else{@+print_esc("dimen");print_int(n-scaled_base);
5533 }
5534 print_char('=');print_scaled(eqtb[n].sc);print("pt");
5535 }
5536
5537 @ Here is a procedure that displays the contents of |eqtb[n]|
5538 symbolically.
5539
5540 @p @t\4@>@<Declare the procedure called |print_cmd_chr|@>@;@/
5541 #ifdef @!STAT
5542 static void show_eqtb(pointer @!n)
5543 {@+if (n < active_base) print_char('?'); /*this can't happen*/
5544 else if (n < glue_base) @<Show equivalent |n|, in region 1 or 2@>@;
5545 else if (n < local_base) @<Show equivalent |n|, in region 3@>@;
5546 else if (n < int_base) @<Show equivalent |n|, in region 4@>@;
5547 else if (n < dimen_base) @<Show equivalent |n|, in region 5@>@;
5548 else if (n <= eqtb_size) @<Show equivalent |n|, in region 6@>@;
5549 else if (n <= utf_code_limit) @<Show equivalent |n|, in the utf tables@>@;
5550 else print_char('?'); /*this can't happen either*/
5551 }
5552 #endif
5553
5554 @ The last two regions of |eqtb| have fullword values instead of the
5555 three fields |eq_level|, |eq_type|, and |equiv|. An |eq_type| is unnecessary,
5556 but \TeX\ needs to store the |eq_level| information in another array
5557 called |xeq_level|.
5558
5559 @<Glob...@>=
5560 static memory_word @!eqtb0[eqtb_size-active_base+1],
5561 *const @!eqtb = @!eqtb0-active_base;
5562 static memory_word hfactor_eqtb0[dimen_pars+256]={{{0}}},
5563 *const @!hfactor_eqtb = @!hfactor_eqtb0-dimen_base;
5564 static memory_word vfactor_eqtb0[dimen_pars+256]={{{0}}},
5565 *const @!vfactor_eqtb = @!vfactor_eqtb0-dimen_base;
5566 static scaled par_shape_hfactor=0, par_shape_vfactor=0;
5567 static scaled hhsize=0,hvsize=0;
5568 static quarterword @!xeq_level0[eqtb_size-int_base+1],
5569 *const @!xeq_level = @!xeq_level0-int_base;
5570
5571 @ @<Set init...@>=
5572 for (k=int_base; k<=eqtb_size; k++) xeq_level[k]=level_one;
5573
5574 @ When the debugging routine |search_mem| is looking for pointers having a
5575 given value, it is interested only in regions 1 to~3 of~|eqtb|, and in the
5576 first part of region~4.
5577
5578 @<Search |eqtb| for equivalents equal to |p|@>=
5579 for (q=active_base; q<=box_base+255; q++)
5580 {@+if (equiv(q)==p)
5581 {@+print_nl("EQUIV(");print_int(q);print_char(')');
5582 }
5583 }
5584
5585 @* The hash table.
5586 Control sequences are stored and retrieved by means of a fairly standard hash
5587 table algorithm called the method of ``coalescing lists'' (cf.\ Algorithm 6.4C
5588 in {\sl The Art of Computer Programming\/}). Once a control sequence enters the
5589 table, it is never removed, because there are complicated situations
5590 involving \.{\\gdef} where the removal of a control sequence at the end of
5591 a group would be a mistake preventable only by the introduction of a
5592 complicated reference-count mechanism.
5593
5594 The actual sequence of letters forming a control sequence identifier is
5595 stored in the |str_pool| array together with all the other strings. An
5596 auxiliary array |hash| consists of items with two halfword fields per
5597 word. The first of these, called |next(p)|, points to the next identifier
5598 belonging to the same coalesced list as the identifier corresponding to~|p|;
5599 and the other, called |text(p)|, points to the |str_start| entry for
5600 |p|'s identifier. If position~|p| of the hash table is empty, we have
5601 |text(p)==0|; if position |p| is either empty or the end of a coalesced
5602 hash list, we have |next(p)==0|. An auxiliary pointer variable called
5603 |hash_used| is maintained in such a way that all locations |p >= hash_used|
5604 are nonempty. The global variable |cs_count| tells how many multiletter
5605 control sequences have been defined, if statistics are being kept.
5606
5607 A global boolean variable called |no_new_control_sequence| is set to
5608 |true| during the time that new hash table entries are forbidden.
5609
5610 @d next(A) hash[A].lh /*link for coalesced lists*/
5611 @d text(A) hash[A].rh /*string number for control sequence name*/
5612 @d hash_is_full (hash_used==hash_base) /*test if all positions are occupied*/
5613 @d font_id_text(A) text(font_id_base+A) /*a frozen font identifier's name*/
5614
5615 @<Glob...@>=
5616 static two_halves @!hash0[undefined_control_sequence-hash_base],
5617 *const @!hash = @!hash0-hash_base;
5618 /*the hash table*/
5619 static pointer @!hash_used; /*allocation pointer for |hash|*/
5620 static bool @!no_new_control_sequence; /*are new identifiers legal?*/
5621 static int @!cs_count; /*total number of known identifiers*/
5622
5623 @ @<Set init...@>=
5624 no_new_control_sequence=true; /*new identifiers are usually forbidden*/
5625 next(hash_base)=0;text(hash_base)=0;
5626 for (k=hash_base+1; k<=undefined_control_sequence-1; k++) hash[k]=hash[hash_base];
5627
5628 @ @<Initialize table entries...@>=
5629 hash_used=frozen_control_sequence; /*nothing is used*/
5630 cs_count=0;
5631 eq_type(frozen_dont_expand)=dont_expand;
5632 text(frozen_dont_expand)=s_no("notexpanded:");
5633 @.notexpanded:@>
5634
5635 @ Here is the subroutine that searches the hash table for an identifier
5636 that matches a given string of length |l > 1| appearing in |buffer[j dotdot
5637 (j+l-1)]|. If the identifier is found, the corresponding hash table address
5638 is returned. Otherwise, if the global variable |no_new_control_sequence|
5639 is |true|, the dummy address |undefined_control_sequence| is returned.
5640 Otherwise the identifier is inserted into the hash table and its location
5641 is returned.
5642
5643 @p static pointer id_lookup(int @!j, int @!l) /*search the hash table*/
5644 {@+int h; /*hash code*/
5645 int @!d; /*number of characters in incomplete current string*/
5646 pointer @!p; /*index in |hash| array*/
5647 int @!k; /*index in |buffer| array*/
5648 @<Compute the hash code |h|@>;
5649 p=h+hash_base; /*we start searching here; note that |0 <= h < hash_prime|*/
5650 loop@+{@+if (text(p) > 0) if (length(text(p))==l)
5651 if (str_eq_buf(text(p), buffer+j)) goto found;
5652 if (next(p)==0)
5653 {@+if (no_new_control_sequence)
5654 p=undefined_control_sequence;
5655 else@<Insert a new control sequence after |p|, then make |p| point to
5656 it@>;
5657 goto found;
5658 }
5659 p=next(p);
5660 }
5661 found: return p;
5662 }
5663
5664 @ @<Insert a new control...@>=
5665 {@+if (text(p) > 0)
5666 {@+@/do@+{if (hash_is_full) overflow("hash size", hash_size);
5667 @:TeX capacity exceeded hash size}{\quad hash size@>
5668 decr(hash_used);
5669 }@+ while (!(text(hash_used)==0)); /*search for an empty location in |hash|*/
5670 next(p)=hash_used;p=hash_used;
5671 }
5672 str_room(l);d=cur_length;
5673 while (pool_ptr > str_start[str_ptr])
5674 {@+decr(pool_ptr);str_pool[pool_ptr+l]=str_pool[pool_ptr];
5675 } /*move current string up to make room for another*/
5676 for (k=j; k<=j+l-1; k++) append_char(buffer[k]);
5677 text(p)=make_string();pool_ptr=pool_ptr+d;
5678 #ifdef @!STAT
5679 incr(cs_count);
5680 #endif
5681 @;@/
5682 }
5683
5684 @ The value of |hash_prime| should be roughly 85\pct! of |hash_size|, and it
5685 should be a prime number. The theory of hashing tells us to expect fewer
5686 than two table probes, on the average, when the search is successful.
5687 [See J.~S. Vitter, {\sl Journal of the ACM\/ \bf30} (1983), 231--258.]
5688 @^Vitter, Jeffrey Scott@>
5689
5690 @<Compute the hash code |h|@>=
5691 h=buffer[j];
5692 for (k=j+1; k<=j+l-1; k++)
5693 {@+h=h+h+buffer[k];
5694 while (h >= hash_prime) h=h-hash_prime;
5695 }
5696
5697 @ Single-character control sequences do not need to be looked up in a hash
5698 table, since we can use the character code itself as a direct address.
5699 The procedure |print_cs| prints the name of a control sequence, given
5700 a pointer to its address in |eqtb|. A space is printed after the name
5701 unless it is a single nonletter or an active character. This procedure
5702 might be invoked with invalid data, so it is ``extra robust.'' The
5703 individual characters must be printed one at a time using |print|, since
5704 they may be unprintable.
5705
5706 @<Basic printing...@>=
5707 static void print_cs(int @!p) /*prints a purported control sequence*/
5708 {@+if (p < hash_base) /*single character*/
5709 if (p >= single_base)
5710 if (p==null_cs)
5711 {@+print_esc("csname");print_esc("endcsname");print_char(' ');
5712 }
5713 else{@+printn_esc(p-single_base);
5714 if (equiv(cat_code_base+p-single_base)==letter) print_char(' ');
5715 }
5716 else if (p < active_base) print_esc("IMPOSSIBLE.");
5717 @.IMPOSSIBLE@>
5718 else if (p< active_hash_base) printn(p-active_base);
5719 else if (active_hash[p]==0) print_esc("NONEXISTENT.");
5720 else print_utf8(active_hash[p]);
5721 else if (p >= undefined_control_sequence) print_esc("IMPOSSIBLE.");
5722 else if ((text(p) < 0)||(text(p) >= str_ptr)) print_esc("NONEXISTENT.");
5723 @.NONEXISTENT@>
5724 else{@+if (p==frozen_primitive) print_esc("primitive");
5725 printn_esc(text(p));print_char(' ');
5726 }
5727 }
5728
5729 @ Here is a similar procedure; it avoids the error checks, and it never
5730 prints a space after the control sequence.
5731
5732 @<Basic printing procedures@>=
5733 static void sprint_cs(pointer @!p) /*prints a control sequence*/
5734 {@+if (p < hash_base)
5735 { if (p< active_hash_base) printn(p-active_base);
5736 else if (p < single_base) print_utf8(active_hash[p]);
5737 else if (p < null_cs) printn_esc(p-single_base);
5738 else{@+print_esc("csname");print_esc("endcsname"); }
5739 }
5740 else printn_esc(text(p));
5741 }
5742
5743 @ We need to put \TeX's ``primitive'' control sequences into the hash
5744 table, together with their command code (which will be the |eq_type|)
5745 and an operand (which will be the |equiv|). The |primitive| procedure
5746 does this, in a way that no \TeX\ user can. The global value |cur_val|
5747 contains the new |eqtb| pointer after |primitive| has acted.
5748
5749 @p
5750 #ifdef @!INIT
5751 static void primitive(char *@!str, quarterword @!c, halfword @!o)
5752 {@+str_number s=s_no(str);
5753 int k; /*index into |str_pool|*/
5754 int @!j; /*index into |buffer|*/
5755 small_number @!l; /*length of the string*/
5756 pointer @!p; /*pointer in |ROM|*/
5757 if (s < 256) cur_val=s+single_base;
5758 else{@+k=str_start[s];l=str_start[s+1]-k;
5759 /*we will move |s| into the (possibly non-empty) |buffer|*/
5760 if (first+l > buf_size+1)
5761 overflow("buffer size", buf_size);
5762 @:TeX capacity exceeded buffer size}{\quad buffer size@>
5763 for (j=0; j<=l-1; j++) buffer[first+j]=str_pool[k+j];
5764 cur_val=id_lookup(first, l); /*|no_new_control_sequence| is |false|*/
5765 flush_string;text(cur_val)=s; /*we don't want to have the string twice*/
5766 }
5767 eq_level(cur_val)=level_one;eq_type(cur_val)=c;equiv(cur_val)=o;
5768 @<Add primitive definition to the |ROM| array@>;
5769 }
5770 #endif
5771
5772 @ Many of \TeX's primitives need no |equiv|, since they are identifiable
5773 by their |eq_type| alone. These primitives are loaded into the hash table
5774 as follows:
5775
5776 @<Put each of \TeX's primitives into the hash table@>=
5777 primitive(" ", ex_space, 0);@/
5778 @!@:Single-character primitives /}{\quad\.{\\\ }@>
5779 primitive("/", ital_corr, 0);@/
5780 @!@:Single-character primitives /}{\quad\.{\\/}@>
5781 primitive("accent", accent, 0);@/
5782 @!@:accent\_}{\.{\\accent} primitive@>
5783 primitive("advance", advance, 0);@/
5784 @!@:advance\_}{\.{\\advance} primitive@>
5785 primitive("afterassignment", after_assignment, 0);@/
5786 @!@:after\_assignment\_}{\.{\\afterassignment} primitive@>
5787 primitive("aftergroup", after_group, 0);@/
5788 @!@:after\_group\_}{\.{\\aftergroup} primitive@>
5789 primitive("begingroup", begin_group, 0);@/
5790 @!@:begin\_group\_}{\.{\\begingroup} primitive@>
5791 primitive("char", char_num, 0);@/
5792 @!@:char\_}{\.{\\char} primitive@>
5793 primitive("csname", cs_name, 0);@/
5794 @!@:cs\_name\_}{\.{\\csname} primitive@>
5795 primitive("delimiter", delim_num, 0);@/
5796 @!@:delimiter\_}{\.{\\delimiter} primitive@>
5797 primitive("divide", divide, 0);@/
5798 @!@:divide\_}{\.{\\divide} primitive@>
5799 primitive("endcsname", end_cs_name, 0);@/
5800 @!@:end\_cs\_name\_}{\.{\\endcsname} primitive@>
5801 primitive("endgroup", end_group, 0);
5802 @!@:end\_group\_}{\.{\\endgroup} primitive@>
5803 text(frozen_end_group)=text(cur_val);eqtb[frozen_end_group]=eqtb[cur_val];@/
5804 primitive("expandafter", expand_after, 0);@/
5805 @!@:expand\_after\_}{\.{\\expandafter} primitive@>
5806 primitive("font", def_font, 0);@/
5807 @!@:font\_}{\.{\\font} primitive@>
5808 primitive("fontdimen", assign_font_dimen, 0);@/
5809 @!@:font\_dimen\_}{\.{\\fontdimen} primitive@>
5810 primitive("halign", halign, 0);@/
5811 @!@:halign\_}{\.{\\halign} primitive@>
5812 primitive("hrule", hrule, 0);@/
5813 @!@:hrule\_}{\.{\\hrule} primitive@>
5814 primitive("ignorespaces", ignore_spaces, 0);@/
5815 @!@:ignore\_spaces\_}{\.{\\ignorespaces} primitive@>
5816 primitive("insert", insert, 0);@/
5817 @!@:insert\_}{\.{\\insert} primitive@>
5818 primitive("mark", mark, 0);@/
5819 @!@:mark\_}{\.{\\mark} primitive@>
5820 primitive("mathaccent", math_accent, 0);@/
5821 @!@:math\_accent\_}{\.{\\mathaccent} primitive@>
5822 primitive("mathchar", math_char_num, 0);@/
5823 @!@:math\_char\_}{\.{\\mathchar} primitive@>
5824 primitive("mathchoice", math_choice, 0);@/
5825 @!@:math\_choice\_}{\.{\\mathchoice} primitive@>
5826 primitive("multiply", multiply, 0);@/
5827 @!@:multiply\_}{\.{\\multiply} primitive@>
5828 primitive("noalign", no_align, 0);@/
5829 @!@:no\_align\_}{\.{\\noalign} primitive@>
5830 primitive("noboundary", no_boundary, 0);@/
5831 @!@:no\_boundary\_}{\.{\\noboundary} primitive@>
5832 primitive("noexpand", no_expand, 0);@/
5833 @!@:no\_expand\_}{\.{\\noexpand} primitive@>
5834 primitive("nonscript", non_script, 0);@/
5835 @!@:non\_script\_}{\.{\\nonscript} primitive@>
5836 primitive("omit", omit, 0);@/
5837 @!@:omit\_}{\.{\\omit} primitive@>
5838 primitive("parshape", set_shape, par_shape_loc);@/
5839 @!@:par\_shape\_}{\.{\\parshape} primitive@>
5840 primitive("penalty", break_penalty, 0);@/
5841 @!@:penalty\_}{\.{\\penalty} primitive@>
5842 primitive("prevgraf", set_prev_graf, 0);@/
5843 @!@:prev\_graf\_}{\.{\\prevgraf} primitive@>
5844 primitive("radical", radical, 0);@/
5845 @!@:radical\_}{\.{\\radical} primitive@>
5846 primitive("read", read_to_cs, 0);@/
5847 @!@:read\_}{\.{\\read} primitive@>
5848 primitive("relax", relax, 256); /*cf.\ |scan_file_name|*/
5849 @!@:relax\_}{\.{\\relax} primitive@>
5850 text(frozen_relax)=text(cur_val);eqtb[frozen_relax]=eqtb[cur_val];@/
5851 primitive("setbox", set_box, 0);@/
5852 @!@:set\_box\_}{\.{\\setbox} primitive@>
5853 primitive("the", the, 0);@/
5854 @!@:the\_}{\.{\\the} primitive@>
5855 primitive("toks", toks_register, mem_bot);@/
5856 @!@:toks\_}{\.{\\toks} primitive@>
5857 primitive("vadjust", vadjust, 0);@/
5858 @!@:vadjust\_}{\.{\\vadjust} primitive@>
5859 primitive("valign", valign, 0);@/
5860 @!@:valign\_}{\.{\\valign} primitive@>
5861 primitive("vcenter", vcenter, 0);@/
5862 @!@:vcenter\_}{\.{\\vcenter} primitive@>
5863 primitive("vrule", vrule, 0);@/
5864 @!@:vrule\_}{\.{\\vrule} primitive@>
5865
5866 @ Each primitive has a corresponding inverse, so that it is possible to
5867 display the cryptic numeric contents of |eqtb| in symbolic form.
5868 Every call of |primitive| in this program is therefore accompanied by some
5869 straightforward code that forms part of the |print_cmd_chr| routine
5870 below.
5871
5872 @<Cases of |print_cmd_chr|...@>=
5873 case accent: print_esc("accent");@+break;
5874 case advance: print_esc("advance");@+break;
5875 case after_assignment: print_esc("afterassignment");@+break;
5876 case after_group: print_esc("aftergroup");@+break;
5877 case assign_font_dimen: print_esc("fontdimen");@+break;
5878 case begin_group: print_esc("begingroup");@+break;
5879 case break_penalty: print_esc("penalty");@+break;
5880 case char_num: print_esc("char");@+break;
5881 case cs_name: print_esc("csname");@+break;
5882 case def_font: print_esc("font");@+break;
5883 case delim_num: print_esc("delimiter");@+break;
5884 case divide: print_esc("divide");@+break;
5885 case end_cs_name: print_esc("endcsname");@+break;
5886 case end_group: print_esc("endgroup");@+break;
5887 case ex_space: print_esc(" ");@+break;
5888 case expand_after: switch (chr_code) {
5889 case 0: print_esc("expandafter");@+break;
5890 @/@<Cases of |expandafter| for |print_cmd_chr|@>@/
5891 } @+break; /*there are no other cases*/
5892 case halign: print_esc("halign");@+break;
5893 case hrule: print_esc("hrule");@+break;
5894 case ignore_spaces: print_esc("ignorespaces");@+break;
5895 case insert: print_esc("insert");@+break;
5896 case ital_corr: print_esc("/");@+break;
5897 case mark: {@+print_esc("mark");
5898 if (chr_code > 0) print_char('s');
5899 } @+break;
5900 case math_accent: print_esc("mathaccent");@+break;
5901 case math_char_num: print_esc("mathchar");@+break;
5902 case math_choice: print_esc("mathchoice");@+break;
5903 case multiply: print_esc("multiply");@+break;
5904 case no_align: print_esc("noalign");@+break;
5905 case no_boundary: print_esc("noboundary");@+break;
5906 case no_expand: print_esc("noexpand");@+break;
5907 case non_script: print_esc("nonscript");@+break;
5908 case omit: print_esc("omit");@+break;
5909 case radical: print_esc("radical");@+break;
5910 case read_to_cs: if (chr_code==0) print_esc("read")
5911 @<Cases of |read| for |print_cmd_chr|@>;@+break;
5912 case relax: print_esc("relax");@+break;
5913 case set_box: print_esc("setbox");@+break;
5914 case set_prev_graf: print_esc("prevgraf");@+break;
5915 case set_shape: switch (chr_code) {
5916 case par_shape_loc: print_esc("parshape");@+break;
5917 @<Cases of |set_shape| for |print_cmd_chr|@>@;@/
5918 } @+break; /*there are no other cases*/
5919 case the: if (chr_code==0) print_esc("the")
5920 @<Cases of |the| for |print_cmd_chr|@>;@+break;
5921 case toks_register: @<Cases of |toks_register| for |print_cmd_chr|@>@;@+break;
5922 case vadjust: print_esc("vadjust");@+break;
5923 case valign: print_esc("valign");@+break;
5924 case vcenter: print_esc("vcenter");@+break;
5925 case vrule: print_esc("vrule");@+break;
5926
5927 @ We will deal with the other primitives later, at some point in the program
5928 where their |eq_type| and |equiv| values are more meaningful. For example,
5929 the primitives for math mode will be loaded when we consider the routines
5930 that deal with formulas. It is easy to find where each particular
5931 primitive was treated by looking in the index at the end; for example, the
5932 section where |"radical"| entered |eqtb| is listed under `\.{\\radical}
5933 primitive'. (Primitives consisting of a single nonalphabetic character,
5934 @!like `\.{\\/}', are listed under `Single-character primitives'.)
5935 @!@^Single-character primitives@>
5936
5937 Meanwhile, this is a convenient place to catch up on something we were unable
5938 to do before the hash table was defined:
5939
5940 @<Print the font identifier for |font(p)|@>=
5941 printn_esc(font_id_text(font(p)))
5942
5943 @* Saving and restoring equivalents.
5944 The nested structure provided by `$\.{\char'173}\ldots\.{\char'175}$' groups
5945 in \TeX\ means that |eqtb| entries valid in outer groups should be saved
5946 and restored later if they are overridden inside the braces. When a new |eqtb|
5947 value is being assigned, the program therefore checks to see if the previous
5948 entry belongs to an outer level. In such a case, the old value is placed
5949 on the |save_stack| just before the new value enters |eqtb|. At the
5950 end of a grouping level, i.e., when the right brace is sensed, the
5951 |save_stack| is used to restore the outer values, and the inner ones are
5952 destroyed.
5953
5954 Entries on the |save_stack| are of type |memory_word|. The top item on
5955 this stack is |save_stack[p]|, where |p==save_ptr-1|; it contains three
5956 fields called |save_type|, |save_level|, and |save_index|, and it is
5957 interpreted in one of five ways:
5958
5959 \yskip\hangg 1) If |save_type(p)==restore_old_value|, then
5960 |save_index(p)| is a location in |eqtb| whose current value should
5961 be destroyed at the end of the current group and replaced by |save_stack[p-1]|.
5962 Furthermore if |save_index(p) >= int_base|, then |save_level(p)|
5963 should replace the corresponding entry in |xeq_level|.
5964
5965 \yskip\hangg 2) If |save_type(p)==restore_zero|, then |save_index(p)|
5966 is a location in |eqtb| whose current value should be destroyed at the end
5967 of the current group, when it should be
5968 replaced by the value of |eqtb[undefined_control_sequence]|.
5969
5970 \yskip\hangg 3) If |save_type(p)==insert_token|, then |save_index(p)|
5971 is a token that should be inserted into \TeX's input when the current
5972 group ends.
5973
5974 \yskip\hangg 4) If |save_type(p)==level_boundary|, then |save_level(p)|
5975 is a code explaining what kind of group we were previously in, and
5976 |save_index(p)| points to the level boundary word at the bottom of
5977 the entries for that group.
5978 Furthermore, in extended \eTeX\ mode, |save_stack[p-1]| contains the
5979 source line number at which the current level of grouping was entered.
5980
5981 \yskip\hang 5) If |save_type(p)==restore_sa|, then |sa_chain| points to a
5982 chain of sparse array entries to be restored at the end of the current
5983 group. Furthermore |save_index(p)| and |save_level(p)| should replace
5984 the values of |sa_chain| and |sa_level| respectively.
5985
5986 @d save_type(A) save_stack[A].hh.b0 /*classifies a |save_stack| entry*/
5987 @d save_level(A) save_stack[A].hh.b1
5988 /*saved level for regions 5 and 6, or group code*/
5989 @d save_index(A) save_stack[A].hh.rh
5990 /*|eqtb| location or token or |save_stack| location*/
5991 @d restore_old_value 0 /*|save_type| when a value should be restored later*/
5992 @d restore_zero 1 /*|save_type| when an undefined entry should be restored*/
5993 @d insert_token 2 /*|save_type| when a token is being saved for later use*/
5994 @d level_boundary 3 /*|save_type| corresponding to beginning of group*/
5995 @d restore_sa 4 /*|save_type| when sparse array entries should be restored*/
5996
5997 @p @t\4@>@<Declare \eTeX\ procedures for tracing and input@>@;
5998
5999 @ Here are the group codes that are used to discriminate between different
6000 kinds of groups. They allow \TeX\ to decide what special actions, if any,
6001 should be performed when a group ends.
6002 \def\grp{\.{\char'173...\char'175}}
6003
6004 Some groups are not supposed to be ended by right braces. For example,
6005 the `\.\$' that begins a math formula causes a |math_shift_group| to
6006 be started, and this should be terminated by a matching `\.\$'. Similarly,
6007 a group that starts with \.{\\left} should end with \.{\\right}, and
6008 one that starts with \.{\\begingroup} should end with \.{\\endgroup}.
6009
6010 @d bottom_level 0 /*group code for the outside world*/
6011 @d simple_group 1 /*group code for local structure only*/
6012 @d hbox_group 2 /*code for `\.{\\hbox}\grp'*/
6013 @d adjusted_hbox_group 3 /*code for `\.{\\hbox}\grp' in vertical mode*/
6014 @d vbox_group 4 /*code for `\.{\\vbox}\grp'*/
6015 @d vtop_group 5 /*code for `\.{\\vtop}\grp'*/
6016 @d align_group 6 /*code for `\.{\\halign}\grp', `\.{\\valign}\grp'*/
6017 @d no_align_group 7 /*code for `\.{\\noalign}\grp'*/
6018 @d output_group 8 /*code for output routine*/
6019 @d math_group 9 /*code for, e.g., `\.{\char'136}\grp'*/
6020 @d disc_group 10 /*code for `\.{\\discretionary}\grp\grp\grp'*/
6021 @d insert_group 11 /*code for `\.{\\insert}\grp', `\.{\\vadjust}\grp'*/
6022 @d vcenter_group 12 /*code for `\.{\\vcenter}\grp'*/
6023 @d math_choice_group 13 /*code for `\.{\\mathchoice}\grp\grp\grp\grp'*/
6024 @d semi_simple_group 14 /*code for `\.{\\begingroup...\\endgroup}'*/
6025 @d math_shift_group 15 /*code for `\.{\$...\$}'*/
6026 @d math_left_group 16 /*code for `\.{\\left...\\right}'*/
6027 @d page_group 17
6028 @d stream_group 18
6029 @d stream_before_group 19
6030 @d stream_after_group 20
6031 @d outline_group 21
6032 @d max_group_code 21
6033
6034 @<Types...@>=
6035 typedef int8_t group_code; /*|save_level| for a level boundary*/
6036
6037 @ The global variable |cur_group| keeps track of what sort of group we are
6038 currently in. Another global variable, |cur_boundary|, points to the
6039 topmost |level_boundary| word. And |cur_level| is the current depth of
6040 nesting. The routines are designed to preserve the condition that no entry
6041 in the |save_stack| or in |eqtb| ever has a level greater than |cur_level|.
6042
6043 @ @<Glob...@>=
6044 static memory_word @!save_stack[save_size+1];
6045 static memory_word @!save_hfactor[save_size+1];
6046 static memory_word @!save_vfactor[save_size+1];
6047 static int @!save_ptr; /*first unused entry on |save_stack|*/
6048 static int @!max_save_stack; /*maximum usage of save stack*/
6049 static quarterword @!cur_level; /*current nesting level for groups*/
6050 static group_code @!cur_group; /*current group type*/
6051 static int @!cur_boundary; /*where the current level begins*/
6052
6053 @ At this time it might be a good idea for the reader to review the introduction
6054 to |eqtb| that was given above just before the long lists of parameter names.
6055 Recall that the ``outer level'' of the program is |level_one|, since
6056 undefined control sequences are assumed to be ``defined'' at |level_zero|.
6057
6058 @<Set init...@>=
6059 save_ptr=0;cur_level=level_one;cur_group=bottom_level;cur_boundary=0;
6060 max_save_stack=0;
6061
6062 @ The following macro is used to test if there is room for up to seven more
6063 entries on |save_stack|. By making a conservative test like this, we can
6064 get by with testing for overflow in only a few places.
6065
6066 @d check_full_save_stack if (save_ptr > max_save_stack)
6067 {@+max_save_stack=save_ptr;
6068 if (max_save_stack > save_size-7) overflow("save size", save_size);
6069 @:TeX capacity exceeded save size}{\quad save size@>
6070 }
6071
6072 @ Procedure |new_save_level| is called when a group begins. The
6073 argument is a group identification code like `|hbox_group|'. After
6074 calling this routine, it is safe to put five more entries on |save_stack|.
6075
6076 In some cases integer-valued items are placed onto the
6077 |save_stack| just below a |level_boundary| word, because this is a
6078 convenient place to keep information that is supposed to ``pop up'' just
6079 when the group has finished.
6080 For example, when `\.{\\hbox to 100pt}\grp' is being treated, the 100pt
6081 dimension is stored on |save_stack| just before |new_save_level| is
6082 called.
6083
6084 We use the notation |saved(k)| to stand for an integer item that
6085 appears in location |save_ptr+k| of the save stack.
6086
6087 @d saved(A) save_stack[save_ptr+A].i
6088 @d saved_hfactor(A) save_hfactor[save_ptr+A].i
6089 @d saved_vfactor(A) save_vfactor[save_ptr+A].i
6090
6091 @p static void new_save_level(group_code @!c) /*begin a new level of grouping*/
6092 {@+check_full_save_stack;
6093 if (eTeX_ex)
6094 {@+saved(0)=line;incr(save_ptr);
6095 }
6096 save_type(save_ptr)=level_boundary;save_level(save_ptr)=cur_group;
6097 save_index(save_ptr)=cur_boundary;
6098 if (cur_level==max_quarterword) overflow("grouping levels",
6099 @:TeX capacity exceeded grouping levels}{\quad grouping levels@>
6100 max_quarterword-min_quarterword);
6101 /*quit if |(cur_level+1)| is too big to be stored in |eqtb|*/
6102 cur_boundary=save_ptr;cur_group=c;
6103 #ifdef @!STAT
6104 if (tracing_groups > 0) group_trace(false);
6105 #endif
6106 @;@/
6107 incr(cur_level);incr(save_ptr);
6108 }
6109
6110 @ Just before an entry of |eqtb| is changed, the following procedure should
6111 be called to update the other data structures properly. It is important
6112 to keep in mind that reference counts in |mem| include references from
6113 within |save_stack|, so these counts must be handled carefully.
6114 @^reference counts@>
6115
6116 @p static void eq_destroy(memory_word @!w) /*gets ready to forget |w|*/
6117 {@+pointer q; /*|equiv| field of |w|*/
6118 switch (eq_type_field(w)) {
6119 case call: case long_call: case outer_call:
6120 case long_outer_call: delete_token_ref(equiv_field(w));@+break;
6121 case glue_ref: delete_glue_ref(equiv_field(w));@+break;
6122 case shape_ref: {@+q=equiv_field(w); /*we need to free a \.{\\parshape} block*/
6123 if (q!=null) free_node(q, info(q)+info(q)+1);
6124 } @+break; /*such a block is |2 n+1| words long, where |n==info(q)|*/
6125 case box_ref: flush_node_list(equiv_field(w));@+break;
6126 @/@<Cases for |eq_destroy|@>@/
6127 default:do_nothing;
6128 }
6129 }
6130
6131 @ To save a value of |eqtb[p]| that was established at level |l|, we
6132 can use the following subroutine.
6133
6134 @p static void eq_save(pointer @!p, quarterword @!l) /*saves |eqtb[p]|*/
6135 {@+check_full_save_stack;
6136 if (l==level_zero) save_type(save_ptr)=restore_zero;
6137 else{@+save_stack[save_ptr]=eqtb[p];
6138 if (p>=dimen_base)
6139 { save_hfactor[save_ptr]=hfactor_eqtb[p];
6140 save_vfactor[save_ptr]=vfactor_eqtb[p];
6141 }
6142 else if (p==par_shape_loc)
6143 { save_hfactor[save_ptr].i=par_shape_hfactor;
6144 save_vfactor[save_ptr].i=par_shape_vfactor;
6145 }
6146 incr(save_ptr);
6147 save_type(save_ptr)=restore_old_value;
6148 }
6149 save_level(save_ptr)=l;save_index(save_ptr)=p;incr(save_ptr);
6150 }
6151
6152 @ The procedure |eq_define| defines an |eqtb| entry having specified
6153 |eq_type| and |equiv| fields, and saves the former value if appropriate.
6154 This procedure is used only for entries in the first four regions of |eqtb|,
6155 i.e., only for entries that have |eq_type| and |equiv| fields.
6156 After calling this routine, it is safe to put four more entries on
6157 |save_stack|, provided that there was room for four more entries before
6158 the call, since |eq_save| makes the necessary test.
6159
6160 @p
6161 #ifdef @!STAT
6162 #define assign_trace(A, B) if (tracing_assigns > 0) restore_trace(A, B);
6163 #else
6164 #define assign_trace(A, B)
6165 #endif
6166
6167 static void eq_define(pointer @!p, quarterword @!t, halfword @!e)
6168 /*new data for |eqtb|*/
6169 {@+
6170 if (eTeX_ex&&(eq_type(p)==t)&&(equiv(p)==e))
6171 {@+assign_trace(p,"reassigning")@;@/
6172 eq_destroy(eqtb[p]);return;
6173 }
6174 assign_trace(p,"changing")@;@/
6175 if (eq_level(p)==cur_level) eq_destroy(eqtb[p]);
6176 else if (cur_level > level_one) eq_save(p, eq_level(p));
6177 eq_level(p)=cur_level;eq_type(p)=t;equiv(p)=e;
6178 if (p==par_shape_loc)
6179 { par_shape_hfactor=cur_hfactor;
6180 par_shape_vfactor=cur_vfactor;
6181 }
6182 assign_trace(p,"into")@;@/
6183 }
6184
6185 @ The counterpart of |eq_define| for the remaining (fullword) positions in
6186 |eqtb| is called |eq_word_define|. Since |xeq_level[p] >= level_one| for all
6187 |p|, a `|restore_zero|' will never be used in this case.
6188
6189 @p static void eq_word_define(pointer @!p, int @!w)
6190 {@+
6191 assign_trace(p,"changing")@;@/
6192 if (cur_level==level_one)@t\1@>
6193 { if (p==dimen_base+hsize_code)
6194 { hhsize=w+round(((double)cur_hfactor*hhsize +(double)cur_vfactor*hvsize)/unity); return; @+}
6195 if (p==dimen_base+vsize_code)
6196 { hvsize=w+round(((double)cur_hfactor*hhsize +(double)cur_vfactor*hvsize)/unity); return; @+}
6197 }
6198 if (xeq_level[p]!=cur_level)
6199 {@+eq_save(p, xeq_level[p]);xeq_level[p]=cur_level;
6200 }
6201 eqtb[p].i=w;
6202 if (p>=dimen_base)
6203 { hfactor_eqtb[p].i=cur_hfactor;
6204 vfactor_eqtb[p].i=cur_vfactor;
6205 }
6206 assign_trace(p,"into")@;@/
6207 }
6208
6209 @ The |eq_define| and |eq_word_define| routines take care of local definitions.
6210 @^global definitions@>
6211 Global definitions are done in almost the same way, but there is no need
6212 to save old values, and the new value is associated with |level_one|.
6213
6214 @p static void geq_define(pointer @!p, quarterword @!t, halfword @!e)
6215 /*global |eq_define|*/
6216 {@+assign_trace(p,"globally changing")@;@/
6217 {@+eq_destroy(eqtb[p]);
6218 eq_level(p)=level_one;eq_type(p)=t;equiv(p)=e;
6219 }
6220 assign_trace(p,"into");@/
6221 }
6222 @#
6223 static void geq_word_define(pointer @!p, int @!w) /*global |eq_word_define|*/
6224 {@+assign_trace(p,"globally changing")@;@/
6225 {@t\1@>xeq_level[p]=level_one;
6226 if (p==dimen_base+hsize_code)
6227 hhsize=w+round(((double)cur_hfactor*hhsize +(double)cur_vfactor*hvsize)/unity);
6228 else if (p==dimen_base+vsize_code)
6229 hvsize=w+round(((double)cur_hfactor*hhsize +(double)cur_vfactor*hvsize)/unity);
6230 else
6231 { eqtb[p].i=w;
6232 if (p>=dimen_base)
6233 { hfactor_eqtb[p].i=cur_hfactor;
6234 vfactor_eqtb[p].i=cur_vfactor;
6235 }
6236 }
6237 }
6238 assign_trace(p,"into");@/
6239 }
6240
6241 @ Subroutine |save_for_after| puts a token on the stack for save-keeping.
6242
6243 @p static void save_for_after(halfword @!t)
6244 {@+if (cur_level > level_one)
6245 {@+check_full_save_stack;
6246 save_type(save_ptr)=insert_token;save_level(save_ptr)=level_zero;
6247 save_index(save_ptr)=t;incr(save_ptr);
6248 }
6249 }
6250
6251 @ The |unsave| routine goes the other way, taking items off of |save_stack|.
6252 This routine takes care of restoration when a level ends; everything
6253 belonging to the topmost group is cleared off of the save stack.
6254
6255 @p
6256 static void back_input(void);
6257 static void unsave(void) /*pops the top level off the save stack*/
6258 {@+
6259 pointer p; /*position to be restored*/
6260 quarterword @!l; /*saved level, if in fullword regions of |eqtb|*/
6261 halfword @!t; /*saved value of |cur_tok|*/
6262 bool @!a; /*have we already processed an \.{\\aftergroup} ?*/
6263 a=false;
6264 if (cur_level > level_one)
6265 {@+decr(cur_level);
6266 @<Clear off top level from |save_stack|@>;
6267 }
6268 else confusion("curlevel"); /*|unsave| is not used when |cur_group==bottom_level|*/
6269 @:this can't happen curlevel}{\quad curlevel@>
6270 }
6271
6272 @ @<Clear off...@>=
6273 loop@+{@+decr(save_ptr);
6274 if (save_type(save_ptr)==level_boundary) goto done;
6275 p=save_index(save_ptr);
6276 if (save_type(save_ptr)==insert_token)
6277 @<Insert token |p| into \TeX's input@>@;
6278 else if (save_type(save_ptr)==restore_sa)
6279 {@+sa_restore();sa_chain=p;sa_level=save_level(save_ptr);
6280 }
6281 else if (save_type(save_ptr)==restore_utf_none)
6282 { utf_unsave_list=save_level(save_ptr); decr(save_ptr); }
6283 else if (save_type(save_ptr)==restore_utf) utf_unsave(p);
6284 else{@+if (save_type(save_ptr)==restore_old_value)
6285 {@+l=save_level(save_ptr);decr(save_ptr);
6286 }
6287 else save_stack[save_ptr]=eqtb[undefined_control_sequence];
6288 @<Store \(s)|save_stack[save_ptr]| in |eqtb[p]|, unless |eqtb[p]| holds a global value@>;
6289 }
6290 }
6291 done:
6292 #ifdef @!STAT
6293 if (tracing_groups > 0) group_trace(true);
6294 #endif
6295 @;@/
6296 if (grp_stack[in_open]==cur_boundary) group_warning();
6297 /*groups possibly not properly nested with files*/
6298 cur_group=save_level(save_ptr);cur_boundary=save_index(save_ptr);
6299 if (eTeX_ex) decr(save_ptr)
6300
6301 @ A global definition, which sets the level to |level_one|,
6302 @^global definitions@>
6303 will not be undone by |unsave|. If at least one global definition of
6304 |eqtb[p]| has been carried out within the group that just ended, the
6305 last such definition will therefore survive.
6306
6307 @<Store \(s)|save...@>=
6308 if (p < int_base)
6309 if (eq_level(p)==level_one)
6310 {@+eq_destroy(save_stack[save_ptr]); /*destroy the saved value*/
6311 #ifdef @!STAT
6312 if (tracing_restores > 0) restore_trace(p,"retaining");
6313 #endif
6314 @;@/
6315 }
6316 else{@+eq_destroy(eqtb[p]); /*destroy the current value*/
6317 eqtb[p]=save_stack[save_ptr]; /*restore the saved value*/
6318 if (p==par_shape_loc)
6319 { par_shape_hfactor=save_hfactor[save_ptr].i;
6320 par_shape_vfactor=save_vfactor[save_ptr].i;
6321 }
6322 #ifdef @!STAT
6323 if (tracing_restores > 0) restore_trace(p,"restoring");
6324 #endif
6325 @;@/
6326 }
6327 else if (xeq_level[p]!=level_one)
6328 {@t\1@>@+eqtb[p]=save_stack[save_ptr];
6329 if (p>=dimen_base)
6330 { hfactor_eqtb[p]=save_hfactor[save_ptr];
6331 vfactor_eqtb[p]=save_vfactor[save_ptr];
6332 }
6333 xeq_level[p]=l;
6334 #ifdef @!STAT
6335 if (tracing_restores > 0) restore_trace(p,"restoring");
6336 #endif
6337 @;@/
6338 }
6339 else{
6340 #ifdef @!STAT
6341 if (tracing_restores > 0) restore_trace(p,"retaining");
6342 #endif
6343 @;@/
6344 }
6345
6346 @ @<Declare \eTeX\ procedures for tr...@>=
6347 #ifdef @!STAT
6348 static void restore_trace(pointer @!p, char *@!s)
6349 /*|eqtb[p]| has just been restored or retained*/
6350 {@+begin_diagnostic();print_char('{');print(s);print_char(' ');
6351 show_eqtb(p);print_char('}');
6352 end_diagnostic(false);
6353 }
6354 #endif
6355
6356 @ When looking for possible pointers to a memory location, it is helpful
6357 to look for references from |eqtb| that might be waiting on the
6358 save stack. Of course, we might find spurious pointers too; but this
6359 routine is merely an aid when debugging, and at such times we are
6360 grateful for any scraps of information, even if they prove to be irrelevant.
6361 @^dirty \PASCAL@>
6362
6363 @<Search |save_stack| for equivalents that point to |p|@>=
6364 if (save_ptr > 0) for (q=0; q<=save_ptr-1; q++)
6365 {@+if (equiv_field(save_stack[q])==p)
6366 {@+print_nl("SAVE(");print_int(q);print_char(')');
6367 }
6368 }
6369
6370 @ Most of the parameters kept in |eqtb| can be changed freely, but there's
6371 an exception: The magnification should not be used with two different
6372 values during any \TeX\ job, since a single magnification is applied to an
6373 entire run. The global variable |mag_set| is set to the current magnification
6374 whenever it becomes necessary to ``freeze'' it at a particular value.
6375
6376 @<Glob...@>=
6377 static int @!mag_set; /*if nonzero, this magnification should be used henceforth*/
6378
6379 @ @<Set init...@>=
6380 mag_set=0;
6381
6382 @ The |prepare_mag| subroutine is called whenever \TeX\ wants to use |mag|
6383 for magnification.
6384
6385 @p static void prepare_mag(void)
6386 {@+if ((mag_set > 0)&&(mag!=mag_set))
6387 {@+print_err("Incompatible magnification (");print_int(mag);
6388 @.Incompatible magnification@>
6389 print(");");print_nl(" the previous value will be retained");
6390 help2("I can handle only one magnification ratio per job. So I've",@/
6391 "reverted to the magnification you used earlier on this run.");@/
6392 int_error(mag_set);
6393 geq_word_define(int_base+mag_code, mag_set); /*|mag=mag_set|*/
6394 }
6395 if ((mag <= 0)||(mag > 32768))
6396 {@+print_err("Illegal magnification has been changed to 1000");@/
6397 @.Illegal magnification...@>
6398 help1("The magnification ratio must be between 1 and 32768.");
6399 int_error(mag);geq_word_define(int_base+mag_code, 1000);
6400 }
6401 mag_set=mag;
6402 }
6403
6404 @* Token lists.
6405 A \TeX\ token is either a character or a control sequence, and it is
6406 @^token@>
6407 @^UTF@>
6408 represented internally in one of two ways:
6409 (1)~A character whose utf
6410 code number is |c| and whose command code is |m| is represented as the
6411 number $2^{24}m+c$; the command code is in the range |1 <= m <= 14|.
6412 (2)~A control sequence whose |eqtb| address is |p| is represented as the number
6413 |cs_token_flag+p|. Here |cs_token_flag==@t$2^{28}-1$@>| is larger than
6414 $2^{24}m+c$, yet it is small enough that |cs_token_flag+p < max_halfword|;
6415 thus, a token fits comfortably in a halfword.
6416
6417 A token |t| represents a |left_brace| command if and only if
6418 |t < left_brace_limit|; it represents a |right_brace| command if and only if
6419 we have |left_brace_limit <= t < right_brace_limit|; and it represents a |match| or
6420 |end_match| command if and only if |match_token <= t <= end_match_token|.
6421 The following definitions take care of these token-oriented constants
6422 and a few others.
6423
6424 @d cs_token_flag ((1<<28)-1) /*amount added to the |eqtb| location in a
6425 token that stands for a control sequence; is a multiple of~256, less~1*/
6426 @d cmd_factor (1<<24)
6427 @d cmd_token(A) ((A)<<24) /*$8^{24}\cdot|A|$*/
6428 @d left_brace_token (left_brace<<24) /*$2^{24}\cdot|left_brace|$*/
6429 @d left_brace_limit ((left_brace+1)<<24) /*$2^{24}\cdot(|left_brace|+1)$*/
6430 @d right_brace_token (right_brace<<24) /*$2^{24}\cdot|right_brace|$*/
6431 @d right_brace_limit ((right_brace+1)<<24) /*$2^{24}\cdot(|right_brace|+1)$*/
6432 @d math_shift_token (math_shift<<24) /*$2^{24}\cdot|math_shift|$*/
6433 @d tab_token (tab_mark<<24) /*$2^{24}\cdot|tab_mark|$*/
6434 @d out_param_token (out_param<<24) /*$2^{24}\cdot|out_param|$*/
6435 @d space_token ((spacer<<24)+' ') /*$2^{24}\cdot|spacer|+|' '|$*/
6436 @d letter_token (letter<<24)/*$2^{24}\cdot|letter|$*/
6437 @d other_token (other_char<<24) /*$2^{24}\cdot|other_char|$*/
6438 @d match_token (match<<24) /*$2^{24}\cdot|match|$*/
6439 @d end_match_token (end_match<<24) /*$2^{24}\cdot|end_match|$*/
6440 @d protected_token (end_match<<24)+1 /*$2^{24}\cdot|end_match|+1$*/
6441
6442 @ @<Check the ``constant''...@>=
6443 if (cs_token_flag+undefined_control_sequence > max_halfword) bad=21;
6444
6445 @ A token list is a singly linked list of one-word nodes in |mem|, where
6446 each word contains a token and a link. Macro definitions, output-routine
6447 definitions, marks, \.{\\write} texts, and a few other things
6448 are remembered by \TeX\ in the form
6449 of token lists, usually preceded by a node with a reference count in its
6450 |token_ref_count| field. The token stored in location |p| is called
6451 |info(p)|.
6452
6453 Three special commands appear in the token lists of macro definitions.
6454 When |m==match|, it means that \TeX\ should scan a parameter
6455 for the current macro; when |m==end_match|, it means that parameter
6456 matching should end and \TeX\ should start reading the macro text; and
6457 when |m==out_param|, it means that \TeX\ should insert parameter
6458 number |c| into the text at this point.
6459
6460 The enclosing \.{\char'173} and \.{\char'175} characters of a macro
6461 definition are omitted, but an output routine
6462 will be enclosed in braces.
6463
6464 Here is an example macro definition that illustrates these conventions.
6465 After \TeX\ processes the text
6466 $$\.{\\def\\mac a\#1\#2 \\b \{\#1\\-a \#\#1\#2 \#2\}}$$
6467 the definition of \.{\\mac} is represented as a token list containing
6468 $$\def\,{\hskip2pt}
6469 \vbox{\halign{\hfil#\hfil\cr
6470 (reference count), |letter|\,\.a, |match|\,\#, |match|\,\#, |spacer|\,\.\ ,
6471 \.{\\b}, |end_match|,\cr
6472 |out_param|\,1, \.{\\-}, |letter|\,\.a, |spacer|\,\.\ , |mac_param|\,\#,
6473 |other_char|\,\.1,\cr
6474 |out_param|\,2, |spacer|\,\.\ , |out_param|\,2.\cr}}$$
6475 The procedure |scan_toks| builds such token lists, and |macro_call|
6476 does the parameter matching.
6477 @^reference counts@>
6478
6479 Examples such as
6480 $$\.{\\def\\m\{\\def\\m\{a\}\ b\}}$$
6481 explain why reference counts would be needed even if \TeX\ had no \.{\\let}
6482 operation: When the token list for \.{\\m} is being read, the redefinition of
6483 \.{\\m} changes the |eqtb| entry before the token list has been fully
6484 consumed, so we dare not simply destroy a token list when its
6485 control sequence is being redefined.
6486
6487 If the parameter-matching part of a definition ends with `\.{\#\{}',
6488 the corresponding token list will have `\.\{' just before the `|end_match|'
6489 and also at the very end. The first `\.\{' is used to delimit the parameter; the
6490 second one keeps the first from disappearing.
6491
6492 @ The procedure |show_token_list|, which prints a symbolic form of
6493 the token list that starts at a given node |p|, illustrates these
6494 conventions. The token list being displayed should not begin with a reference
6495 count. However, the procedure is intended to be robust, so that if the
6496 memory links are awry or if |p| is not really a pointer to a token list,
6497 nothing catastrophic will happen.
6498
6499 An additional parameter |q| is also given; this parameter is either null
6500 or it points to a node in the token list where a certain magic computation
6501 takes place that will be explained later. (Basically, |q| is non-null when
6502 we are printing the two-line context information at the time of an error
6503 message; |q| marks the place corresponding to where the second line
6504 should begin.)
6505
6506 For example, if |p| points to the node containing the first \.a in the
6507 token list above, then |show_token_list| will print the string
6508 $$\hbox{`\.{a\#1\#2\ \\b\ ->\#1\\-a\ \#\#1\#2\ \#2}';}$$
6509 and if |q| points to the node containing the second \.a,
6510 the magic computation will be performed just before the second \.a is printed.
6511
6512 The generation will stop, and `\.{\\ETC.}' will be printed, if the length
6513 of printing exceeds a given limit~|l|. Anomalous entries are printed in the
6514 form of control sequences that are not followed by a blank space, e.g.,
6515 `\.{\\BAD.}'; this cannot be confused with actual control sequences because
6516 a real control sequence named \.{BAD} would come out `\.{\\BAD\ }'.
6517
6518 @<Declare the procedure called |show_token_list|@>=
6519 static void show_token_list(int @!p, int @!q, int @!l)
6520 {@+
6521 int m, @!c; /*pieces of a token*/
6522 UTF8_code @!match_chr; /*character used in a `|match|'*/
6523 UTF8_code @!n; /*the highest parameter number, as an ASCII digit*/
6524 match_chr='#';n='0';tally=0;
6525 while ((p!=null)&&(tally < l))
6526 {@+if (p==q) @<Do magic computation@>;
6527 @<Display token |p|, and |return| if there are problems@>;
6528 p=link(p);
6529 }
6530 if (p!=null) print_esc("ETC.");
6531 @.ETC@>
6532
6533 }
6534
6535 @ @<Display token |p|...@>=
6536 if ((p < hi_mem_min)||(p > mem_end))
6537 {@+print_esc("CLOBBERED.");return;
6538 @.CLOBBERED@>
6539 }
6540 if (info(p) >= cs_token_flag) print_cs(info(p)-cs_token_flag);
6541 else{@+m=info(p)/cmd_factor;c=info(p)%cmd_factor;
6542 if (info(p) < 0) print_esc("BAD.");
6543 @.BAD@>
6544 else@<Display the token $(|m|,|c|)$@>;
6545 }
6546
6547 @ The procedure usually ``learns'' the character code used for macro
6548 parameters by seeing one in a |match| command before it runs into any
6549 |out_param| commands.
6550
6551 @<Display the token...@>=
6552 switch (m) {
6553 case left_brace: case right_brace: case math_shift:
6554 case tab_mark: case sup_mark: case sub_mark:
6555 case spacer:
6556 case letter: case other_char:
6557 if (c<0x80) printn(c); else print_utf8(c); @+break;
6558 case mac_param: {@+printn(c);printn(c);
6559 } @+break;
6560 case out_param: {@+printn(match_chr);
6561 if (c <= 9) print_char(c+'0');
6562 else{@+print_char('!');return;
6563 }
6564 } @+break;
6565 case match: {@+match_chr=c;printn(c);incr(n);print_char(n);
6566 if (n > '9') return;
6567 } @+break;
6568 case end_match: if (c==0) print("->");@+break;
6569 @.->@>
6570 default:print_esc("BAD.");
6571 @.BAD@>
6572 }
6573
6574 @ Here's the way we sometimes want to display a token list, given a pointer
6575 to its reference count; the pointer may be null.
6576
6577 @p static void token_show(pointer @!p)
6578 {@+if (p!=null) show_token_list(link(p), null, 10000000);
6579 }
6580
6581 @ The |print_meaning| subroutine displays |cur_cmd| and |cur_chr| in
6582 symbolic form, including the expansion of a macro or mark.
6583
6584 @p static void print_meaning(void)
6585 {@+print_cmd_chr(cur_cmd, cur_chr);
6586 if (cur_cmd >= call)
6587 {@+print_char(':');print_ln();token_show(cur_chr);
6588 }
6589 else if ((cur_cmd==top_bot_mark)&&(cur_chr < marks_code))
6590 {@+print_char(':');print_ln();
6591 token_show(cur_mark[cur_chr]);
6592 }
6593 }
6594
6595 @* Introduction to the syntactic routines.
6596 Let's pause a moment now and try to look at the Big Picture.
6597 The \TeX\ program consists of three main parts: syntactic routines,
6598 semantic routines, and output routines. The chief purpose of the
6599 syntactic routines is to deliver the user's input to the semantic routines,
6600 one token at a time. The semantic routines act as an interpreter
6601 responding to these tokens, which may be regarded as commands. And the
6602 output routines are periodically called on to convert box-and-glue
6603 lists into a compact set of instructions that will be sent
6604 to a typesetter. We have discussed the basic data structures and utility
6605 routines of \TeX, so we are good and ready to plunge into the real activity by
6606 considering the syntactic routines.
6607
6608 Our current goal is to come to grips with the |get_next| procedure,
6609 which is the keystone of \TeX's input mechanism. Each call of |get_next|
6610 sets the value of three variables |cur_cmd|, |cur_chr|, and |cur_cs|,
6611 representing the next input token.
6612 $$\vbox{\halign{#\hfil\cr
6613 \hbox{|cur_cmd| denotes a command code from the long list of codes
6614 given above;}\cr
6615 \hbox{|cur_chr| denotes a character code or other modifier of the command
6616 code;}\cr
6617 \hbox{|cur_cs| is the |eqtb| location of the current control sequence,}\cr
6618 \hbox{\qquad if the current token was a control sequence,
6619 otherwise it's zero.}\cr}}$$
6620 Underlying this external behavior of |get_next| is all the machinery
6621 necessary to convert from character files to tokens. At a given time we
6622 may be only partially finished with the reading of several files (for
6623 which \.{\\input} was specified), and partially finished with the expansion
6624 of some user-defined macros and/or some macro parameters, and partially
6625 finished with the generation of some text in a template for \.{\\halign},
6626 and so on. When reading a character file, special characters must be
6627 classified as math delimiters, etc.; comments and extra blank spaces must
6628 be removed, paragraphs must be recognized, and control sequences must be
6629 found in the hash table. Furthermore there are occasions in which the
6630 scanning routines have looked ahead for a word like `\.{plus}' but only
6631 part of that word was found, hence a few characters must be put back
6632 into the input and scanned again.
6633
6634 To handle these situations, which might all be present simultaneously,
6635 \TeX\ uses various stacks that hold information about the incomplete
6636 activities, and there is a finite state control for each level of the
6637 input mechanism. These stacks record the current state of an implicitly
6638 recursive process, but the |get_next| procedure is not recursive.
6639 Therefore it will not be difficult to translate these algorithms into
6640 low-level languages that do not support recursion.
6641
6642 @<Glob...@>=
6643 static eight_bits @!cur_cmd; /*current command set by |get_next|*/
6644 static halfword @!cur_chr; /*operand of current command*/
6645 static pointer @!cur_cs; /*control sequence found here, zero if none found*/
6646 static halfword @!cur_tok; /*packed representative of |cur_cmd| and |cur_chr|*/
6647
6648 @ The |print_cmd_chr| routine prints a symbolic interpretation of a
6649 command code and its modifier. This is used in certain `\.{You can\'t}'
6650 error messages, and in the implementation of diagnostic routines like
6651 \.{\\show}.
6652
6653 The body of |print_cmd_chr| is a rather tedious listing of print
6654 commands, and most of it is essentially an inverse to the |primitive|
6655 routine that enters a \TeX\ primitive into |eqtb|. Therefore much of
6656 this procedure appears elsewhere in the program,
6657 together with the corresponding |primitive| calls.
6658
6659 @d chr_cmd(A) {@+print(A);print_ASCII(chr_code);
6660 }
6661
6662 @<Declare the procedure called |print_cmd_chr|@>=
6663 static void print_cmd_chr(quarterword @!cmd, halfword @!chr_code)
6664 {@+int n; /*temp variable*/
6665 switch (cmd) {
6666 case left_brace: chr_cmd("begin-group character ")@;@+break;
6667 case right_brace: chr_cmd("end-group character ")@;@+break;
6668 case math_shift: chr_cmd("math shift character ")@;@+break;
6669 case mac_param: chr_cmd("macro parameter character ")@;@+break;
6670 case sup_mark: chr_cmd("superscript character ")@;@+break;
6671 case sub_mark: chr_cmd("subscript character ")@;@+break;
6672 case endv: print("end of alignment template");@+break;
6673 case spacer: chr_cmd("blank space ")@;@+break;
6674 case letter: chr_cmd("the letter ")@;@+break;
6675 case other_char: chr_cmd("the character ")@;@+break;
6676 @t\4@>@<Cases of |print_cmd_chr| for symbolic printing of primitives@>@/
6677 default:print("[unknown command code!]");
6678 }
6679 }
6680
6681 @ Here is a procedure that displays the current command.
6682
6683 @p static void show_cur_cmd_chr(void)
6684 {@+int n; /*level of \.{\\if...\\fi} nesting*/
6685 int @!l; /*line where \.{\\if} started*/
6686 pointer @!p;
6687 begin_diagnostic();print_nl("{");
6688 if (mode!=shown_mode)
6689 {@+print_mode(mode);print(": ");shown_mode=mode;
6690 }
6691 print_cmd_chr(cur_cmd, cur_chr);
6692 if (tracing_ifs > 0)
6693 if (cur_cmd >= if_test) if (cur_cmd <= fi_or_else)
6694 {@+print(": ");
6695 if (cur_cmd==fi_or_else)
6696 {@+print_cmd_chr(if_test, cur_if);print_char(' ');
6697 n=0;l=if_line;
6698 }
6699 else{@+n=1;l=line;
6700 }
6701 p=cond_ptr;
6702 while (p!=null)
6703 {@+incr(n);p=link(p);
6704 }
6705 print("(level ");print_int(n);print_char(')');print_if_line(l);
6706 }
6707 print_char('}');
6708 end_diagnostic(false);
6709 }
6710
6711 @* Input stacks and states.
6712 This implementation of
6713 \TeX\ uses two different conventions for representing sequential stacks.
6714 @^stack conventions@>@^conventions for representing stacks@>
6715
6716 \yskip\hangg 1) If there is frequent access to the top entry, and if the
6717 stack is essentially never empty, then the top entry is kept in a global
6718 variable (even better would be a machine register), and the other entries
6719 appear in the array $\\{stack}[0\to(\\{ptr}-1)]$. For example, the
6720 semantic stack described above is handled this way, and so is the input
6721 stack that we are about to study.
6722
6723 \yskip\hangg 2) If there is infrequent top access, the entire stack contents
6724 are in the array $\\{stack}[0\to(\\{ptr}-1)]$. For example, the |save_stack|
6725 is treated this way, as we have seen.
6726
6727 \yskip\noindent
6728 The state of \TeX's input mechanism appears in the input stack, whose
6729 entries are records with six fields, called |state|, |index|, |start|, |loc|,
6730 |limit|, and |name|. This stack is maintained with
6731 convention~(1), so it is declared in the following way:
6732
6733 @<Types...@>=
6734 typedef struct {
6735 quarterword @!state_field, @!index_field;
6736 halfword @!start_field, @!loc_field, @!limit_field, @!name_field;
6737 } in_state_record;
6738
6739 @ @<Glob...@>=
6740 static in_state_record @!input_stack[stack_size+1];
6741 static int @!input_ptr; /*first unused location of |input_stack|*/
6742 static int @!max_in_stack; /*largest value of |input_ptr| when pushing*/
6743 static in_state_record @!cur_input;
6744 /*the ``top'' input state, according to convention (1)*/
6745
6746 @ We've already defined the special variable |loc====cur_input.loc_field|
6747 in our discussion of basic input-output routines. The other components of
6748 |cur_input| are defined in the same way:
6749
6750 @d state cur_input.state_field /*current scanner state*/
6751 @d index cur_input.index_field /*reference for buffer information*/
6752 @d start cur_input.start_field /*starting position in |buffer|*/
6753 @d limit cur_input.limit_field /*end of current line in |buffer|*/
6754 @d name cur_input.name_field /*name of the current file*/
6755
6756 @ Let's look more closely now at the control variables
6757 (|state|,~|index|,~|start|,~|loc|,~|limit|,~|name|),
6758 assuming that \TeX\ is reading a line of characters that have been input
6759 from some file or from the user's terminal. There is an array called
6760 |buffer| that acts as a stack of all lines of characters that are
6761 currently being read from files, including all lines on subsidiary
6762 levels of the input stack that are not yet completed. \TeX\ will return to
6763 the other lines when it is finished with the present input file.
6764
6765 (Incidentally, on a machine with byte-oriented addressing, it might be
6766 appropriate to combine |buffer| with the |str_pool| array,
6767 letting the buffer entries grow downward from the top of the string pool
6768 and checking that these two tables don't bump into each other.)
6769
6770 The line we are currently working on begins in position |start| of the
6771 buffer; the next character we are about to read is |buffer[loc]|; and
6772 |limit| is the location of the last character present. If |loc > limit|,
6773 the line has been completely read. Usually |buffer[limit]| is the
6774 |end_line_char|, denoting the end of a line, but this is not
6775 true if the current line is an insertion that was entered on the user's
6776 terminal in response to an error message.
6777
6778 The |name| variable is a string number that designates the name of
6779 the current file, if we are reading a text file. It is zero if we
6780 are reading from the terminal; it is |n+1| if we are reading from
6781 input stream |n|, where |0 <= n <= 16|. (Input stream 16 stands for
6782 an invalid stream number; in such cases the input is actually from
6783 the terminal, under control of the procedure |read_toks|.)
6784 Finally |18 <= name <= 19| indicates that we are reading a pseudo file
6785 created by the \.{\\scantokens} command.
6786
6787 The |state| variable has one of three values, when we are scanning such
6788 files:
6789 $$\baselineskip 15pt\vbox{\halign{#\hfil\cr
6790 1) |state==mid_line| is the normal state.\cr
6791 2) |state==skip_blanks| is like |mid_line|, but blanks are ignored.\cr
6792 3) |state==new_line| is the state at the beginning of a line.\cr}}$$
6793 These state values are assigned numeric codes so that if we add the state
6794 code to the next character's command code, we get distinct values. For
6795 example, `|mid_line+spacer|' stands for the case that a blank
6796 space character occurs in the middle of a line when it is not being
6797 ignored; after this case is processed, the next value of |state| will
6798 be |skip_blanks|.
6799
6800 @d mid_line 1 /*|state| code when scanning a line of characters*/
6801 @d skip_blanks (2+max_char_code) /*|state| code when ignoring blanks*/
6802 @d new_line (3+max_char_code+max_char_code) /*|state| code at start of line*/
6803
6804 @ Additional information about the current line is available via the
6805 |index| variable, which counts how many lines of characters are present
6806 in the buffer below the current level. We have |index==0| when reading
6807 from the terminal and prompting the user for each line; then if the user types,
6808 e.g., `\.{\\input paper}', we will have |index==1| while reading
6809 the file \.{paper.tex}. However, it does not follow that |index| is the
6810 same as the input stack pointer, since many of the levels on the input
6811 stack may come from token lists. For example, the instruction `\.{\\input
6812 paper}' might occur in a token list.
6813
6814 The global variable |in_open| is equal to the |index|
6815 value of the highest non-token-list level. Thus, the number of partially read
6816 lines in the buffer is |in_open+1|, and we have |in_open==index|
6817 when we are not reading a token list.
6818
6819 If we are not currently reading from the terminal, or from an input
6820 stream, we are reading from the file variable |input_file[index]|. We use
6821 the notation |terminal_input| as a convenient abbreviation for |name==0|,
6822 and |cur_file| as an abbreviation for |input_file[index]|.
6823
6824 The global variable |line| contains the line number in the topmost
6825 open file, for use in error messages. If we are not reading from
6826 the terminal, |line_stack[index]| holds the line number for the
6827 enclosing level, so that |line| can be restored when the current
6828 file has been read. Line numbers should never be negative, since the
6829 negative of the current line number is used to identify the user's output
6830 routine in the |mode_line| field of the semantic nest entries.
6831
6832 If more information about the input state is needed, it can be
6833 included in small arrays like those shown here. For example,
6834 the current page or segment number in the input file might be
6835 put into a variable |@!page|, maintained for enclosing levels in
6836 `\ignorespaces|@!page_stack: array[1 dotdot max_in_open]int|\unskip'
6837 by analogy with |line_stack|.
6838 @^system dependencies@>
6839
6840 @d terminal_input (name==0) /*are we reading from the terminal?*/
6841 @d cur_file input_file[index] /*the current |alpha_file| variable*/
6842
6843 @<Glob...@>=
6844 static int @!in_open; /*the number of lines in the buffer, less one*/
6845 static int @!open_parens; /*the number of open text files*/
6846 static alpha_file @!input_file0[max_in_open],
6847 *const @!input_file = @!input_file0-1;
6848 static int @!line; /*current line number in the current source file*/
6849 static int @!line_stack0[max_in_open],
6850 *const @!line_stack = @!line_stack0-1;
6851
6852 @ Users of \TeX\ sometimes forget to balance left and right braces properly,
6853 and one of the ways \TeX\ tries to spot such errors is by considering an
6854 input file as broken into subfiles by control sequences that
6855 are declared to be \.{\\outer}.
6856
6857 A variable called |scanner_status| tells \TeX\ whether or not to complain
6858 when a subfile ends. This variable has six possible values:
6859
6860 \yskip\hang|normal|, means that a subfile can safely end here without incident.
6861
6862 \yskip\hang|skipping|, means that a subfile can safely end here, but not a file,
6863 because we're reading past some conditional text that was not selected.
6864
6865 \yskip\hang|defining|, means that a subfile shouldn't end now because a
6866 macro is being defined.
6867
6868 \yskip\hang|matching|, means that a subfile shouldn't end now because a
6869 macro is being used and we are searching for the end of its arguments.
6870
6871 \yskip\hang|aligning|, means that a subfile shouldn't end now because we are
6872 not finished with the preamble of an \.{\\halign} or \.{\\valign}.
6873
6874 \yskip\hang|absorbing|, means that a subfile shouldn't end now because we are
6875 reading a balanced token list for \.{\\message}, \.{\\write}, etc.
6876
6877 \yskip\noindent
6878 If the |scanner_status| is not |normal|, the variable |warning_index| points
6879 to the |eqtb| location for the relevant control sequence name to print
6880 in an error message.
6881
6882 @d skipping 1 /*|scanner_status| when passing conditional text*/
6883 @d defining 2 /*|scanner_status| when reading a macro definition*/
6884 @d matching 3 /*|scanner_status| when reading macro arguments*/
6885 @d aligning 4 /*|scanner_status| when reading an alignment preamble*/
6886 @d absorbing 5 /*|scanner_status| when reading a balanced text*/
6887
6888 @<Glob...@>=
6889 static int @!scanner_status; /*can a subfile end now?*/
6890 static pointer @!warning_index; /*identifier relevant to non-|normal| scanner status*/
6891 static pointer @!def_ref; /*reference count of token list being defined*/
6892
6893 @ Here is a procedure that uses |scanner_status| to print a warning message
6894 when a subfile has ended, and at certain other crucial times:
6895
6896 @<Declare the procedure called |runaway|@>=
6897 static void runaway(void)
6898 {@+pointer p; /*head of runaway list*/
6899 if (scanner_status > skipping)
6900 {@+print_nl("Runaway ");
6901 @.Runaway...@>
6902 switch (scanner_status) {
6903 case defining: {@+print("definition");p=def_ref;
6904 } @+break;
6905 case matching: {@+print("argument");p=temp_head;
6906 } @+break;
6907 case aligning: {@+print("preamble");p=hold_head;
6908 } @+break;
6909 case absorbing: {@+print("text");p=def_ref;
6910 }
6911 } /*there are no other cases*/
6912 print_char('?');print_ln();show_token_list(link(p), null, error_line-10);
6913 }
6914 }
6915
6916 @ However, all this discussion about input state really applies only to the
6917 case that we are inputting from a file. There is another important case,
6918 namely when we are currently getting input from a token list. In this case
6919 |state==token_list|, and the conventions about the other state variables
6920 are different:
6921
6922 \yskip\hang|loc| is a pointer to the current node in the token list, i.e.,
6923 the node that will be read next. If |loc==null|, the token list has been
6924 fully read.
6925
6926 \yskip\hang|start| points to the first node of the token list; this node
6927 may or may not contain a reference count, depending on the type of token
6928 list involved.
6929
6930 \yskip\hang|token_type|, which takes the place of |index| in the
6931 discussion above, is a code number that explains what kind of token list
6932 is being scanned.
6933
6934 \yskip\hang|name| points to the |eqtb| address of the control sequence
6935 being expanded, if the current token list is a macro.
6936
6937 \yskip\hang|param_start|, which takes the place of |limit|, tells where
6938 the parameters of the current macro begin in the |param_stack|, if the
6939 current token list is a macro.
6940
6941 \yskip\noindent The |token_type| can take several values, depending on
6942 where the current token list came from:
6943
6944 \yskip\hang|parameter|, if a parameter is being scanned;
6945
6946 \hang|u_template|, if the \<u_j> part of an alignment
6947 template is being scanned;
6948
6949 \hang|v_template|, if the \<v_j> part of an alignment
6950 template is being scanned;
6951
6952 \hang|backed_up|, if the token list being scanned has been inserted as
6953 `to be read again';
6954
6955 \hang|inserted|, if the token list being scanned has been inserted as
6956 the text expansion of a \.{\\count} or similar variable;
6957
6958 \hang|macro|, if a user-defined control sequence is being scanned;
6959
6960 \hang|output_text|, if an \.{\\output} routine is being scanned;
6961
6962 \hang|every_par_text|, if the text of \.{\\everypar} is being scanned;
6963
6964 \hang|every_math_text|, if the text of \.{\\everymath} is being scanned;
6965
6966 \hang|every_display_text|, if the text of \.{\\everydisplay} is being scanned;
6967
6968 \hang|every_hbox_text|, if the text of \.{\\everyhbox} is being scanned;
6969
6970 \hang|every_vbox_text|, if the text of \.{\\everyvbox} is being scanned;
6971
6972 \hang|every_job_text|, if the text of \.{\\everyjob} is being scanned;
6973
6974 \hang|every_cr_text|, if the text of \.{\\everycr} is being scanned;
6975
6976 \hang|mark_text|, if the text of a \.{\\mark} is being scanned;
6977
6978 \hang|write_text|, if the text of a \.{\\write} is being scanned.
6979
6980 \yskip\noindent
6981 The codes for |output_text|, |every_par_text|, etc., are equal to a constant
6982 plus the corresponding codes for token list parameters |output_routine_loc|,
6983 |every_par_loc|, etc. The token list begins with a reference count if and
6984 only if |token_type >= macro|.
6985 @^reference counts@>
6986
6987 Since \eTeX's additional token list parameters precede |toks_base|, the
6988 corresponding token types must precede |write_text|.
6989
6990 @d token_list 0 /*|state| code when scanning a token list*/
6991 @d token_type index /*type of current token list*/
6992 @d param_start limit /*base of macro parameters in |param_stack|*/
6993 @d parameter 0 /*|token_type| code for parameter*/
6994 @d u_template 1 /*|token_type| code for \<u_j> template*/
6995 @d v_template 2 /*|token_type| code for \<v_j> template*/
6996 @d backed_up 3 /*|token_type| code for text to be reread*/
6997 @d inserted 4 /*|token_type| code for inserted texts*/
6998 @d macro 5 /*|token_type| code for defined control sequences*/
6999 @d output_text 6 /*|token_type| code for output routines*/
7000 @d every_par_text 7 /*|token_type| code for \.{\\everypar}*/
7001 @d every_math_text 8 /*|token_type| code for \.{\\everymath}*/
7002 @d every_display_text 9 /*|token_type| code for \.{\\everydisplay}*/
7003 @d every_hbox_text 10 /*|token_type| code for \.{\\everyhbox}*/
7004 @d every_vbox_text 11 /*|token_type| code for \.{\\everyvbox}*/
7005 @d every_job_text 12 /*|token_type| code for \.{\\everyjob}*/
7006 @d every_cr_text 13 /*|token_type| code for \.{\\everycr}*/
7007 @d mark_text 14 /*|token_type| code for \.{\\topmark}, etc.*/
7008 @#
7009 @d eTeX_text_offset (output_routine_loc-output_text)
7010 @d every_eof_text (every_eof_loc-eTeX_text_offset)
7011 /*|token_type| code for \.{\\everyeof}*/
7012 @#
7013 @d write_text (toks_base-eTeX_text_offset) /*|token_type| code for \.{\\write}*/
7014
7015 @ The |param_stack| is an auxiliary array used to hold pointers to the token
7016 lists for parameters at the current level and subsidiary levels of input.
7017 This stack is maintained with convention (2), and it grows at a different
7018 rate from the others.
7019
7020 @<Glob...@>=
7021 static pointer @!param_stack[param_size+1];
7022 /*token list pointers for parameters*/
7023 static int @!param_ptr; /*first unused entry in |param_stack|*/
7024 static int @!max_param_stack;
7025 /*largest value of |param_ptr|, will be | <= param_size+9|*/
7026
7027 @ The input routines must also interact with the processing of
7028 \.{\\halign} and \.{\\valign}, since the appearance of tab marks and
7029 \.{\\cr} in certain places is supposed to trigger the beginning of special
7030 \<v_j> template text in the scanner. This magic is accomplished by an
7031 |align_state| variable that is increased by~1 when a `\.{\char'173}' is
7032 scanned and decreased by~1 when a `\.{\char'175}' is scanned. The |align_state|
7033 is nonzero during the \<u_j> template, after which it is set to zero; the
7034 \<v_j> template begins when a tab mark or \.{\\cr} occurs at a time that
7035 |align_state==0|.
7036
7037 The same principle applies when entering the definition of a
7038 control sequence between \.{\\csname} and \.{\\endcsname}.
7039
7040 @<Glob...@>=
7041 static int @!align_state; /*group level with respect to current alignment*/
7042 static int @!incsname_state; /*group level with respect to in csname state*/
7043
7044 @ Thus, the ``current input state'' can be very complicated indeed; there
7045 can be many levels and each level can arise in a variety of ways. The
7046 |show_context| procedure, which is used by \TeX's error-reporting routine to
7047 print out the current input state on all levels down to the most recent
7048 line of characters from an input file, illustrates most of these conventions.
7049 The global variable |base_ptr| contains the lowest level that was
7050 displayed by this procedure.
7051
7052 @<Glob...@>=
7053 static int @!base_ptr; /*shallowest level shown by |show_context|*/
7054
7055 @ The status at each level is indicated by printing two lines, where the first
7056 line indicates what was read so far and the second line shows what remains
7057 to be read. The context is cropped, if necessary, so that the first line
7058 contains at most |half_error_line| characters, and the second contains
7059 at most |error_line|. Non-current input levels whose |token_type| is
7060 `|backed_up|' are shown only if they have not been fully read.
7061
7062 @p static void show_context(void) /*prints where the scanner is*/
7063 {@+
7064 int old_setting; /*saved |selector| setting*/
7065 int @!nn; /*number of contexts shown so far, less one*/
7066 bool @!bottom_line; /*have we reached the final context to be shown?*/
7067 @<Local variables for formatting calculations@>@/
7068 base_ptr=input_ptr;input_stack[base_ptr]=cur_input;
7069 /*store current state*/
7070 nn=-1;bottom_line=false;
7071 loop@+{@+cur_input=input_stack[base_ptr]; /*enter into the context*/
7072 if ((state!=token_list))
7073 if ((name > 19)||(base_ptr==0)) bottom_line=true;
7074 if ((base_ptr==input_ptr)||bottom_line||(nn < error_context_lines))
7075 @<Display the current context@>@;
7076 else if (nn==error_context_lines)
7077 {@+print_nl("...");incr(nn); /*omitted if |error_context_lines < 0|*/
7078 }
7079 if (bottom_line) goto done;
7080 decr(base_ptr);
7081 }
7082 done: cur_input=input_stack[input_ptr]; /*restore original state*/
7083 }
7084
7085 @ @<Display the current context@>=
7086 {@+if ((base_ptr==input_ptr)||(state!=token_list)||
7087 (token_type!=backed_up)||(loc!=null))
7088 /*we omit backed-up token lists that have already been read*/
7089 {@+tally=0; /*get ready to count characters*/
7090 old_setting=selector;
7091 if (state!=token_list)
7092 {@+@<Print location of current line@>;
7093 @<Pseudoprint the line@>;
7094 }
7095 else{@+@<Print type of token list@>;
7096 @<Pseudoprint the token list@>;
7097 }
7098 selector=old_setting; /*stop pseudoprinting*/
7099 @<Print two lines using the tricky pseudoprinted information@>;
7100 incr(nn);
7101 }
7102 }
7103
7104 @ This routine should be changed, if necessary, to give the best possible
7105 indication of where the current line resides in the input file.
7106 For example, on some systems it is best to print both a page and line number.
7107 @^system dependencies@>
7108
7109 @<Print location of current line@>=
7110 if (name <= 17)
7111 if (terminal_input)
7112 if (base_ptr==0) print_nl("<*>");else print_nl("<insert> ");
7113 else{@+print_nl("<read ");
7114 if (name==17) print_char('*');@+else print_int(name-1);
7115 @.*\relax@>
7116 print_char('>');
7117 }
7118 else{@+print_nl("l.");
7119 if (index==in_open) print_int(line);
7120 else print_int(line_stack[index+1]); /*input from a pseudo file*/
7121 }
7122 print_char(' ')
7123
7124 @ @<Print type of token list@>=
7125 switch (token_type) {
7126 case parameter: print_nl("<argument> ");@+break;
7127 case u_template: case v_template: print_nl("<template> ");@+break;
7128 case backed_up: if (loc==null) print_nl("<recently read> ");
7129 else print_nl("<to be read again> ");@+break;
7130 case inserted: print_nl("<inserted text> ");@+break;
7131 case macro: {@+print_ln();print_cs(name);
7132 } @+break;
7133 case output_text: print_nl("<output> ");@+break;
7134 case every_par_text: print_nl("<everypar> ");@+break;
7135 case every_math_text: print_nl("<everymath> ");@+break;
7136 case every_display_text: print_nl("<everydisplay> ");@+break;
7137 case every_hbox_text: print_nl("<everyhbox> ");@+break;
7138 case every_vbox_text: print_nl("<everyvbox> ");@+break;
7139 case every_job_text: print_nl("<everyjob> ");@+break;
7140 case every_cr_text: print_nl("<everycr> ");@+break;
7141 case mark_text: print_nl("<mark> ");@+break;
7142 case every_eof_text: print_nl("<everyeof> ");@+break;
7143 case write_text: print_nl("<write> ");@+break;
7144 default:print_nl("?"); /*this should never happen*/
7145 }
7146
7147 @ Here it is necessary to explain a little trick. We don't want to store a long
7148 string that corresponds to a token list, because that string might take up
7149 lots of memory; and we are printing during a time when an error message is
7150 being given, so we dare not do anything that might overflow one of \TeX's
7151 tables. So `pseudoprinting' is the answer: We enter a mode of printing
7152 that stores characters into a buffer of length |error_line|, where character
7153 $k+1$ is placed into \hbox{|trick_buf[k%error_line]|} if
7154 |k < trick_count|, otherwise character |k| is dropped. Initially we set
7155 |tally=0| and |trick_count=1000000|; then when we reach the
7156 point where transition from line 1 to line 2 should occur, we
7157 set |first_count=tally| and |trick_count=@tmax@>(error_line,
7158 tally+1+error_line-half_error_line)|. At the end of the
7159 pseudoprinting, the values of |first_count|, |tally|, and
7160 |trick_count| give us all the information we need to print the two lines,
7161 and all of the necessary text is in |trick_buf|.
7162
7163 Namely, let |l| be the length of the descriptive information that appears
7164 on the first line. The length of the context information gathered for that
7165 line is |k==first_count|, and the length of the context information
7166 gathered for line~2 is $m=\min(|tally|, |trick_count|)-k$. If |l+k <= h|,
7167 where |h==half_error_line|, we print |trick_buf[0 dotdot k-1]| after the
7168 descriptive information on line~1, and set |n=l+k|; here |n| is the
7169 length of line~1. If $l+k>h$, some cropping is necessary, so we set |n=h|
7170 and print `\.{...}' followed by
7171 $$\hbox{|trick_buf[(l+k-h+3)dotdot k-1]|,}$$
7172 where subscripts of |trick_buf| are circular modulo |error_line|. The
7173 second line consists of |n|~spaces followed by |trick_buf[k dotdot(k+m-1)]|,
7174 unless |n+m > error_line|; in the latter case, further cropping is done.
7175 This is easier to program than to explain.
7176
7177 @<Local variables for formatting...@>=
7178 int @!i; /*index into |buffer|*/
7179 int @!j; /*end of current line in |buffer|*/
7180 int @!l; /*length of descriptive information on line 1*/
7181 int @!m; /*context information gathered for line 2*/
7182 int @!n; /*length of line 1*/
7183 int @!p; /*starting or ending place in |trick_buf|*/
7184 int @!q; /*temporary index*/
7185
7186 @ The following code sets up the print routines so that they will gather
7187 the desired information.
7188
7189 @d begin_pseudoprint
7190 {@+l=tally;tally=0;selector=pseudo;
7191 trick_count=1000000;
7192 }
7193 @d set_trick_count
7194 {@+first_count=tally;
7195 trick_count=tally+1+error_line-half_error_line;
7196 if (trick_count < error_line) trick_count=error_line;
7197 }
7198
7199 @ And the following code uses the information after it has been gathered.
7200
7201 @<Print two lines using the tricky pseudoprinted information@>=
7202 if (trick_count==1000000) set_trick_count;
7203 /*|set_trick_count| must be performed*/
7204 if (tally < trick_count) m=tally-first_count;
7205 else m=trick_count-first_count; /*context on line 2*/
7206 if (l+first_count <= half_error_line)
7207 {@+p=0;n=l+first_count;
7208 }
7209 else{@+print("...");p=l+first_count-half_error_line+3;
7210 n=half_error_line;
7211 }
7212 for (q=p; q<=first_count-1; q++) print_char(trick_buf[q%error_line]);
7213 print_ln();
7214 for (q=1; q<=n; q++) print_char(' '); /*print |n| spaces to begin line~2*/
7215 if (m+n <= error_line) p=first_count+m;else p=first_count+(error_line-n-3);
7216 for (q=first_count; q<=p-1; q++) print_char(trick_buf[q%error_line]);
7217 if (m+n > error_line) print("...")
7218
7219 @ But the trick is distracting us from our current goal, which is to
7220 understand the input state. So let's concentrate on the data structures that
7221 are being pseudoprinted as we finish up the |show_context| procedure.
7222
7223 @<Pseudoprint the line@>=
7224 begin_pseudoprint;
7225 if (buffer[limit]==end_line_char) j=limit;
7226 else j=limit+1; /*determine the effective end of the line*/
7227 if (j > 0) for (i=start; i<=j-1; i++)
7228 {@+if (i==loc) set_trick_count;
7229 printn(buffer[i]);
7230 }
7231
7232 @ @<Pseudoprint the token list@>=
7233 begin_pseudoprint;
7234 if (token_type < macro) show_token_list(start, loc, 100000);
7235 else show_token_list(link(start), loc, 100000) /*avoid reference count*/
7236
7237 @ Here is the missing piece of |show_token_list| that is activated when the
7238 token beginning line~2 is about to be shown:
7239
7240 @<Do magic computation@>=set_trick_count
7241
7242 @* Maintaining the input stacks.
7243 The following subroutines change the input status in commonly needed ways.
7244
7245 First comes |push_input|, which stores the current state and creates a
7246 new level (having, initially, the same properties as the old).
7247
7248 @d push_input @t@> /*enter a new input level, save the old*/
7249 {@+if (input_ptr > max_in_stack)
7250 {@+max_in_stack=input_ptr;
7251 if (input_ptr==stack_size) overflow("input stack size", stack_size);
7252 @:TeX capacity exceeded input stack size}{\quad input stack size@>
7253 }
7254 input_stack[input_ptr]=cur_input; /*stack the record*/
7255 incr(input_ptr);
7256 }
7257
7258 @ And of course what goes up must come down.
7259
7260 @d pop_input @t@> /*leave an input level, re-enter the old*/
7261 {@+decr(input_ptr);cur_input=input_stack[input_ptr];
7262 }
7263
7264 @ Here is a procedure that starts a new level of token-list input, given
7265 a token list |p| and its type |t|. If |t==macro|, the calling routine should
7266 set |name| and |loc|.
7267
7268 @d back_list(A) begin_token_list(A, backed_up) /*backs up a simple token list*/
7269 @d ins_list(A) begin_token_list(A, inserted) /*inserts a simple token list*/
7270
7271 @p static void begin_token_list(pointer @!p, quarterword @!t)
7272 {@+push_input;state=token_list;start=p;token_type=t;
7273 if (t >= macro) /*the token list starts with a reference count*/
7274 {@+add_token_ref(p);
7275 if (t==macro) param_start=param_ptr;
7276 else{@+loc=link(p);
7277 if (tracing_macros > 1)
7278 {@+begin_diagnostic();print_nl("");
7279 switch (t) {
7280 case mark_text: print_esc("mark");@+break;
7281 case write_text: print_esc("write");@+break;
7282 default:print_cmd_chr(assign_toks, t-output_text+output_routine_loc);
7283 } @/
7284 print("->");token_show(p);end_diagnostic(false);
7285 }
7286 }
7287 }
7288 else loc=p;
7289 }
7290
7291 @ When a token list has been fully scanned, the following computations
7292 should be done as we leave that level of input. The |token_type| tends
7293 to be equal to either |backed_up| or |inserted| about 2/3 of the time.
7294 @^inner loop@>
7295
7296 @p static void end_token_list(void) /*leave a token-list input level*/
7297 {@+if (token_type >= backed_up) /*token list to be deleted*/
7298 {@+if (token_type <= inserted) flush_list(start);
7299 else{@+delete_token_ref(start); /*update reference count*/
7300 if (token_type==macro) /*parameters must be flushed*/
7301 while (param_ptr > param_start)
7302 {@+decr(param_ptr);
7303 flush_list(param_stack[param_ptr]);
7304 }
7305 }
7306 }
7307 else if (token_type==u_template)
7308 if (align_state > 500000) align_state=0;
7309 else fatal_error("(interwoven alignment preambles are not allowed)");
7310 @.interwoven alignment preambles...@>
7311 pop_input;
7312 check_interrupt;
7313 }
7314
7315 @ Sometimes \TeX\ has read too far and wants to ``unscan'' what it has
7316 seen. The |back_input| procedure takes care of this by putting the token
7317 just scanned back into the input stream, ready to be read again. This
7318 procedure can be used only if |cur_tok| represents the token to be
7319 replaced. Some applications of \TeX\ use this procedure a lot,
7320 so it has been slightly optimized for speed.
7321 @^inner loop@>
7322
7323 @p static void back_input(void) /*undoes one token of input*/
7324 {@+pointer p; /*a token list of length one*/
7325 while ((state==token_list)&&(loc==null)&&(token_type!=v_template))
7326 end_token_list(); /*conserve stack space*/
7327 p=get_avail();info(p)=cur_tok;
7328 if (cur_tok < right_brace_limit)
7329 if (cur_tok < left_brace_limit) decr(align_state);
7330 else incr(align_state);
7331 push_input;state=token_list;start=p;token_type=backed_up;
7332 loc=p; /*that was |back_list(p)|, without procedure overhead*/
7333 }
7334
7335 @ @<Insert token |p| into \TeX's input@>=
7336 {@+t=cur_tok;cur_tok=p;
7337 if (a)
7338 {@+p=get_avail();info(p)=cur_tok;link(p)=loc;loc=p;start=p;
7339 if (cur_tok < right_brace_limit)
7340 if (cur_tok < left_brace_limit) decr(align_state);
7341 else incr(align_state);
7342 }
7343 else{@+back_input();a=eTeX_ex;
7344 }
7345 cur_tok=t;
7346 }
7347
7348 @ The |back_error| routine is used when we want to replace an offending token
7349 just before issuing an error message. This routine, like |back_input|,
7350 requires that |cur_tok| has been set. We disable interrupts during the
7351 call of |back_input| so that the help message won't be lost.
7352
7353 @p static void back_error(void) /*back up one token and call |error|*/
7354 {@+OK_to_interrupt=false;back_input();OK_to_interrupt=true;error();
7355 }
7356 @#
7357 static void ins_error(void) /*back up one inserted token and call |error|*/
7358 {@+OK_to_interrupt=false;back_input();token_type=inserted;
7359 OK_to_interrupt=true;error();
7360 }
7361
7362 @ The |begin_file_reading| procedure starts a new level of input for lines
7363 of characters to be read from a file, or as an insertion from the
7364 terminal. It does not take care of opening the file, nor does it set |loc|
7365 or |limit| or |line|.
7366 @^system dependencies@>
7367
7368 @p static void begin_file_reading(void)
7369 {@+if (in_open==max_in_open) overflow("text input levels", max_in_open);
7370 @:TeX capacity exceeded text input levels}{\quad text input levels@>
7371 if (first==buf_size) overflow("buffer size", buf_size);
7372 @:TeX capacity exceeded buffer size}{\quad buffer size@>
7373 incr(in_open);push_input;index=in_open;@/
7374 source_filename_stack[index]=NULL; /* \TeX\ Live */
7375 full_source_filename_stack[index]=NULL; /* \TeX\ Live */
7376 eof_seen[index]=false;
7377 grp_stack[index]=cur_boundary;if_stack[index]=cond_ptr;
7378 line_stack[index]=line;start=first;state=mid_line;
7379 name=0; /*|terminal_input| is now |true|*/
7380 }
7381
7382 @ Conversely, the variables must be downdated when such a level of input
7383 is finished:
7384
7385 @p static void end_file_reading(void)
7386 {@+first=start;line=line_stack[index];
7387 if ((name==18)||(name==19)) pseudo_close();else
7388 if (name > 17) a_close(&cur_file); /*forget it*/
7389 if (full_source_filename_stack[in_open]!=NULL)
7390 { free(full_source_filename_stack[in_open]);
7391 full_source_filename_stack[in_open]=NULL;
7392 }
7393 pop_input;decr(in_open);
7394 }
7395
7396 @ In order to keep the stack from overflowing during a long sequence of
7397 inserted `\.{\\show}' commands, the following routine removes completed
7398 error-inserted lines from memory.
7399
7400 @p static void clear_for_error_prompt(void)
7401 {@+while ((state!=token_list)&&terminal_input&&@|
7402 (input_ptr > 0)&&(loc > limit)) end_file_reading();
7403 print_ln();clear_terminal;
7404 }
7405
7406 @ To get \TeX's whole input mechanism going, we perform the following
7407 actions.
7408
7409 @<Initialize the input routines@>=
7410 {@+input_ptr=0;max_in_stack=0;
7411 in_open=0;open_parens=0;max_buf_stack=0;
7412 grp_stack[0]=0;if_stack[0]=null;
7413 param_ptr=0;max_param_stack=0;
7414 first=buf_size;@/do@+{buffer[first]=0;decr(first);}@+ while (!(first==0));
7415 scanner_status=normal;warning_index=null;first=1;
7416 state=new_line;start=1;index=0;line=0;name=0;
7417 force_eof=false;
7418 align_state=1000000;@/
7419 if (!init_terminal()) exit(0);
7420 limit=last;first=last+1; /*|init_terminal| has set |loc| and |last|*/
7421 }
7422
7423 @* Getting the next token.
7424 The heart of \TeX's input mechanism is the |get_next| procedure, which
7425 we shall develop in the next few sections of the program. Perhaps we
7426 shouldn't actually call it the ``heart,'' however, because it really acts
7427 as \TeX's eyes and mouth, reading the source files and gobbling them up.
7428 And it also helps \TeX\ to regurgitate stored token lists that are to be
7429 processed again.
7430 @^eyes and mouth@>
7431
7432 The main duty of |get_next| is to input one token and to set |cur_cmd|
7433 and |cur_chr| to that token's command code and modifier. Furthermore, if
7434 the input token is a control sequence, the |eqtb| location of that control
7435 sequence is stored in |cur_cs|; otherwise |cur_cs| is set to zero.
7436
7437 Underlying this simple description is a certain amount of complexity
7438 because of all the cases that need to be handled.
7439 However, the inner loop of |get_next| is reasonably short and fast.
7440
7441 When |get_next| is asked to get the next token of a \.{\\read} line,
7442 it sets |cur_cmd==cur_chr==cur_cs==0| in the case that no more tokens
7443 appear on that line. (There might not be any tokens at all, if the
7444 |end_line_char| has |ignore| as its catcode.)
7445
7446 @ The value of |par_loc| is the |eqtb| address of `\.{\\par}'. This quantity
7447 is needed because a blank line of input is supposed to be exactly equivalent
7448 to the appearance of \.{\\par}; we must set |cur_cs:=par_loc|
7449 when detecting a blank line.
7450
7451 The same is true for the input, for the warning message, since input
7452 is expected by default before every scanning and hence setting of
7453 |cur_cs|.
7454
7455 @<Glob...@>=
7456 static pointer @!par_loc; /*location of `\.{\\par}' in |eqtb|*/
7457 static halfword @!par_token; /*token representing `\.{\\par}'*/
7458 static pointer @!input_loc; /*location of `\.{\\input}' in |eqtb|*/
7459 static halfword @!input_token; /*token representing `\.{\\input}'*/
7460
7461 @ @<Put each...@>=
7462 primitive("par", par_end, 256); /*cf.\ |scan_file_name|*/
7463 @!@:par\_}{\.{\\par} primitive@>
7464 par_loc=cur_val;par_token=cs_token_flag+par_loc;
7465
7466 @ @<Cases of |print_cmd_chr|...@>=
7467 case par_end: print_esc("par");@+break;
7468
7469 @ Before getting into |get_next|, let's consider the subroutine that
7470 is called when an `\.{\\outer}' control sequence has been scanned or
7471 when the end of a file has been reached. These two cases are distinguished
7472 by |cur_cs|, which is zero at the end of a file.
7473
7474 @p static void check_outer_validity(void)
7475 {@+pointer p; /*points to inserted token list*/
7476 pointer @!q; /*auxiliary pointer*/
7477 if (scanner_status!=normal)
7478 {@+deletions_allowed=false;
7479 @<Back up an outer control sequence so that it can be reread@>;
7480 if (scanner_status > skipping)
7481 @<Tell the user what has run away and try to recover@>@;
7482 else{@+print_err("Incomplete ");print_cmd_chr(if_test, cur_if);
7483 @.Incomplete \\if...@>
7484 print("; all text was ignored after line ");print_int(skip_line);
7485 help3("A forbidden control sequence occurred in skipped text.",@/
7486 "This kind of error happens when you say `\\if...' and forget",@/
7487 "the matching `\\fi'. I've inserted a `\\fi'; this might work.");
7488 if (cur_cs!=0) cur_cs=0;
7489 else help_line[2]=@|
7490 "The file ended while I was skipping conditional text.";
7491 cur_tok=cs_token_flag+frozen_fi;ins_error();
7492 }
7493 deletions_allowed=true;
7494 }
7495 }
7496
7497 @ An outer control sequence that occurs in a \.{\\read} will not be reread,
7498 since the error recovery for \.{\\read} is not very powerful.
7499
7500 @<Back up an outer control sequence so that it can be reread@>=
7501 if (cur_cs!=0)
7502 {@+if ((state==token_list)||(name < 1)||(name > 17))
7503 {@+p=get_avail();info(p)=cs_token_flag+cur_cs;
7504 back_list(p); /*prepare to read the control sequence again*/
7505 }
7506 cur_cmd=spacer;cur_chr=' '; /*replace it by a space*/
7507 }
7508
7509 @ @<Tell the user what has run away...@>=
7510 {@+runaway(); /*print a definition, argument, or preamble*/
7511 if (cur_cs==0) print_err("File ended");
7512 @.File ended while scanning...@>
7513 else{@+cur_cs=0;print_err("Forbidden control sequence found");
7514 @.Forbidden control sequence...@>
7515 }
7516 print(" while scanning ");
7517 @<Print either `\.{definition}' or `\.{use}' or `\.{preamble}' or `\.{text}',
7518 and insert tokens that should lead to recovery@>;
7519 print(" of ");sprint_cs(warning_index);
7520 help4("I suspect you have forgotten a `}', causing me",@/
7521 "to read past where you wanted me to stop.",@/
7522 "I'll try to recover; but if the error is serious,",@/
7523 "you'd better type `E' or `X' now and fix your file.");@/
7524 error();
7525 }
7526
7527 @ The recovery procedure can't be fully understood without knowing more
7528 about the \TeX\ routines that should be aborted, but we can sketch the
7529 ideas here: For a runaway definition or a runaway balanced text
7530 we will insert a right brace; for a
7531 runaway preamble, we will insert a special \.{\\cr} token and a right
7532 brace; and for a runaway argument, we will set |long_state| to
7533 |outer_call| and insert \.{\\par}.
7534
7535 @<Print either `\.{definition}' or...@>=
7536 p=get_avail();
7537 switch (scanner_status) {
7538 case defining: {@+print("definition");info(p)=right_brace_token+'}';
7539 } @+break;
7540 case matching: {@+print("use");info(p)=par_token;long_state=outer_call;
7541 } @+break;
7542 case aligning: {@+print("preamble");info(p)=right_brace_token+'}';q=p;
7543 p=get_avail();link(p)=q;info(p)=cs_token_flag+frozen_cr;
7544 align_state=-1000000;
7545 } @+break;
7546 case absorbing: {@+print("text");info(p)=right_brace_token+'}';
7547 }
7548 } /*there are no other cases*/
7549 ins_list(p)
7550
7551 @ We need to mention a procedure here that may be called by |get_next|.
7552
7553 @p static void firm_up_the_line(void);
7554
7555 @ Now we're ready to take the plunge into |get_next| itself. Parts of
7556 this routine are executed more often than any other instructions of \TeX.
7557 @^mastication@>@^inner loop@>
7558
7559 @p static void get_next(void) /*sets |cur_cmd|, |cur_chr|, |cur_cs| to next token*/
7560 {@+ /*go here to get the next input token*/
7561 /*go here to eat the next character from a file*/
7562 /*go here to digest it again*/
7563 /*go here to start looking for a control sequence*/
7564 /*go here when a control sequence has been found*/
7565 /*go here when the next input token has been got*/
7566 int k; /*an index into |buffer|*/
7567 halfword @!t; /*a token*/
7568 int @!cat; /*|equiv(cat_code_base+cur_chr)|, usually*/
7569 UTF8_code @!c, @!cc; /*constituents of a possible expanded code*/
7570 int @!d; /*number of excess characters in an expanded code*/
7571 restart: cur_cs=0;
7572 if (state!=token_list)
7573 @<Input from external file, |goto restart| if no input found@>@;
7574 else@<Input from token list, |goto restart| if end of list or if a parameter
7575 needs to be expanded@>;
7576 @<If an alignment entry has just ended, take appropriate action@>;
7577 }
7578
7579 @ An alignment entry ends when a tab or \.{\\cr} occurs, provided that the
7580 current level of braces is the same as the level that was present at the
7581 beginning of that alignment entry; i.e., provided that |align_state| has
7582 returned to the value it had after the \<u_j> template for that entry.
7583 @^inner loop@>
7584
7585 @<If an alignment entry has just ended, take appropriate action@>=
7586 if (cur_cmd <= car_ret) if (cur_cmd >= tab_mark) if (align_state==0)
7587 @<Insert the \(v)\<v_j> template and |goto restart|@>@;
7588
7589 @ @<Input from external file, |goto restart| if no input found@>=
7590 @^inner loop@>
7591 {@+get_cur_chr: if (loc <= limit) /*current line not yet finished*/
7592 {@+
7593 loc=utf8_get_cur_chr(buffer,loc,limit);
7594 reswitch: cur_cmd=cat_code(cur_chr);
7595 @<Change state if necessary, and |goto switch| if the current character
7596 should be ignored, or |goto reswitch| if the current character changes to
7597 another@>;
7598 }
7599 else{@+state=new_line;@/
7600 @<Move to next line of file, or |goto restart| if there is no next line,
7601 or |return| if a \.{\\read} line has finished@>;
7602 check_interrupt;
7603 goto get_cur_chr;
7604 }
7605 }
7606
7607 @ The following 48-way switch accomplishes the scanning quickly, assuming
7608 that a decent \PASCAL\ compiler has translated the code. Note that the numeric
7609 values for |mid_line|, |skip_blanks|, and |new_line| are spaced
7610 apart from each other by |max_char_code+1|, so we can add a character's
7611 command code to the state to get a single number that characterizes both.
7612
7613 @d any_state_plus(A) case mid_line+A:
7614 case skip_blanks+A: case new_line+A
7615
7616 @<Change state if necessary...@>=
7617 switch (state+cur_cmd) {
7618 @<Cases where character is ignored@>: goto get_cur_chr;
7619 any_state_plus(escape): @<Scan a control sequence and set |state:=skip_blanks|
7620 or |mid_line|@>@;@+break;
7621 any_state_plus(active_char): @<Process an active-character control sequence
7622 and set |state:=mid_line|@>@;@+break;
7623 any_state_plus(sup_mark): @<If this |sup_mark| starts an expanded character
7624 like~\.{\^\^A} or~\.{\^\^df}, then |goto reswitch|, otherwise set |state:=mid_line|@>@;@+break;
7625 any_state_plus(invalid_char): @<Decry the invalid character and |goto restart|@>@;
7626 @t\4@>@<Handle situations involving spaces, braces, changes of state@>@;
7627 default:do_nothing;
7628 }
7629
7630 @ @<Cases where character is ignored@>=
7631 any_state_plus(ignore): case skip_blanks+spacer:
7632 case new_line+spacer
7633
7634 @ We go to |restart| instead of to |get_cur_chr|, because |state| might equal
7635 |token_list| after the error has been dealt with
7636 (cf.\ |clear_for_error_prompt|).
7637
7638 @<Decry the invalid...@>=
7639 {@+print_err("Text line contains an invalid character");
7640 @.Text line contains...@>
7641 help2("A funny symbol that I can't read has just been input.",@/
7642 "Continue, and I'll forget that it ever happened.");@/
7643 deletions_allowed=false;error();deletions_allowed=true;
7644 goto restart;
7645 }
7646
7647 @ @d add_delims_to(A) A+math_shift: A+tab_mark: A+mac_param:
7648 A+sub_mark: A+letter: A+other_char
7649
7650 @<Handle situations involving spaces, braces, changes of state@>=
7651 case mid_line+spacer: @<Enter |skip_blanks| state, emit a space@>@;@+break;
7652 case mid_line+car_ret: @<Finish line, emit a space@>@;@+break;
7653 case skip_blanks+car_ret: any_state_plus(comment):
7654 @<Finish line, |goto switch|@>@;
7655 case new_line+car_ret: @<Finish line, emit a \.{\\par}@>@;@+break;
7656 case mid_line+left_brace: incr(align_state);@+break;
7657 case skip_blanks+left_brace: case new_line+left_brace: {@+
7658 state=mid_line;incr(align_state);
7659 } @+break;
7660 case mid_line+right_brace: decr(align_state);@+break;
7661 case skip_blanks+right_brace: case new_line+right_brace: {@+
7662 state=mid_line;decr(align_state);
7663 } @+break;
7664 add_delims_to(case skip_blanks): add_delims_to(
7665 case new_line): state=mid_line;@+break;
7666
7667 @ When a character of type |spacer| gets through, its character code is
7668 changed to $\.{"\ "}=040$. This means that the ASCII codes for tab and space,
7669 and for the space inserted at the end of a line, will
7670 be treated alike when macro parameters are being matched. We do this
7671 since such characters are indistinguishable on most computer terminal displays.
7672
7673 @<Finish line, emit a space@>=
7674 {@+loc=limit+1;cur_cmd=spacer;cur_chr=' ';
7675 }
7676
7677 @ The following code is performed only when |cur_cmd==spacer|.
7678
7679 @<Enter |skip_blanks| state, emit a space@>=
7680 {@+state=skip_blanks;cur_chr=' ';
7681 }
7682
7683 @ @<Finish line, |goto switch|@>=
7684 {@+loc=limit+1;goto get_cur_chr;
7685 }
7686
7687 @ @<Finish line, emit a \.{\\par}@>=
7688 {@+loc=limit+1;cur_cs=par_loc;cur_cmd=eq_type(cur_cs);
7689 cur_chr=equiv(cur_cs);
7690 if (cur_cmd >= outer_call) check_outer_validity();
7691 }
7692
7693 @ Notice that a code like \.{\^\^8} becomes \.x if not followed by a hex digit.
7694
7695 @d is_hex(A) (((A >= '0')&&(A <= '9'))||((A >= 'a')&&(A <= 'f')))
7696 @d hex_to_cur_chr
7697 if (c <= '9') cur_chr=c-'0';@+else cur_chr=c-'a'+10;
7698 if (cc <= '9') cur_chr=16*cur_chr+cc-'0';
7699 else cur_chr=16*cur_chr+cc-'a'+10
7700
7701 @<If this |sup_mark| starts an expanded character...@>=
7702 {@+if (cur_chr==buffer[loc]) if (loc < limit)
7703 {@+c=buffer[loc+1];@+if (c < 0200) /*yes we have an expanded char*/
7704 {@+loc=loc+2;
7705 if (is_hex(c)) if (loc <= limit)
7706 {@+cc=buffer[loc];@+if (is_hex(cc))
7707 {@+incr(loc);hex_to_cur_chr;goto reswitch;
7708 }
7709 }
7710 if (c < 0100) cur_chr=c+0100;@+else cur_chr=c-0100;
7711 goto reswitch;
7712 }
7713 }
7714 state=mid_line;
7715 }
7716
7717 @ Active characters $x$ in the range 0 to |0x7F| are represented by single
7718 byte in UTF8 and the current equivalents are as usual in
7719 |eqtb[active_base + $x$]|. To extend this table to cover all
7720 active characters would be a waste of memory. Therefore, we store the equivalents
7721 of active characters $x$ in the range |0x80| and above in
7722 |eqtb[active_hash_base+$y$]| and determine $y$ from $x$ using a separate
7723 hashttable and a lookup function |active_lookup| that resembles |id_lookup|, except that
7724 the hash value is directly computed from the UTF codepoint, and
7725 the |text| field will not store a pointer into the string pool but
7726 directly the UTF codepoint.
7727
7728
7729 @<Process an active-character...@>=
7730 {@+if (cur_chr<utf8_single_size)
7731 cur_cs=cur_chr+active_base;
7732 else
7733 cur_cs=active_lookup(cur_chr);
7734 cur_cmd=eq_type(cur_cs);cur_chr=equiv(cur_cs);state=mid_line;
7735 if (cur_cmd >= outer_call) check_outer_validity();
7736 }
7737
7738 @ Control sequence names are scanned only when they appear in some line of
7739 a file; once they have been scanned the first time, their |eqtb| location
7740 serves as a unique identification, so \TeX\ doesn't need to refer to the
7741 original name any more except when it prints the equivalent in symbolic form.
7742
7743 The program that scans a control sequence has been written carefully
7744 in order to avoid the blowups that might otherwise occur if a malicious
7745 user tried something like `\.{\\catcode\'15=0}'. The algorithm might
7746 look at |buffer[limit+1]|, but it never looks at |buffer[limit+2]|.
7747
7748 If expanded characters like `\.{\^\^A}' or `\.{\^\^df}'
7749 appear in or just following
7750 a control sequence name, they are converted to single characters in the
7751 buffer and the process is repeated, slowly but surely.
7752
7753 @<Scan a control...@>=
7754 {@+if (loc > limit) cur_cs=null_cs; /*|state| is irrelevant in this case*/
7755 else{@+start_cs: k=loc;k=utf8_get_cur_chr(buffer, k, limit);
7756 cat=cat_code(cur_chr);
7757 if (cat==letter) state=skip_blanks;
7758 else if (cat==spacer) state=skip_blanks;
7759 else state=mid_line;
7760 if ((cat==letter)&&(k <= limit))
7761 @<Scan ahead in the buffer until finding a nonletter; if an expanded code
7762 is encountered, reduce it and |goto start_cs|; otherwise if a multiletter
7763 control sequence is found, adjust |cur_cs| and |loc|, and |goto found|@>@;
7764 else@<If an expanded code is present, reduce it and |goto start_cs|@>;
7765 /*single character control sequence*/
7766 k=utf8_get_cur_chr(buffer, loc, limit);
7767 if (cur_chr<utf8_single_size)
7768 { cur_cs=single_base+cur_chr; loc=k; }
7769 else
7770 { cur_cs=id_lookup(loc, k-loc); loc=k; }
7771 }
7772 found: cur_cmd=eq_type(cur_cs);cur_chr=equiv(cur_cs);
7773 if (cur_cmd >= outer_call) check_outer_validity();
7774 }
7775
7776 @ Whenever we reach the following piece of code, we will have
7777 |cur_chr==buffer[k-1]| and |k <= limit+1| and |cat==cat_code(cur_chr)|. If an
7778 expanded code like \.{\^\^A} or \.{\^\^df} appears in |buffer[(k-1)dotdot(k+1)]|
7779 or |buffer[(k-1)dotdot(k+2)]|, we
7780 will store the corresponding UTF8 code in |buffer[(k-1)dotdot(k+2)]| and shift the rest of
7781 the buffer left to close the gap.
7782
7783 @<If an expanded...@>=
7784 {@+if (cat==sup_mark && buffer[k]==cur_chr && k < limit)
7785 {@+c=buffer[k+1];@+if (c < 0200) /*yes, one is indeed present*/
7786 {@+d=2;
7787 if (is_hex(c)) @+if (k+2 <= limit)
7788 {@+cc=buffer[k+2];@+if (is_hex(cc)) incr(d);
7789 }
7790 if (d > 2)
7791 {@+hex_to_cur_chr;
7792 if (cur_chr<0x80) buffer[k-1]=cur_chr;
7793 else
7794 { buffer[k-1]=0xC0|(cur_chr>>6); buffer[k]=0x80|(cur_chr&0x3F);decr(d); incr(k);
7795 }
7796 }
7797 else if (c < 0100) buffer[k-1]=c+0100;
7798 else buffer[k-1]=c-0100;
7799 limit=limit-d;first=first-d;
7800 while (k <= limit)
7801 {@+buffer[k]=buffer[k+d];incr(k);
7802 }
7803 goto start_cs;
7804 }
7805 }
7806 }
7807
7808 @ @<Scan ahead in the buffer...@>=
7809 {@+int j;
7810 @/do@+{j=k; k=utf8_get_cur_chr(buffer,k,limit);
7811 cat=cat_code(cur_chr);
7812 }@+ while (!((cat!=letter)||(k > limit)));
7813 @<If an expanded...@>;
7814 if (cat!=letter) k=j;
7815 /*now |k| points to first nonletter*/
7816 if (k > loc+1) /*multiletter control sequence has been scanned*/
7817 {@+cur_cs=id_lookup(loc, k-loc);loc=k;goto found;
7818 }
7819 }
7820
7821 @ Let's consider now what happens when |get_next| is looking at a token list.
7822
7823 @<Input from token list, |goto restart| if end of list or if a parameter needs
7824 to be expanded@>=
7825 if (loc!=null) /*list not exhausted*/
7826 @^inner loop@>
7827 {@+t=info(loc);loc=link(loc); /*move to next*/
7828 if (t >= cs_token_flag) /*a control sequence token*/
7829 {@+cur_cs=t-cs_token_flag;
7830 cur_cmd=eq_type(cur_cs);cur_chr=equiv(cur_cs);
7831 if (cur_cmd >= outer_call)
7832 if (cur_cmd==dont_expand)
7833 @<Get the next token, suppressing expansion@>@;
7834 else check_outer_validity();
7835 }
7836 else{@+cur_cmd=t/cmd_factor;cur_chr=t%cmd_factor;
7837 switch (cur_cmd) {
7838 case left_brace: incr(align_state);@+break;
7839 case right_brace: decr(align_state);@+break;
7840 case out_param: @<Insert macro parameter and |goto restart|@>@;
7841 default:do_nothing;
7842 }
7843 }
7844 }
7845 else{@+ /*we are done with this token list*/
7846 end_token_list();goto restart; /*resume previous level*/
7847 }
7848
7849 @ The present point in the program is reached only when the |expand|
7850 routine has inserted a special marker into the input. In this special
7851 case, |info(loc)| is known to be a control sequence token, and |link(loc)==null|.
7852
7853 @d no_expand_flag 257 /*this characterizes a special variant of |relax|*/
7854
7855 @<Get the next token, suppressing expansion@>=
7856 {@+cur_cs=info(loc)-cs_token_flag;loc=null;@/
7857 cur_cmd=eq_type(cur_cs);cur_chr=equiv(cur_cs);
7858 if (cur_cmd > max_command)
7859 {@+cur_cmd=relax;cur_chr=no_expand_flag;
7860 }
7861 }
7862
7863 @ @<Insert macro parameter...@>=
7864 {@+begin_token_list(param_stack[param_start+cur_chr-1], parameter);
7865 goto restart;
7866 }
7867
7868 @ All of the easy branches of |get_next| have now been taken care of.
7869 There is one more branch.
7870
7871 @d end_line_char_inactive (end_line_char < 0)||(end_line_char > 255)
7872
7873 @<Move to next line of file, or |goto restart|...@>=
7874 if (name > 17) @<Read next line of file into |buffer|, or |goto restart| if
7875 the file has ended@>@;
7876 else{@+if (!terminal_input) /*\.{\\read} line has ended*/
7877 {@+cur_cmd=0;cur_chr=0;return;
7878 }
7879 if (input_ptr > 0) /*text was inserted during error recovery*/
7880 {@+end_file_reading();goto restart; /*resume previous level*/
7881 }
7882 if (selector < log_only) open_log_file();
7883 if (interaction > nonstop_mode)
7884 {@+if (end_line_char_inactive) incr(limit);
7885 if (limit==start) /*previous line was empty*/
7886 print_nl("(Please type a command or say `\\end')");
7887 @.Please type...@>
7888 print_ln();first=start;
7889 prompt_input("*"); /*input on-line into |buffer|*/
7890 @.*\relax@>
7891 limit=last;
7892 if (end_line_char_inactive) decr(limit);
7893 else buffer[limit]=end_line_char;
7894 first=limit+1;
7895 loc=start;
7896 }
7897 else fatal_error("*** (job aborted, no legal \\end found)");
7898 @.job aborted@>
7899 /*nonstop mode, which is intended for overnight batch processing,
7900 never waits for on-line input*/
7901 }
7902
7903 @ The global variable |force_eof| is normally |false|; it is set |true|
7904 by an \.{\\endinput} command.
7905
7906 @<Glob...@>=
7907 static bool @!force_eof; /*should the next \.{\\input} be aborted early?*/
7908
7909 @ @<Read next line of file into |buffer|, or |goto restart| if the file has
7910 ended@>=
7911 {@+incr(line);first=start;
7912 if (!force_eof)
7913 if (name <= 19)
7914 {@+if (pseudo_input()) /*not end of file*/
7915 firm_up_the_line(); /*this sets |limit|*/
7916 else if ((every_eof!=null)&&!eof_seen[index])
7917 {@+limit=first-1;eof_seen[index]=true; /*fake one empty line*/
7918 begin_token_list(every_eof, every_eof_text);goto restart;
7919 }
7920 else force_eof=true;
7921 }
7922 else
7923 {@+if (input_ln(&cur_file, true)) /*not end of file*/
7924 firm_up_the_line(); /*this sets |limit|*/
7925 else if ((every_eof!=null)&&!eof_seen[index])
7926 {@+limit=first-1;eof_seen[index]=true; /*fake one empty line*/
7927 begin_token_list(every_eof, every_eof_text);goto restart;
7928 }
7929 else force_eof=true;
7930 }
7931 if (force_eof)
7932 {@+if (tracing_nesting > 0)
7933 if ((grp_stack[in_open]!=cur_boundary)||@|
7934 (if_stack[in_open]!=cond_ptr)) file_warning();
7935 /*give warning for some unfinished groups and/or conditionals*/
7936 if (name >= 19)
7937 {@+print_char(')');decr(open_parens);
7938 update_terminal; /*show user that file has been read*/
7939 }
7940 force_eof=false;
7941 end_file_reading(); /*resume previous level*/
7942 check_outer_validity();goto restart;
7943 }
7944 if (end_line_char_inactive) decr(limit);
7945 else buffer[limit]=end_line_char;
7946 first=limit+1;loc=start; /*ready to read*/
7947 }
7948
7949 @ If the user has set the |pausing| parameter to some positive value,
7950 and if nonstop mode has not been selected, each line of input is displayed
7951 on the terminal and the transcript file, followed by `\.{=>}'.
7952 \TeX\ waits for a response. If the response is simply |carriage_return|, the
7953 line is accepted as it stands, otherwise the line typed is
7954 used instead of the line in the file.
7955
7956 @p static void firm_up_the_line(void)
7957 {@+int k; /*an index into |buffer|*/
7958 limit=last;
7959 if (pausing > 0) if (interaction > nonstop_mode)
7960 {@+wake_up_terminal;print_ln();
7961 if (start < limit) for (k=start; k<=limit-1; k++) printn(buffer[k]);
7962 first=limit;prompt_input("=>"); /*wait for user response*/
7963 @.=>@>
7964 if (last > first)
7965 {@+for (k=first; k<=last-1; k++) /*move line down in buffer*/
7966 buffer[k+start-first]=buffer[k];
7967 limit=start+last-first;
7968 }
7969 }
7970 }
7971
7972 @ Since |get_next| is used so frequently in \TeX, it is convenient
7973 to define three related procedures that do a little more:
7974
7975 \yskip\hang|get_token| not only sets |cur_cmd| and |cur_chr|, it
7976 also sets |cur_tok|, a packed halfword version of the current token.
7977
7978 \yskip\hang|get_x_token|, meaning ``get an expanded token,'' is like
7979 |get_token|, but if the current token turns out to be a user-defined
7980 control sequence (i.e., a macro call), or a conditional,
7981 or something like \.{\\topmark} or \.{\\expandafter} or \.{\\csname},
7982 it is eliminated from the input by beginning the expansion of the macro
7983 or the evaluation of the conditional.
7984
7985 \yskip\hang|x_token| is like |get_x_token| except that it assumes that
7986 |get_next| has already been called.
7987
7988 \yskip\noindent
7989 In fact, these three procedures account for almost every use of |get_next|.
7990
7991 @ No new control sequences will be defined except during a call of
7992 |get_token|, or when \.{\\csname} compresses a token list, because
7993 |no_new_control_sequence| is always |true| at other times.
7994
7995 @p static void get_token(void) /*sets |cur_cmd|, |cur_chr|, |cur_tok|*/
7996 {@+no_new_control_sequence=false;get_next();no_new_control_sequence=true;
7997 @^inner loop@>
7998 if (cur_cs==0) cur_tok=cmd_token(cur_cmd)+cur_chr;
7999 else cur_tok=cs_token_flag+cur_cs;
8000 }
8001
8002 @* Expanding the next token.
8003 Only a dozen or so command codes | > max_command| can possibly be returned by
8004 |get_next|; in increasing order, they are |undefined_cs|, |expand_after|,
8005 |no_expand|, |input|, |if_test|, |fi_or_else|, |cs_name|, |convert|, |the|,
8006 |top_bot_mark|, |call|, |long_call|, |outer_call|, |long_outer_call|, and
8007 |end_template|.{\emergencystretch=40pt\par}
8008
8009 The |expand| subroutine is used when |cur_cmd > max_command|. It removes a
8010 ``call'' or a conditional or one of the other special operations just
8011 listed. It follows that |expand| might invoke itself recursively. In all
8012 cases, |expand| destroys the current token, but it sets things up so that
8013 the next |get_next| will deliver the appropriate next token. The value of
8014 |cur_tok| need not be known when |expand| is called.
8015
8016 Since several of the basic scanning routines communicate via global variables,
8017 their values are saved as local variables of |expand| so that
8018 recursive calls don't invalidate them.
8019 @^recursion@>
8020
8021 @p @t\4@>@<Declare the procedure called |macro_call|@>@;@/
8022 @t\4@>@<Declare the procedure called |insert_relax|@>@;@/
8023 @t\4@>@<Declare \eTeX\ procedures for expanding@>@;@/
8024 static void pass_text(void);
8025 static void start_input(void);
8026 static void conditional(void);
8027 static void get_x_token(void);
8028 static void conv_toks(void);
8029 static void ins_the_toks(void);
8030 static void expand(void)
8031 {@+
8032 halfword t; /*token that is being ``expanded after''*/
8033 pointer @!p, @!q, @!r; /*for list manipulation*/
8034 int @!j; /*index into |buffer|*/
8035 int @!cv_backup; /*to save the global quantity |cur_val|*/
8036 small_number @!cvl_backup, @!radix_backup, @!co_backup;
8037 /*to save |cur_val_level|, etc.*/
8038 pointer @!backup_backup; /*to save |link(backup_head)|*/
8039 small_number @!save_scanner_status; /*temporary storage of |scanner_status|*/
8040 cv_backup=cur_val;cvl_backup=cur_val_level;radix_backup=radix;
8041 co_backup=cur_order;backup_backup=link(backup_head);
8042 reswitch:
8043 if (cur_cmd < call) @<Expand a nonmacro@>@;
8044 else if (cur_cmd < end_template) macro_call();
8045 else@<Insert a token containing |frozen_endv|@>;
8046 cur_val=cv_backup;cur_val_level=cvl_backup;radix=radix_backup;
8047 cur_order=co_backup;link(backup_head)=backup_backup;
8048 }
8049
8050 @ @<Expand a nonmacro@>=
8051 {@+if (tracing_commands > 1) show_cur_cmd_chr();
8052 switch (cur_cmd) {
8053 case top_bot_mark: @<Insert the \(a)appropriate mark text into the scanner@>@;@+break;
8054 case expand_after: switch (cur_chr) {
8055 case 0: @<Expand the token after the next token@>@;@+break;
8056 case 1: @<Negate a boolean conditional and |goto reswitch|@>@;@+break;
8057 @/@<Cases for |expandafter|@>@/
8058 } @+break; /*there are no other cases*/
8059 case no_expand: @<Suppress expansion of the next token@>@;@+break;
8060 case cs_name: @<Manufacture a control sequence name@>@;@+break;
8061 case convert: conv_toks();@+break; /*this procedure is discussed in Part 27 below*/
8062 case the: ins_the_toks();@+break; /*this procedure is discussed in Part 27 below*/
8063 case if_test: conditional();@+break; /*this procedure is discussed in Part 28 below*/
8064 case fi_or_else: @<Terminate the current conditional and skip to \.{\\fi}@>@;@+break;
8065 case input: @<Initiate or terminate input from a file@>;@+break;
8066 default:@<Complain about an undefined macro@>@;
8067 }
8068 }
8069
8070 @ It takes only a little shuffling to do what \TeX\ calls \.{\\expandafter}.
8071
8072 @<Expand the token after...@>=
8073 {@+get_token();t=cur_tok;get_token();
8074 if (cur_cmd > max_command) expand();@+else back_input();
8075 cur_tok=t;back_input();
8076 }
8077
8078 @ The implementation of \.{\\noexpand} is a bit trickier, because it is
8079 necessary to insert a special `|dont_expand|' marker into \TeX's reading
8080 mechanism. This special marker is processed by |get_next|, but it does
8081 not slow down the inner loop.
8082
8083 Since \.{\\outer} macros might arise here, we must also
8084 clear the |scanner_status| temporarily.
8085
8086 @<Suppress expansion...@>=
8087 {@+save_scanner_status=scanner_status;scanner_status=normal;
8088 get_token();scanner_status=save_scanner_status;t=cur_tok;
8089 back_input(); /*now |start| and |loc| point to the backed-up token |t|*/
8090 if (t >= cs_token_flag)
8091 {@+p=get_avail();info(p)=cs_token_flag+frozen_dont_expand;
8092 link(p)=loc;start=p;loc=p;
8093 }
8094 }
8095
8096 @ @<Complain about an undefined macro@>=
8097 {@+print_err("Undefined control sequence");
8098 @.Undefined control sequence@>
8099 help5("The control sequence at the end of the top line",@/
8100 "of your error message was never \\def'ed. If you have",@/
8101 "misspelled it (e.g., `\\hobx'), type `I' and the correct",@/
8102 "spelling (e.g., `I\\hbox'). Otherwise just continue,",@/
8103 "and I'll forget about whatever was undefined.");
8104 error();
8105 }
8106
8107 @ The |expand| procedure and some other routines that construct token
8108 lists find it convenient to use the following macros, which are valid only if
8109 the variables |p| and |q| are reserved for token-list building.
8110
8111 @d store_new_token(A) {@+q=get_avail();link(p)=q;info(q)=A;
8112 p=q; /*|link(p)| is |null|*/
8113 }
8114 @d fast_store_new_token(A) {@+fast_get_avail(q);link(p)=q;info(q)=A;
8115 p=q; /*|link(p)| is |null|*/
8116 }
8117
8118 @ @<Manufacture a control...@>=
8119 {@+r=get_avail();p=r; /*head of the list of characters*/
8120 incr(incsname_state);
8121 @/do@+{get_x_token();
8122 if (cur_cs==0) store_new_token(cur_tok);
8123 }@+ while (!(cur_cs!=0));
8124 if (cur_cmd!=end_cs_name) @<Complain about missing \.{\\endcsname}@>;
8125 decr(incsname_state);
8126 @<Look up the characters of list |r| in the hash table, and set |cur_cs|@>;
8127 flush_list(r);
8128 if (eq_type(cur_cs)==undefined_cs)
8129 {@+eq_define(cur_cs, relax, 256); /*N.B.: The |save_stack| might change*/
8130 } /*the control sequence will now match `\.{\\relax}'*/
8131 cur_tok=cur_cs+cs_token_flag;back_input();
8132 }
8133
8134 @ @<Complain about missing \.{\\endcsname}@>=
8135 {@+print_err("Missing ");print_esc("endcsname");print(" inserted");
8136 @.Missing \\endcsname...@>
8137 help2("The control sequence marked <to be read again> should",@/
8138 "not appear between \\csname and \\endcsname.");
8139 back_error();
8140 }
8141
8142 @ @<Look up the characters of list |r| in the hash table...@>=
8143 j=first;p=link(r);
8144 while (p!=null)
8145 {@+if (j >= max_buf_stack)
8146 {@+max_buf_stack=j+1;
8147 if (max_buf_stack==buf_size)
8148 overflow("buffer size", buf_size);
8149 @:TeX capacity exceeded buffer size}{\quad buffer size@>
8150 }
8151 buffer[j]=info(p)%cmd_factor;incr(j);p=link(p);
8152 }
8153 if (j==first) cur_cs=null_cs; /*the list is empty*/
8154 else if (j > first+1)
8155 {@+no_new_control_sequence=false;cur_cs=id_lookup(first, j-first);
8156 no_new_control_sequence=true;
8157 }
8158 else cur_cs=single_base+buffer[first] /*the list has length one*/
8159
8160 @ An |end_template| command is effectively changed to an |endv| command
8161 by the following code. (The reason for this is discussed below; the
8162 |frozen_end_template| at the end of the template has passed the
8163 |check_outer_validity| test, so its mission of error detection has been
8164 accomplished.)
8165
8166 @<Insert a token containing |frozen_endv|@>=
8167 {@+cur_tok=cs_token_flag+frozen_endv;back_input();
8168 }
8169
8170 @ The processing of \.{\\input} involves the |start_input| subroutine,
8171 which will be declared later; the processing of \.{\\endinput} is trivial.
8172
8173 @<Put each...@>=
8174 primitive("input", input, 0);@/
8175 @!@:input\_}{\.{\\input} primitive@>
8176 input_loc=cur_val;input_token=cs_token_flag+input_loc;
8177 primitive("endinput", input, 1);@/
8178 @!@:end\_input\_}{\.{\\endinput} primitive@>
8179
8180 @ @<Cases of |print_cmd_chr|...@>=
8181 case input: if (chr_code==0) print_esc("input")
8182 @/@<Cases of |input| for |print_cmd_chr|@>;@/
8183 else print_esc("endinput");@+break;
8184
8185 @ @<Initiate or terminate input...@>=
8186 if (cur_chr==1) force_eof=true
8187 @/@<Cases for |input|@>;@/
8188 else if (name_in_progress) insert_relax();
8189 else start_input()
8190
8191 @ Sometimes the expansion looks too far ahead, so we want to insert
8192 a harmless \.{\\relax} into the user's input.
8193
8194 @<Declare the procedure called |insert_relax|@>=
8195 static void insert_relax(void)
8196 {@+cur_tok=cs_token_flag+cur_cs;back_input();
8197 cur_tok=cs_token_flag+frozen_relax;back_input();token_type=inserted;
8198 }
8199
8200 @ Here is a recursive procedure that is \TeX's usual way to get the
8201 next token of input. It has been slightly optimized to take account of
8202 common cases.
8203
8204 @p static void get_x_token(void) /*sets |cur_cmd|, |cur_chr|, |cur_tok|,
8205 and expands macros*/
8206 {@+
8207 restart: get_next();
8208 @^inner loop@>
8209 if (cur_cmd <= max_command) goto done;
8210 if (cur_cmd >= call)
8211 if (cur_cmd < end_template) macro_call();
8212 else{@+cur_cs=frozen_endv;cur_cmd=endv;
8213 goto done; /*|cur_chr==null_list|*/
8214 }
8215 else expand();
8216 goto restart;
8217 done: if (cur_cs==0) cur_tok=cmd_token(cur_cmd)+cur_chr;
8218 else cur_tok=cs_token_flag+cur_cs;
8219 }
8220
8221 @ The |get_x_token| procedure is essentially equivalent to two consecutive
8222 procedure calls: |get_next;x_token|.
8223
8224 @p static void x_token(void) /*|get_x_token| without the initial |get_next|*/
8225 {@+while (cur_cmd > max_command)
8226 {@+expand();
8227 get_next();
8228 }
8229 if (cur_cs==0) cur_tok=cmd_token(cur_cmd)+cur_chr;
8230 else cur_tok=cs_token_flag+cur_cs;
8231 }
8232
8233 @ A control sequence that has been \.{\\def}'ed by the user is expanded by
8234 \TeX's |macro_call| procedure.
8235
8236 Before we get into the details of |macro_call|, however, let's consider the
8237 treatment of primitives like \.{\\topmark}, since they are essentially
8238 macros without parameters. The token lists for such marks are kept in a
8239 global array of five pointers; we refer to the individual entries of this
8240 array by symbolic names |top_mark|, etc. The value of |top_mark| is either
8241 |null| or a pointer to the reference count of a token list.
8242
8243 @d marks_code 5 /*add this for \.{\\topmarks} etc.*/
8244 @#
8245 @d top_mark_code 0 /*the mark in effect at the previous page break*/
8246 @d first_mark_code 1 /*the first mark between |top_mark| and |bot_mark|*/
8247 @d bot_mark_code 2 /*the mark in effect at the current page break*/
8248 @d split_first_mark_code 3 /*the first mark found by \.{\\vsplit}*/
8249 @d split_bot_mark_code 4 /*the last mark found by \.{\\vsplit}*/
8250 @d top_mark cur_mark[top_mark_code]
8251 @d first_mark cur_mark[first_mark_code]
8252 @d bot_mark cur_mark[bot_mark_code]
8253 @d split_first_mark cur_mark[split_first_mark_code]
8254 @d split_bot_mark cur_mark[split_bot_mark_code]
8255
8256 @<Glob...@>=
8257 static pointer @!cur_mark0[split_bot_mark_code-top_mark_code+1],
8258 *const @!cur_mark = @!cur_mark0-top_mark_code;
8259 /*token lists for marks*/
8260
8261 @ @<Set init...@>=
8262 top_mark=null;first_mark=null;bot_mark=null;
8263 split_first_mark=null;split_bot_mark=null;
8264
8265 @ @<Put each...@>=
8266 primitive("topmark", top_bot_mark, top_mark_code);
8267 @!@:top\_mark\_}{\.{\\topmark} primitive@>
8268 primitive("firstmark", top_bot_mark, first_mark_code);
8269 @!@:first\_mark\_}{\.{\\firstmark} primitive@>
8270 primitive("botmark", top_bot_mark, bot_mark_code);
8271 @!@:bot\_mark\_}{\.{\\botmark} primitive@>
8272 primitive("splitfirstmark", top_bot_mark, split_first_mark_code);
8273 @!@:split\_first\_mark\_}{\.{\\splitfirstmark} primitive@>
8274 primitive("splitbotmark", top_bot_mark, split_bot_mark_code);
8275 @!@:split\_bot\_mark\_}{\.{\\splitbotmark} primitive@>
8276
8277 @ @<Cases of |print_cmd_chr|...@>=
8278 case top_bot_mark: {@+switch ((chr_code%marks_code)) {
8279 case first_mark_code: print_esc("firstmark");@+break;
8280 case bot_mark_code: print_esc("botmark");@+break;
8281 case split_first_mark_code: print_esc("splitfirstmark");@+break;
8282 case split_bot_mark_code: print_esc("splitbotmark");@+break;
8283 default:print_esc("topmark");
8284 }
8285 if (chr_code >= marks_code) print_char('s');
8286 } @+break;
8287
8288 @ The following code is activated when |cur_cmd==top_bot_mark| and
8289 when |cur_chr| is a code like |top_mark_code|.
8290
8291 @<Insert the \(a)appropriate mark text into the scanner@>=
8292 {@+t=cur_chr%marks_code;
8293 if (cur_chr >= marks_code) scan_register_num();@+else cur_val=0;
8294 if (cur_val==0) cur_ptr=cur_mark[t];
8295 else@<Compute the mark pointer for mark type |t| and class |cur_val|@>;
8296 if (cur_ptr!=null) begin_token_list(cur_ptr, mark_text);
8297 }
8298
8299 @ Now let's consider |macro_call| itself, which is invoked when \TeX\ is
8300 scanning a control sequence whose |cur_cmd| is either |call|, |long_call|,
8301 |outer_call|, or |long_outer_call|. The control sequence definition
8302 appears in the token list whose reference count is in location |cur_chr|
8303 of |mem|.
8304
8305 The global variable |long_state| will be set to |call| or to |long_call|,
8306 depending on whether or not the control sequence disallows \.{\\par}
8307 in its parameters. The |get_next| routine will set |long_state| to
8308 |outer_call| and emit \.{\\par}, if a file ends or if an \.{\\outer}
8309 control sequence occurs in the midst of an argument.
8310
8311 @<Glob...@>=
8312 static int @!long_state; /*governs the acceptance of \.{\\par}*/
8313
8314 @ The parameters, if any, must be scanned before the macro is expanded.
8315 Parameters are token lists without reference counts. They are placed on
8316 an auxiliary stack called |pstack| while they are being scanned, since
8317 the |param_stack| may be losing entries during the matching process.
8318 (Note that |param_stack| can't be gaining entries, since |macro_call| is
8319 the only routine that puts anything onto |param_stack|, and it
8320 is not recursive.)
8321
8322 @<Glob...@>=
8323 static pointer @!pstack[9]; /*arguments supplied to a macro*/
8324
8325 @ After parameter scanning is complete, the parameters are moved to the
8326 |param_stack|. Then the macro body is fed to the scanner; in other words,
8327 |macro_call| places the defined text of the control sequence at the
8328 top of\/ \TeX's input stack, so that |get_next| will proceed to read it
8329 next.
8330
8331 The global variable |cur_cs| contains the |eqtb| address of the control sequence
8332 being expanded, when |macro_call| begins. If this control sequence has not been
8333 declared \.{\\long}, i.e., if its command code in the |eq_type| field is
8334 not |long_call| or |long_outer_call|, its parameters are not allowed to contain
8335 the control sequence \.{\\par}. If an illegal \.{\\par} appears, the macro
8336 call is aborted, and the \.{\\par} will be rescanned.
8337
8338 @<Declare the procedure called |macro_call|@>=
8339 static void macro_call(void) /*invokes a user-defined control sequence*/
8340 {@+
8341 pointer r; /*current node in the macro's token list*/
8342 pointer @!p; /*current node in parameter token list being built*/
8343 pointer @!q; /*new node being put into the token list*/
8344 pointer @!s; /*backup pointer for parameter matching*/
8345 pointer @!t; /*cycle pointer for backup recovery*/
8346 pointer @!u, @!v; /*auxiliary pointers for backup recovery*/
8347 pointer @!rbrace_ptr; /*one step before the last |right_brace| token*/
8348 small_number @!n; /*the number of parameters scanned*/
8349 halfword @!unbalance; /*unmatched left braces in current parameter*/
8350 int @!m; /*the number of tokens or groups (usually)*/
8351 pointer @!ref_count; /*start of the token list*/
8352 small_number @!save_scanner_status; /*|scanner_status| upon entry*/
8353 pointer @!save_warning_index; /*|warning_index| upon entry*/
8354 UTF8_code @!match_chr; /*character used in parameter*/
8355 save_scanner_status=scanner_status;save_warning_index=warning_index;
8356 warning_index=cur_cs;ref_count=cur_chr;r=link(ref_count);n=0;
8357 if (tracing_macros > 0) @<Show the text of the macro being expanded@>;
8358 if (info(r)==protected_token) r=link(r);
8359 if (info(r)!=end_match_token)
8360 @<Scan the parameters and make |link(r)| point to the macro body; but |return|
8361 if an illegal \.{\\par} is detected@>;
8362 @<Feed the macro body and its parameters to the scanner@>;
8363 end: scanner_status=save_scanner_status;warning_index=save_warning_index;
8364 }
8365
8366 @ Before we put a new token list on the input stack, it is wise to clean off
8367 all token lists that have recently been depleted. Then a user macro that ends
8368 with a call to itself will not require unbounded stack space.
8369
8370 @<Feed the macro body and its parameters to the scanner@>=
8371 while ((state==token_list)&&(loc==null)&&(token_type!=v_template))
8372 end_token_list(); /*conserve stack space*/
8373 begin_token_list(ref_count, macro);name=warning_index;loc=link(r);
8374 if (n > 0)
8375 {@+if (param_ptr+n > max_param_stack)
8376 {@+max_param_stack=param_ptr+n;
8377 if (max_param_stack > param_size)
8378 overflow("parameter stack size", param_size);
8379 @:TeX capacity exceeded parameter stack size}{\quad parameter stack size@>
8380 }
8381 for (m=0; m<=n-1; m++) param_stack[param_ptr+m]=pstack[m];
8382 param_ptr=param_ptr+n;
8383 }
8384
8385 @ At this point, the reader will find it advisable to review the explanation
8386 of token list format that was presented earlier, since many aspects of that
8387 format are of importance chiefly in the |macro_call| routine.
8388
8389 The token list might begin with a string of compulsory tokens before the
8390 first |match| or |end_match|. In that case the macro name is supposed to be
8391 followed by those tokens; the following program will set |s==null| to
8392 represent this restriction. Otherwise |s| will be set to the first token of
8393 a string that will delimit the next parameter.
8394
8395 @<Scan the parameters and make |link(r)| point to the macro body...@>=
8396 {@+scanner_status=matching;unbalance=0;
8397 long_state=eq_type(cur_cs);
8398 if (long_state >= outer_call) long_state=long_state-2;
8399 @/do@+{link(temp_head)=null;
8400 if ((info(r) > match_token+255)||(info(r) < match_token)) s=null;
8401 else{@+match_chr=info(r)-match_token;s=link(r);r=s;
8402 p=temp_head;m=0;
8403 }
8404 @<Scan a parameter until its delimiter string has been found; or, if |s=null|,
8405 simply scan the delimiter string@>;@/
8406 /*now |info(r)| is a token whose command code is either |match| or |end_match|*/
8407 }@+ while (!(info(r)==end_match_token));
8408 }
8409
8410 @ If |info(r)| is a |match| or |end_match| command, it cannot be equal to
8411 any token found by |get_token|. Therefore an undelimited parameter---i.e.,
8412 a |match| that is immediately followed by |match| or |end_match|---will
8413 always fail the test `|cur_tok==info(r)|' in the following algorithm.
8414
8415 @<Scan a parameter until its delimiter string has been found; or,...@>=
8416 resume: get_token(); /*set |cur_tok| to the next token of input*/
8417 if (cur_tok==info(r))
8418 @<Advance \(r)|r|; |goto found| if the parameter delimiter has been fully
8419 matched, otherwise |goto resume|@>;
8420 @<Contribute the recently matched tokens to the current parameter, and |goto
8421 resume| if a partial match is still in effect; but abort if |s=null|@>;
8422 if (cur_tok==par_token) if (long_state!=long_call)
8423 @<Report a runaway argument and abort@>;
8424 if (cur_tok < right_brace_limit)
8425 if (cur_tok < left_brace_limit)
8426 @<Contribute an entire group to the current parameter@>@;
8427 else@<Report an extra right brace and |goto resume|@>@;
8428 else@<Store the current token, but |goto resume| if it is a blank space
8429 that would become an undelimited parameter@>;
8430 incr(m);
8431 if (info(r) > end_match_token) goto resume;
8432 if (info(r) < match_token) goto resume;
8433 found: if (s!=null) @<Tidy up the parameter just scanned, and tuck it away@>@;
8434
8435 @ @<Store the current token, but |goto resume| if it is...@>=
8436 {@+if (cur_tok==space_token)
8437 if (info(r) <= end_match_token)
8438 if (info(r) >= match_token) goto resume;
8439 store_new_token(cur_tok);
8440 }
8441
8442 @ A slightly subtle point arises here: When the parameter delimiter ends
8443 with `\.{\#\{}', the token list will have a left brace both before and
8444 after the |end_match|\kern-.4pt. Only one of these should affect the
8445 |align_state|, but both will be scanned, so we must make a correction.
8446
8447 @<Advance \(r)|r|; |goto found| if the parameter delimiter has been fully...@>=
8448 {@+r=link(r);
8449 if ((info(r) >= match_token)&&(info(r) <= end_match_token))
8450 {@+if (cur_tok < left_brace_limit) decr(align_state);
8451 goto found;
8452 }
8453 else goto resume;
8454 }
8455
8456 @ @<Report an extra right brace and |goto resume|@>=
8457 {@+back_input();print_err("Argument of ");sprint_cs(warning_index);
8458 @.Argument of \\x has...@>
8459 print(" has an extra }");
8460 help6("I've run across a `}' that doesn't seem to match anything.",@/
8461 "For example, `\\def\\a#1{...}' and `\\a}' would produce",@/
8462 "this error. If you simply proceed now, the `\\par' that",@/
8463 "I've just inserted will cause me to report a runaway",@/
8464 "argument that might be the root of the problem. But if",@/
8465 "your `}' was spurious, just type `2' and it will go away.");
8466 incr(align_state);long_state=call;cur_tok=par_token;ins_error();
8467 goto resume;
8468 } /*a white lie; the \.{\\par} won't always trigger a runaway*/
8469
8470 @ If |long_state==outer_call|, a runaway argument has already been reported.
8471
8472 @<Report a runaway argument and abort@>=
8473 {@+if (long_state==call)
8474 {@+runaway();print_err("Paragraph ended before ");
8475 @.Paragraph ended before...@>
8476 sprint_cs(warning_index);print(" was complete");
8477 help3("I suspect you've forgotten a `}', causing me to apply this",@/
8478 "control sequence to too much text. How can we recover?",@/
8479 "My plan is to forget the whole thing and hope for the best.");
8480 back_error();
8481 }
8482 pstack[n]=link(temp_head);align_state=align_state-unbalance;
8483 for (m=0; m<=n; m++) flush_list(pstack[m]);
8484 goto end;
8485 }
8486
8487 @ When the following code becomes active, we have matched tokens from |s| to
8488 the predecessor of |r|, and we have found that |cur_tok!=info(r)|. An
8489 interesting situation now presents itself: If the parameter is to be
8490 delimited by a string such as `\.{ab}', and if we have scanned `\.{aa}',
8491 we want to contribute one `\.a' to the current parameter and resume
8492 looking for a `\.b'. The program must account for such partial matches and
8493 for others that can be quite complex. But most of the time we have |s==r|
8494 and nothing needs to be done.
8495
8496 Incidentally, it is possible for \.{\\par} tokens to sneak in to certain
8497 parameters of non-\.{\\long} macros. For example, consider a case like
8498 `\.{\\def\\a\#1\\par!\{...\}}' where the first \.{\\par} is not followed
8499 by an exclamation point. In such situations it does not seem appropriate
8500 to prohibit the \.{\\par}, so \TeX\ keeps quiet about this bending of
8501 the rules.
8502
8503 @<Contribute the recently matched tokens to the current parameter...@>=
8504 if (s!=r)
8505 if (s==null) @<Report an improper use of the macro and abort@>@;
8506 else{@+t=s;
8507 @/do@+{store_new_token(info(t));incr(m);u=link(t);v=s;
8508 loop@+{@+if (u==r)
8509 if (cur_tok!=info(v)) goto done;
8510 else{@+r=link(v);goto resume;
8511 }
8512 if (info(u)!=info(v)) goto done;
8513 u=link(u);v=link(v);
8514 }
8515 done: t=link(t);
8516 }@+ while (!(t==r));
8517 r=s; /*at this point, no tokens are recently matched*/
8518 }
8519
8520 @ @<Report an improper use...@>=
8521 {@+print_err("Use of ");sprint_cs(warning_index);
8522 @.Use of x doesn't match...@>
8523 print(" doesn't match its definition");
8524 help4("If you say, e.g., `\\def\\a1{...}', then you must always",@/
8525 "put `1' after `\\a', since control sequence names are",@/
8526 "made up of letters only. The macro here has not been",@/
8527 "followed by the required stuff, so I'm ignoring it.");
8528 error();goto end;
8529 }
8530
8531 @ @<Contribute an entire group to the current parameter@>=
8532 {@+unbalance=1;
8533 @^inner loop@>
8534 loop@+{@+fast_store_new_token(cur_tok);get_token();
8535 if (cur_tok==par_token) if (long_state!=long_call)
8536 @<Report a runaway argument and abort@>;
8537 if (cur_tok < right_brace_limit)
8538 if (cur_tok < left_brace_limit) incr(unbalance);
8539 else{@+decr(unbalance);
8540 if (unbalance==0) goto done1;
8541 }
8542 }
8543 done1: rbrace_ptr=p;store_new_token(cur_tok);
8544 }
8545
8546 @ If the parameter consists of a single group enclosed in braces, we must
8547 strip off the enclosing braces. That's why |rbrace_ptr| was introduced.
8548
8549 @<Tidy up the parameter just scanned, and tuck it away@>=
8550 {@+if ((m==1)&&(info(p) < right_brace_limit))
8551 {@+link(rbrace_ptr)=null;free_avail(p);
8552 p=link(temp_head);pstack[n]=link(p);free_avail(p);
8553 }
8554 else pstack[n]=link(temp_head);
8555 incr(n);
8556 if (tracing_macros > 0)
8557 if ((tracing_stack_levels==0)||(input_ptr < tracing_stack_levels))
8558 {@+begin_diagnostic();print_nl("");printn(match_chr);print_int(n);
8559 print("<-");show_token_list(pstack[n-1], null, 1000);
8560 end_diagnostic(false);
8561 }
8562 }
8563
8564 @ @<Show the text of the macro being expanded@>=
8565 {@+begin_diagnostic();
8566 if (tracing_stack_levels > 0)
8567 { if (input_ptr < tracing_stack_levels)
8568 {@+
8569 int v=input_ptr;
8570 print_ln();print_char('~');
8571 while (v-- > 0) print_char('.');
8572 print_cs(warning_index);token_show(ref_count);
8573 }
8574 else{@+print_char('~');print_char('~');print_cs(warning_index);}
8575 }
8576 else{@+print_ln();print_cs(warning_index);token_show(ref_count);}
8577 end_diagnostic(false);
8578 }
8579
8580 @* Basic scanning subroutines.
8581 Let's turn now to some procedures that \TeX\ calls upon frequently to digest
8582 certain kinds of patterns in the input. Most of these are quite simple;
8583 some are quite elaborate. Almost all of the routines call |get_x_token|,
8584 which can cause them to be invoked recursively.
8585 @^stomach@>
8586 @^recursion@>
8587
8588 @ The |scan_left_brace| routine is called when a left brace is supposed to be
8589 the next non-blank token. (The term ``left brace'' means, more precisely,
8590 a character whose catcode is |left_brace|.) \TeX\ allows \.{\\relax} to
8591 appear before the |left_brace|.
8592
8593 @p static void scan_left_brace(void) /*reads a mandatory |left_brace|*/
8594 {@+@<Get the next non-blank non-relax non-call token@>;
8595 if (cur_cmd!=left_brace)
8596 {@+print_err("Missing { inserted");
8597 @.Missing \{ inserted@>
8598 help4("A left brace was mandatory here, so I've put one in.",@/
8599 "You might want to delete and/or insert some corrections",@/
8600 "so that I will find a matching right brace soon.",@/
8601 "(If you're confused by all this, try typing `I}' now.)");
8602 back_error();cur_tok=left_brace_token+'{';cur_cmd=left_brace;
8603 cur_chr='{';incr(align_state);
8604 }
8605 }
8606
8607 @ @<Get the next non-blank non-relax non-call token@>=
8608 @/do@+{get_x_token();
8609 }@+ while (!((cur_cmd!=spacer)&&(cur_cmd!=relax)))
8610
8611 @ The |scan_optional_equals| routine looks for an optional `\.=' sign preceded
8612 by optional spaces; `\.{\\relax}' is not ignored here.
8613
8614 @p static void scan_optional_equals(void)
8615 {@+@<Get the next non-blank non-call token@>;
8616 if (cur_tok!=other_token+'=') back_input();
8617 }
8618
8619 @ @<Get the next non-blank non-call token@>=
8620 @/do@+{get_x_token();
8621 }@+ while (!(cur_cmd!=spacer))
8622
8623 @ In case you are getting bored, here is a slightly less trivial routine:
8624 Given a string of lowercase letters, like `\.{pt}' or `\.{plus}' or
8625 `\.{width}', the |scan_keyword| routine checks to see whether the next
8626 tokens of input match this string. The match must be exact, except that
8627 uppercase letters will match their lowercase counterparts; uppercase
8628 equivalents are determined by subtracting |'a'-'A'|, rather than using the
8629 |uc_code| table, since \TeX\ uses this routine only for its own limited
8630 set of keywords.
8631
8632 If a match is found, the characters are effectively removed from the input
8633 and |true| is returned. Otherwise |false| is returned, and the input
8634 is left essentially unchanged (except for the fact that some macros
8635 may have been expanded, etc.).
8636 @^inner loop@>
8637
8638 @p static bool scan_keyword(char *@!s) /*look for a given string*/
8639 {@+
8640 pointer p; /*tail of the backup list*/
8641 pointer @!q; /*new node being added to the token list via |store_new_token|*/
8642 p=backup_head;link(p)=null;
8643 while (*s!=0)
8644 {@+get_x_token(); /*recursion is possible here*/
8645 @^recursion@>
8646 if ((cur_cs==0)&&@|
8647 ((cur_chr==*s)||(cur_chr==*s-'a'+'A')))
8648 {@+store_new_token(cur_tok);incr(s);
8649 }
8650 else if ((cur_cmd!=spacer)||(p!=backup_head))
8651 {@+back_input();
8652 if (p!=backup_head) back_list(link(backup_head));
8653 return false;
8654 }
8655 }
8656 flush_list(link(backup_head));return true;
8657 }
8658
8659 @ Here is a procedure that sounds an alarm when mu and non-mu units
8660 are being switched.
8661
8662 @p static void mu_error(void)
8663 {@+print_err("Incompatible glue units");
8664 @.Incompatible glue units@>
8665 help1("I'm going to assume that 1mu=1pt when they're mixed.");
8666 error();
8667 }
8668
8669 @ The next routine `|scan_something_internal|' is used to fetch internal
8670 numeric quantities like `\.{\\hsize}', and also to handle the `\.{\\the}'
8671 when expanding constructions like `\.{\\the\\toks0}' and
8672 `\.{\\the\\baselineskip}'. Soon we will be considering the |scan_int|
8673 procedure, which calls |scan_something_internal|; on the other hand,
8674 |scan_something_internal| also calls |scan_int|, for constructions like
8675 `\.{\\catcode\`\\\$}' or `\.{\\fontdimen} \.3 \.{\\ff}'. So we
8676 have to declare |scan_int| as a |forward| procedure. A few other
8677 procedures are also declared at this point.
8678
8679 @p static void scan_int(void); /*scans an integer value*/
8680 @t\4\4@>@<Declare procedures that scan restricted classes of integers@>@;
8681 @t\4\4@>@<Declare \eTeX\ procedures for scanning@>@;
8682 @t\4\4@>@<Declare procedures that scan font-related stuff@>@;
8683
8684 @ \TeX\ doesn't know exactly what to expect when |scan_something_internal|
8685 begins. For example, an integer or dimension or glue value could occur
8686 immediately after `\.{\\hskip}'; and one can even say \.{\\the} with
8687 respect to token lists in constructions like
8688 `\.{\\xdef\\o\{\\the\\output\}}'. On the other hand, only integers are
8689 allowed after a construction like `\.{\\count}'. To handle the various
8690 possibilities, |scan_something_internal| has a |level| parameter, which
8691 tells the ``highest'' kind of quantity that |scan_something_internal| is
8692 allowed to produce. Six levels are distinguished, namely |int_val|,
8693 |dimen_val|, |glue_val|, |mu_val|, |ident_val|, and |tok_val|.
8694
8695 The output of |scan_something_internal| (and of the other routines
8696 |scan_int|, |scan_dimen|, and |scan_glue| below) is put into the global
8697 variable |cur_val|, and its level is put into |cur_val_level|. The highest
8698 values of |cur_val_level| are special: |mu_val| is used only when
8699 |cur_val| points to something in a ``muskip'' register, or to one of the
8700 three parameters \.{\\thinmuskip}, \.{\\medmuskip}, \.{\\thickmuskip};
8701 |ident_val| is used only when |cur_val| points to a font identifier;
8702 |tok_val| is used only when |cur_val| points to |null| or to the reference
8703 count of a token list. The last two cases are allowed only when
8704 |scan_something_internal| is called with |level==tok_val|.
8705
8706 If the output is glue, |cur_val| will point to a glue specification, and
8707 the reference count of that glue will have been updated to reflect this
8708 reference; if the output is a nonempty token list, |cur_val| will point to
8709 its reference count, but in this case the count will not have been updated.
8710 Otherwise |cur_val| will contain the integer or scaled value in question.
8711
8712 @d int_val 0 /*integer values*/
8713 @d dimen_val 1 /*dimension values*/
8714 @d glue_val 2 /*glue specifications*/
8715 @d mu_val 3 /*math glue specifications*/
8716 @d ident_val 4 /*font identifier*/
8717 @d tok_val 5 /*token lists*/
8718 @d has_factor (cur_hfactor!=0 || cur_vfactor!=0)
8719
8720 @<Glob...@>=
8721 static int @!cur_val, @!cur_hfactor, @!cur_vfactor; /*value returned by numeric scanners*/
8722 static int @!cur_val_level; /*the ``level'' of this value*/
8723
8724 @ The hash table is initialized with `\.{\\count}', `\.{\\dimen}', `\.{\\skip}',
8725 and `\.{\\muskip}' all having |internal_register| as their command code; they are
8726 distinguished by the |chr_code|, which is either |int_val|, |dimen_val|,
8727 |glue_val|, or |mu_val| more than |mem_bot| (dynamic variable-size nodes
8728 cannot have these values)
8729
8730 @<Put each...@>=
8731 primitive("count", internal_register, mem_bot+int_val);
8732 @!@:count\_}{\.{\\count} primitive@>
8733 primitive("dimen", internal_register, mem_bot+dimen_val);
8734 @!@:dimen\_}{\.{\\dimen} primitive@>
8735 primitive("skip", internal_register, mem_bot+glue_val);
8736 @!@:skip\_}{\.{\\skip} primitive@>
8737 primitive("muskip", internal_register, mem_bot+mu_val);
8738 @!@:mu\_skip\_}{\.{\\muskip} primitive@>
8739
8740 @ @<Cases of |print_cmd_chr|...@>=
8741 case internal_register: @<Cases of |register| for |print_cmd_chr|@>@;@+break;
8742
8743 @ OK, we're ready for |scan_something_internal| itself. A second parameter,
8744 |negative|, is set |true| if the value that is found should be negated.
8745 It is assumed that |cur_cmd| and |cur_chr| represent the first token of
8746 the internal quantity to be scanned; an error will be signalled if
8747 |cur_cmd < min_internal| or |cur_cmd > max_internal|.
8748
8749 @d scanned_result(A, B) @+{@+cur_val=A;cur_val_level=B;@+}
8750
8751 @p static void scan_something_internal(small_number @!level, bool @!negative)
8752 /*fetch an internal parameter*/
8753 {@+
8754 halfword m; /*|chr_code| part of the operand token*/
8755 pointer @!q; /*general purpose indices*/
8756 pointer @!tx; /*effective tail node*/
8757 int @!p; /*index into |nest|*/
8758 m=cur_chr;
8759 switch (cur_cmd) {
8760 case def_code: @<Fetch a character code from some table@>@;@+break;
8761 case toks_register: case assign_toks:
8762 case def_family: case set_font: case def_font: @<Fetch a token list or font
8763 identifier, provided that |level=tok_val|@>@;@+break;
8764 case assign_int: scanned_result(eqtb[m].i, int_val)@;@+break;
8765 case assign_dimen:
8766 scanned_result(eqtb[m].sc, dimen_val);
8767 if (m>=dimen_base)@/
8768 { cur_hfactor=hfactor_eqtb[m].sc;@+
8769 cur_vfactor=vfactor_eqtb[m].sc;@+
8770 }
8771 else
8772 cur_hfactor=cur_vfactor=0;@/
8773 @+break;
8774 case assign_glue: scanned_result(equiv(m), glue_val)@;@+break;
8775 case assign_mu_glue: scanned_result(equiv(m), mu_val)@;@+break;
8776 case set_aux: @<Fetch the |space_factor| or the |prev_depth|@>@;@+break;
8777 case set_prev_graf: @<Fetch the |prev_graf|@>@;@+break;
8778 case set_page_int: @<Fetch the |dead_cycles| or the |insert_penalties|@>@;@+break;
8779 case set_page_dimen: @<Fetch something on the |page_so_far|@>@;@+break;
8780 case set_shape: @<Fetch the |par_shape| size@>@;@+break;
8781 case set_box_dimen: @<Fetch a box dimension@>@;@+break;
8782 case char_given: scanned_result(cur_chr, int_val)@;@+break;
8783 case math_given: Umath_to_math(cur_chr); scanned_result(cur_chr, int_val)@;@+break;
8784 case assign_font_dimen: @<Fetch a font dimension@>@;@+break;
8785 case assign_font_int: @<Fetch a font integer@>@;@+break;
8786 case internal_register: @<Fetch a register@>@;@+break;
8787 case last_item: @<Fetch an item in the current node, if appropriate@>@;@+break;
8788 default:@<Complain that \.{\\the} can't do this; give zero result@>@;
8789 } @/
8790 while (cur_val_level > level) @<Convert \(c)|cur_val| to a lower level@>;
8791 @<Fix the reference count, if any, and negate |cur_val| if |negative|@>;
8792 }
8793
8794 @ @<Fetch a character code from some table@>=
8795 {@+scan_char_num();
8796 if (m>=utf_first_base && cur_val<0x100) m=utf_adjust_base(m);
8797 if (m>=utf_first_base) scanned_result(utf_lookup(m,cur_val), int_val)@;
8798 else if (m==math_code_base) scanned_result(ho(math_code(cur_val)), int_val)@;
8799 else if (m < math_code_base) scanned_result(equiv(m+cur_val), int_val)@;
8800 else scanned_result(eqtb[m+cur_val].i, int_val);
8801 }
8802
8803 @ @<Fetch a token list...@>=
8804 if (level!=tok_val)
8805 {@+print_err("Missing number, treated as zero");
8806 @.Missing number...@>
8807 help3("A number should have been here; I inserted `0'.",@/
8808 "(If you can't figure out why I needed to see a number,",@/
8809 "look up `weird error' in the index to The TeXbook.)");
8810 @:TeXbook}{\sl The \TeX book@>
8811 back_error();scanned_result(0, dimen_val);
8812 }
8813 else if (cur_cmd <= assign_toks)
8814 {@+if (cur_cmd < assign_toks) /*|cur_cmd==toks_register|*/
8815 if (m==mem_bot)
8816 {@+scan_register_num();
8817 if (cur_val < 256) cur_val=equiv(toks_base+cur_val);
8818 else{@+find_sa_element(tok_val, cur_val, false);
8819 if (cur_ptr==null) cur_val=null;
8820 else cur_val=sa_ptr(cur_ptr);
8821 }
8822 }
8823 else cur_val=sa_ptr(m);
8824 else
8825 { if (m<utf_first_base) cur_val=equiv(m);
8826 else cur_val=utf_lookup(m&utf_base_mask,m&utf_cp_mask);
8827 }
8828 cur_val_level=tok_val;
8829 }
8830 else{@+back_input();scan_font_ident();
8831 scanned_result(font_id_base+cur_val, ident_val);
8832 }
8833
8834 @ Users refer to `\.{\\the\\spacefactor}' only in horizontal
8835 mode, and to `\.{\\the\\prevdepth}' only in vertical mode; so we put the
8836 associated mode in the modifier part of the |set_aux| command.
8837 The |set_page_int| command has modifier 0 or 1, for `\.{\\deadcycles}' and
8838 `\.{\\insertpenalties}', respectively. The |set_box_dimen| command is
8839 modified by either |width_offset|, |height_offset|, or |depth_offset|.
8840 And the |last_item| command is modified by either |int_val|, |dimen_val|,
8841 |glue_val|, |input_line_no_code|, or |badness_code|.
8842 \eTeX\ inserts |last_node_type_code| after |glue_val| and adds
8843 the codes for its extensions: |eTeX_version_code|, \dots\ .
8844
8845 @d last_node_type_code (glue_val+1) /*code for \.{\\lastnodetype}*/
8846 @d input_line_no_code (glue_val+2) /*code for \.{\\inputlineno}*/
8847 @d badness_code (input_line_no_code+1) /*code for \.{\\badness}*/
8848 @#
8849 @d eTeX_int (badness_code+1) /*first of \eTeX\ codes for integers*/
8850 @d eTeX_dim (eTeX_int+8) /*first of \eTeX\ codes for dimensions*/
8851 @d eTeX_glue (eTeX_dim+9) /*first of \eTeX\ codes for glue*/
8852 @d eTeX_mu (eTeX_glue+1) /*first of \eTeX\ codes for muglue*/
8853 @d eTeX_expr (eTeX_mu+1) /*first of \eTeX\ codes for expressions*/
8854 @d eTeX_last_last_item_cmd_mod (eTeX_expr-int_val+mu_val) /*\.{\\muexpr}*/
8855
8856 @<Put each...@>=
8857 primitive("spacefactor", set_aux, hmode);
8858 @!@:space\_factor\_}{\.{\\spacefactor} primitive@>
8859 primitive("prevdepth", set_aux, vmode);@/
8860 @!@:prev\_depth\_}{\.{\\prevdepth} primitive@>
8861 primitive("deadcycles", set_page_int, 0);
8862 @!@:dead\_cycles\_}{\.{\\deadcycles} primitive@>
8863 primitive("insertpenalties", set_page_int, 1);
8864 @!@:insert\_penalties\_}{\.{\\insertpenalties} primitive@>
8865 primitive("wd", set_box_dimen, width_offset);
8866 @!@:wd\_}{\.{\\wd} primitive@>
8867 primitive("ht", set_box_dimen, height_offset);
8868 @!@:ht\_}{\.{\\ht} primitive@>
8869 primitive("dp", set_box_dimen, depth_offset);
8870 @!@:dp\_}{\.{\\dp} primitive@>
8871 primitive("lastpenalty", last_item, int_val);
8872 @!@:last\_penalty\_}{\.{\\lastpenalty} primitive@>
8873 primitive("lastkern", last_item, dimen_val);
8874 @!@:last\_kern\_}{\.{\\lastkern} primitive@>
8875 primitive("lastskip", last_item, glue_val);
8876 @!@:last\_skip\_}{\.{\\lastskip} primitive@>
8877 primitive("inputlineno", last_item, input_line_no_code);
8878 @!@:input\_line\_no\_}{\.{\\inputlineno} primitive@>
8879 primitive("badness", last_item, badness_code);
8880 @!@:badness\_}{\.{\\badness} primitive@>
8881
8882 @ @<Cases of |print_cmd_chr|...@>=
8883 case set_aux: if (chr_code==vmode) print_esc("prevdepth");
8884 @+else print_esc("spacefactor");@+break;
8885 case set_page_int: if (chr_code==0) print_esc("deadcycles")
8886 @/@<Cases of |set_page_int| for |print_cmd_chr|@>;@/
8887 @+else print_esc("insertpenalties");@+break;
8888 case set_box_dimen: if (chr_code==width_offset) print_esc("wd");
8889 else if (chr_code==height_offset) print_esc("ht");
8890 else print_esc("dp");@+break;
8891 case last_item: switch (chr_code) {
8892 case int_val: print_esc("lastpenalty");@+break;
8893 case dimen_val: print_esc("lastkern");@+break;
8894 case glue_val: print_esc("lastskip");@+break;
8895 case input_line_no_code: print_esc("inputlineno");@+break;
8896 @/@<Cases of |last_item| for |print_cmd_chr|@>@/
8897 default:print_esc("badness");
8898 } @+break;
8899
8900 @ @<Fetch the |space_factor| or the |prev_depth|@>=
8901 if (abs(mode)!=m)
8902 {@+print_err("Improper ");print_cmd_chr(set_aux, m);
8903 @.Improper \\spacefactor@>
8904 @.Improper \\prevdepth@>
8905 help4("You can refer to \\spacefactor only in horizontal mode;",@/
8906 "you can refer to \\prevdepth only in vertical mode; and",@/
8907 "neither of these is meaningful inside \\write. So",@/
8908 "I'm forgetting what you said and using zero instead.");
8909 error();
8910 if (level!=tok_val) scanned_result(0, dimen_val)@;
8911 else scanned_result(0, int_val);
8912 }
8913 else if (m==vmode)
8914 scanned_result(prev_depth==unknown_depth?0:prev_depth, dimen_val)@;
8915 else scanned_result(space_factor, int_val)
8916
8917 @ @<Fetch the |dead_cycles| or the |insert_penalties|@>=
8918 {@+if (m==0) cur_val=dead_cycles
8919 @/@<Cases for `Fetch the |dead_cycles| or the |insert_penalties|'@>;@/
8920 else cur_val=insert_penalties;
8921 cur_val_level=int_val;
8922 }
8923
8924 @ @<Fetch a box dimension@>=
8925 {@+scan_register_num();fetch_box(q);
8926 if (q==null) cur_val=0;@+else cur_val=mem[q+m].sc;
8927 cur_val_level=dimen_val;
8928 }
8929
8930 @ Inside an \.{\\output} routine, a user may wish to look at the page totals
8931 that were present at the moment when output was triggered.
8932
8933 @d max_dimen 07777777777 /*$2^{30}-1$*/
8934
8935 @<Fetch something on the |page_so_far|@>=
8936 {@+if ((page_contents==empty)&&(!output_active))
8937 if (m==0) cur_val=max_dimen;@+else cur_val=0;
8938 else cur_val=page_so_far[m];
8939 cur_val_level=dimen_val;
8940 }
8941
8942 @ @<Fetch the |prev_graf|@>=
8943 if (mode==0) scanned_result(0, int_val)@; /*|prev_graf==0| within \.{\\write}*/
8944 else{@+nest[nest_ptr]=cur_list;p=nest_ptr;
8945 while (abs(nest[p].mode_field)!=vmode) decr(p);
8946 scanned_result(nest[p].pg_field, int_val);
8947 }
8948
8949 @ @<Fetch the |par_shape| size@>=
8950 {@+if (m > par_shape_loc) @<Fetch a penalties array element@>@;
8951 else if (par_shape_ptr==null) cur_val=0;
8952 else cur_val=info(par_shape_ptr);
8953 cur_val_level=int_val;
8954 }
8955
8956 @ Here is where \.{\\lastpenalty}, \.{\\lastkern}, \.{\\lastskip}, and
8957 \.{\\lastnodetype} are
8958 implemented. The reference count for \.{\\lastskip} will be updated later.
8959
8960 We also handle \.{\\inputlineno} and \.{\\badness} here, because they are
8961 legal in similar contexts.
8962
8963 @<Fetch an item in the current node...@>=
8964 if (m > eTeX_last_last_item_cmd_mod)
8965 @/@<Fetch a \Prote\ item@>@;@/
8966 else if (m >= input_line_no_code)
8967 if (m >= eTeX_glue) @<Process an expression and |return|@>@;
8968 else if (m >= eTeX_dim)
8969 {@+switch (m) {
8970 @/@<Cases for fetching a dimension value@>@/
8971 } /*there are no other cases*/
8972 cur_val_level=dimen_val;
8973 }
8974 else{@+switch (m) {
8975 case input_line_no_code: cur_val=line;@+break;
8976 case badness_code: cur_val=last_badness;@+break;
8977 @/@<Cases for fetching an integer value@>@/
8978 } /*there are no other cases*/
8979 cur_val_level=int_val;
8980 }
8981 else{@+if (cur_chr==glue_val) cur_val=zero_glue;@+else cur_val=0;
8982 tx=tail;
8983 if (cur_chr==last_node_type_code)
8984 {@+cur_val_level=int_val;
8985 if ((tx==head)||(mode==0)) cur_val=-1;
8986 }
8987 else cur_val_level=cur_chr;
8988 if (!is_char_node(tx)&&(mode!=0))
8989 switch (cur_chr) {
8990 case int_val: if (type(tx)==penalty_node) cur_val=penalty(tx);@+break;
8991 case dimen_val: if (type(tx)==kern_node) cur_val=width(tx);@+break;
8992 case glue_val: if (type(tx)==glue_node)
8993 {@+cur_val=glue_ptr(tx);
8994 if (subtype(tx)==mu_glue) cur_val_level=mu_val;
8995 } @+break;
8996 case last_node_type_code: if (type(tx) <= unset_node) cur_val=type(tx)+1;
8997 else cur_val=unset_node+2;
8998 } /*there are no other cases*/
8999 else if ((mode==vmode)&&(tx==head))
9000 switch (cur_chr) {
9001 case int_val: cur_val=last_penalty;@+break;
9002 case dimen_val: cur_val=last_kern;@+break;
9003 case glue_val: if (last_glue!=max_halfword) cur_val=last_glue;@+break;
9004 case last_node_type_code: cur_val=last_node_type;
9005 } /*there are no other cases*/
9006 }
9007
9008 @ @<Fetch a font dimension@>=
9009 {@+find_font_dimen(false);font_info[fmem_ptr].sc=0;
9010 scanned_result(font_info[cur_val].sc, dimen_val);
9011 }
9012
9013 @ @<Fetch a font integer@>=
9014 {@+scan_font_ident();
9015 if (m==0) scanned_result(hyphen_char[cur_val], int_val)@;
9016 else scanned_result(skew_char[cur_val], int_val);
9017 }
9018
9019 @ @<Fetch a register@>=
9020 {@+if ((m < mem_bot)||(m > lo_mem_stat_max))
9021 {@+cur_val_level=sa_type(m);
9022 if (cur_val_level < glue_val) cur_val=sa_int(m);
9023 else cur_val=sa_ptr(m);
9024 }
9025 else{@+scan_register_num();cur_val_level=m-mem_bot;
9026 if (cur_val > 255)
9027 {@+find_sa_element(cur_val_level, cur_val, false);
9028 if (cur_ptr==null)
9029 if (cur_val_level < glue_val) cur_val=0;
9030 else cur_val=zero_glue;
9031 else if (cur_val_level < glue_val) cur_val=sa_int(cur_ptr);
9032 else cur_val=sa_ptr(cur_ptr);
9033 }
9034 else
9035 switch (cur_val_level) {
9036 case int_val: cur_val=count(cur_val);@+break;
9037 case dimen_val:
9038 cur_hfactor=dimen_hfactor(cur_val);
9039 cur_vfactor=dimen_vfactor(cur_val);
9040 cur_val=dimen(cur_val);@+break;
9041 case glue_val: cur_val=skip(cur_val);@+break;
9042 case mu_val: cur_val=mu_skip(cur_val);
9043 } /*there are no other cases*/
9044 }
9045 }
9046
9047 @ @<Complain that \.{\\the} can't do this; give zero result@>=
9048 {@+print_err("You can't use `");print_cmd_chr(cur_cmd, cur_chr);
9049 @.You can't use x after ...@>
9050 print("' after ");print_esc("the");
9051 help1("I'm forgetting what you said and using zero instead.");
9052 error();
9053 if (level!=tok_val) scanned_result(0, dimen_val)@;
9054 else scanned_result(0, int_val);
9055 }
9056
9057 @ When a |glue_val| changes to a |dimen_val|, we use the width component
9058 of the glue; there is no need to decrease the reference count, since it
9059 has not yet been increased. When a |dimen_val| changes to an |int_val|,
9060 we use scaled points so that the value doesn't actually change. And when a
9061 |mu_val| changes to a |glue_val|, the value doesn't change either.
9062
9063 @<Convert \(c)|cur_val| to a lower level@>=
9064 {@+if (cur_val_level==glue_val) cur_val=width(cur_val);
9065 else if (cur_val_level==mu_val) mu_error();
9066 decr(cur_val_level);
9067 }
9068
9069 @ If |cur_val| points to a glue specification at this point, the reference
9070 count for the glue does not yet include the reference by |cur_val|.
9071 If |negative| is |true|, |cur_val_level| is known to be | <= mu_val|.
9072
9073 @<Fix the reference count, if any,...@>=
9074 if (negative)
9075 if (cur_val_level >= glue_val)
9076 {@+cur_val=new_spec(cur_val);
9077 @<Negate all three glue components of |cur_val|@>;
9078 }
9079 else {@+ negate(cur_val);@+ negate(cur_hfactor); @+negate(cur_vfactor); @+}
9080 else if ((cur_val_level >= glue_val)&&(cur_val_level <= mu_val))
9081 add_glue_ref(cur_val)
9082
9083 @ @<Negate all three...@>=
9084 {@+negate(width(cur_val));
9085 negate(stretch(cur_val));
9086 negate(shrink(cur_val));
9087 }
9088
9089 @ Our next goal is to write the |scan_int| procedure, which scans anything that
9090 \TeX\ treats as an integer. But first we might as well look at some simple
9091 applications of |scan_int| that have already been made inside of
9092 |scan_something_internal|.
9093
9094 @ @<Declare procedures that scan restricted classes of integers@>=
9095 static void scan_eight_bit_int(void)
9096 {@+scan_int();
9097 if ((cur_val < 0)||(cur_val > 255))
9098 {@+print_err("Bad register code");
9099 @.Bad register code@>
9100 help2("A register number must be between 0 and 255.",@/
9101 "I changed this one to zero.");int_error(cur_val);cur_val=0;
9102 }
9103 }
9104
9105 @ @<Declare procedures that scan restricted classes of integers@>=
9106 static void scan_char_num(void)
9107 {@+scan_int();
9108 if ((cur_val < 0)||(cur_val > 0x10ffff))
9109 {@+print_err("Bad character code");
9110 @.Bad character code@>
9111 help2("A character number must be between 0 and 0x10FFFF.",@/
9112 "I changed this one to zero.");int_error(cur_val);cur_val=0;
9113 }
9114 }
9115
9116 @ While we're at it, we might as well deal with similar routines that
9117 will be needed later.
9118
9119 @<Declare procedures that scan restricted classes of integers@>=
9120 static void scan_four_bit_int(void)
9121 {@+scan_int();
9122 if ((cur_val < 0)||(cur_val > 15))
9123 {@+print_err("Bad number");
9124 @.Bad number@>
9125 help2("Since I expected to read a number between 0 and 15,",@/
9126 "I changed this one to zero.");int_error(cur_val);cur_val=0;
9127 }
9128 }
9129
9130 @ @<Declare procedures that scan restricted classes of integers@>=
9131 static void scan_fifteen_bit_int(void)
9132 {@+scan_int();
9133 if ((cur_val < 0)||(cur_val > 077777))
9134 {@+print_err("Bad mathchar");
9135 @.Bad mathchar@>
9136 help2("A mathchar number must be between 0 and 32767.",@/
9137 "I changed this one to zero.");int_error(cur_val);cur_val=0;
9138 }
9139 }
9140
9141 @ @<Declare procedures that scan restricted classes of integers@>=
9142 static void scan_twenty_seven_bit_int(void)
9143 {@+scan_int();
9144 if ((cur_val < 0)||(cur_val > 0777777777))
9145 {@+print_err("Bad delimiter code");
9146 @.Bad delimiter code@>
9147 help2("A numeric delimiter code must be between 0 and 2^{27}-1.",@/
9148 "I changed this one to zero.");int_error(cur_val);cur_val=0;
9149 }
9150 }
9151
9152 @ An integer number can be preceded by any number of spaces and `\.+' or
9153 `\.-' signs. Then comes either a decimal constant (i.e., radix 10), an
9154 octal constant (i.e., radix 8, preceded by~\.\'), a hexadecimal constant
9155 (radix 16, preceded by~\."), an alphabetic constant (preceded by~\.\`), or
9156 an internal variable. After scanning is complete,
9157 |cur_val| will contain the answer, which must be at most
9158 $2^{31}-1=2147483647$ in absolute value. The value of |radix| is set to
9159 10, 8, or 16 in the cases of decimal, octal, or hexadecimal constants,
9160 otherwise |radix| is set to zero. An optional space follows a constant.
9161
9162 @d octal_token (other_token+'\'') /*apostrophe, indicates an octal constant*/
9163 @d hex_token (other_token+'"') /*double quote, indicates a hex constant*/
9164 @d alpha_token (other_token+'`') /*reverse apostrophe, precedes alpha constants*/
9165 @d point_token (other_token+'.') /*decimal point*/
9166 @d continental_point_token (other_token+',') /*decimal point, Eurostyle*/
9167
9168 @<Glob...@>=
9169 static small_number @!radix; /*|scan_int| sets this to 8, 10, 16, or zero*/
9170
9171 @ We initialize the following global variables just in case |expand|
9172 comes into action before any of the basic scanning routines has assigned
9173 them a value.
9174
9175 @<Set init...@>=
9176 cur_val=0;cur_val_level=int_val;radix=0;cur_order=normal;
9177
9178 @ The |scan_int| routine is used also to scan the integer part of a
9179 fraction; for example, the `\.3' in `\.{3.14159}' will be found by
9180 |scan_int|. The |scan_dimen| routine assumes that |cur_tok==point_token|
9181 after the integer part of such a fraction has been scanned by |scan_int|,
9182 and that the decimal point has been backed up to be scanned again.
9183
9184 @p static void scan_int(void) /*sets |cur_val| to an integer*/
9185 {@+
9186 bool negative; /*should the answer be negated?*/
9187 int @!m; /*|@t$2^{31}$@>/radix|, the threshold of danger*/
9188 small_number @!d; /*the digit just scanned*/
9189 bool @!vacuous; /*have no digits appeared?*/
9190 bool @!OK_so_far; /*has an error message been issued?*/
9191 radix=0;OK_so_far=true;@/
9192 @<Get the next non-blank non-sign token; set |negative| appropriately@>;
9193 if (cur_tok==alpha_token) @<Scan an alphabetic character code into |cur_val|@>@;
9194 else if ((cur_cmd >= min_internal)&&(cur_cmd <= max_internal))
9195 scan_something_internal(int_val, false);
9196 else@<Scan a numeric constant@>;
9197 if (negative) negate(cur_val);
9198 }
9199
9200 @ @<Get the next non-blank non-sign token...@>=
9201 negative=false;
9202 @/do@+{@<Get the next non-blank non-call token@>;
9203 if (cur_tok==other_token+'-')
9204 {@+negative=!negative;cur_tok=other_token+'+';
9205 }
9206 }@+ while (!(cur_tok!=other_token+'+'))
9207
9208 @ A space is ignored after an alphabetic character constant, so that
9209 such constants behave like numeric ones.
9210
9211 @<Scan an alphabetic character code into |cur_val|@>=
9212 {@+get_token(); /*suppress macro expansion*/
9213 if (cur_tok < cs_token_flag)
9214 {@+cur_val=cur_chr;
9215 if (cur_cmd <= right_brace)
9216 if (cur_cmd==right_brace) incr(align_state);
9217 else decr(align_state);
9218 }
9219 else if (cur_tok < cs_token_flag+single_base)
9220 { if (cur_tok < cs_token_flag+ active_hash_base)
9221 cur_val=cur_tok-cs_token_flag-active_base;
9222 else
9223 cur_val=active_hash[cur_tok-cs_token_flag];
9224 }
9225 else if (cur_tok < cs_token_flag+null_cs)
9226 cur_val=cur_tok-cs_token_flag-single_base;
9227 else /* a single UTF8 character controll sequence with a value greater than 255 */
9228 { pointer p = cur_tok-cs_token_flag;
9229 int t=text(p);
9230 int i=str_start[t];
9231 int j=str_start[t+1];
9232 int k=utf8_get_cur_chr(str_pool,i,j);
9233 if (k==j)
9234 cur_val=cur_chr;
9235 else
9236 cur_val=0x110000;
9237 }
9238 if (cur_val > 0x10ffff)
9239 {@+print_err("Improper alphabetic constant");
9240 @.Improper alphabetic constant@>
9241 help2("A one-character control sequence belongs after a ` mark.",@/
9242 "So I'm essentially inserting \\0 here.");
9243 cur_val='0';back_error();
9244 }
9245 else@<Scan an optional space@>;
9246 }
9247
9248 @ @<Scan an optional space@>=
9249 {@+get_x_token();if (cur_cmd!=spacer) back_input();
9250 }
9251
9252 @ @<Scan a numeric constant@>=
9253 {@+radix=10;m=214748364;
9254 if (cur_tok==octal_token)
9255 {@+radix=8;m=02000000000;get_x_token();
9256 }
9257 else if (cur_tok==hex_token)
9258 {@+radix=16;m=01000000000;get_x_token();
9259 }
9260 vacuous=true;cur_val=0;@/
9261 @<Accumulate the constant until |cur_tok| is not a suitable digit@>;
9262 if (vacuous) @<Express astonishment that no number was here@>@;
9263 else if (cur_cmd!=spacer) back_input();
9264 }
9265
9266 @ @d infinity 017777777777 /*the largest positive value that \TeX\ knows*/
9267 @d zero_token (other_token+'0') /*zero, the smallest digit*/
9268 @d A_token (letter_token+'A') /*the smallest special hex digit*/
9269 @d other_A_token (other_token+'A') /*special hex digit of type |other_char|*/
9270
9271 @<Accumulate the constant...@>=
9272 loop@+{@+if ((cur_tok < zero_token+radix)&&(cur_tok >= zero_token)&&
9273 (cur_tok <= zero_token+9)) d=cur_tok-zero_token;
9274 else if (radix==16)
9275 if ((cur_tok <= A_token+5)&&(cur_tok >= A_token)) d=cur_tok-A_token+10;
9276 else if ((cur_tok <= other_A_token+5)&&(cur_tok >= other_A_token))
9277 d=cur_tok-other_A_token+10;
9278 else goto done;
9279 else goto done;
9280 vacuous=false;
9281 if ((cur_val >= m)&&((cur_val > m)||(d > 7)||(radix!=10)))
9282 {@+if (OK_so_far)
9283 {@+print_err("Number too big");
9284 @.Number too big@>
9285 help2("I can only go up to 2147483647='17777777777=\"7FFFFFFF,",@/
9286 "so I'm using that number instead of yours.");
9287 error();cur_val=infinity;OK_so_far=false;
9288 }
9289 }
9290 else cur_val=cur_val*radix+d;
9291 get_x_token();
9292 }
9293 done:
9294
9295 @ @<Express astonishment...@>=
9296 {@+print_err("Missing number, treated as zero");
9297 @.Missing number...@>
9298 help3("A number should have been here; I inserted `0'.",@/
9299 "(If you can't figure out why I needed to see a number,",@/
9300 "look up `weird error' in the index to The TeXbook.)");
9301 @:TeXbook}{\sl The \TeX book@>
9302 back_error();
9303 }
9304
9305 @ The |scan_dimen| routine is similar to |scan_int|, but it sets |cur_val| to
9306 a |scaled| value, i.e., an integral number of sp. One of its main tasks
9307 is therefore to interpret the abbreviations for various kinds of units and
9308 to convert measurements to scaled points.
9309
9310 There are three parameters: |mu| is |true| if the finite units must be
9311 `\.{mu}', while |mu| is |false| if `\.{mu}' units are disallowed;
9312 |inf| is |true| if the infinite units `\.{fil}', `\.{fill}', `\.{filll}'
9313 are permitted; and |shortcut| is |true| if |cur_val| already contains
9314 an integer and only the units need to be considered.
9315
9316 The order of infinity that was found in the case of infinite glue is returned
9317 in the global variable |cur_order|.
9318
9319 @<Glob...@>=
9320 static glue_ord @!cur_order; /*order of infinity found by |scan_dimen|*/
9321
9322 @ Constructions like `\.{-\'77 pt}' are legal dimensions, so |scan_dimen|
9323 may begin with |scan_int|. This explains why it is convenient to use
9324 |scan_int| also for the integer part of a decimal fraction.
9325
9326 Several branches of |scan_dimen| work with |cur_val| as an integer and
9327 with an auxiliary fraction |f|, so that the actual quantity of interest is
9328 $|cur_val|+|f|/2^{16}$. At the end of the routine, this ``unpacked''
9329 representation is put into the single word |cur_val|, which suddenly
9330 switches significance from |int| to |scaled|.
9331
9332 @d scan_normal_dimen scan_dimen(false, false, false)
9333
9334 @p static void scan_dimen(bool @!mu, bool @!inf, bool @!shortcut)
9335 /*sets |cur_val| to a dimension*/
9336 {@+
9337 bool negative; /*should the answer be negated?*/
9338 int @!f; /*numerator of a fraction whose denominator is $2^{16}$*/
9339 @<Local variables for dimension calculations@>@;
9340 f=0;arith_error=false;cur_order=normal;negative=false;
9341 cur_hfactor=cur_vfactor=0;
9342 if (!shortcut)
9343 {@+@<Get the next non-blank non-sign...@>;
9344 if ((cur_cmd >= min_internal)&&(cur_cmd <= max_internal))
9345 @<Fetch an internal dimension and |goto attach_sign|, or fetch an internal
9346 integer@>@;
9347 else{@+back_input();
9348 if (cur_tok==continental_point_token) cur_tok=point_token;
9349 if (cur_tok!=point_token) scan_int();
9350 else{@+radix=10;cur_val=0;
9351 }
9352 if (cur_tok==continental_point_token) cur_tok=point_token;
9353 if ((radix==10)&&(cur_tok==point_token)) @<Scan decimal fraction@>;
9354 }
9355 }
9356 if (cur_val < 0) /*in this case |f==0|*/
9357 {@+negative=!negative;negate(cur_val);
9358 }
9359 @<Scan units and set |cur_val| to $x\cdot(|cur_val|+f/2^{16})$, where there
9360 are |x| sp per unit; |goto attach_sign| if the units are internal@>;
9361 @<Scan an optional space@>;
9362 attach_sign:
9363 if (arith_error||(abs(cur_val) >= 010000000000)||
9364 (abs(cur_hfactor) >= 010000000000) || (abs(cur_vfactor) >= 010000000000))
9365 @<Report that this dimension is out of range@>;
9366 if (negative) @/{@+ negate(cur_val);@+ negate(cur_hfactor); @+negate(cur_vfactor);@+ }
9367 }
9368
9369 @ @<Fetch an internal dimension and |goto attach_sign|...@>=
9370 if (mu)
9371 {@+scan_something_internal(mu_val, false);
9372 @<Coerce glue to a dimension@>;
9373 if (cur_val_level==mu_val) goto attach_sign;
9374 if (cur_val_level!=int_val) mu_error();
9375 }
9376 else{@+scan_something_internal(dimen_val, false);
9377 if (cur_val_level==dimen_val) goto attach_sign;
9378 }
9379
9380 @ @<Local variables for dimension calculations@>=
9381 int @!num, @!denom; /*conversion ratio for the scanned units*/
9382 int @!k, @!kk; /*number of digits in a decimal fraction*/
9383 pointer @!p, @!q; /*top of decimal digit stack*/
9384 scaled @!v; /*an internal dimension*/
9385 int @!save_cur_val; /*temporary storage of |cur_val|*/
9386
9387 @ The following code is executed when |scan_something_internal| was
9388 called asking for |mu_val|, when we really wanted a ``mudimen'' instead
9389 of ``muglue.''
9390
9391 @<Coerce glue to a dimension@>=
9392 if (cur_val_level >= glue_val)
9393 {@+v=width(cur_val);delete_glue_ref(cur_val);cur_val=v;
9394 }
9395
9396 @ When the following code is executed, we have |cur_tok==point_token|, but this
9397 token has been backed up using |back_input|; we must first discard it.
9398
9399 It turns out that a decimal point all by itself is equivalent to `\.{0.0}'.
9400 Let's hope people don't use that fact.
9401
9402 @<Scan decimal fraction@>=
9403 {@+k=0;p=null;get_token(); /*|point_token| is being re-scanned*/
9404 loop@+{@+get_x_token();
9405 if ((cur_tok > zero_token+9)||(cur_tok < zero_token)) goto done1;
9406 if (k < 17) /*digits for |k >= 17| cannot affect the result*/
9407 {@+q=get_avail();link(q)=p;info(q)=cur_tok-zero_token;
9408 p=q;incr(k);
9409 }
9410 }
9411 done1: for (kk=k; kk>=1; kk--)
9412 {@+dig[kk-1]=info(p);q=p;p=link(p);free_avail(q);
9413 }
9414 f=round_decimals(k);
9415 if (cur_cmd!=spacer) back_input();
9416 }
9417
9418 @ Now comes the harder part: At this point in the program, |cur_val| is a
9419 nonnegative integer and $f/2^{16}$ is a nonnegative fraction less than 1;
9420 we want to multiply the sum of these two quantities by the appropriate
9421 factor, based on the specified units, in order to produce a |scaled|
9422 result, and we want to do the calculation with fixed point arithmetic that
9423 does not overflow.
9424
9425 @<Scan units and set |cur_val| to $x\cdot(|cur_val|+f/2^{16})$...@>=
9426 if (inf) @<Scan for \(f)\.{fil} units; |goto attach_fraction| if found@>;
9427 @<Scan for \(u)units that are internal dimensions; |goto attach_sign| with
9428 |cur_val| set if found@>;
9429 if (mu) @<Scan for \(m)\.{mu} units and |goto attach_fraction|@>;
9430 if (scan_keyword("true")) @<Adjust \(f)for the magnification ratio@>;
9431 @.true@>
9432 if (scan_keyword("pt")) goto attach_fraction; /*the easy case*/
9433 @.pt@>
9434 @<Scan for \(a)all other units and adjust |cur_val| and |f| accordingly; |goto
9435 done| in the case of scaled points@>;
9436 attach_fraction: if (cur_val >= 040000) arith_error=true;
9437 else cur_val=cur_val*unity+f;
9438 done:
9439
9440 @ A specification like `\.{filllll}' or `\.{fill L L L}' will lead to two
9441 error messages (one for each additional keyword \.{"l"}).
9442
9443 @<Scan for \(f)\.{fil} units...@>=
9444 if (scan_keyword("fil"))
9445 @.fil@>
9446 {@+cur_order=fil;
9447 while (scan_keyword("l"))
9448 {@+if (cur_order==filll)
9449 {@+print_err("Illegal unit of measure (");
9450 @.Illegal unit of measure@>
9451 print("replaced by filll)");
9452 help1("I dddon't go any higher than filll.");error();
9453 }
9454 else incr(cur_order);
9455 }
9456 goto attach_fraction;
9457 }
9458
9459 @ @<Scan for \(u)units that are internal dimensions...@>=
9460 save_cur_val=cur_val;
9461 if (has_factor)
9462 { print_err("Factor is not constant. Linear component ignored");
9463 cur_hfactor=cur_vfactor=0;
9464 }
9465 @<Get the next non-blank non-call...@>;
9466 if ((cur_cmd < min_internal)||(cur_cmd > max_internal)) back_input();
9467 else{@+if (mu)
9468 {@+scan_something_internal(mu_val, false);@<Coerce glue...@>;
9469 if (cur_val_level!=mu_val) mu_error();
9470 }
9471 else scan_something_internal(dimen_val, false);
9472 v=cur_val;goto found;
9473 }
9474 if (mu) goto not_found;
9475 if (scan_keyword("em")) v=(@<The em width for |cur_font|@>);
9476 @.em@>
9477 else if (scan_keyword("ex")) v=(@<The x-height for |cur_font|@>);
9478 @.ex@>
9479 else goto not_found;
9480 @<Scan an optional space@>;
9481 found:
9482 if (has_factor)
9483 { cur_hfactor=nx_plus_y(save_cur_val, cur_hfactor, xn_over_d(cur_hfactor, f, unity));
9484 cur_vfactor=nx_plus_y(save_cur_val, cur_vfactor, xn_over_d(cur_vfactor, f, unity));
9485 }
9486 cur_val=nx_plus_y(save_cur_val, v, xn_over_d(v, f, unity));
9487 goto attach_sign;
9488 not_found:
9489
9490 @ @<Scan for \(m)\.{mu} units and |goto attach_fraction|@>=
9491 if (scan_keyword("mu")) goto attach_fraction;
9492 @.mu@>
9493 else{@+print_err("Illegal unit of measure (");print("mu inserted)");
9494 @.Illegal unit of measure@>
9495 help4("The unit of measurement in math glue must be mu.",@/
9496 "To recover gracefully from this error, it's best to",@/
9497 "delete the erroneous units; e.g., type `2' to delete",@/
9498 "two letters. (See Chapter 27 of The TeXbook.)");
9499 @:TeXbook}{\sl The \TeX book@>
9500 error();goto attach_fraction;
9501 }
9502
9503 @ @<Adjust \(f)for the magnification ratio@>=
9504 {@+prepare_mag();
9505 if (mag!=1000)
9506 {@+cur_val=xn_over_d(cur_val, 1000, mag);
9507 f=(1000*f+0200000*rem)/mag;
9508 cur_val=cur_val+(f/0200000);f=f%0200000;
9509 }
9510 }
9511
9512 @ The necessary conversion factors can all be specified exactly as
9513 fractions whose numerator and denominator sum to 32768 or less.
9514 According to the definitions here, $\rm2660\,dd\approx1000.33297\,mm$;
9515 this agrees well with the value $\rm1000.333\,mm$ cited by Bosshard
9516 @^Bosshard, Hans Rudolf@>
9517 in {\sl Technische Grundlagen zur Satzherstellung\/} (Bern, 1980).
9518
9519 @d set_conversion(A, B) @+{@+num=A;denom=B;}
9520
9521 @<Scan for \(a)all other units and adjust |cur_val| and |f|...@>=
9522 if (scan_keyword("in")) set_conversion(7227, 100)@;
9523 @.in@>
9524 else if (scan_keyword("pc")) set_conversion(12, 1)@;
9525 @.pc@>
9526 else if (scan_keyword("cm")) set_conversion(7227, 254)@;
9527 @.cm@>
9528 else if (scan_keyword("mm")) set_conversion(7227, 2540)@;
9529 @.mm@>
9530 else if (scan_keyword("bp")) set_conversion(7227, 7200)@;
9531 @.bp@>
9532 else if (scan_keyword("dd")) set_conversion(1238, 1157)@;
9533 @.dd@>
9534 else if (scan_keyword("cc")) set_conversion(14856, 1157)@;
9535 @.cc@>
9536 else if (scan_keyword("sp")) goto done;
9537 @.sp@>
9538 else@<Complain about unknown unit and |goto done2|@>;
9539 cur_val=xn_over_d(cur_val, num, denom);
9540 f=(num*f+0200000*rem)/denom;@/
9541 cur_val=cur_val+(f/0200000);f=f%0200000;
9542 done2:
9543
9544 @ @<Complain about unknown unit...@>=
9545 {@+print_err("Illegal unit of measure (");print("pt inserted)");
9546 @.Illegal unit of measure@>
9547 help6("Dimensions can be in units of em, ex, in, pt, pc,",@/
9548 "cm, mm, dd, cc, bp, or sp; but yours is a new one!",@/
9549 "I'll assume that you meant to say pt, for printer's points.",@/
9550 "To recover gracefully from this error, it's best to",@/
9551 "delete the erroneous units; e.g., type `2' to delete",@/
9552 "two letters. (See Chapter 27 of The TeXbook.)");
9553 @:TeXbook}{\sl The \TeX book@>
9554 error();goto done2;
9555 }
9556
9557
9558 @ @<Report that this dimension is out of range@>=
9559 {@+print_err("Dimension too large");
9560 @.Dimension too large@>
9561 help2("I can't work with sizes bigger than about 19 feet.",@/
9562 "Continue and I'll use the largest value I can.");@/
9563 error();cur_val=max_dimen;arith_error=false;
9564 }
9565
9566 @ The final member of \TeX's value-scanning trio is |scan_glue|, which
9567 makes |cur_val| point to a glue specification. The reference count of that
9568 glue spec will take account of the fact that |cur_val| is pointing to~it.
9569
9570 The |level| parameter should be either |glue_val| or |mu_val|.
9571
9572 Since |scan_dimen| was so much more complex than |scan_int|, we might expect
9573 |scan_glue| to be even worse. But fortunately, it is very simple, since
9574 most of the work has already been done.
9575
9576 @p static void scan_glue(small_number @!level)
9577 /*sets |cur_val| to a glue spec pointer*/
9578 {@+
9579 bool negative; /*should the answer be negated?*/
9580 pointer @!q; /*new glue specification*/
9581 bool @!mu; /*does |level==mu_val|?*/
9582 mu=(level==mu_val);@<Get the next non-blank non-sign...@>;
9583 if ((cur_cmd >= min_internal)&&(cur_cmd <= max_internal))
9584 {@+scan_something_internal(level, negative);
9585 if (cur_val_level >= glue_val)
9586 {@+if (cur_val_level!=level) mu_error();
9587 return;
9588 }
9589 if (cur_val_level==int_val) scan_dimen(mu, false, true);
9590 else if (level==mu_val) mu_error();
9591 }
9592 else{@+back_input();scan_dimen(mu, false, false);
9593 if (negative) { negate(cur_val); negate(cur_hfactor); negate(cur_vfactor);}
9594 }
9595 @<Create a new glue specification whose width is |cur_val|; scan for its stretch
9596 and shrink components@>;
9597 }
9598 @#
9599 @<Declare procedures needed for expressions@>@;
9600
9601 @ @<Create a new glue specification whose width is |cur_val|...@>=
9602 q=new_spec(zero_glue);width(q)=cur_val;
9603 if (scan_keyword("plus"))
9604 @.plus@>
9605 {@+scan_dimen(mu, true, false);
9606 stretch(q)=cur_val;stretch_order(q)=cur_order;
9607 }
9608 if (scan_keyword("minus"))
9609 @.minus@>
9610 {@+scan_dimen(mu, true, false);
9611 shrink(q)=cur_val;shrink_order(q)=cur_order;
9612 }
9613 cur_val=q
9614
9615 @ Here's a similar procedure that returns a pointer to a rule node. This
9616 routine is called just after \TeX\ has seen \.{\\hrule} or \.{\\vrule};
9617 therefore |cur_cmd| will be either |hrule| or |vrule|. The idea is to store
9618 the default rule dimensions in the node, then to override them if
9619 `\.{height}' or `\.{width}' or `\.{depth}' specifications are
9620 found (in any order).
9621
9622 @d default_rule 26214 /*0.4\thinspace pt*/
9623
9624 @p static pointer scan_rule_spec(void)
9625 {@+
9626 pointer q; /*the rule node being created*/
9627 q=new_rule(); /*|width|, |depth|, and |height| all equal |null_flag| now*/
9628 if (cur_cmd==vrule) width(q)=default_rule;
9629 else{@+height(q)=default_rule;depth(q)=0;
9630 }
9631 reswitch: if (scan_keyword("width"))
9632 @.width@>
9633 {@+scan_normal_dimen;width(q)=cur_val;goto reswitch;
9634 }
9635 if (scan_keyword("height"))
9636 @.height@>
9637 {@+scan_normal_dimen;height(q)=cur_val;goto reswitch;
9638 }
9639 if (scan_keyword("depth"))
9640 @.depth@>
9641 {@+scan_normal_dimen;depth(q)=cur_val;goto reswitch;
9642 }
9643 return q;
9644 }
9645
9646 @* Building token lists.
9647 The token lists for macros and for other things like \.{\\mark} and \.{\\output}
9648 and \.{\\write} are produced by a procedure called |scan_toks|.
9649
9650 Before we get into the details of |scan_toks|, let's consider a much
9651 simpler task, that of converting the current string into a token list.
9652 The |str_toks| function does this; it classifies spaces as type |spacer|
9653 and everything else as type |other_char|.
9654
9655 The token list created by |str_toks| begins at |link(temp_head)| and ends
9656 at the value |p| that is returned. (If |p==temp_head|, the list is empty.)
9657
9658 The |str_toks_cat| function is the same, except that the catcode |cat| is
9659 stamped on all the characters, unless zero is passed in which case it
9660 chooses |spacer| or |other_char| automatically.
9661
9662 @p @t\4@>@<Declare \eTeX\ procedures for token lists@>@;@/
9663 static pointer str_toks_cat(pool_pointer @!b, small_number cat)
9664 /*converts |str_pool[b dotdot pool_ptr-1]| to a token list*/
9665 {@+pointer p; /*tail of the token list*/
9666 pointer @!q; /*new node being added to the token list via |store_new_token|*/
9667 halfword @!t; /*token being appended*/
9668 int save_chr;
9669 pool_pointer @!k; /*index into |str_pool|*/
9670 save_chr=cur_chr; /*not shure if this is necessary*/
9671 str_room(1);
9672 p=temp_head;link(p)=null;k=b;
9673 while (k < pool_ptr)
9674 {@+ k=utf8_get_cur_chr(str_pool,k,pool_ptr);
9675 if (cur_chr==' ' && cat==0) t=space_token;
9676 else if (cat==0) t=other_token+cur_chr;
9677 else if (cat==active_char)
9678 { if (cur_chr<utf8_single_size) t= cs_token_flag+active_base+cur_chr;
9679 else t = cs_token_flag+ active_lookup(cur_chr);
9680 }
9681 else t= cmd_token(cat) +cur_chr;
9682 fast_store_new_token(t);
9683 }
9684 cur_chr=save_chr;
9685 pool_ptr=b;return p;
9686 }
9687
9688 static pointer str_toks(pool_pointer @!b)
9689 { return str_toks_cat(b,0);
9690 }
9691
9692
9693 @ The main reason for wanting |str_toks| is the next function,
9694 |the_toks|, which has similar input/output characteristics.
9695
9696 This procedure is supposed to scan something like `\.{\\skip\\count12}',
9697 i.e., whatever can follow `\.{\\the}', and it constructs a token list
9698 containing something like `\.{-3.0pt minus 0.5fill}'.
9699
9700 @p static pointer the_toks(void)
9701 {@+
9702 int old_setting; /*holds |selector| setting*/
9703 pointer @!p, @!q, @!r; /*used for copying a token list*/
9704 pool_pointer @!b; /*base of temporary string*/
9705 small_number @!c; /*value of |cur_chr|*/
9706 @<Handle \.{\\unexpanded} or \.{\\detokenize} and |return|@>;@/
9707 get_x_token();scan_something_internal(tok_val, false);
9708 if (cur_val_level >= ident_val) @<Copy the token list@>@;
9709 else{@+old_setting=selector;selector=new_string;b=pool_ptr;
9710 switch (cur_val_level) {
9711 case int_val: print_int(cur_val);@+break;
9712 case dimen_val: {@+print_scaled(cur_val);print("pt");
9713 } @+break;
9714 case glue_val: {@+print_spec(cur_val,"pt");delete_glue_ref(cur_val);
9715 } @+break;
9716 case mu_val: {@+print_spec(cur_val,"mu");delete_glue_ref(cur_val);
9717 }
9718 } /*there are no other cases*/
9719 selector=old_setting;return str_toks(b);
9720 }
9721 }
9722
9723 @ @<Copy the token list@>=
9724 {@+p=temp_head;link(p)=null;
9725 if (cur_val_level==ident_val) store_new_token(cs_token_flag+cur_val)@;
9726 else if (cur_val!=null)
9727 {@+r=link(cur_val); /*do not copy the reference count*/
9728 while (r!=null)
9729 {@+fast_store_new_token(info(r));r=link(r);
9730 }
9731 }
9732 return p;
9733 }
9734
9735 @ Here's part of the |expand| subroutine that we are now ready to complete:
9736
9737 @p static void ins_the_toks(void)
9738 {@+link(garbage)=the_toks();ins_list(link(temp_head));
9739 }
9740
9741 @ The primitives \.{\\number}, \.{\\romannumeral}, \.{\\string}, \.{\\meaning},
9742 \.{\\fontname}, and \.{\\jobname} are defined as follows.
9743
9744 @d number_code 0 /*command code for \.{\\number}*/
9745 @d roman_numeral_code 1 /*command code for \.{\\romannumeral}*/
9746 @d string_code 2 /*command code for \.{\\string}*/
9747 @d meaning_code 3 /*command code for \.{\\meaning}*/
9748 @d font_name_code 4 /*command code for \.{\\fontname}*/
9749 @d job_name_code 5 /*command code for \.{\\jobname}*/
9750 @d Uchar_code 6 /*command code for \.{\\Uchar}*/
9751 @d Ucharcat_code 7 /*command code for \.{\\Ucharcat}*/
9752 @d etex_convert_base (Ucharcat_code+1) /*base for \eTeX's command codes*/
9753 @d eTeX_revision_code etex_convert_base /*command code for \.{\\eTeXrevision}*/
9754 @d etex_convert_codes (etex_convert_base+1) /*end of \eTeX's command codes*/
9755 @d eTeX_last_convert_cmd_mod etex_convert_codes
9756
9757 @<Put each...@>=
9758 primitive("number", convert, number_code);@/
9759 @!@:number\_}{\.{\\number} primitive@>
9760 primitive("romannumeral", convert, roman_numeral_code);@/
9761 @!@:roman\_numeral\_}{\.{\\romannumeral} primitive@>
9762 primitive("string", convert, string_code);@/
9763 @!@:string\_}{\.{\\string} primitive@>
9764 primitive("meaning", convert, meaning_code);@/
9765 @!@:meaning\_}{\.{\\meaning} primitive@>
9766 primitive("fontname", convert, font_name_code);@/
9767 @!@:font\_name\_}{\.{\\fontname} primitive@>
9768 primitive("jobname", convert, job_name_code);@/
9769 @!@:job\_name\_}{\.{\\jobname} primitive@>
9770 @#
9771 primitive("Uchar", convert, Uchar_code);@/
9772 @!@:Uchar\_}{\.{\\Uchar} primitive@>
9773 primitive("Ucharcat", convert, Ucharcat_code);@/
9774 @!@:Ucharcat\_}{\.{\\Ucharcat} primitive@>
9775
9776
9777 @ @<Cases of |print_cmd_chr|...@>=
9778 case convert: switch (chr_code) {
9779 case number_code: print_esc("number");@+break;
9780 case roman_numeral_code: print_esc("romannumeral");@+break;
9781 case string_code: print_esc("string");@+break;
9782 case meaning_code: print_esc("meaning");@+break;
9783 case font_name_code: print_esc("fontname");@+break;
9784 case job_name_code: print_esc("jobname");@+break;
9785 case Uchar_code: print_esc("Uchar");@+break;
9786 case Ucharcat_code: print_esc("Ucharcat");@+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 conv_toks(void)
9796 {@+int old_setting; /*holds |selector| setting*/
9797 int @!c; /*desired type of conversion*/
9798 small_number cat; /*desired catcode, or 0 for automatic |spacer|/|other_char| selection*/
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 cat=0; 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_cat(b,cat);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 @#
9820 case Uchar_code: scan_char_num();@+break;
9821 case Ucharcat_code:
9822 { int saved_val;
9823 scan_char_num();
9824 saved_val=cur_val;
9825 scan_int();
9826 if (cur_val<left_brace||cur_val>active_char||
9827 cur_val==out_param||cur_val==ignore)
9828 { print_err("Invalid code ("); print_int(cur_val);
9829 @.Invalid code@>
9830 print("), should be in the ranges 1..4, 6..8, 10..13");
9831 help1("I'm going to use 12 instead of that illegal code value.");@/
9832 error(); cat=12;
9833 }
9834 else
9835 cat=cur_val;
9836 cur_val=saved_val;
9837 }@+break;
9838 @#
9839 case eTeX_revision_code: do_nothing;@+break;
9840 @/@<Cases of `Scan the argument for command |c|'@>@/
9841 } /*there are no other cases*/
9842
9843 @ @<Print the result of command |c|@>=
9844 switch (c) {
9845 case number_code: print_int(cur_val);@+break;
9846 case roman_numeral_code: print_roman_int(cur_val);@+break;
9847 case string_code: if (cur_cs!=0) sprint_cs(cur_cs);
9848 else print_utf8(cur_chr);@+break;
9849 case meaning_code: print_meaning();@+break;
9850 case font_name_code: {@+printn(font_name[cur_val]);
9851 if (font_size[cur_val]!=font_dsize[cur_val])
9852 {@+print(" at ");print_scaled(font_size[cur_val]);
9853 print("pt");
9854 }
9855 } @+break;
9856 case eTeX_revision_code: print(eTeX_revision);@+break;
9857 case job_name_code: printn(job_name);@+break;
9858 case Uchar_code: case Ucharcat_code: print_char(cur_val); break;
9859 @/@<Cases of `Print the result of command |c|'@>@/
9860 } /*there are no other cases*/
9861
9862 @ Now we can't postpone the difficulties any longer; we must bravely tackle
9863 |scan_toks|. This function returns a pointer to the tail of a new token
9864 list, and it also makes |def_ref| point to the reference count at the
9865 head of that list.
9866
9867 There are two boolean parameters, |macro_def| and |xpand|. If |macro_def|
9868 is true, the goal is to create the token list for a macro definition;
9869 otherwise the goal is to create the token list for some other \TeX\
9870 primitive: \.{\\mark}, \.{\\output}, \.{\\everypar}, \.{\\lowercase},
9871 \.{\\uppercase}, \.{\\message}, \.{\\errmessage}, \.{\\write}, or
9872 \.{\\special}. In the latter cases a left brace must be scanned next; this
9873 left brace will not be part of the token list, nor will the matching right
9874 brace that comes at the end. If |xpand| is false, the token list will
9875 simply be copied from the input using |get_token|. Otherwise all expandable
9876 tokens will be expanded until unexpandable tokens are left, except that
9877 the results of expanding `\.{\\the}' are not expanded further.
9878 If both |macro_def| and |xpand| are true, the expansion applies
9879 only to the macro body (i.e., to the material following the first
9880 |left_brace| character).
9881
9882 The value of |cur_cs| when |scan_toks| begins should be the |eqtb|
9883 address of the control sequence to display in ``runaway'' error
9884 messages.
9885
9886 @p static pointer scan_toks(bool @!macro_def, bool @!xpand)
9887 {@+
9888 halfword t; /*token representing the highest parameter number*/
9889 halfword @!s; /*saved token*/
9890 pointer @!p; /*tail of the token list being built*/
9891 pointer @!q; /*new node being added to the token list via |store_new_token|*/
9892 halfword @!unbalance; /*number of unmatched left braces*/
9893 halfword @!hash_brace; /*possible `\.{\#\{}' token*/
9894 if (macro_def) scanner_status=defining;
9895 @+else scanner_status=absorbing;
9896 warning_index=cur_cs;def_ref=get_avail();token_ref_count(def_ref)=null;
9897 p=def_ref;hash_brace=0;t=zero_token;
9898 if (macro_def) @<Scan and build the parameter part of the macro definition@>@;
9899 else scan_left_brace(); /*remove the compulsory left brace*/
9900 @<Scan and build the body of the token list; |goto found| when finished@>;
9901 found: scanner_status=normal;
9902 if (hash_brace!=0) store_new_token(hash_brace);
9903 return p;
9904 }
9905 @t\4@>@<Declare \Prote\ procedures for token lists@>@;@/
9906
9907 @ @<Scan and build the parameter part...@>=
9908 {@+loop{@+resume: get_token(); /*set |cur_cmd|, |cur_chr|, |cur_tok|*/
9909 if (cur_tok < right_brace_limit) goto done1;
9910 if (cur_cmd==mac_param)
9911 @<If the next character is a parameter number, make |cur_tok| a |match|
9912 token; but if it is a left brace, store `|left_brace|, |end_match|', set |hash_brace|,
9913 and |goto done|@>;
9914 store_new_token(cur_tok);
9915 }
9916 done1: store_new_token(end_match_token);
9917 if (cur_cmd==right_brace)
9918 @<Express shock at the missing left brace; |goto found|@>;
9919 done: ;}
9920
9921 @ @<Express shock...@>=
9922 {@+print_err("Missing { inserted");incr(align_state);
9923 @.Missing \{ inserted@>
9924 help2("Where was the left brace? You said something like `\\def\\a}',",@/
9925 "which I'm going to interpret as `\\def\\a{}'.");error();goto found;
9926 }
9927
9928 @ @<If the next character is a parameter number...@>=
9929 {@+s=match_token+cur_chr;get_token();
9930 if (cur_tok < left_brace_limit)
9931 {@+hash_brace=cur_tok;
9932 store_new_token(cur_tok);store_new_token(end_match_token);
9933 goto done;
9934 }
9935 if (t==zero_token+9)
9936 {@+print_err("You already have nine parameters");
9937 @.You already have nine...@>
9938 help2("I'm going to ignore the # sign you just used,",@/
9939 "as well as the token that followed it.");error();goto resume;
9940 }
9941 else{@+incr(t);
9942 if (cur_tok!=t)
9943 {@+print_err("Parameters must be numbered consecutively");
9944 @.Parameters...consecutively@>
9945 help2("I've inserted the digit you should have used after the #.",@/
9946 "Type `1' to delete what you did use.");back_error();
9947 }
9948 cur_tok=s;
9949 }
9950 }
9951
9952 @ @<Scan and build the body of the token list; |goto found| when finished@>=
9953 unbalance=1;
9954 loop@+{@+if (xpand) @<Expand the next part of the input@>@;
9955 else get_token();
9956 if (cur_tok < right_brace_limit)
9957 if (cur_cmd < right_brace) incr(unbalance);
9958 else{@+decr(unbalance);
9959 if (unbalance==0) goto found;
9960 }
9961 else if (cur_cmd==mac_param)
9962 if (macro_def) @<Look for parameter number or \.{\#\#}@>;
9963 store_new_token(cur_tok);
9964 }
9965
9966 @ Here we insert an entire token list created by |the_toks| without
9967 expanding it further.
9968
9969 @<Expand the next part of the input@>=
9970 {@+loop{@+get_next();
9971 if (cur_cmd >= call)
9972 if (info(link(cur_chr))==protected_token)
9973 {@+cur_cmd=relax;cur_chr=no_expand_flag;
9974 }
9975 if (cur_cmd <= max_command) goto done2;
9976 if (cur_cmd!=the) expand();
9977 else{@+q=the_toks();
9978 if (link(temp_head)!=null)
9979 {@+link(p)=link(temp_head);p=q;
9980 }
9981 }
9982 }
9983 done2: x_token();
9984 }
9985
9986 @ @<Look for parameter number...@>=
9987 {@+s=cur_tok;
9988 if (xpand) get_x_token();else get_token();
9989 if (cur_cmd!=mac_param)
9990 if ((cur_tok <= zero_token)||(cur_tok > t))
9991 {@+print_err("Illegal parameter number in definition of ");
9992 @.Illegal parameter number...@>
9993 sprint_cs(warning_index);
9994 help3("You meant to type ## instead of #, right?",@/
9995 "Or maybe a } was forgotten somewhere earlier, and things",@/
9996 "are all screwed up? I'm going to assume that you meant ##.");
9997 back_error();cur_tok=s;
9998 }
9999 else cur_tok=out_param_token-'0'+cur_chr;
10000 }
10001
10002 @ Another way to create a token list is via the \.{\\read} command. The
10003 sixteen files potentially usable for reading appear in the following
10004 global variables. The value of |read_open[n]| will be |closed| if
10005 stream number |n| has not been opened or if it has been fully read;
10006 |just_open| if an \.{\\openin} but not a \.{\\read} has been done;
10007 and |normal| if it is open and ready to read the next line.
10008
10009 @d closed 2 /*not open, or at end of file*/
10010 @d just_open 1 /*newly opened, first line not yet read*/
10011
10012 @<Glob...@>=
10013 static alpha_file @!read_file[16]; /*used for \.{\\read}*/
10014 static int8_t @!read_open[17]; /*state of |read_file[n]|*/
10015
10016 @ @<Set init...@>=
10017 for (k=0; k<=16; k++) read_open[k]=closed;
10018
10019 @ The |read_toks| procedure constructs a token list like that for any
10020 macro definition, and makes |cur_val| point to it. Parameter |r| points
10021 to the control sequence that will receive this token list.
10022
10023 @p static void read_toks(int @!n, pointer @!r, halfword @!j)
10024 {@+
10025 pointer p; /*tail of the token list*/
10026 pointer @!q; /*new node being added to the token list via |store_new_token|*/
10027 int @!s; /*saved value of |align_state|*/
10028 small_number @!m; /*stream number*/
10029 scanner_status=defining;warning_index=r;
10030 def_ref=get_avail();token_ref_count(def_ref)=null;
10031 p=def_ref; /*the reference count*/
10032 store_new_token(end_match_token);
10033 if ((n < 0)||(n > 15)) m=16;@+else m=n;
10034 s=align_state;align_state=1000000; /*disable tab marks, etc.*/
10035 @/do@+{@<Input and store tokens from the next line of the file@>;
10036 }@+ while (!(align_state==1000000));
10037 cur_val=def_ref;scanner_status=normal;align_state=s;
10038 }
10039
10040 @ @<Input and store tokens from the next line of the file@>=
10041 begin_file_reading();name=m+1;
10042 if (read_open[m]==closed) @<Input for \.{\\read} from the terminal@>;
10043 else if (read_open[m]==just_open) @<Input the first line of |read_file[m]|@>@;
10044 else@<Input the next line of |read_file[m]|@>;
10045 limit=last;
10046 if (end_line_char_inactive) decr(limit);
10047 else buffer[limit]=end_line_char;
10048 first=limit+1;loc=start;state=new_line;@/
10049 @<Handle \.{\\readline} and |goto done|@>;@/
10050 loop@+{@+get_token();
10051 if (cur_tok==0) goto done;
10052 /*|cur_cmd==cur_chr==0| will occur at the end of the line*/
10053 if (align_state < 1000000) /*unmatched `\.\}' aborts the line*/
10054 {@+@/do@+{get_token();}@+ while (!(cur_tok==0));
10055 align_state=1000000;goto done;
10056 }
10057 store_new_token(cur_tok);
10058 }
10059 done: end_file_reading()
10060
10061 @ Here we input on-line into the |buffer| array, prompting the user explicitly
10062 if |n >= 0|. The value of |n| is set negative so that additional prompts
10063 will not be given in the case of multi-line input.
10064
10065 @<Input for \.{\\read} from the terminal@>=
10066 if (interaction > nonstop_mode)
10067 if (n < 0) prompt_input("")@;
10068 else{@+wake_up_terminal;
10069 print_ln();sprint_cs(r);prompt_input("=");n=-1;
10070 }
10071 else fatal_error("*** (cannot \\read from terminal in nonstop modes)")
10072 @.cannot \\read@>
10073
10074 @ The first line of a file must be treated specially, since |input_ln|
10075 must be told not to start with |get|.
10076 @^system dependencies@>
10077
10078 @<Input the first line of |read_file[m]|@>=
10079 if (input_ln(&read_file[m], false)) read_open[m]=normal;
10080 else{@+a_close(&read_file[m]);read_open[m]=closed;
10081 }
10082
10083 @ An empty line is appended at the end of a |read_file|.
10084 @^empty line at end of file@>
10085
10086 @<Input the next line of |read_file[m]|@>=
10087 {@+if (!input_ln(&read_file[m], true))
10088 {@+a_close(&read_file[m]);read_open[m]=closed;
10089 if (align_state!=1000000)
10090 {@+runaway();
10091 print_err("File ended within ");print_esc("read");
10092 @.File ended within \\read@>
10093 help1("This \\read has unbalanced braces.");
10094 align_state=1000000;limit=0;error();
10095 }
10096 }
10097 }
10098
10099 @* Conditional processing.
10100 We consider now the way \TeX\ handles various kinds of \.{\\if} commands.
10101
10102 @d unless_code 32 /*amount added for `\.{\\unless}' prefix*/
10103 @#
10104 @d if_char_code 0 /* `\.{\\if}' */
10105 @d if_cat_code 1 /* `\.{\\ifcat}' */
10106 @d if_int_code 2 /* `\.{\\ifnum}' */
10107 @d if_dim_code 3 /* `\.{\\ifdim}' */
10108 @d if_odd_code 4 /* `\.{\\ifodd}' */
10109 @d if_vmode_code 5 /* `\.{\\ifvmode}' */
10110 @d if_hmode_code 6 /* `\.{\\ifhmode}' */
10111 @d if_mmode_code 7 /* `\.{\\ifmmode}' */
10112 @d if_inner_code 8 /* `\.{\\ifinner}' */
10113 @d if_void_code 9 /* `\.{\\ifvoid}' */
10114 @d if_hbox_code 10 /* `\.{\\ifhbox}' */
10115 @d if_vbox_code 11 /* `\.{\\ifvbox}' */
10116 @d ifx_code 12 /* `\.{\\ifx}' */
10117 @d if_eof_code 13 /* `\.{\\ifeof}' */
10118 @d if_true_code 14 /* `\.{\\iftrue}' */
10119 @d if_false_code 15 /* `\.{\\iffalse}' */
10120 @d if_case_code 16 /* `\.{\\ifcase}' */
10121
10122 @<Put each...@>=
10123 primitive("if", if_test, if_char_code);
10124 @!@:if\_char\_}{\.{\\if} primitive@>
10125 primitive("ifcat", if_test, if_cat_code);
10126 @!@:if\_cat\_code\_}{\.{\\ifcat} primitive@>
10127 primitive("ifnum", if_test, if_int_code);
10128 @!@:if\_int\_}{\.{\\ifnum} primitive@>
10129 primitive("ifdim", if_test, if_dim_code);
10130 @!@:if\_dim\_}{\.{\\ifdim} primitive@>
10131 primitive("ifodd", if_test, if_odd_code);
10132 @!@:if\_odd\_}{\.{\\ifodd} primitive@>
10133 primitive("ifvmode", if_test, if_vmode_code);
10134 @!@:if\_vmode\_}{\.{\\ifvmode} primitive@>
10135 primitive("ifhmode", if_test, if_hmode_code);
10136 @!@:if\_hmode\_}{\.{\\ifhmode} primitive@>
10137 primitive("ifmmode", if_test, if_mmode_code);
10138 @!@:if\_mmode\_}{\.{\\ifmmode} primitive@>
10139 primitive("ifinner", if_test, if_inner_code);
10140 @!@:if\_inner\_}{\.{\\ifinner} primitive@>
10141 primitive("ifvoid", if_test, if_void_code);
10142 @!@:if\_void\_}{\.{\\ifvoid} primitive@>
10143 primitive("ifhbox", if_test, if_hbox_code);
10144 @!@:if\_hbox\_}{\.{\\ifhbox} primitive@>
10145 primitive("ifvbox", if_test, if_vbox_code);
10146 @!@:if\_vbox\_}{\.{\\ifvbox} primitive@>
10147 primitive("ifx", if_test, ifx_code);
10148 @!@:ifx\_}{\.{\\ifx} primitive@>
10149 primitive("ifeof", if_test, if_eof_code);
10150 @!@:if\_eof\_}{\.{\\ifeof} primitive@>
10151 primitive("iftrue", if_test, if_true_code);
10152 @!@:if\_true\_}{\.{\\iftrue} primitive@>
10153 primitive("iffalse", if_test, if_false_code);
10154 @!@:if\_false\_}{\.{\\iffalse} primitive@>
10155 primitive("ifcase", if_test, if_case_code);
10156 @!@:if\_case\_}{\.{\\ifcase} primitive@>
10157
10158 @ @<Cases of |print_cmd_chr|...@>=
10159 case if_test: {@+if (chr_code >= unless_code) print_esc("unless");
10160 switch (chr_code%unless_code) {
10161 case if_cat_code: print_esc("ifcat");@+break;
10162 case if_int_code: print_esc("ifnum");@+break;
10163 case if_dim_code: print_esc("ifdim");@+break;
10164 case if_odd_code: print_esc("ifodd");@+break;
10165 case if_vmode_code: print_esc("ifvmode");@+break;
10166 case if_hmode_code: print_esc("ifhmode");@+break;
10167 case if_mmode_code: print_esc("ifmmode");@+break;
10168 case if_inner_code: print_esc("ifinner");@+break;
10169 case if_void_code: print_esc("ifvoid");@+break;
10170 case if_hbox_code: print_esc("ifhbox");@+break;
10171 case if_vbox_code: print_esc("ifvbox");@+break;
10172 case ifx_code: print_esc("ifx");@+break;
10173 case if_eof_code: print_esc("ifeof");@+break;
10174 case if_true_code: print_esc("iftrue");@+break;
10175 case if_false_code: print_esc("iffalse");@+break;
10176 case if_case_code: print_esc("ifcase");@+break;
10177 @/@<Cases of |if_test| for |print_cmd_chr|@>@/
10178 default:print_esc("if");
10179 }
10180 } @+break;
10181
10182 @ Conditions can be inside conditions, and this nesting has a stack
10183 that is independent of the |save_stack|.
10184
10185 Four global variables represent the top of the condition stack:
10186 |cond_ptr| points to pushed-down entries, if any; |if_limit| specifies
10187 the largest code of a |fi_or_else| command that is syntactically legal;
10188 |cur_if| is the name of the current type of conditional; and |if_line|
10189 is the line number at which it began.
10190
10191 If no conditions are currently in progress, the condition stack has the
10192 special state |cond_ptr==null|, |if_limit==normal|, |cur_if==0|, |if_line==0|.
10193 Otherwise |cond_ptr| points to a two-word node; the |type|, |subtype|, and
10194 |link| fields of the first word contain |if_limit|, |cur_if|, and
10195 |cond_ptr| at the next level, and the second word contains the
10196 corresponding |if_line|.
10197
10198 @d if_node_size 2 /*number of words in stack entry for conditionals*/
10199 @d if_line_field(A) mem[A+1].i
10200 @d if_code 1 /*code for \.{\\if...} being evaluated*/
10201 @d fi_code 2 /*code for \.{\\fi}*/
10202 @d else_code 3 /*code for \.{\\else}*/
10203 @d or_code 4 /*code for \.{\\or}*/
10204
10205 @<Glob...@>=
10206 static pointer @!cond_ptr; /*top of the condition stack*/
10207 static int @!if_limit; /*upper bound on |fi_or_else| codes*/
10208 static small_number @!cur_if; /*type of conditional being worked on*/
10209 static int @!if_line; /*line where that conditional began*/
10210
10211 @ @<Set init...@>=
10212 cond_ptr=null;if_limit=normal;cur_if=0;if_line=0;
10213
10214 @ @<Put each...@>=
10215 primitive("fi", fi_or_else, fi_code);
10216 @!@:fi\_}{\.{\\fi} primitive@>
10217 text(frozen_fi)=text(cur_val);eqtb[frozen_fi]=eqtb[cur_val];
10218 primitive("or", fi_or_else, or_code);
10219 @!@:or\_}{\.{\\or} primitive@>
10220 primitive("else", fi_or_else, else_code);
10221 @!@:else\_}{\.{\\else} primitive@>
10222
10223 @ @<Cases of |print_cmd_chr|...@>=
10224 case fi_or_else: if (chr_code==fi_code) print_esc("fi");
10225 else if (chr_code==or_code) print_esc("or");
10226 else print_esc("else");@+break;
10227
10228 @ When we skip conditional text, we keep track of the line number
10229 where skipping began, for use in error messages.
10230
10231 @<Glob...@>=
10232 static int @!skip_line; /*skipping began here*/
10233
10234 @ Here is a procedure that ignores text until coming to an \.{\\or},
10235 \.{\\else}, or \.{\\fi} at the current level of $\.{\\if}\ldots\.{\\fi}$
10236 nesting. After it has acted, |cur_chr| will indicate the token that
10237 was found, but |cur_tok| will not be set (because this makes the
10238 procedure run faster).
10239
10240 @p static void pass_text(void)
10241 {@+
10242 int l; /*level of $\.{\\if}\ldots\.{\\fi}$ nesting*/
10243 small_number @!save_scanner_status; /*|scanner_status| upon entry*/
10244 save_scanner_status=scanner_status;scanner_status=skipping;l=0;
10245 skip_line=line;
10246 loop@+{@+get_next();
10247 if (cur_cmd==fi_or_else)
10248 {@+if (l==0) goto done;
10249 if (cur_chr==fi_code) decr(l);
10250 }
10251 else if (cur_cmd==if_test) incr(l);
10252 }
10253 done: scanner_status=save_scanner_status;
10254 if (tracing_ifs > 0) show_cur_cmd_chr();
10255 }
10256
10257 @ When we begin to process a new \.{\\if}, we set |if_limit=if_code|; then
10258 if\/ \.{\\or} or \.{\\else} or \.{\\fi} occurs before the current \.{\\if}
10259 condition has been evaluated, \.{\\relax} will be inserted.
10260 For example, a sequence of commands like `\.{\\ifvoid1\\else...\\fi}'
10261 would otherwise require something after the `\.1'.
10262
10263 @<Push the condition stack@>=
10264 {@+p=get_node(if_node_size);link(p)=cond_ptr;type(p)=if_limit;
10265 subtype(p)=cur_if;if_line_field(p)=if_line;
10266 cond_ptr=p;cur_if=cur_chr;if_limit=if_code;if_line=line;
10267 }
10268
10269 @ @<Pop the condition stack@>=
10270 {@+if (if_stack[in_open]==cond_ptr) if_warning();
10271 /*conditionals possibly not properly nested with files*/
10272 p=cond_ptr;if_line=if_line_field(p);
10273 cur_if=subtype(p);if_limit=type(p);cond_ptr=link(p);
10274 free_node(p, if_node_size);
10275 }
10276
10277 @ Here's a procedure that changes the |if_limit| code corresponding to
10278 a given value of |cond_ptr|.
10279
10280 @p static void change_if_limit(small_number @!l, pointer @!p)
10281 {@+
10282 pointer q;
10283 if (p==cond_ptr) if_limit=l; /*that's the easy case*/
10284 else{@+q=cond_ptr;
10285 loop@+{@+if (q==null) confusion("if");
10286 @:this can't happen if}{\quad if@>
10287 if (link(q)==p)
10288 {@+type(q)=l;return;
10289 }
10290 q=link(q);
10291 }
10292 }
10293 }
10294
10295 @ A condition is started when the |expand| procedure encounters
10296 an |if_test| command; in that case |expand| reduces to |conditional|,
10297 which is a recursive procedure.
10298 @^recursion@>
10299
10300 @p static void conditional(void)
10301 {@+
10302 bool b; /*is the condition true?*/
10303 int @!r; /*relation to be evaluated*/
10304 int @!m, @!n; /*to be tested against the second operand*/
10305 pointer @!p, @!q; /*for traversing token lists in \.{\\ifx} tests*/
10306 small_number @!save_scanner_status; /*|scanner_status| upon entry*/
10307 pointer @!save_cond_ptr; /*|cond_ptr| corresponding to this conditional*/
10308 small_number @!this_if; /*type of this conditional*/
10309 bool @!is_unless; /*was this if preceded by `\.{\\unless}' ?*/
10310 if (tracing_ifs > 0) if (tracing_commands <= 1) show_cur_cmd_chr();
10311 @<Push the condition stack@>;@+save_cond_ptr=cond_ptr;
10312 is_unless=(cur_chr >= unless_code);this_if=cur_chr%unless_code;@/
10313 @<Either process \.{\\ifcase} or set |b| to the value of a boolean condition@>;
10314 if (is_unless) b=!b;
10315 if (tracing_commands > 1) @<Display the value of |b|@>;
10316 if (b)
10317 {@+change_if_limit(else_code, save_cond_ptr);
10318 return; /*wait for \.{\\else} or \.{\\fi}*/
10319 }
10320 @<Skip to \.{\\else} or \.{\\fi}, then |goto common_ending|@>;
10321 common_ending: if (cur_chr==fi_code) @<Pop the condition stack@>@;
10322 else if_limit=fi_code; /*wait for \.{\\fi}*/
10323 }
10324
10325 @ In a construction like `\.{\\if\\iftrue abc\\else d\\fi}', the first
10326 \.{\\else} that we come to after learning that the \.{\\if} is false is
10327 not the \.{\\else} we're looking for. Hence the following curious
10328 logic is needed.
10329
10330 @ @<Skip to \.{\\else} or \.{\\fi}...@>=
10331 loop@+{@+pass_text();
10332 if (cond_ptr==save_cond_ptr)
10333 {@+if (cur_chr!=or_code) goto common_ending;
10334 print_err("Extra ");print_esc("or");
10335 @.Extra \\or@>
10336 help1("I'm ignoring this; it doesn't match any \\if.");
10337 error();
10338 }
10339 else if (cur_chr==fi_code) @<Pop the condition stack@>;
10340 }
10341
10342 @ @<Either process \.{\\ifcase} or set |b|...@>=
10343 switch (this_if) {
10344 case if_char_code: case if_cat_code: @<Test if two characters match@>@;@+break;
10345 case if_int_code: case if_dim_code: @<Test relation between integers or dimensions@>@;@+break;
10346 case if_odd_code: @<Test if an integer is odd@>@;@+break;
10347 case if_vmode_code: b=(abs(mode)==vmode);@+break;
10348 case if_hmode_code: b=(abs(mode)==hmode);@+break;
10349 case if_mmode_code: b=(abs(mode)==mmode);@+break;
10350 case if_inner_code: b=(mode < 0);@+break;
10351 case if_void_code: case if_hbox_code:
10352 case if_vbox_code: @<Test box register status@>@;@+break;
10353 case ifx_code: @<Test if two tokens match@>@;@+break;
10354 case if_eof_code: {@+scan_four_bit_int();b=(read_open[cur_val]==closed);
10355 } @+break;
10356 case if_true_code: b=true;@+break;
10357 case if_false_code: b=false;@+break;
10358 @/@<Cases for |conditional|@>@/
10359 case if_case_code: @<Select the appropriate case and |return| or |goto common_ending|@>;
10360 } /*there are no other cases*/
10361
10362 @ @<Display the value of |b|@>=
10363 {@+begin_diagnostic();
10364 if (b) print("{true}");@+else print("{false}");
10365 end_diagnostic(false);
10366 }
10367
10368 @ Here we use the fact that |'<'|, |'='|, and |'>'| are consecutive ASCII
10369 codes.
10370 @^ASCII code@>
10371
10372 @<Test relation between integers or dimensions@>=
10373 {@+if (this_if==if_int_code) scan_int();@+else scan_normal_dimen;
10374 n=cur_val;@<Get the next non-blank non-call...@>;
10375 if ((cur_tok >= other_token+'<')&&(cur_tok <= other_token+'>'))
10376 r=cur_tok-other_token;
10377 else{@+print_err("Missing = inserted for ");
10378 @.Missing = inserted@>
10379 print_cmd_chr(if_test, this_if);
10380 help1("I was expecting to see `<', `=', or `>'. Didn't.");
10381 back_error();r='=';
10382 }
10383 if (this_if==if_int_code) scan_int();@+else scan_normal_dimen;
10384 switch (r) {
10385 case '<': b=(n < cur_val);@+break;
10386 case '=': b=(n==cur_val);@+break;
10387 case '>': b=(n > cur_val);
10388 }
10389 }
10390
10391 @ @<Test if an integer is odd@>=
10392 {@+scan_int();b=odd(cur_val);
10393 }
10394
10395 @ @<Test box register status@>=
10396 {@+scan_register_num();fetch_box(p);
10397 if (this_if==if_void_code) b=(p==null);
10398 else if (p==null) b=false;
10399 else if (this_if==if_hbox_code) b=(type(p)==hlist_node);
10400 else b=(type(p)==vlist_node);
10401 }
10402
10403 @ An active character will be treated as category 13 following
10404 \.{\\if\\noexpand} or following \.{\\ifcat\\noexpand}. We use the fact that
10405 active characters have the smallest tokens, among all control sequences.
10406
10407 @d get_x_token_or_active_char @t@>@;
10408 {@+get_x_token();
10409 if (cur_cmd==relax) if (cur_chr==no_expand_flag)
10410 {@+cur_cmd=active_char;
10411 cur_chr=cur_tok-cs_token_flag-active_base;
10412 if (cur_chr>=utf8_single_size)
10413 cur_chr=active_hash[cur_tok-cs_token_flag];
10414 }
10415 }
10416
10417 @<Test if two characters match@>=
10418 {@+get_x_token_or_active_char;
10419 if ((cur_cmd > active_char)||(cur_chr > biggest_char)) /*not a character*/
10420 {@+m=relax;n=biggest_char+1;
10421 }
10422 else{@+m=cur_cmd;n=cur_chr;
10423 }
10424 get_x_token_or_active_char;
10425 if ((cur_cmd > active_char)||(cur_chr > biggest_char))
10426 {@+cur_cmd=relax;cur_chr=biggest_char+1;
10427 }
10428 if (this_if==if_char_code) b=(n==cur_chr);@+else b=(m==cur_cmd);
10429 }
10430
10431 @ Note that `\.{\\ifx}' will declare two macros different if one is \\{long}
10432 or \\{outer} and the other isn't, even though the texts of the macros are
10433 the same.
10434
10435 We need to reset |scanner_status|, since \.{\\outer} control sequences
10436 are allowed, but we might be scanning a macro definition or preamble.
10437
10438 @<Test if two tokens match@>=
10439 {@+save_scanner_status=scanner_status;scanner_status=normal;
10440 get_next();n=cur_cs;p=cur_cmd;q=cur_chr;
10441 get_next();if (cur_cmd!=p) b=false;
10442 else if (cur_cmd < call) b=(cur_chr==q);
10443 else@<Test if two macro texts match@>;
10444 scanner_status=save_scanner_status;
10445 }
10446
10447 @ Note also that `\.{\\ifx}' decides that macros \.{\\a} and \.{\\b} are
10448 different in examples like this:
10449 $$\vbox{\halign{\.{#}\hfil&\qquad\.{#}\hfil\cr
10450 {}\\def\\a\{\\c\}&
10451 {}\\def\\c\{\}\cr
10452 {}\\def\\b\{\\d\}&
10453 {}\\def\\d\{\}\cr}}$$
10454
10455 @<Test if two macro texts match@>=
10456 {@+p=link(cur_chr);q=link(equiv(n)); /*omit reference counts*/
10457 if (p==q) b=true;
10458 else{@+while ((p!=null)&&(q!=null))
10459 if (info(p)!=info(q)) p=null;
10460 else{@+p=link(p);q=link(q);
10461 }
10462 b=((p==null)&&(q==null));
10463 }
10464 }
10465
10466 @ @<Select the appropriate case and |return| or |goto common_ending|@>=
10467 {@+scan_int();n=cur_val; /*|n| is the number of cases to pass*/
10468 if (tracing_commands > 1)
10469 {@+begin_diagnostic();print("{case ");print_int(n);print_char('}');
10470 end_diagnostic(false);
10471 }
10472 while (n!=0)
10473 {@+pass_text();
10474 if (cond_ptr==save_cond_ptr)
10475 if (cur_chr==or_code) decr(n);
10476 else goto common_ending;
10477 else if (cur_chr==fi_code) @<Pop the condition stack@>;
10478 }
10479 change_if_limit(or_code, save_cond_ptr);
10480 return; /*wait for \.{\\or}, \.{\\else}, or \.{\\fi}*/
10481 }
10482
10483 @ The processing of conditionals is complete except for the following
10484 code, which is actually part of |expand|. It comes into play when
10485 \.{\\or}, \.{\\else}, or \.{\\fi} is scanned.
10486
10487 @<Terminate the current conditional and skip to \.{\\fi}@>=
10488 {@+if (tracing_ifs > 0) if (tracing_commands <= 1) show_cur_cmd_chr();
10489 if (cur_chr > if_limit)
10490 if (if_limit==if_code) insert_relax(); /*condition not yet evaluated*/
10491 else{@+print_err("Extra ");print_cmd_chr(fi_or_else, cur_chr);
10492 @.Extra \\or@>
10493 @.Extra \\else@>
10494 @.Extra \\fi@>
10495 help1("I'm ignoring this; it doesn't match any \\if.");
10496 error();
10497 }
10498 else{@+while (cur_chr!=fi_code) pass_text(); /*skip to \.{\\fi}*/
10499 @<Pop the condition stack@>;
10500 }
10501 }
10502
10503 @* File names.
10504 It's time now to fret about file names. Besides the fact that different
10505 operating systems treat files in different ways, we must cope with the
10506 fact that completely different naming conventions are used by different
10507 groups of people. The following programs show what is required for one
10508 particular operating system; similar routines for other systems are not
10509 difficult to devise.
10510 @^fingers@>
10511 @^system dependencies@>
10512
10513 \TeX\ assumes that a file name has three parts: the name proper; its
10514 ``extension''; and a ``file area'' where it is found in an external file
10515 system. The extension of an input file or a write file is assumed to be
10516 `\.{.tex}' unless otherwise specified; it is `\.{.log}' on the
10517 transcript file that records each run of \TeX; it is `\.{.tfm}' on the font
10518 metric files that describe characters in the fonts \TeX\ uses; it is
10519 `\.{.dvi}' on the output files that specify typesetting information; and it
10520 is `\.{.fmt}' on the format files written by \.{INITEX} to initialize \TeX.
10521 The file area can be arbitrary on input files, but files are usually
10522 output to the user's current area. If an input file cannot be
10523 found on the specified area, \TeX\ will look for it on a special system
10524 area; this special area is intended for commonly used input files like
10525 \.{webmac.tex}.
10526
10527 Simple uses of \TeX\ refer only to file names that have no explicit
10528 extension or area. For example, a person usually says `\.{\\input} \.{paper}'
10529 or `\.{\\font\\tenrm} \.= \.{helvetica}' instead of `\.{\\input}
10530 \.{paper.new}' or `\.{\\font\\tenrm} \.= \.{<csd.knuth>test}'. Simple file
10531 names are best, because they make the \TeX\ source files portable;
10532 whenever a file name consists entirely of letters and digits, it should be
10533 treated in the same way by all implementations of \TeX. However, users
10534 need the ability to refer to other files in their environment, especially
10535 when responding to error messages concerning unopenable files; therefore
10536 we want to let them use the syntax that appears in their favorite
10537 operating system.
10538
10539 The following procedures don't allow spaces to be part of
10540 file names; but some users seem to like names that are spaced-out.
10541 System-dependent changes to allow such things should probably
10542 be made with reluctance, and only when an entire file name that
10543 includes spaces is ``quoted'' somehow.
10544
10545 @ In order to isolate the system-dependent aspects of file names, the
10546 @^system dependencies@>
10547 system-independent parts of \TeX\ are expressed in terms
10548 of three system-dependent
10549 procedures called |begin_name|, |more_name|, and |end_name|. In
10550 essence, if the user-specified characters of the file name are $c_1\ldots c_n$,
10551 the system-independent driver program does the operations
10552 $$|begin_name|;\,|more_name|(c_1);\,\ldots\,;\,|more_name|(c_n);
10553 \,|end_name|.$$
10554 These three procedures communicate with each other via global variables.
10555 Afterwards the file name will appear in the string pool as three strings
10556 called |cur_name|\penalty10000\hskip-.05em,
10557 |cur_area|, and |cur_ext|; the latter two are null (i.e.,
10558 |""|), unless they were explicitly specified by the user.
10559
10560 Actually the situation is slightly more complicated, because \TeX\ needs
10561 to know when the file name ends. The |more_name| routine is a function
10562 (with side effects) that returns |true| on the calls |more_name|$(c_1)$,
10563 \dots, |more_name|$(c_{n-1})$. The final call |more_name|$(c_n)$
10564 returns |false|; or, it returns |true| and the token following $c_n$ is
10565 something like `\.{\\hbox}' (i.e., not a character). In other words,
10566 |more_name| is supposed to return |true| unless it is sure that the
10567 file name has been completely scanned; and |end_name| is supposed to be able
10568 to finish the assembly of |cur_name|, |cur_area|, and |cur_ext| regardless of
10569 whether $|more_name|(c_n)$ returned |true| or |false|.
10570
10571 @<Glob...@>=
10572 static str_number @!cur_name; /*name of file just scanned*/
10573 static str_number @!cur_area; /*file area just scanned, or \.{""}*/
10574 static str_number @!cur_ext; /*file extension just scanned, or \.{""}*/
10575
10576 @ The file names we shall deal with for illustrative purposes have the
10577 following structure: If the name contains `\.>' or `\.:', the file area
10578 consists of all characters up to and including the final such character;
10579 otherwise the file area is null. If the remaining file name contains
10580 `\..', the file extension consists of all such characters from the first
10581 remaining `\..' to the end, otherwise the file extension is null.
10582 @^system dependencies@>
10583
10584 We can scan such file names easily by using two global variables that keep track
10585 of the occurrences of area and extension delimiters:
10586
10587 @<Glob...@>=
10588 static pool_pointer @!area_delimiter; /*the most recent `\.>' or `\.:', if any*/
10589 static pool_pointer @!ext_delimiter; /*the relevant `\..', if any*/
10590
10591 @ Here now is the first of the system-dependent routines for file name scanning.
10592 @^system dependencies@>
10593
10594 @p static bool quoted_filename,inside_quote;
10595 static void begin_name(void)
10596 {@+area_delimiter=0;ext_delimiter=0; quoted_filename=inside_quote=false;
10597 }
10598
10599 @ And here's the second. The string pool might change as the file name is
10600 being scanned, since a new \.{\\csname} might be entered; therefore we keep
10601 |area_delimiter| and |ext_delimiter| relative to the beginning of the current
10602 string, instead of assigning an absolute address like |pool_ptr| to them.
10603 @^system dependencies@>
10604
10605 @p static bool more_name(uint32_t @!c)
10606 {@+if (c==' ' && !inside_quote) return false;
10607 else if (c=='"') {@+ if (cur_length==0) quoted_filename=true;
10608 inside_quote=!inside_quote; return true; }
10609 else {@+str_room(1);append_char(c); /*contribute |c| to the current string*/
10610 if (IS_DIR_SEP(c)) {@+area_delimiter=cur_length;ext_delimiter=0; }
10611 else if (c=='.') ext_delimiter=cur_length;
10612 return true;
10613 }
10614 }
10615
10616 @ The third.
10617 @^system dependencies@>
10618
10619 @p static void end_name(void)
10620 {@+if (str_ptr+3 > max_strings)
10621 overflow("number of strings", max_strings-init_str_ptr);
10622 @:TeX capacity exceeded number of strings}{\quad number of strings@>
10623 if (area_delimiter==0) cur_area=empty_string;
10624 else{@+cur_area=str_ptr;
10625 str_start[str_ptr+1]=str_start[str_ptr]+area_delimiter;incr(str_ptr);
10626 }
10627 if (ext_delimiter==0)
10628 {@+cur_ext=empty_string;cur_name=make_string();
10629 }
10630 else{@+cur_name=str_ptr;
10631 str_start[str_ptr+1]=str_start[str_ptr]+ext_delimiter-area_delimiter-1;
10632 incr(str_ptr);cur_ext=make_string();
10633 }
10634 }
10635
10636 @ Conversely, here is a routine that takes three strings and prints a file
10637 name that might have produced them. (The routine is system dependent, because
10638 some operating systems put the file area last instead of first.)
10639 @^system dependencies@>
10640
10641 @<Basic printing...@>=
10642 static void print_file_name(int @!n, int @!a, int @!e)
10643 {@+slow_print(a);slow_print(n);slow_print(e);
10644 }
10645
10646 @ Another system-dependent routine is needed to convert three internal
10647 \TeX\ strings
10648 into the |name_of_file| value that is used to open files. The present code
10649 allows both lowercase and uppercase letters in the file name.
10650 @^system dependencies@>
10651
10652 @d append_to_name(A) {@+c=A;incr(k);
10653 if (k <= file_name_size) name_of_file[k]=c;
10654 }
10655
10656 @p static void pack_file_name(str_number @!n, str_number @!a, str_number @!e, char *@!f)
10657 {@+int k; /*number of positions filled in |name_of_file|*/
10658 UTF8_code @!c; /*character being packed*/
10659 int @!j; /*index into |str_pool|*/
10660 k=0;
10661 for (j=str_start[a]; j<=str_start[a+1]-1; j++) append_to_name(str_pool[j])@;
10662 for (j=str_start[n]; j<=str_start[n+1]-1; j++) append_to_name(str_pool[j])@;
10663 if (f==NULL)
10664 for (j=str_start[e]; j<=str_start[e+1]-1; j++) append_to_name(str_pool[j])@;
10665 else
10666 while(*f!=0) append_to_name(*f++)@;
10667 if (k <= file_name_size) name_length=k;@+else name_length=file_name_size;
10668 name_of_file[name_length+1]=0;
10669 }
10670
10671
10672
10673 @ \TeX\ Live does not use the global variable |TEX_format_default|. It is no longer needed
10674 to supply the text for default system areas
10675 and extensions related to format files.
10676
10677 @ Consequently \TeX\ Live does not need the initialization of |TEX_format_default| either.
10678
10679 @ And \TeX\ Live does not check the length of |TEX_format_default|.
10680
10681 @ The |format_extension|, however, is needed by \TeX\ Live
10682 to create the format name from the job name.
10683
10684 @d format_extension ".fmt"
10685
10686 @ This part of the program
10687 becomes active when a ``virgin'' \TeX\ is trying to get going, just after
10688 the preliminary initialization, or when the user is substituting another
10689 format file by typing `\.\&' after the initial `\.{**}' prompt. The buffer
10690 contains the first line of input in |buffer[loc dotdot(last-1)]|, where
10691 |loc < last| and |buffer[loc]!=' '|.
10692
10693 \TeX\ Live uses the {\tt kpathsearch} library to implement access to files.
10694 |open_fmt_file| is declared here and the
10695 actual implementation is in the section on \TeX\ Live Integration.
10696
10697 @<Declare the function called |open_fmt_file|@>=
10698 static bool open_fmt_file(void);
10699
10700 @ Operating systems often make it possible to determine the exact name (and
10701 possible version number) of a file that has been opened. The following routine,
10702 which simply makes a \TeX\ string from the value of |name_of_file|, should
10703 ideally be changed to deduce the full name of file~|f|, which is the file
10704 most recently opened, if it is possible to do this in a \PASCAL\ program.
10705 @^system dependencies@>
10706
10707 This routine might be called after string memory has overflowed, hence
10708 we dare not use `|str_room|'.
10709
10710 @p static str_number make_name_string(void)
10711 {@+int k; /*index into |name_of_file|*/
10712 if ((pool_ptr+name_length > pool_size)||(str_ptr==max_strings)||
10713 (cur_length > 0))
10714 return'?';
10715 else{@+for (k=1; k<=name_length; k++) append_char(name_of_file[k]);
10716 return make_string();
10717 }
10718 }
10719 static str_number a_make_name_string(alpha_file *f)
10720 {@+return make_name_string();
10721 }
10722
10723 #ifdef @!INIT
10724 static str_number w_make_name_string(word_file *f)
10725 {@+return make_name_string();
10726 }
10727 #endif
10728
10729 @ Now let's consider the ``driver''
10730 routines by which \TeX\ deals with file names
10731 in a system-independent manner. First comes a procedure that looks for a
10732 file name.
10733 There are two ways to specify the file name: as a general text argument
10734 or as a token (after expansion).
10735 The traditional token delimiter is the space. For a file name, however,
10736 a double quote is used as the token delimiter if the token starts
10737 with a double quote.
10738
10739 Once the |area_delimiter| and the |ext_delimiter| are defined,
10740 the final processing is shared for all variants.
10741
10742 When starting, \.{\\relax} is skipped as well as blanks and non-calls.
10743 Then a test for the |left_brace| will branch to the code for scanning
10744 a general text.
10745 % consider the case where a double quote is made an active character
10746 % equivalent to a left brace!
10747
10748 @p static void scan_file_name(void)
10749 {@+
10750 pool_pointer @!j, k; /*index into |str_pool|*/
10751 int @!old_setting; /*holds |selector| setting*/
10752 name_in_progress=true;begin_name();
10753 @<Get the next non-blank non-relax...@>;
10754 if (cur_cmd==left_brace)
10755 @<Define a general text file name and |goto done|@>@;
10756 loop@+{@+if ((cur_cmd==relax) || (cur_cmd > other_char) || (cur_chr > biggest_char)) /*not a character*/
10757 {@+back_input();goto done;
10758 }
10759 #if 0
10760 /* This is from pdftex-final.ch. I don't know these `some cases',
10761 and I am not sure whether the name should end even if quoting is on.*/
10762 /*If |cur_chr| is a space and we're not scanning a token list, check
10763 whether we're at the end of the buffer. Otherwise we end up adding
10764 spurious spaces to file names in some cases.*/
10765 if (cur_chr==' ' && state!=token_list && loc>limit) goto done;
10766 #endif
10767 if (!more_name(cur_chr)) goto done;
10768 get_x_token();
10769 }
10770 done: end_name();name_in_progress=false;
10771 }
10772
10773 @ The global variable |name_in_progress| is used to prevent recursive
10774 use of |scan_file_name|, since the |begin_name| and other procedures
10775 communicate via global variables. Recursion would arise only by
10776 devious tricks like `\.{\\input\\input f}'; such attempts at sabotage
10777 must be thwarted. Furthermore, |name_in_progress| prevents \.{\\input}
10778 @^recursion@>
10779 from being initiated when a font size specification is being scanned.
10780
10781 Another global variable, |job_name|, contains the file name that was first
10782 \.{\\input} by the user. This name is extended by `\.{.log}' and `\.{.dvi}'
10783 and `\.{.fmt}' in the names of \TeX's output files.
10784
10785 @<Glob...@>=
10786 static bool @!name_in_progress; /*is a file name being scanned?*/
10787 static str_number @!job_name; /*principal file name*/
10788 static bool @!log_opened; /*has the transcript file been opened?*/
10789
10790 @ Initially |job_name==0|; it becomes nonzero as soon as the true name is known.
10791 We have |job_name==0| if and only if the `\.{log}' file has not been opened,
10792 except of course for a short time just after |job_name| has become nonzero.
10793
10794 @<Initialize the output...@>=
10795 job_name=0;name_in_progress=false;log_opened=false;
10796
10797 @ Here is a routine that manufactures the output file names, assuming that
10798 |job_name!=0|. It ignores and changes the current settings of |cur_area|
10799 and |cur_ext|.
10800
10801 @d pack_cur_name(A) if (cur_ext==empty_string) pack_file_name(cur_name, cur_area, cur_ext,A);
10802 else pack_file_name(cur_name, cur_area, cur_ext,NULL)
10803
10804 @p static void pack_job_name(char *@!s) /*|s==".log"|, |".dvi"|, or
10805 |format_extension|*/
10806 {@+cur_area=empty_string;cur_ext=empty_string;
10807 cur_name=job_name;pack_cur_name(s);
10808 }
10809
10810 @ If some trouble arises when \TeX\ tries to open a file, the following
10811 routine calls upon the user to supply another file name. Parameter~|s|
10812 is used in the error message to identify the type of file; parameter~|e|
10813 is the default extension if none is given.
10814 We handle the specification of a file name with possibly spaces in
10815 double quotes (the last one is optional if this is the end of line
10816 i.e. the end of the buffer).
10817 Upon exit from the routine,
10818 variables |cur_name|, |cur_area|, |cur_ext|, and |name_of_file| are
10819 ready for another attempt at file opening.
10820
10821 @p static void prompt_file_name(char *@!s, char *@!e)
10822 {@+
10823 int k; /*index into |buffer|*/
10824 if (interaction==scroll_mode) wake_up_terminal;
10825 if (strcmp(s,"input file name")==0) print_err("I can't find file `");
10826 @.I can't find file x@>
10827 else print_err("I can't write on file `");
10828 @.I can't write on file x@>
10829 print_file_name(cur_name, cur_area, cur_ext);print("'.");
10830 if (strcmp(e,".tex")==0) show_context();
10831 print_nl("Please type another ");print(s);
10832 @.Please type...@>
10833 if (interaction < scroll_mode)
10834 fatal_error("*** (job aborted, file error in nonstop mode)");
10835 @.job aborted, file error...@>
10836 clear_terminal;prompt_input(": ");@<Scan file name in the buffer@>;
10837 pack_cur_name(e);
10838 }
10839
10840 @ @<Scan file name in the buffer@>=
10841 {@+
10842 begin_name();k=first;
10843 while ((buffer[k]==' ')&&(k < last)) incr(k);
10844 loop@+{@+if (k==last) goto done;
10845 if (!more_name(buffer[k])) goto done;
10846 incr(k);
10847 }
10848 done: end_name();
10849 }
10850
10851 @ @<Glob...@>=
10852 static str_number @!output_file_name; /*full name of the output file*/
10853 static str_number @!log_name; /*full name of the log file*/
10854
10855 @ @<Initialize the output...@>=output_file_name=0;
10856
10857 @ The |open_log_file| routine is used to open the transcript file and to help
10858 it catch up to what has previously been printed on the terminal.
10859
10860 @p static void open_log_file(void)
10861 {@+int old_setting; /*previous |selector| setting*/
10862 int @!k; /*index into |months| and |buffer|*/
10863 int @!l; /*end of first input line*/
10864 char @!months[]=" JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"; /*abbreviations of month names*/
10865 old_setting=selector;
10866 if (job_name==0) job_name=s_no(c_job_name?c_job_name:"texput"); /* \TeX\ Live */
10867 pack_job_name(".fls");
10868 recorder_change_filename((char *)name_of_file+1);
10869 @.texput@>
10870 pack_job_name(".log");
10871 while (!a_open_out(&log_file)) @<Try to get a different log file name@>;
10872 log_name=a_make_name_string(&log_file);
10873 selector=log_only;log_opened=true;
10874 @<Print the banner line, including the date and time@>;
10875 input_stack[input_ptr]=cur_input; /*make sure bottom level is in memory*/
10876 print_nl("**");
10877 @.**@>
10878 l=input_stack[0].limit_field; /*last position of first line*/
10879 if (buffer[l]==end_line_char) decr(l);
10880 for (k=1; k<=l; k++) printn(buffer[k]);
10881 print_ln(); /*now the transcript file contains the first line of input*/
10882 selector=old_setting+2; /*|log_only| or |term_and_log|*/
10883 }
10884
10885 @ Sometimes |open_log_file| is called at awkward moments when \TeX\ is
10886 unable to print error messages or even to |show_context|.
10887 The |prompt_file_name| routine can result in a |fatal_error|, but the |error|
10888 routine will not be invoked because |log_opened| will be false.
10889
10890 The normal idea of |batch_mode| is that nothing at all should be written
10891 on the terminal. However, in the unusual case that
10892 no log file could be opened, we make an exception and allow
10893 an explanatory message to be seen.
10894
10895 Incidentally, the program always refers to the log file as a `\.{transcript
10896 file}', because some systems cannot use the extension `\.{.log}' for
10897 this file.
10898
10899 @<Try to get a different log file name@>=
10900 {@+selector=term_only;
10901 prompt_file_name("transcript file name",".log");
10902 }
10903
10904 @ @<Print the banner...@>=
10905 {@+wlog("%s",banner);
10906 slow_print(format_ident);print(" ");
10907 print_int(sys_day);print_char(' ');
10908 for (k=3*sys_month-2; k<=3*sys_month; k++) wlog("%c",months[k]);
10909 print_char(' ');print_int(sys_year);print_char(' ');
10910 print_two(sys_time/60);print_char(':');print_two(sys_time%60);
10911 if (eTeX_ex)
10912 {@+;wlog_cr;wlog("entering extended mode");
10913 }
10914 if (Prote_ex)
10915 {@+;wlog_cr;wlog("entering Prote mode");
10916 }
10917 }
10918
10919 @ Let's turn now to the procedure that is used to initiate file reading
10920 when an `\.{\\input}' command is being processed.
10921 Beware: For historic reasons, this code foolishly conserves a tiny bit
10922 of string pool space; but that can confuse the interactive `\.E' option.
10923 @^system dependencies@>
10924
10925 @p static void start_input(void) /*\TeX\ will \.{\\input} something*/
10926 {@+
10927 scan_file_name(); /*set |cur_name| to desired file name*/
10928 pack_cur_name("");
10929 loop@+{@+begin_file_reading(); /*set up |cur_file| and new level of input*/
10930 if (kpse_in_name_ok((char*)name_of_file+1) && a_open_in(&cur_file)) goto done;
10931 end_file_reading(); /*remove the level that didn't work*/
10932 prompt_file_name("input file name",".tex");
10933 }
10934 done: name=a_make_name_string(&cur_file);@/
10935 if (source_filename_stack[in_open]!=NULL)
10936 free(source_filename_stack[in_open]);
10937 source_filename_stack[in_open]=strdup((char *)name_of_file+1); /*\TeX\ Live*/
10938 if (full_source_filename_stack[in_open]!=NULL)
10939 free(full_source_filename_stack[in_open]);
10940 full_source_filename_stack[in_open]=strdup(full_name_of_file);
10941 if (job_name==0)
10942 {@+if (c_job_name==NULL) job_name=cur_name;
10943 else job_name=s_no(c_job_name); open_log_file(); /* \TeX\ Live*/
10944 } /*|open_log_file| doesn't |show_context|, so |limit|
10945 and |loc| needn't be set to meaningful values yet*/
10946 if (term_offset+strlen(full_source_filename_stack[in_open]) > max_print_line-2)
10947 print_ln();
10948 else if ((term_offset > 0)||(file_offset > 0)) print_char(' ');
10949 print_char('(');incr(open_parens);
10950 print(full_source_filename_stack[in_open]);update_terminal;
10951 if (tracing_stack_levels > 0)
10952 {@+int v;
10953 begin_diagnostic();print_ln();
10954 print_char('~');
10955 v=input_ptr-1;
10956 if (v < tracing_stack_levels)
10957 while (v-- > 0) print_char('.');
10958 else print_char('~');
10959 print("INPUT ");slow_print(cur_name);slow_print(cur_ext);print_ln();
10960 end_diagnostic(false);
10961 }
10962 state=new_line;
10963 if (name==str_ptr-1) /*conserve string pool space (but see note above)*/
10964 {@+flush_string;name=cur_name;
10965 }
10966 @<Read the first line of the new file@>;
10967 }
10968
10969 @ Here we have to remember to tell the |input_ln| routine not to
10970 start with a |get|. If the file is empty, it is considered to
10971 contain a single blank line.
10972 @^system dependencies@>
10973 @^empty line at end of file@>
10974
10975 @<Read the first line...@>=
10976 {@+line=1;
10977 if (input_ln(&cur_file, false)) do_nothing;
10978 firm_up_the_line();
10979 if (end_line_char_inactive) decr(limit);
10980 else buffer[limit]=end_line_char;
10981 first=limit+1;loc=start;
10982 }
10983
10984 @* Font metric data.
10985 \TeX\ gets its knowledge about fonts from font metric files, also called
10986 \.{TFM} files; the `\.T' in `\.{TFM}' stands for \TeX,
10987 but other programs know about them too.
10988 @:TFM files}{\.{TFM} files@>
10989 @^font metric files@>
10990
10991 The information in a \.{TFM} file appears in a sequence of 8-bit bytes.
10992 Since the number of bytes is always a multiple of 4, we could
10993 also regard the file as a sequence of 32-bit words, but \TeX\ uses the
10994 byte interpretation. The format of \.{TFM} files was designed by
10995 Lyle Ramshaw in 1980. The intent is to convey a lot of different kinds
10996 @^Ramshaw, Lyle Harold@>
10997 of information in a compact but useful form.
10998
10999 @<Glob...@>=
11000 static byte_file @!tfm_file;
11001
11002 @ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit
11003 integers that give the lengths of the various subsequent portions
11004 of the file. These twelve integers are, in order:
11005 $$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr
11006 |lf|&length of the entire file, in words;\cr
11007 |lh|&length of the header data, in words;\cr
11008 |bc|&smallest character code in the font;\cr
11009 |ec|&largest character code in the font;\cr
11010 |nw|&number of words in the width table;\cr
11011 |nh|&number of words in the height table;\cr
11012 |nd|&number of words in the depth table;\cr
11013 |ni|&number of words in the italic correction table;\cr
11014 |nl|&number of words in the lig/kern table;\cr
11015 |nk|&number of words in the kern table;\cr
11016 |ne|&number of words in the extensible character table;\cr
11017 |np|&number of font parameter words.\cr}}$$
11018 They are all nonnegative and less than $2^{15}$. We must have |bc-1 <= ec <= 255|,
11019 and
11020 $$\hbox{|lf==6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$
11021 Note that a font may contain as many as 256 characters (if |bc==0| and |ec==255|),
11022 and as few as 0 characters (if |bc==ec+1|).
11023
11024 Incidentally, when two or more 8-bit bytes are combined to form an integer of
11025 16 or more bits, the most significant bytes appear first in the file.
11026 This is called BigEndian order.
11027 @!@^BigEndian order@>
11028
11029 @ The rest of the \.{TFM} file may be regarded as a sequence of ten data
11030 arrays having the informal specification
11031 $$\def\arr$[#1]#2${\&{array} $[#1]$ \&{of} #2}
11032 \def\PB#1{\arr#1}
11033 \vbox{\halign{\hfil\\{#}&$\,:\,$#\hfil\cr
11034 header&|[0 dotdot lh-1]@t\\{stuff}@>|\cr
11035 char\_info&|[bc dotdot ec]char_info_word|\cr
11036 width&|[0 dotdot nw-1]fix_word|\cr
11037 height&|[0 dotdot nh-1]fix_word|\cr
11038 depth&|[0 dotdot nd-1]fix_word|\cr
11039 italic&|[0 dotdot ni-1]fix_word|\cr
11040 lig\_kern&|[0 dotdot nl-1]lig_kern_command|\cr
11041 kern&|[0 dotdot nk-1]fix_word|\cr
11042 exten&|[0 dotdot ne-1]extensible_recipe|\cr
11043 param&|[1 dotdot np]fix_word|\cr}}$$
11044 The most important data type used here is a |@!fix_word|, which is
11045 a 32-bit representation of a binary fraction. A |fix_word| is a signed
11046 quantity, with the two's complement of the entire word used to represent
11047 negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the
11048 binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and
11049 the smallest is $-2048$. We will see below, however, that all but two of
11050 the |fix_word| values must lie between $-16$ and $+16$.
11051
11052 @ The first data array is a block of header information, which contains
11053 general facts about the font. The header must contain at least two words,
11054 |header[0]| and |header[1]|, whose meaning is explained below.
11055 Additional header information of use to other software routines might
11056 also be included, but \TeX82 does not need to know about such details.
11057 For example, 16 more words of header information are in use at the Xerox
11058 Palo Alto Research Center; the first ten specify the character coding
11059 scheme used (e.g., `\.{XEROX text}' or `\.{TeX math symbols}'), the next five
11060 give the font identifier (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the
11061 last gives the ``face byte.'' The program that converts \.{DVI} files
11062 to Xerox printing format gets this information by looking at the \.{TFM}
11063 file, which it needs to read anyway because of other information that
11064 is not explicitly repeated in \.{DVI}~format.
11065
11066 \yskip\hang|header[0]| is a 32-bit check sum that \TeX\ will copy into
11067 the \.{DVI} output file. Later on when the \.{DVI} file is printed,
11068 possibly on another computer, the actual font that gets used is supposed
11069 to have a check sum that agrees with the one in the \.{TFM} file used by
11070 \TeX. In this way, users will be warned about potential incompatibilities.
11071 (However, if the check sum is zero in either the font file or the \.{TFM}
11072 file, no check is made.) The actual relation between this check sum and
11073 the rest of the \.{TFM} file is not important; the check sum is simply an
11074 identification number with the property that incompatible fonts almost
11075 always have distinct check sums.
11076 @^check sum@>
11077
11078 \yskip\hang|header[1]| is a |fix_word| containing the design size of
11079 the font, in units of \TeX\ points. This number must be at least 1.0; it is
11080 fairly arbitrary, but usually the design size is 10.0 for a ``10 point''
11081 font, i.e., a font that was designed to look best at a 10-point size,
11082 whatever that really means. When a \TeX\ user asks for a font
11083 `\.{at} $\delta$ \.{pt}', the effect is to override the design size
11084 and replace it by $\delta$, and to multiply the $x$ and~$y$ coordinates
11085 of the points in the font image by a factor of $\delta$ divided by the
11086 design size. {\sl All other dimensions in the\/ \.{TFM} file are
11087 |fix_word|\kern-1pt\ numbers in design-size units}, with the exception of
11088 |param[1]| (which denotes the slant ratio). Thus, for example, the value
11089 of |param[6]|, which defines the \.{em} unit, is often the |fix_word| value
11090 $2^{20}=1.0$, since many fonts have a design size equal to one em.
11091 The other dimensions must be less than 16 design-size units in absolute
11092 value; thus, |header[1]| and |param[1]| are the only |fix_word|
11093 entries in the whole \.{TFM} file whose first byte might be something
11094 besides 0 or 255.
11095
11096 @ Next comes the |char_info| array, which contains one |@!char_info_word|
11097 per character. Each word in this part of the file contains six fields
11098 packed into four bytes as follows.
11099
11100 \yskip\hang first byte: |@!width_index| (8 bits)\par
11101 \hang second byte: |@!height_index| (4 bits) times 16, plus |@!depth_index|
11102 (4~bits)\par
11103 \hang third byte: |@!italic_index| (6 bits) times 4, plus |@!tag|
11104 (2~bits)\par
11105 \hang fourth byte: |@!rem| (8 bits)\par
11106 \yskip\noindent
11107 The actual width of a character is \\{width}|[width_index]|, in design-size
11108 units; this is a device for compressing information, since many characters
11109 have the same width. Since it is quite common for many characters
11110 to have the same height, depth, or italic correction, the \.{TFM} format
11111 imposes a limit of 16 different heights, 16 different depths, and
11112 64 different italic corrections.
11113
11114 @!@^italic correction@>
11115 The italic correction of a character has two different uses.
11116 (a)~In ordinary text, the italic correction is added to the width only if
11117 the \TeX\ user specifies `\.{\\/}' after the character.
11118 (b)~In math formulas, the italic correction is always added to the width,
11119 except with respect to the positioning of subscripts.
11120
11121 Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]=
11122 \\{italic}[0]=0$ should always hold, so that an index of zero implies a
11123 value of zero. The |width_index| should never be zero unless the
11124 character does not exist in the font, since a character is valid if and
11125 only if it lies between |bc| and |ec| and has a nonzero |width_index|.
11126
11127 @ The |tag| field in a |char_info_word| has four values that explain how to
11128 interpret the |rem| field.
11129
11130 \yskip\hangg|tag==0| (|no_tag|) means that |rem| is unused.\par
11131 \hangg|tag==1| (|lig_tag|) means that this character has a ligature/kerning
11132 program starting at position |rem| in the |lig_kern| array.\par
11133 \hangg|tag==2| (|list_tag|) means that this character is part of a chain of
11134 characters of ascending sizes, and not the largest in the chain. The
11135 |rem| field gives the character code of the next larger character.\par
11136 \hangg|tag==3| (|ext_tag|) means that this character code represents an
11137 extensible character, i.e., a character that is built up of smaller pieces
11138 so that it can be made arbitrarily large. The pieces are specified in
11139 |@!exten[rem]|.\par
11140 \yskip\noindent
11141 Characters with |tag==2| and |tag==3| are treated as characters with |tag==0|
11142 unless they are used in special circumstances in math formulas. For example,
11143 the \.{\\sum} operation looks for a |list_tag|, and the \.{\\left}
11144 operation looks for both |list_tag| and |ext_tag|.
11145
11146 @d no_tag 0 /*vanilla character*/
11147 @d lig_tag 1 /*character has a ligature/kerning program*/
11148 @d list_tag 2 /*character has a successor in a charlist*/
11149 @d ext_tag 3 /*character is extensible*/
11150
11151 @ The |lig_kern| array contains instructions in a simple programming language
11152 that explains what to do for special letter pairs. Each word in this array is a
11153 |@!lig_kern_command| of four bytes.
11154
11155 \yskip\hang first byte: |skip_byte|, indicates that this is the final program
11156 step if the byte is 128 or more, otherwise the next step is obtained by
11157 skipping this number of intervening steps.\par
11158 \hang second byte: |next_char|, ``if |next_char| follows the current character,
11159 then perform the operation and stop, otherwise continue.''\par
11160 \hang third byte: |op_byte|, indicates a ligature step if less than~128,
11161 a kern step otherwise.\par
11162 \hang fourth byte: |rem|.\par
11163 \yskip\noindent
11164 In a kern step, an
11165 additional space equal to |kern[256*(op_byte-128)+rem]| is inserted
11166 between the current character and |next_char|. This amount is
11167 often negative, so that the characters are brought closer together
11168 by kerning; but it might be positive.
11169
11170 There are eight kinds of ligature steps, having |op_byte| codes $4a+2b+c$ where
11171 $0\le a\le b+c$ and $0\le b,c\le1$. The character whose code is
11172 |rem| is inserted between the current character and |next_char|;
11173 then the current character is deleted if $b=0$, and |next_char| is
11174 deleted if $c=0$; then we pass over $a$~characters to reach the next
11175 current character (which may have a ligature/kerning program of its own).
11176
11177 If the very first instruction of the |lig_kern| array has |skip_byte==255|,
11178 the |next_char| byte is the so-called boundary character of this font;
11179 the value of |next_char| need not lie between |bc| and~|ec|.
11180 If the very last instruction of the |lig_kern| array has |skip_byte==255|,
11181 there is a special ligature/kerning program for a boundary character at the
11182 left, beginning at location |256*op_byte+rem|.
11183 The interpretation is that \TeX\ puts implicit boundary characters
11184 before and after each consecutive string of characters from the same font.
11185 These implicit characters do not appear in the output, but they can affect
11186 ligatures and kerning.
11187
11188 If the very first instruction of a character's |lig_kern| program has
11189 |skip_byte > 128|, the program actually begins in location
11190 |256*op_byte+rem|. This feature allows access to large |lig_kern|
11191 arrays, because the first instruction must otherwise
11192 appear in a location | <= 255|.
11193
11194 Any instruction with |skip_byte > 128| in the |lig_kern| array must satisfy
11195 the condition
11196 $$\hbox{|256*op_byte+rem < nl|.}$$
11197 If such an instruction is encountered during
11198 normal program execution, it denotes an unconditional halt; no ligature
11199 or kerning command is performed.
11200
11201 @d stop_flag qi(128) /*value indicating `\.{STOP}' in a lig/kern program*/
11202 @d kern_flag qi(128) /*op code for a kern step*/
11203 @d skip_byte(A) A.b0
11204 @d next_char(A) A.b1
11205 @d op_byte(A) A.b2
11206 @d rem_byte(A) A.b3
11207
11208 @ Extensible characters are specified by an |@!extensible_recipe|, which
11209 consists of four bytes called |@!top|, |@!mid|, |@!bot|, and |@!rep| (in this
11210 order). These bytes are the character codes of individual pieces used to
11211 build up a large symbol. If |top|, |mid|, or |bot| are zero, they are not
11212 present in the built-up result. For example, an extensible vertical line is
11213 like an extensible bracket, except that the top and bottom pieces are missing.
11214
11215 Let $T$, $M$, $B$, and $R$ denote the respective pieces, or an empty box
11216 if the piece isn't present. Then the extensible characters have the form
11217 $TR^kMR^kB$ from top to bottom, for some |k >= 0|, unless $M$ is absent;
11218 in the latter case we can have $TR^kB$ for both even and odd values of~|k|.
11219 The width of the extensible character is the width of $R$; and the
11220 height-plus-depth is the sum of the individual height-plus-depths of the
11221 components used, since the pieces are butted together in a vertical list.
11222
11223 @d ext_top(A) A.b0 /*|top| piece in a recipe*/
11224 @d ext_mid(A) A.b1 /*|mid| piece in a recipe*/
11225 @d ext_bot(A) A.b2 /*|bot| piece in a recipe*/
11226 @d ext_rep(A) A.b3 /*|rep| piece in a recipe*/
11227
11228 @ The final portion of a \.{TFM} file is the |param| array, which is another
11229 sequence of |fix_word| values.
11230
11231 \yskip\hang|param[1]==slant| is the amount of italic slant, which is used
11232 to help position accents. For example, |slant==.25| means that when you go
11233 up one unit, you also go .25 units to the right. The |slant| is a pure
11234 number; it's the only |fix_word| other than the design size itself that is
11235 not scaled by the design size.
11236
11237 \hang|param[2]==space| is the normal spacing between words in text.
11238 Note that character |' '| in the font need not have anything to do with
11239 blank spaces.
11240
11241 \hang|param[3]==space_stretch| is the amount of glue stretching between words.
11242
11243 \hang|param[4]==space_shrink| is the amount of glue shrinking between words.
11244
11245 \hang|param[5]==x_height| is the size of one ex in the font; it is also
11246 the height of letters for which accents don't have to be raised or lowered.
11247
11248 \hang|param[6]==quad| is the size of one em in the font.
11249
11250 \hang|param[7]==extra_space| is the amount added to |param[2]| at the
11251 ends of sentences.
11252
11253 \yskip\noindent
11254 If fewer than seven parameters are present, \TeX\ sets the missing parameters
11255 to zero. Fonts used for math symbols are required to have
11256 additional parameter information, which is explained later.
11257
11258 @d slant_code 1
11259 @d space_code 2
11260 @d space_stretch_code 3
11261 @d space_shrink_code 4
11262 @d x_height_code 5
11263 @d quad_code 6
11264 @d extra_space_code 7
11265
11266 @ So that is what \.{TFM} files hold. Since \TeX\ has to absorb such information
11267 about lots of fonts, it stores most of the data in a large array called
11268 |font_info|. Each item of |font_info| is a |memory_word|; the |fix_word|
11269 data gets converted into |scaled| entries, while everything else goes into
11270 words of type |four_quarters|.
11271
11272 When the user defines \.{\\font\\f}, say, \TeX\ assigns an internal number
11273 to the user's font~\.{\\f}. Adding this number to |font_id_base| gives the
11274 |eqtb| location of a ``frozen'' control sequence that will always select
11275 the font.
11276
11277 @<Types...@>=
11278 typedef uint8_t internal_font_number; /*|font| in a |char_node|*/
11279 typedef int32_t font_index; /*index into |font_info|*/
11280
11281 @ Here now is the (rather formidable) array of font arrays.
11282
11283 @d non_char qi(256) /*a |halfword| code that can't match a real character*/
11284 @d non_address 0 /*a spurious |bchar_label|*/
11285
11286 @<Glob...@>=
11287 static memory_word @!font_info[font_mem_size+1];
11288 /*the big collection of font data*/
11289 static font_index @!fmem_ptr; /*first unused word of |font_info|*/
11290 static internal_font_number @!font_ptr; /*largest internal font number in use*/
11291 static four_quarters @!font_check0[font_max-font_base+1],
11292 *const @!font_check = @!font_check0-font_base; /*check sum*/
11293 static scaled @!font_size0[font_max-font_base+1],
11294 *const @!font_size = @!font_size0-font_base; /*``at'' size*/
11295 static scaled @!font_dsize0[font_max-font_base+1],
11296 *const @!font_dsize = @!font_dsize0-font_base; /*``design'' size*/
11297 static font_index @!font_params0[font_max-font_base+1],
11298 *const @!font_params = @!font_params0-font_base; /*how many font
11299 parameters are present*/
11300 static str_number @!font_name0[font_max-font_base+1],
11301 *const @!font_name = @!font_name0-font_base; /*name of the font*/
11302 static str_number @!font_area0[font_max-font_base+1],
11303 *const @!font_area = @!font_area0-font_base; /*area of the font*/
11304 static int @!font_bc0[font_max-font_base+1],
11305 *const @!font_bc = @!font_bc0-font_base;
11306 /*beginning (smallest) character code*/
11307 static int @!font_ec0[font_max-font_base+1],
11308 *const @!font_ec = @!font_ec0-font_base;
11309 /*ending (largest) character code*/
11310 static pointer @!font_glue0[font_max-font_base+1],
11311 *const @!font_glue = @!font_glue0-font_base;
11312 /*glue specification for interword space, |null| if not allocated*/
11313 static int @!hyphen_char0[font_max-font_base+1],
11314 *const @!hyphen_char = @!hyphen_char0-font_base;
11315 /*current \.{\\hyphenchar} values*/
11316 static int @!skew_char0[font_max-font_base+1],
11317 *const @!skew_char = @!skew_char0-font_base;
11318 /*current \.{\\skewchar} values*/
11319 static font_index @!bchar_label0[font_max-font_base+1],
11320 *const @!bchar_label = @!bchar_label0-font_base;
11321 /*start of |lig_kern| program for left boundary character,
11322 |non_address| if there is none*/
11323 static int16_t @!font_bchar0[font_max-font_base+1],
11324 *const @!font_bchar = @!font_bchar0-font_base;
11325 /*boundary character, |non_char| if there is none*/
11326 static int16_t @!font_false_bchar0[font_max-font_base+1],
11327 *const @!font_false_bchar = @!font_false_bchar0-font_base;
11328 /*|font_bchar| if it doesn't exist in the font, otherwise |non_char|*/
11329
11330 @ Besides the arrays just enumerated, we have directory arrays that make it
11331 easy to get at the individual entries in |font_info|. For example, the
11332 |char_info| data for character |c| in font |f| will be in
11333 |font_info[char_base[f]+c].qqqq|; and if |w| is the |width_index|
11334 part of this word (the |b0| field), the width of the character is
11335 |font_info[width_base[f]+w].sc|. (These formulas assume that
11336 |min_quarterword| has already been added to |c| and to |w|, since \TeX\
11337 stores its quarterwords that way.)
11338
11339 @<Glob...@>=
11340 static int @!char_base0[font_max-font_base+1],
11341 *const @!char_base = @!char_base0-font_base;
11342 /*base addresses for |char_info|*/
11343 static int @!width_base0[font_max-font_base+1],
11344 *const @!width_base = @!width_base0-font_base;
11345 /*base addresses for widths*/
11346 static int @!height_base0[font_max-font_base+1],
11347 *const @!height_base = @!height_base0-font_base;
11348 /*base addresses for heights*/
11349 static int @!depth_base0[font_max-font_base+1],
11350 *const @!depth_base = @!depth_base0-font_base;
11351 /*base addresses for depths*/
11352 static int @!italic_base0[font_max-font_base+1],
11353 *const @!italic_base = @!italic_base0-font_base;
11354 /*base addresses for italic corrections*/
11355 static int @!lig_kern_base0[font_max-font_base+1],
11356 *const @!lig_kern_base = @!lig_kern_base0-font_base;
11357 /*base addresses for ligature/kerning programs*/
11358 static int @!kern_base0[font_max-font_base+1],
11359 *const @!kern_base = @!kern_base0-font_base;
11360 /*base addresses for kerns*/
11361 static int @!exten_base0[font_max-font_base+1],
11362 *const @!exten_base = @!exten_base0-font_base;
11363 /*base addresses for extensible recipes*/
11364 static int @!param_base0[font_max-font_base+1],
11365 *const @!param_base = @!param_base0-font_base;
11366 /*base addresses for font parameters*/
11367
11368 @ \TeX\ always knows at least one font, namely the null font. It has no
11369 characters, and its seven parameters are all equal to zero.
11370
11371 @<Initialize table...@>=
11372 font_ptr=null_font;fmem_ptr=7;
11373 font_name[null_font]=s_no("nullfont");font_area[null_font]=empty_string;
11374 hyphen_char[null_font]='-';skew_char[null_font]=-1;
11375 bchar_label[null_font]=non_address;
11376 font_bchar[null_font]=non_char;font_false_bchar[null_font]=non_char;
11377 font_bc[null_font]=1;font_ec[null_font]=0;
11378 font_size[null_font]=0;font_dsize[null_font]=0;
11379 char_base[null_font]=0;width_base[null_font]=0;
11380 height_base[null_font]=0;depth_base[null_font]=0;
11381 italic_base[null_font]=0;lig_kern_base[null_font]=0;
11382 kern_base[null_font]=0;exten_base[null_font]=0;
11383 font_glue[null_font]=null;font_params[null_font]=7;
11384 param_base[null_font]=-1;
11385 for (k=0; k<=6; k++) font_info[k].sc=0;
11386
11387 @ @<Put each...@>=
11388 primitive("nullfont", set_font, null_font);
11389 @!@:null\_font\_}{\.{\\nullfont} primitive@>
11390 text(frozen_null_font)=text(cur_val);eqtb[frozen_null_font]=eqtb[cur_val];
11391
11392 @ Of course we want to define macros that suppress the detail of how font
11393 information is actually packed, so that we don't have to write things like
11394 $$\hbox{|font_info[width_base[f]+font_info[char_base[f]+c].qqqq.b0].sc|}$$
11395 too often. The \.{WEB} definitions here make |char_info(f)(c)| the
11396 |four_quarters| word of font information corresponding to character
11397 |c| of font |f|. If |q| is such a word, |char_width(f)(q)| will be
11398 the character's width; hence the long formula above is at least
11399 abbreviated to
11400 $$\hbox{|char_width(f)(char_info(f)(c))|.}$$
11401 Usually, of course, we will fetch |q| first and look at several of its
11402 fields at the same time.
11403
11404 The italic correction of a character will be denoted by
11405 |char_italic(f)(q)|, so it is analogous to |char_width|. But we will get
11406 at the height and depth in a slightly different way, since we usually want
11407 to compute both height and depth if we want either one. The value of
11408 |height_depth(q)| will be the 8-bit quantity
11409 $$b=|height_index|\times16+|depth_index|,$$ and if |b| is such a byte we
11410 will write |char_height(f)(b)| and |char_depth(f)(b)| for the height and
11411 depth of the character |c| for which |q==char_info(f)(c)|. Got that?
11412
11413 The tag field will be called |char_tag(q)|; the remainder byte will be
11414 called |rem_byte(q)|, using a macro that we have already defined above.
11415
11416 Access to a character's |width|, |height|, |depth|, and |tag| fields is
11417 part of \TeX's inner loop, so we want these macros to produce code that is
11418 as fast as possible under the circumstances.
11419 @^inner loop@>
11420
11421 @d char_info(A, B) (IS_X_FONT(A)?null_character:font_info[char_base[A]+B].qqqq)
11422 @d char_width(A, B) (IS_X_FONT(A)?x_char_width(A,B):font_info[width_base[A]+char_info(A,B).b0].sc)
11423 @d char_exists(A,B) (IS_X_FONT(A)?x_char_exists(A,B): char_info(A,B).b0 > min_quarterword)
11424 @d char_italic(A, B) (IS_X_FONT(A)? x_char_italic(A,B):font_info[italic_base[A]+(char_info(A,B).b2)/4].sc)
11425 @d height_depth(A) qo(A.b1)
11426 @d char_height(A, B) (IS_X_FONT(A)? x_char_height(A,B):font_info[height_base[A]+(char_info(A,B).b1)/16].sc)
11427 @d char_depth(A, B) (IS_X_FONT(A)? x_char_depth(A,B):font_info[depth_base[A]+(char_info(A,B).b1)%16].sc)
11428 @d char_tag(A,B) (IS_X_FONT(A)? no_tag:((qo(B.b2))%4)) /*we need extended font |A|*/
11429
11430 @ The global variable |null_character| is set up to be a word of
11431 |char_info| for a character that doesn't exist. Such a word provides a
11432 convenient way to deal with erroneous situations.
11433
11434 @<Glob...@>=
11435 static four_quarters @!null_character; /*nonexistent character information*/
11436
11437 @ @<Set init...@>=
11438 null_character.b0=min_quarterword;null_character.b1=min_quarterword;
11439 null_character.b2=min_quarterword;null_character.b3=min_quarterword;
11440
11441 @ Here are some macros that help process ligatures and kerns.
11442 We write |char_kern(f)(j)| to find the amount of kerning specified by
11443 kerning command~|j| in font~|f|. If |j| is the |char_info| for a character
11444 with a ligature/kern program, the first instruction of that program is either
11445 |i==font_info[lig_kern_start(f)(j)]| or |font_info[lig_kern_restart(f)(i)]|,
11446 depending on whether or not |skip_byte(i) <= stop_flag|.
11447
11448 The constant |kern_base_offset| should be simplified, for \PASCAL\ compilers
11449 that do not do local optimization.
11450 @^system dependencies@>
11451
11452 @d char_kern(A, B) font_info[kern_base[A]+256*op_byte(B)+rem_byte(B)].sc
11453 @d kern_base_offset 256*(128+min_quarterword)
11454 @d lig_kern_start(A, B) lig_kern_base[A]+B.b3 /*beginning of lig/kern program*/
11455 @d lig_kern_restart(A, B) lig_kern_base[A]+256*op_byte(B)+rem_byte(B)+32768-kern_base_offset
11456
11457 @ Font parameters are referred to as |slant(f)|, |space(f)|, etc.
11458
11459 @d param(A,B) font_info[A+param_base[B]].sc
11460 @d slant(B) param(slant_code,B) /*slant to the right, per unit distance upward*/
11461 @d space(B) param(space_code,B) /*normal space between words*/
11462 @d space_stretch(B) param(space_stretch_code,B) /*stretch between words*/
11463 @d space_shrink(B) param(space_shrink_code,B) /*shrink between words*/
11464 @d x_height(B) param(x_height_code,B) /*one ex*/
11465 @d quad(B) param(quad_code,B) /*one em*/
11466 @d extra_space(B) param(extra_space_code,B) /*additional space at end of sentence*/
11467
11468 @<The em width for |cur_font|@>=quad(cur_font)
11469
11470 @ @<The x-height for |cur_font|@>=x_height(cur_font)
11471
11472 @ \TeX\ checks the information of a \.{TFM} file for validity as the
11473 file is being read in, so that no further checks will be needed when
11474 typesetting is going on. The somewhat tedious subroutine that does this
11475 is called |read_font_info|. It has four parameters: the user font
11476 identifier~|u|, the file name and area strings |nom| and |aire|, and the
11477 ``at'' size~|s|. If |s|~is negative, it's the negative of a scale factor
11478 to be applied to the design size; |s==-1000| is the normal case.
11479 Otherwise |s| will be substituted for the design size; in this
11480 case, |s| must be positive and less than $2048\rm\,pt$
11481 (i.e., it must be less than $2^{27}$ when considered as an integer).
11482
11483 The subroutine opens and closes a global file variable called |tfm_file|.
11484 It returns the value of the internal font number that was just loaded.
11485 If an error is detected, an error message is issued and no font
11486 information is stored; |null_font| is returned in this case.
11487
11488 @d abort goto bad_tfm /*do this when the \.{TFM} data is wrong*/
11489
11490 @p static internal_font_number read_font_info(str_number t, str_number @!nom, str_number @!aire,
11491 str_number @!ext,
11492 scaled @!s) /*input a font file*/
11493 {@+
11494 int k; /*index into |font_info|*/
11495 halfword @!lf, @!lh, @!bc, @!ec, @!nw, @!nh, @!nd, @!ni, @!nl, @!nk, @!ne, @!np;
11496 /*sizes of subfiles*/
11497 internal_font_number @!f; /*the new font's number*/
11498 internal_font_number @!g; /*the number to return*/
11499 eight_bits @!a, @!b, @!c, @!d; /*byte variables*/
11500 four_quarters @!qw;scaled @!sw; /*accumulators*/
11501 int @!bch_label; /*left boundary start location, or infinity*/
11502 int @!bchar; /*boundary character, or 256*/
11503 scaled @!z; /*the design size or the ``at'' size*/
11504 int @!alpha;int @!beta; /*auxiliary quantities used in fixed-point multiplication*/
11505
11506 g=null_font;@/
11507 @<Read and check the font data; |abort| if the font file is malformed;
11508 if there's no room for this font, say so and |goto done|; otherwise |incr(font_ptr)|
11509 and |goto done|@>;
11510 bad_tfm: @<Report a bad tfm file@>;
11511 done: if (tfm_file.f!=NULL) b_close(&tfm_file);
11512 return g;
11513 }
11514
11515 static void read_extended_font( internal_font_number g,str_number t,
11516 str_number @!nom, str_number @!aire,
11517 scaled @!s, char * path) /*input a font file*/
11518 { @<load an extended font@>@;
11519 @<Trace the new extended font@>@;
11520 }
11521
11522 static void read_predefined_font(internal_font_number g)
11523 { char *path;
11524 str_number t;
11525 pack_file_name(empty_string, font_area[g], empty_string,"");
11526 path=(char*)name_of_file+1;
11527 t=font_id_text(g);
11528 read_extended_font(g,t,font_name[g], font_area[g],font_size[g],path);
11529 }
11530
11531 @ If an extended font |k| is defined and then dumped into a format file,
11532 the format file will contain the following information about it:
11533 |font_size[k]|, |font_dsize[k]|, |font_name[k]|, |font_bc[k]|, |font_ec[k]|,
11534 and the seven basic font parameters |slant|, |space|, |space_stretch|,
11535 |space_shrink|, |extra_space|, |quad|, and |x_height|.
11536 Further, the |font_area[k]| will contain the full name of the font file.
11537
11538 If an extended font |k| is defined in a format file, however,
11539 it will not be loaded into memory together with the format file,
11540 and consequently, |x_font[k]| will be |NULL|. The decission not
11541 to load all fonts specified in a format makes sense because
11542 formats define a general purpose setting that usually defines
11543 many more fonts that are used in any specific document.
11544 For example, the plain \TeX\ format specifies 50 different fonts!
11545 \HiTeX\ will load a predefined font only if needed.
11546
11547 The test |x_font[k]!=NULL| is used frequently in \HiTeX\ to test for
11548 extended fonts. To make this test work for predefined fonts,
11549 it is necessary to load these fonts before the access to |x_font[k]|.
11550 So \HiTeX\ checks for predefined fonts when setting the current font
11551 or setting a font in one of the seven font families used at the end
11552 of math mode processing.
11553 In addition it is necessary to check characters that
11554 are defined using \.{\\mathcode} or \.{\\mathchardef} because
11555 these primitives allow the selection of any of the 16 available
11556 font families.
11557
11558 To tell an extended font from an font with a \.{.tfm} file,
11559 we store |-256| in |char_base[k]|. The char |char_base| array
11560 is not used for extended fonts and for other fonts its
11561 values are usually not negative but definitely bigger than the
11562 negative value of the smallest character code in the font.
11563
11564 @d extended_base -256
11565 @d needs_loading(A) (char_base[A]==extended_base && x_font[A]==NULL)
11566
11567 @ There are programs called \.{TFtoPL} and \.{PLtoTF} that convert
11568 between the \.{TFM} format and a symbolic property-list format
11569 that can be easily edited. These programs contain extensive
11570 diagnostic information, so \TeX\ does not have to bother giving
11571 precise details about why it rejects a particular \.{TFM} file.
11572 @.TFtoPL@> @.PLtoTF@>
11573
11574 @d start_font_error_message print_err("Font ");printn_esc(t);
11575 print_char('=');print_file_name(nom, aire, empty_string);
11576 if (s >= 0)
11577 {@+print(" at ");print_scaled(s);print("pt");
11578 }
11579 else if (s!=-1000)
11580 {@+print(" scaled ");print_int(-s);
11581 }
11582
11583 @<Report a bad tfm file@>=
11584 start_font_error_message;
11585 @.Font x=xx not loadable...@>
11586 print(" not loadable: Bad font file");
11587 help5("I wasn't able to read the data for this font,",@/
11588 "so I will ignore the font specification.",@/
11589 "[Wizards can fix TFM files using TFtoPL/PLtoTF.]",@/
11590 "You might try inserting a different font spec;",@/
11591 "e.g., type `I\\font<same font id>=<substitute font name>'.");
11592 error()
11593
11594
11595
11596 @ @<Read and check...@>=
11597 @<Read the {\.{TFM}} size fields@>;
11598 @<Use size fields to allocate font information@>;
11599 @<Read the {\.{TFM}} header@>;
11600 @<Read character data@>;
11601 @<Read box dimensions@>;
11602 @<Read ligature/kern program@>;
11603 @<Read extensible character recipes@>;
11604 @<Read font parameters@>;
11605 @<Make final adjustments and |goto done|@>@;
11606
11607 @ @<Open |tfm_file| for input@>=
11608 pack_file_name(cur_name, empty_string,empty_string,".tfm"); /* \TeX\ Live */
11609 path=kpse_find_file((char*)name_of_file+1, kpse_tfm_format, 0);
11610 if (path!=NULL && b_open_in(&tfm_file,path)) file_opened=true;
11611 else file_opened=false;
11612
11613 @ Note: A malformed \.{TFM} file might be shorter than it claims to be;
11614 thus |eof(tfm_file)| might be true when |read_font_info| refers to
11615 |tfm_file.d| or when it says |get(tfm_file)|. If such circumstances
11616 cause system error messages, you will have to defeat them somehow,
11617 for example by defining |fget| to be `\ignorespaces|{@+get(tfm_file);|
11618 |if (eof(tfm_file)) abort;} |\unskip'.
11619 @^system dependencies@>
11620
11621 @d fget get(tfm_file)
11622 @d fbyte tfm_file.d
11623 @d read_sixteen(A) {@+A=fbyte;
11624 if (A > 127) abort;
11625 fget;A=A*0400+fbyte;
11626 }
11627 @d store_four_quarters(A) {@+fget;a=fbyte;qw.b0=qi(a);
11628 fget;b=fbyte;qw.b1=qi(b);
11629 fget;c=fbyte;qw.b2=qi(c);
11630 fget;d=fbyte;qw.b3=qi(d);
11631 A=qw;
11632 }
11633
11634 @ @<Read the {\.{TFM}} size fields@>=
11635 {@+read_sixteen(lf);
11636 fget;read_sixteen(lh);
11637 fget;read_sixteen(bc);
11638 fget;read_sixteen(ec);
11639 if ((bc > ec+1)||(ec > 255)) abort;
11640 if (bc > 255) /*|bc==256| and |ec==255|*/
11641 {@+bc=1;ec=0;
11642 }
11643 fget;read_sixteen(nw);
11644 fget;read_sixteen(nh);
11645 fget;read_sixteen(nd);
11646 fget;read_sixteen(ni);
11647 fget;read_sixteen(nl);
11648 fget;read_sixteen(nk);
11649 fget;read_sixteen(ne);
11650 fget;read_sixteen(np);
11651 if (lf!=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np) abort;
11652 if ((nw==0)||(nh==0)||(nd==0)||(ni==0)) abort;
11653 }
11654
11655 @ The preliminary settings of the index-offset variables |char_base|,
11656 |width_base|, |lig_kern_base|, |kern_base|, and |exten_base| will be
11657 corrected later by subtracting |min_quarterword| from them; and we will
11658 subtract 1 from |param_base| too. It's best to forget about such anomalies
11659 until later.
11660
11661 @<Use size fields to allocate font information@>=
11662 lf=lf-6-lh; /*|lf| words should be loaded into |font_info|*/
11663 if (np < 7) lf=lf+7-np; /*at least seven parameters will appear*/
11664 if ((font_ptr==font_max)||(fmem_ptr+lf > font_mem_size))
11665 @<Apologize for not loading the font, |goto done|@>;
11666 f=font_ptr+1;
11667 char_base[f]=fmem_ptr-bc;
11668 width_base[f]=char_base[f]+ec+1;
11669 height_base[f]=width_base[f]+nw;
11670 depth_base[f]=height_base[f]+nh;
11671 italic_base[f]=depth_base[f]+nd;
11672 lig_kern_base[f]=italic_base[f]+ni;
11673 kern_base[f]=lig_kern_base[f]+nl-kern_base_offset;
11674 exten_base[f]=kern_base[f]+kern_base_offset+nk;
11675 param_base[f]=exten_base[f]+ne
11676
11677 @ @<Apologize for not loading...@>=
11678 {@+start_font_error_message;
11679 print(" not loaded: Not enough room left");
11680 @.Font x=xx not loaded...@>
11681 help4("I'm afraid I won't be able to make use of this font,",@/
11682 "because my memory for character-size data is too small.",@/
11683 "If you're really stuck, ask a wizard to enlarge me.",@/
11684 "Or maybe try `I\\font<same font id>=<name of loaded font>'.");
11685 error();goto done;
11686 }
11687
11688 @ Only the first two words of the header are needed by \TeX82.
11689
11690 @<Read the {\.{TFM}} header@>=
11691 {@+if (lh < 2) abort;
11692 store_four_quarters(font_check[f]);
11693 fget;read_sixteen(z); /*this rejects a negative design size*/
11694 fget;z=z*0400+fbyte;fget;z=(z*020)+(fbyte/020);
11695 if (z < unity) abort;
11696 while (lh > 2)
11697 {@+fget;fget;fget;fget;decr(lh); /*ignore the rest of the header*/
11698 }
11699 font_dsize[f]=z;
11700 if (s!=-1000)
11701 if (s >= 0) z=s;
11702 else z=xn_over_d(z,-s, 1000);
11703 font_size[f]=z;
11704 }
11705
11706 @ @<Read character data@>=
11707 for (k=fmem_ptr; k<=width_base[f]-1; k++)
11708 {@+store_four_quarters(font_info[k].qqqq);
11709 if ((a >= nw)||(b/020 >= nh)||(b%020 >= nd)||
11710 (c/4 >= ni)) abort;
11711 switch (c%4) {
11712 case lig_tag: if (d >= nl) abort;@+break;
11713 case ext_tag: if (d >= ne) abort;@+break;
11714 case list_tag: @<Check for charlist cycle@>@;@+break;
11715 default:do_nothing; /*|no_tag|*/
11716 }
11717 }
11718
11719 @ We want to make sure that there is no cycle of characters linked together
11720 by |list_tag| entries, since such a cycle would get \TeX\ into an endless
11721 loop. If such a cycle exists, the routine here detects it when processing
11722 the largest character code in the cycle.
11723
11724 @d check_byte_range(A) {@+if ((A < bc)||(A > ec)) abort;@+}
11725 @d current_character_being_worked_on k+bc-fmem_ptr
11726
11727 @<Check for charlist cycle@>=
11728 {@+check_byte_range(d);
11729 while (d < current_character_being_worked_on)
11730 {@+qw=char_info(f, d);
11731 /*N.B.: not |qi(d)|, since |char_base[f]| hasn't been adjusted yet*/
11732 if (char_tag(f,qw)!=list_tag) goto not_found;
11733 d=qo(rem_byte(qw)); /*next character on the list*/
11734 }
11735 if (d==current_character_being_worked_on) abort; /*yes, there's a cycle*/
11736 not_found: ;}
11737
11738 @ A |fix_word| whose four bytes are $(a,b,c,d)$ from left to right represents
11739 the number
11740 $$x=\left\{\vcenter{\halign{$#$,\hfil\qquad&if $#$\hfil\cr
11741 b\cdot2^{-4}+c\cdot2^{-12}+d\cdot2^{-20}&a=0;\cr
11742 -16+b\cdot2^{-4}+c\cdot2^{-12}+d\cdot2^{-20}&a=255.\cr}}\right.$$
11743 (No other choices of |a| are allowed, since the magnitude of a number in
11744 design-size units must be less than 16.) We want to multiply this
11745 quantity by the integer~|z|, which is known to be less than $2^{27}$.
11746 If $|z|<2^{23}$, the individual multiplications $b\cdot z$,
11747 $c\cdot z$, $d\cdot z$ cannot overflow; otherwise we will divide |z| by 2,
11748 4, 8, or 16, to obtain a multiplier less than $2^{23}$, and we can
11749 compensate for this later. If |z| has thereby been replaced by
11750 $|z|^\prime=|z|/2^e$, let $\beta=2^{4-e}$; we shall compute
11751 $$\lfloor(b+c\cdot2^{-8}+d\cdot2^{-16})\,z^\prime/\beta\rfloor$$
11752 if $a=0$, or the same quantity minus $\alpha=2^{4+e}z^\prime$ if $a=255$.
11753 This calculation must be done exactly, in order to guarantee portability
11754 of \TeX\ between computers.
11755
11756 @d store_scaled(A) {@+fget;a=fbyte;fget;b=fbyte;
11757 fget;c=fbyte;fget;d=fbyte;@/
11758 sw=(((((d*z)/0400)+(c*z))/0400)+(b*z))/beta;
11759 if (a==0) A=sw;@+else if (a==255) A=sw-alpha;@+else abort;
11760 }
11761
11762 @<Read box dimensions@>=
11763 {@+@<Replace |z| by $|z|^\prime$ and compute $\alpha,\beta$@>;
11764 for (k=width_base[f]; k<=lig_kern_base[f]-1; k++)
11765 store_scaled(font_info[k].sc);
11766 if (font_info[width_base[f]].sc!=0) abort; /*\\{width}[0] must be zero*/
11767 if (font_info[height_base[f]].sc!=0) abort; /*\\{height}[0] must be zero*/
11768 if (font_info[depth_base[f]].sc!=0) abort; /*\\{depth}[0] must be zero*/
11769 if (font_info[italic_base[f]].sc!=0) abort; /*\\{italic}[0] must be zero*/
11770 }
11771
11772 @ @<Replace |z|...@>=
11773 {@+alpha=16;
11774 while (z >= 040000000)
11775 {@+z=z/2;alpha=alpha+alpha;
11776 }
11777 beta=256/alpha;alpha=alpha*z;
11778 }
11779
11780 @ @d check_existence(A) @t@>@;@/
11781 {@+check_byte_range(A);
11782 qw=char_info(f, A); /*N.B.: not |qi(A)|*/
11783 if (!char_exists(f,A)) abort;
11784 }
11785
11786 @<Read ligature/kern program@>=
11787 bch_label=077777;bchar=256;
11788 if (nl > 0)
11789 {@+for (k=lig_kern_base[f]; k<=kern_base[f]+kern_base_offset-1; k++)
11790 {@+store_four_quarters(font_info[k].qqqq);
11791 if (a > 128)
11792 {@+if (256*c+d >= nl) abort;
11793 if (a==255) if (k==lig_kern_base[f]) bchar=b;
11794 }
11795 else{@+if (b!=bchar) check_existence(b);
11796 if (c < 128) check_existence(d)@; /*check ligature*/
11797 else if (256*(c-128)+d >= nk) abort; /*check kern*/
11798 if (a < 128) if (k-lig_kern_base[f]+a+1 >= nl) abort;
11799 }
11800 }
11801 if (a==255) bch_label=256*c+d;
11802 }
11803 for (k=kern_base[f]+kern_base_offset; k<=exten_base[f]-1; k++)
11804 store_scaled(font_info[k].sc);
11805
11806 @ @<Read extensible character recipes@>=
11807 for (k=exten_base[f]; k<=param_base[f]-1; k++)
11808 {@+store_four_quarters(font_info[k].qqqq);
11809 if (a!=0) check_existence(a);
11810 if (b!=0) check_existence(b);
11811 if (c!=0) check_existence(c);
11812 check_existence(d);
11813 }
11814
11815 @ We check to see that the \.{TFM} file doesn't end prematurely; but
11816 no error message is given for files having more than |lf| words.
11817
11818 @<Read font parameters@>=
11819 {@+for (k=1; k<=np; k++)
11820 if (k==1) /*the |slant| parameter is a pure number*/
11821 {@+fget;sw=fbyte;if (sw > 127) sw=sw-256;
11822 fget;sw=sw*0400+fbyte;fget;sw=sw*0400+fbyte;
11823 fget;font_info[param_base[f]].sc=
11824 (sw*020)+(fbyte/020);
11825 }
11826 else store_scaled(font_info[param_base[f]+k-1].sc);
11827 if (eof(tfm_file)) abort;
11828 for (k=np+1; k<=7; k++) font_info[param_base[f]+k-1].sc=0;
11829 }
11830
11831 @ Now to wrap it up, we have checked all the necessary things about the \.{TFM}
11832 file, and all we need to do is put the finishing touches on the data for
11833 the new font.
11834
11835 @d adjust(A) A[f]=qo(A[f])
11836 /*correct for the excess |min_quarterword| that was added*/
11837
11838 @<Make final adjustments...@>=
11839 if (np >= 7) font_params[f]=np;@+else font_params[f]=7;
11840 hyphen_char[f]=default_hyphen_char;skew_char[f]=default_skew_char;
11841 if (bch_label < nl) bchar_label[f]=bch_label+lig_kern_base[f];
11842 else bchar_label[f]=non_address;
11843 font_bchar[f]=qi(bchar);
11844 font_false_bchar[f]=qi(bchar);
11845 if (bchar <= ec) if (bchar >= bc)
11846 {@+qw=char_info(f, bchar); /*N.B.: not |qi(bchar)|*/
11847 if (char_exists(f,bchar)) font_false_bchar[f]=non_char;
11848 }
11849 font_name[f]=nom;
11850 font_area[f]=aire;
11851 font_bc[f]=bc;font_ec[f]=ec;font_glue[f]=null;
11852 adjust(char_base);adjust(width_base);adjust(lig_kern_base);
11853 adjust(kern_base);adjust(exten_base);
11854 decr(param_base[f]);
11855 fmem_ptr=fmem_ptr+lf;font_ptr=f;g=f;goto done;
11856
11857 @ Before we forget about the format of these tables, let's deal with two
11858 of \TeX's basic scanning routines related to font information.
11859
11860 @<Declare procedures that scan font-related stuff@>=
11861 static void scan_font_ident(void)
11862 {@+internal_font_number f;
11863 halfword @!m;
11864 @<Get the next non-blank non-call...@>;
11865 if (cur_cmd==def_font) f=cur_font;
11866 else if (cur_cmd==set_font) f=cur_chr;
11867 else if (cur_cmd==def_family)
11868 {@+m=cur_chr;scan_four_bit_int();f=equiv(m+cur_val);
11869 }
11870 else{@+print_err("Missing font identifier");
11871 @.Missing font identifier@>
11872 help2("I was looking for a control sequence whose",@/
11873 "current meaning has been defined by \\font.");
11874 back_error();f=null_font;
11875 }
11876 cur_val=f;
11877 }
11878
11879 @ The following routine is used to implement `\.{\\fontdimen} |n| |f|'.
11880 The boolean parameter |writing| is set |true| if the calling program
11881 intends to change the parameter value.
11882
11883 @<Declare procedures that scan font-related stuff@>=
11884 static void find_font_dimen(bool @!writing)
11885 /*sets |cur_val| to |font_info| location*/
11886 {@+internal_font_number f;
11887 int @!n; /*the parameter number*/
11888 scan_int();n=cur_val;scan_font_ident();f=cur_val;
11889 if (n <= 0) cur_val=fmem_ptr;
11890 else{@+if (writing&&(n <= space_shrink_code)&&@|
11891 (n >= space_code)&&(font_glue[f]!=null))
11892 {@+delete_glue_ref(font_glue[f]);
11893 font_glue[f]=null;
11894 }
11895 if (n > font_params[f])
11896 if (f < font_ptr) cur_val=fmem_ptr;
11897 else@<Increase the number of parameters in the last font@>@;
11898 else cur_val=n+param_base[f];
11899 }
11900 @<Issue an error message if |cur_val=fmem_ptr|@>;
11901 }
11902
11903 @ @<Issue an error message if |cur_val=fmem_ptr|@>=
11904 if (cur_val==fmem_ptr)
11905 {@+print_err("Font ");printn_esc(font_id_text(f));
11906 print(" has only ");print_int(font_params[f]);
11907 print(" fontdimen parameters");
11908 @.Font x has only...@>
11909 help2("To increase the number of font parameters, you must",@/
11910 "use \\fontdimen immediately after the \\font is loaded.");
11911 error();
11912 }
11913
11914 @ @<Increase the number of parameters...@>=
11915 {@+@/do@+{if (fmem_ptr==font_mem_size)
11916 overflow("font memory", font_mem_size);
11917 @:TeX capacity exceeded font memory}{\quad font memory@>
11918 font_info[fmem_ptr].sc=0;incr(fmem_ptr);incr(font_params[f]);
11919 }@+ while (!(n==font_params[f]));
11920 cur_val=fmem_ptr-1; /*this equals |param_base[f]+font_params[f]|*/
11921 }
11922
11923 @ When \TeX\ wants to typeset a character that doesn't exist, the
11924 character node is not created; thus the output routine can assume
11925 that characters exist when it sees them. The following procedure
11926 prints a warning message unless the user has suppressed it.
11927
11928 @p static void char_warning(internal_font_number @!f, uint32_t @!c)
11929 {@+int old_setting; /*saved value of |tracing_online|*/
11930 if (tracing_lost_chars > 0)
11931 {@+old_setting=tracing_online;
11932 if (eTeX_ex&&(tracing_lost_chars > 1)) tracing_online=1;
11933 {@+begin_diagnostic();
11934 print_nl("Missing character: There is no ");
11935 @.Missing character@>
11936 print_utf8(c);print(" in font ");
11937 slow_print(font_name[f]);print_char('!');end_diagnostic(false);
11938 }
11939 tracing_online=old_setting;
11940 }
11941 }
11942
11943 @ Here is a function that returns a pointer to a character node for a
11944 given character in a given font. If that character doesn't exist,
11945 |null| is returned instead.
11946
11947 @p static pointer new_character(internal_font_number @!f, uint32_t @!c)
11948 {@+
11949 pointer p; /*newly allocated node*/
11950 if (font_bc[f] <= c) if (font_ec[f] >= c)
11951 if (char_exists(f, c))
11952 {@+p=get_avail();font(p)=f;character(p)=c;
11953 return p;
11954 }
11955 char_warning(f, c);
11956 return null;
11957 }
11958
11959 @* Device-independent file format.
11960 The most important output produced by a run of \TeX\ is the ``device
11961 independent'' (\.{DVI}) file that specifies where characters and rules
11962 are to appear on printed pages. The form of these files was designed by
11963 David R. Fuchs in 1979. Almost any reasonable typesetting device can be
11964 @^Fuchs, David Raymond@>
11965 @:DVI\_files}{\.{DVI} files@>
11966 driven by a program that takes \.{DVI} files as input, and dozens of such
11967 \.{DVI}-to-whatever programs have been written. Thus, it is possible to
11968 print the output of \TeX\ on many different kinds of equipment, using \TeX\
11969 as a device-independent ``front end.''
11970
11971 A \.{DVI} file is a stream of 8-bit bytes, which may be regarded as a
11972 series of commands in a machine-like language. The first byte of each command
11973 is the operation code, and this code is followed by zero or more bytes
11974 that provide parameters to the command. The parameters themselves may consist
11975 of several consecutive bytes; for example, the `|set_rule|' command has two
11976 parameters, each of which is four bytes long. Parameters are usually
11977 regarded as nonnegative integers; but four-byte-long parameters,
11978 and shorter parameters that denote distances, can be
11979 either positive or negative. Such parameters are given in two's complement
11980 notation. For example, a two-byte-long distance parameter has a value between
11981 $-2^{15}$ and $2^{15}-1$. As in \.{TFM} files, numbers that occupy
11982 more than one byte position appear in BigEndian order.
11983
11984 A \.{DVI} file consists of a ``preamble,'' followed by a sequence of one
11985 or more ``pages,'' followed by a ``postamble.'' The preamble is simply a
11986 |pre| command, with its parameters that define the dimensions used in the
11987 file; this must come first. Each ``page'' consists of a |bop| command,
11988 followed by any number of other commands that tell where characters are to
11989 be placed on a physical page, followed by an |eop| command. The pages
11990 appear in the order that \TeX\ generated them. If we ignore |nop| commands
11991 and \\{fnt\_def} commands (which are allowed between any two commands in
11992 the file), each |eop| command is immediately followed by a |bop| command,
11993 or by a |post| command; in the latter case, there are no more pages in the
11994 file, and the remaining bytes form the postamble. Further details about
11995 the postamble will be explained later.
11996
11997 Some parameters in \.{DVI} commands are ``pointers.'' These are four-byte
11998 quantities that give the location number of some other byte in the file;
11999 the first byte is number~0, then comes number~1, and so on. For example,
12000 one of the parameters of a |bop| command points to the previous |bop|;
12001 this makes it feasible to read the pages in backwards order, in case the
12002 results are being directed to a device that stacks its output face up.
12003 Suppose the preamble of a \.{DVI} file occupies bytes 0 to 99. Now if the
12004 first page occupies bytes 100 to 999, say, and if the second
12005 page occupies bytes 1000 to 1999, then the |bop| that starts in byte 1000
12006 points to 100 and the |bop| that starts in byte 2000 points to 1000. (The
12007 very first |bop|, i.e., the one starting in byte 100, has a pointer of~$-1$.)
12008
12009 @ The preamble contains basic information about the file as a whole. As
12010 stated above, there are six parameters:
12011 $$\hbox{|@!i[1]| |@!num[4]| |@!den[4]| |@!mag[4]| |@!k[1]| |@!x[k]|.}$$
12012 The |i| byte identifies \.{DVI} format; currently this byte is always set
12013 to~2. (The value |i==3| is currently used for an extended format that
12014 allows a mixture of right-to-left and left-to-right typesetting.
12015 Some day we will set |i==4|, when \.{DVI} format makes another
12016 incompatible change---perhaps in the year 2048.)
12017
12018 The next two parameters, |num| and |den|, are positive integers that define
12019 the units of measurement; they are the numerator and denominator of a
12020 fraction by which all dimensions in the \.{DVI} file could be multiplied
12021 in order to get lengths in units of $10^{-7}$ meters. Since $\rm 7227{pt} =
12022 254{cm}$, and since \TeX\ works with scaled points where there are $2^{16}$
12023 sp in a point, \TeX\ sets
12024 $|num|/|den|=(254\cdot10^5)/(7227\cdot2^{16})=25400000/473628672$.
12025 @^sp@>
12026
12027 The |mag| parameter is what \TeX\ calls \.{\\mag}, i.e., 1000 times the
12028 desired magnification. The actual fraction by which dimensions are
12029 multiplied is therefore $|mag|\cdot|num|/1000|den|$. Note that if a \TeX\
12030 source document does not call for any `\.{true}' dimensions, and if you
12031 change it only by specifying a different \.{\\mag} setting, the \.{DVI}
12032 file that \TeX\ creates will be completely unchanged except for the value
12033 of |mag| in the preamble and postamble. (Fancy \.{DVI}-reading programs allow
12034 users to override the |mag|~setting when a \.{DVI} file is being printed.)
12035
12036 Finally, |k| and |x| allow the \.{DVI} writer to include a comment, which is not
12037 interpreted further. The length of comment |x| is |k|, where |0 <= k < 256|.
12038
12039 @d id_byte 2 /*identifies the kind of \.{DVI} files described here*/
12040
12041 @ Font definitions for a given font number |k| contain further parameters
12042 $$\hbox{|c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.}$$
12043 The four-byte value |c| is the check sum that \TeX\ found in the \.{TFM}
12044 file for this font; |c| should match the check sum of the font found by
12045 programs that read this \.{DVI} file.
12046 @^check sum@>
12047
12048 Parameter |s| contains a fixed-point scale factor that is applied to
12049 the character widths in font |k|; font dimensions in \.{TFM} files and
12050 other font files are relative to this quantity, which is called the
12051 ``at size'' elsewhere in this documentation. The value of |s| is
12052 always positive and less than $2^{27}$. It is given in the same units
12053 as the other \.{DVI} dimensions, i.e., in sp when \TeX82 has made the
12054 file. Parameter |d| is similar to |s|; it is the ``design size,'' and
12055 (like~|s|) it is given in \.{DVI} units. Thus, font |k| is to be used
12056 at $|mag|\cdot s/1000d$ times its normal size.
12057
12058 The remaining part of a font definition gives the external name of the font,
12059 which is an ASCII string of length |a+l|. The number |a| is the length
12060 of the ``area'' or directory, and |l| is the length of the font name itself;
12061 the standard local system font area is supposed to be used when |a==0|.
12062 The |n| field contains the area in its first |a| bytes.
12063
12064 Font definitions must appear before the first use of a particular font number.
12065 Once font |k| is defined, it must not be defined again; however, we
12066 shall see below that font definitions appear in the postamble as well as
12067 in the pages, so in this sense each font number is defined exactly twice,
12068 if at all. Like |nop| commands, font definitions can
12069 appear before the first |bop|, or between an |eop| and a |bop|.
12070
12071 @ Sometimes it is desirable to make horizontal or vertical rules line up
12072 precisely with certain features in characters of a font. It is possible to
12073 guarantee the correct matching between \.{DVI} output and the characters
12074 generated by \MF\ by adhering to the following principles: (1)~The \MF\
12075 characters should be positioned so that a bottom edge or left edge that is
12076 supposed to line up with the bottom or left edge of a rule appears at the
12077 reference point, i.e., in row~0 and column~0 of the \MF\ raster. This
12078 ensures that the position of the rule will not be rounded differently when
12079 the pixel size is not a perfect multiple of the units of measurement in
12080 the \.{DVI} file. (2)~A typeset rule of height $a>0$ and width $b>0$
12081 should be equivalent to a \MF-generated character having black pixels in
12082 precisely those raster positions whose \MF\ coordinates satisfy
12083 |0 <= x < @t$\alpha$@>b| and |0 <= y < @t$\alpha$@>a|, where $\alpha$ is the number
12084 of pixels per \.{DVI} unit.
12085 @:METAFONT}{\MF@>
12086 @^alignment of rules with characters@>
12087 @^rules aligning with characters@>
12088
12089 @ The last page in a \.{DVI} file is followed by `|post|'; this command
12090 introduces the postamble, which summarizes important facts that \TeX\ has
12091 accumulated about the file, making it possible to print subsets of the data
12092 with reasonable efficiency. The postamble has the form
12093 $$\vbox{\halign{\hbox{#\hfil}\cr
12094 |post| |p[4]| |num[4]| |den[4]| |mag[4]| |l[4]| |u[4]| |s[2]| |t[2]|\cr
12095 $\langle\,$font definitions$\,\rangle$\cr
12096 |post_post| |q[4]| |i[1]| 223's$[{\G}4]$\cr}}$$
12097 Here |p| is a pointer to the final |bop| in the file. The next three
12098 parameters, |num|, |den|, and |mag|, are duplicates of the quantities that
12099 appeared in the preamble.
12100
12101 Parameters |l| and |u| give respectively the height-plus-depth of the tallest
12102 page and the width of the widest page, in the same units as other dimensions
12103 of the file. These numbers might be used by a \.{DVI}-reading program to
12104 position individual ``pages'' on large sheets of film or paper; however,
12105 the standard convention for output on normal size paper is to position each
12106 page so that the upper left-hand corner is exactly one inch from the left
12107 and the top. Experience has shown that it is unwise to design \.{DVI}-to-printer
12108 software that attempts cleverly to center the output; a fixed position of
12109 the upper left corner is easiest for users to understand and to work with.
12110 Therefore |l| and~|u| are often ignored.
12111
12112 Parameter |s| is the maximum stack depth (i.e., the largest excess of
12113 |push| commands over |pop| commands) needed to process this file. Then
12114 comes |t|, the total number of pages (|bop| commands) present.
12115
12116 The postamble continues with font definitions, which are any number of
12117 \\{fnt\_def} commands as described above, possibly interspersed with |nop|
12118 commands. Each font number that is used in the \.{DVI} file must be defined
12119 exactly twice: Once before it is first selected by a \\{fnt} command, and once
12120 in the postamble.
12121
12122 @ The last part of the postamble, following the |post_post| byte that
12123 signifies the end of the font definitions, contains |q|, a pointer to the
12124 |post| command that started the postamble. An identification byte, |i|,
12125 comes next; this currently equals~2, as in the preamble.
12126
12127 The |i| byte is followed by four or more bytes that are all equal to
12128 the decimal number 223 (i.e., 0337 in octal). \TeX\ puts out four to seven of
12129 these trailing bytes, until the total length of the file is a multiple of
12130 four bytes, since this works out best on machines that pack four bytes per
12131 word; but any number of 223's is allowed, as long as there are at least four
12132 of them. In effect, 223 is a sort of signature that is added at the very end.
12133 @^Fuchs, David Raymond@>
12134
12135 This curious way to finish off a \.{DVI} file makes it feasible for
12136 \.{DVI}-reading programs to find the postamble first, on most computers,
12137 even though \TeX\ wants to write the postamble last. Most operating
12138 systems permit random access to individual words or bytes of a file, so
12139 the \.{DVI} reader can start at the end and skip backwards over the 223's
12140 until finding the identification byte. Then it can back up four bytes, read
12141 |q|, and move to byte |q| of the file. This byte should, of course,
12142 contain the value 248 (|post|); now the postamble can be read, so the
12143 \.{DVI} reader can discover all the information needed for typesetting the
12144 pages. Note that it is also possible to skip through the \.{DVI} file at
12145 reasonably high speed to locate a particular page, if that proves
12146 desirable. This saves a lot of time, since \.{DVI} files used in production
12147 jobs tend to be large.
12148
12149 Unfortunately, however, standard \PASCAL\ does not include the ability to
12150 @^system dependencies@>
12151 access a random position in a file, or even to determine the length of a file.
12152 Almost all systems nowadays provide the necessary capabilities, so \.{DVI}
12153 format has been designed to work most efficiently with modern operating systems.
12154 But if \.{DVI} files have to be processed under the restrictions of standard
12155 \PASCAL, one can simply read them from front to back, since the necessary
12156 header information is present in the preamble and in the font definitions.
12157 (The |l| and |u| and |s| and |t| parameters, which appear only in the
12158 postamble, are ``frills'' that are handy but not absolutely necessary.)
12159
12160 @* Shipping pages out.
12161 After considering \TeX's eyes and stomach, we come now to the bowels.
12162 @^bowels@>
12163
12164 The |ship_out| procedure is given a pointer to a box; its mission is
12165 to describe that box in \.{DVI} form, outputting a ``page'' to |dvi_file|.
12166 The \.{DVI} coordinates $(h,v)=(0,0)$ should correspond to the upper left
12167 corner of the box being shipped.
12168
12169 Since boxes can be inside of boxes inside of boxes, the main work of
12170 |ship_out| is done by two mutually recursive routines, |hlist_out|
12171 and |vlist_out|, which traverse the hlists and vlists inside of horizontal
12172 and vertical boxes.
12173
12174 As individual pages are being processed, we need to accumulate
12175 information about the entire set of pages, since such statistics must be
12176 reported in the postamble. The global variables |total_pages|, |max_v|,
12177 |max_h|, |max_push|, and |last_bop| are used to record this information.
12178
12179 The variable |doing_leaders| is |true| while leaders are being output.
12180 The variable |dead_cycles| contains the number of times an output routine
12181 has been initiated since the last |ship_out|.
12182
12183 A few additional global variables are also defined here for use in
12184 |vlist_out| and |hlist_out|. They could have been local variables, but
12185 that would waste stack space when boxes are deeply nested, since the
12186 values of these variables are not needed during recursive calls.
12187 @^recursion@>
12188
12189 @<Glob...@>=
12190 static int @!total_pages; /*the number of pages that have been shipped out*/
12191 static scaled @!max_v; /*maximum height-plus-depth of pages shipped so far*/
12192 static scaled @!max_h; /*maximum width of pages shipped so far*/
12193 static int @!max_push; /*deepest nesting of |push| commands encountered so far*/
12194 static int @!last_bop; /*location of previous |bop| in the \.{DVI} output*/
12195 static int @!dead_cycles; /*recent outputs that didn't ship anything out*/
12196 static bool @!doing_leaders; /*are we inside a leader box?*/
12197
12198
12199 @ @<Set init...@>=
12200 total_pages=0;max_v=0;max_h=0;max_push=0;last_bop=-1;
12201 doing_leaders=false;dead_cycles=0;
12202
12203
12204
12205 @ @p @t\4@>@<Declare procedures needed in |hlist_out|, |vlist_out|@>@t@>@/
12206
12207
12208 @ The |hlist_out| and |vlist_out| procedures are now complete, so we are
12209 ready for the |ship_out| routine that gets them started in the first place.
12210
12211 @p static void ship_out(pointer @!p) /*output the box |p|*/
12212 {@+
12213 execute_output(p);
12214 flush_node_list(p);
12215 }
12216
12217
12218 @* Packaging.
12219 We're essentially done with the parts of \TeX\ that are concerned with
12220 the input (|get_next|) and the output (|ship_out|). So it's time to
12221 get heavily into the remaining part, which does the real work of typesetting.
12222
12223 After lists are constructed, \TeX\ wraps them up and puts them into boxes.
12224 Two major subroutines are given the responsibility for this task: |hpack|
12225 applies to horizontal lists (hlists) and |vpack| applies to vertical lists
12226 (vlists). The main duty of |hpack| and |vpack| is to compute the dimensions
12227 of the resulting boxes, and to adjust the glue if one of those dimensions
12228 is pre-specified. The computed sizes normally enclose all of the material
12229 inside the new box; but some items may stick out if negative glue is used,
12230 if the box is overfull, or if a \.{\\vbox} includes other boxes that have
12231 been shifted left.
12232
12233 The subroutine call |hpack(p, w, m)| returns a pointer to an |hlist_node|
12234 for a box containing the hlist that starts at |p|. Parameter |w| specifies
12235 a width; and parameter |m| is either `|exactly|' or `|additional|'. Thus,
12236 |hpack(p, w, exactly)| produces a box whose width is exactly |w|, while
12237 |hpack(p, w, additional)| yields a box whose width is the natural width plus
12238 |w|. It is convenient to define a macro called `|natural|' to cover the
12239 most common case, so that we can say |hpack(p, natural)| to get a box that
12240 has the natural width of list |p|.
12241
12242 Similarly, |vpack(p, w, m)| returns a pointer to a |vlist_node| for a
12243 box containing the vlist that starts at |p|. In this case |w| represents
12244 a height instead of a width; the parameter |m| is interpreted as in |hpack|.
12245
12246 @d exactly 0 /*a box dimension is pre-specified*/
12247 @d additional 1 /*a box dimension is increased from the natural one*/
12248 @d natural 0, 0, 0, additional, false /*shorthand for parameters to |hpack| and |vpack|*/
12249
12250 @ The parameters to |hpack| and |vpack| correspond to \TeX's primitives
12251 like `\.{\\hbox} \.{to} \.{300pt}', `\.{\\hbox} \.{spread} \.{10pt}'; note
12252 that `\.{\\hbox}' with no dimension following it is equivalent to
12253 `\.{\\hbox} \.{spread} \.{0pt}'. The |scan_spec| subroutine scans such
12254 constructions in the user's input, including the mandatory left brace that
12255 follows them, and it puts the specification onto |save_stack| so that the
12256 desired box can later be obtained by executing the following code:
12257 $$\vbox{\halign{#\hfil\cr
12258 |save_ptr=save_ptr-2;|\cr
12259 |hpack(p, saved(1), saved(0)).|\cr}}$$
12260 Special care is necessary to ensure that the special |save_stack| codes
12261 are placed just below the new group code, because scanning can change
12262 |save_stack| when \.{\\csname} appears.
12263
12264 @p static void scan_spec(group_code @!c, bool @!three_codes)
12265 /*scans a box specification and left brace*/
12266 {@+
12267 int @!s; /*temporarily saved value*/
12268 int @!spec_code;
12269 if (three_codes) s=saved(0);
12270 if (scan_keyword("to")) spec_code=exactly;
12271 @.to@>
12272 else if (scan_keyword("spread")) spec_code=additional;
12273 @.spread@>
12274 else{@+spec_code=additional;cur_val=cur_hfactor=cur_vfactor=0;
12275 goto found;
12276 }
12277 scan_normal_dimen;
12278 found: if (three_codes)
12279 {@+saved(0)=s;incr(save_ptr);
12280 }
12281 saved(0)=spec_code;saved(1)=cur_val;
12282 saved_hfactor(1)=cur_hfactor;
12283 saved_vfactor(1)=cur_vfactor;
12284 save_ptr=save_ptr+2;
12285 new_save_level(c);scan_left_brace();
12286 }
12287
12288 @ To figure out the glue setting, |hpack| and |vpack| determine how much
12289 stretchability and shrinkability are present, considering all four orders
12290 of infinity. The highest order of infinity that has a nonzero coefficient
12291 is then used as if no other orders were present.
12292
12293 For example, suppose that the given list contains six glue nodes with
12294 the respective stretchabilities 3pt, 8fill, 5fil, 6pt, $-3$fil, $-8$fill.
12295 Then the total is essentially 2fil; and if a total additional space of 6pt
12296 is to be achieved by stretching, the actual amounts of stretch will be
12297 0pt, 0pt, 15pt, 0pt, $-9$pt, and 0pt, since only `fil' glue will be
12298 considered. (The `fill' glue is therefore not really stretching infinitely
12299 with respect to `fil'; nobody would actually want that to happen.)
12300
12301 The arrays |total_stretch| and |total_shrink| are used to determine how much
12302 glue of each kind is present. A global variable |last_badness| is used
12303 to implement \.{\\badness}.
12304
12305 @<Glob...@>=
12306 static scaled @!total_stretch0[filll-normal+1],
12307 *const @!total_stretch = @!total_stretch0-normal,
12308 @!total_shrink0[filll-normal+1], *const @!total_shrink = @!total_shrink0-normal;
12309 /*glue found by |hpack| or |vpack|*/
12310 static int @!last_badness; /*badness of the most recently packaged box*/
12311
12312 @ If the global variable |adjust_tail| is non-null, the |hpack| routine
12313 also removes all occurrences of |ins_node|, |mark_node|, and |adjust_node|
12314 items and appends the resulting material onto the list that ends at
12315 location |adjust_tail|.
12316
12317 @<Glob...@>=
12318 static pointer @!adjust_tail; /*tail of adjustment list*/
12319
12320 @ @<Set init...@>=adjust_tail=null;last_badness=0;
12321
12322 @ Here now is |hpack|, which contains few if any surprises.
12323
12324 @p static pointer hpack(pointer p, scaled w, scaled hf, scaled vf, small_number m, bool keep_cs);
12325
12326 @ @<Clear dimensions to zero@>=
12327 d=0;x=0;
12328 total_stretch[normal]=0;total_shrink[normal]=0;
12329 total_stretch[fil]=0;total_shrink[fil]=0;
12330 total_stretch[fill]=0;total_shrink[fill]=0;
12331 total_stretch[filll]=0;total_shrink[filll]=0
12332
12333
12334 @ @<Make node |p| look like a |char_node| and |goto reswitch|@>=
12335 {@+mem[lig_trick]=mem[lig_char(p)];link(lig_trick)=link(p);
12336 p=lig_trick;goto reswitch;
12337 }
12338
12339 @ The code here implicitly uses the fact that running dimensions are
12340 indicated by |null_flag|, which will be ignored in the calculations
12341 because it is a highly negative number.
12342
12343 @<Incorporate box dimensions into the dimensions of the hbox...@>=
12344 {@+x=x+width(p);
12345 if (type(p) >= rule_node) s=0;@+else s=shift_amount(p);
12346 if (height(p)-s > h) h=height(p)-s;
12347 if (depth(p)+s > d) d=depth(p)+s;
12348 }
12349
12350 @ The following code is part of \TeX's inner loop; i.e., adding another
12351 character of text to the user's input will cause each of these instructions
12352 to be exercised one more time.
12353 @^inner loop@>
12354
12355 @<Incorporate character dimensions into the dimensions of the hbox...@>=
12356 {@+f=font(p);
12357 if (IS_X_FONT(f))
12358 { hb_codepoint_t glyph;
12359 if (x_glyph(f,character(p),&glyph))
12360 { scaled ph, pd;
12361 x+=x_glyph_width(f,glyph);
12362 x_glyph_height_depth(f,glyph,&ph,&pd);
12363 if (ph>h) h=ph;
12364 if (pd>d) d=pd;
12365 }
12366 }
12367 else
12368 { x=x+char_width(f, character(p));@/
12369 s=char_height(f, character(p));@+if (s > h) h=s;
12370 s=char_depth(f, character(p));@+if (s > d) d=s;
12371 }
12372 p=link(p);
12373 }
12374
12375 @ Although node |q| is not necessarily the immediate predecessor of node |p|,
12376 it always points to some node in the list preceding |p|. Thus, we can delete
12377 nodes by moving |q| when necessary. The algorithm takes linear time, and the
12378 extra computation does not intrude on the inner loop unless it is necessary
12379 to make a deletion.
12380 @^inner loop@>
12381
12382 @<Transfer node |p| to the adjustment list@>=
12383 {@+while (link(q)!=p) q=link(q);
12384 if (type(p)==adjust_node)
12385 {@+link(adjust_tail)=adjust_ptr(p);
12386 while (link(adjust_tail)!=null) adjust_tail=link(adjust_tail);
12387 p=link(p);free_node(link(q), small_node_size);
12388 }
12389 else{@+link(adjust_tail)=p;adjust_tail=p;p=link(p);
12390 }
12391 link(q)=p;p=q;
12392 }
12393
12394 @ @<Incorporate glue into the horizontal totals@>=
12395 {@+g=glue_ptr(p);x=x+width(g);@/
12396 o=stretch_order(g);total_stretch[o]=total_stretch[o]+stretch(g);
12397 o=shrink_order(g);total_shrink[o]=total_shrink[o]+shrink(g);
12398 if (subtype(p) >= a_leaders)
12399 {@+g=leader_ptr(p);
12400 if (height(g) > h) h=height(g);
12401 if (depth(g) > d) d=depth(g);
12402 }
12403 }
12404
12405 @ When we get to the present part of the program, |x| is the natural width
12406 of the box being packaged.
12407
12408 @<Determine the value of |width(r)| and the appropriate glue setting...@>=
12409 if (m==additional) w=x+w;
12410 width(r)=w;x=w-x; /*now |x| is the excess to be made up*/
12411 if (x==0)
12412 {@+glue_sign(r)=normal;glue_order(r)=normal;
12413 set_glue_ratio_zero(glue_set(r));
12414 goto end;
12415 }
12416 else if (x > 0) @<Determine horizontal glue stretch setting, then |return|
12417 or \hbox{|goto common_ending|}@>@;
12418 else@<Determine horizontal glue shrink setting, then |return| or \hbox{|goto
12419 common_ending|}@>@;
12420
12421 @ @<Determine horizontal glue stretch setting...@>=
12422 {@+@<Determine the stretch order@>;
12423 glue_order(r)=o;glue_sign(r)=stretching;
12424 if (total_stretch[o]!=0) glue_set(r)=fix(x/(double)total_stretch[o]);
12425 @^real division@>
12426 else{@+glue_sign(r)=normal;
12427 set_glue_ratio_zero(glue_set(r)); /*there's nothing to stretch*/
12428 }
12429 if (o==normal) if (list_ptr(r)!=null)
12430 @<Report an underfull hbox and |goto common_ending|, if this box is sufficiently
12431 bad@>;
12432 goto end;
12433 }
12434
12435 @ @<Determine the stretch order@>=
12436 if (total_stretch[filll]!=0) o=filll;
12437 else if (total_stretch[fill]!=0) o=fill;
12438 else if (total_stretch[fil]!=0) o=fil;
12439 else o=normal
12440
12441 @ @<Report an underfull hbox and |goto common_ending|, if...@>=
12442 {@+last_badness=badness(x, total_stretch[normal]);
12443 if (last_badness > hbadness)
12444 {@+print_ln();
12445 if (last_badness > 100) print_nl("Underfull");@+else print_nl("Loose");
12446 print(" \\hbox (badness ");print_int(last_badness);
12447 @.Underfull \\hbox...@>
12448 @.Loose \\hbox...@>
12449 goto common_ending;
12450 }
12451 }
12452
12453 @ In order to provide a decent indication of where an overfull or underfull
12454 box originated, we use a global variable |pack_begin_line| that is
12455 set nonzero only when |hpack| is being called by the paragraph builder
12456 or the alignment finishing routine.
12457
12458 @<Glob...@>=
12459 static int @!pack_begin_line; /*source file line where the current paragraph
12460 or alignment began; a negative value denotes alignment*/
12461
12462 @ @<Set init...@>=
12463 pack_begin_line=0;
12464
12465 @ @<Determine horizontal glue shrink setting...@>=
12466 {@+@<Determine the shrink order@>;
12467 glue_order(r)=o;glue_sign(r)=shrinking;
12468 if (total_shrink[o]!=0) glue_set(r)=fix((-x)/(double)total_shrink[o]);
12469 @^real division@>
12470 else{@+glue_sign(r)=normal;
12471 set_glue_ratio_zero(glue_set(r)); /*there's nothing to shrink*/
12472 }
12473 if ((total_shrink[o] < -x)&&(o==normal)&&(list_ptr(r)!=null))
12474 {@+last_badness=1000000;
12475 set_glue_ratio_one(glue_set(r)); /*use the maximum shrinkage*/
12476 @<Report an overfull hbox and |goto common_ending|, if this box is sufficiently
12477 bad@>;
12478 }
12479 else if (o==normal) if (list_ptr(r)!=null)
12480 @<Report a tight hbox and |goto common_ending|, if this box is sufficiently
12481 bad@>;
12482 goto end;
12483 }
12484
12485 @ @<Determine the shrink order@>=
12486 if (total_shrink[filll]!=0) o=filll;
12487 else if (total_shrink[fill]!=0) o=fill;
12488 else if (total_shrink[fil]!=0) o=fil;
12489 else o=normal
12490
12491 @ @<Report an overfull hbox and |goto common_ending|, if...@>=
12492 if ((-x-total_shrink[normal] > hfuzz)||(hbadness < 100))
12493 {@+if ((overfull_rule > 0)&&(-x-total_shrink[normal] > hfuzz))
12494 {@+while (link(q)!=null) q=link(q);
12495 link(q)=new_rule();
12496 width(link(q))=overfull_rule;
12497 }
12498 print_ln();print_nl("Overfull \\hbox (");
12499 @.Overfull \\hbox...@>
12500 print_scaled(-x-total_shrink[normal]);print("pt too wide");
12501 goto common_ending;
12502 }
12503
12504 @ @<Report a tight hbox and |goto common_ending|, if...@>=
12505 {@+last_badness=badness(-x, total_shrink[normal]);
12506 if (last_badness > hbadness)
12507 {@+print_ln();print_nl("Tight \\hbox (badness ");print_int(last_badness);
12508 @.Tight \\hbox...@>
12509 goto common_ending;
12510 }
12511 }
12512
12513 @ The |vpack| subroutine is actually a special case of a slightly more
12514 general routine called |vpackage|, which has four parameters. The fourth
12515 parameter, which is |max_dimen| in the case of |vpack|, specifies the
12516 maximum depth of the page box that is constructed. The depth is first
12517 computed by the normal rules; if it exceeds this limit, the reference
12518 point is simply moved down until the limiting depth is attained.
12519
12520
12521 @p
12522 #define vpack(...) @[vpackage(__VA_ARGS__, max_dimen)@] /*special case of unconstrained depth*/
12523 static pointer vpackage(pointer p, scaled h, scaled hf, scaled vf, small_number m, bool keep_cs, scaled l);
12524
12525 @ When a box is being appended to the current vertical list, the
12526 baselineskip calculation is handled by the |append_to_vlist| routine.
12527
12528 @p static void append_to_vlist(pointer @!b)@t\2\2@>@/
12529 { bool height_known;@t\1@>@/
12530 height_known=(type(b)==hlist_node || type(b)==vlist_node ||@|
12531 (type(b)==whatsit_node && subtype(b)==hset_node));@/
12532 if (prev_depth > ignore_depth && height_known)@/
12533 {@+scaled d;@t\1@> /*deficiency of space between baselines*/
12534 pointer @!p; /*a new glue node*/
12535 {@+d=width(baseline_skip)-prev_depth-height(b);
12536 if (d < line_skip_limit) p=new_param_glue(line_skip_code);
12537 else{@+p=new_skip_param(baseline_skip_code);
12538 width(temp_ptr)=d; /*|temp_ptr==glue_ptr(p)|*/
12539 }
12540 link(tail)=p;tail=p;
12541 }@+
12542 } @+ else @+if (prev_depth<=unknown_depth || prev_depth>ignore_depth )@t\2@>@/
12543 {@+pointer p;
12544 p=new_baseline_node(baseline_skip, line_skip, line_skip_limit);
12545 link(tail)= p;tail= p;
12546 }
12547 link(tail)=b;tail=b;
12548 if (height_known)
12549 prev_depth=depth(b);
12550 else if (type(b)==whatsit_node &&
12551 (subtype(b)==hpack_node || subtype(b)==vpack_node))
12552 prev_depth=depth(b); /* then also depth is (probably) known */
12553 else if (type(b)==whatsit_node && subtype(b)==image_node)
12554 prev_depth=0;
12555 else
12556 prev_depth=unknown_depth;
12557 }
12558
12559 @* Data structures for math mode.
12560 When \TeX\ reads a formula that is enclosed between \.\$'s, it constructs an
12561 {\sl mlist}, which is essentially a tree structure representing that
12562 formula. An mlist is a linear sequence of items, but we can regard it as
12563 a tree structure because mlists can appear within mlists. For example, many
12564 of the entries can be subscripted or superscripted, and such ``scripts''
12565 are mlists in their own right.
12566
12567 An entire formula is parsed into such a tree before any of the actual
12568 typesetting is done, because the current style of type is usually not
12569 known until the formula has been fully scanned. For example, when the
12570 formula `\.{\$a+b \\over c+d\$}' is being read, there is no way to tell
12571 that `\.{a+b}' will be in script size until `\.{\\over}' has appeared.
12572
12573 During the scanning process, each element of the mlist being built is
12574 classified as a relation, a binary operator, an open parenthesis, etc.,
12575 or as a construct like `\.{\\sqrt}' that must be built up. This classification
12576 appears in the mlist data structure.
12577
12578 After a formula has been fully scanned, the mlist is converted to an hlist
12579 so that it can be incorporated into the surrounding text. This conversion is
12580 controlled by a recursive procedure that decides all of the appropriate
12581 styles by a ``top-down'' process starting at the outermost level and working
12582 in towards the subformulas. The formula is ultimately pasted together using
12583 combinations of horizontal and vertical boxes, with glue and penalty nodes
12584 inserted as necessary.
12585
12586 An mlist is represented internally as a linked list consisting chiefly
12587 of ``noads'' (pronounced ``no-adds''), to distinguish them from the somewhat
12588 similar ``nodes'' in hlists and vlists. Certain kinds of ordinary nodes are
12589 allowed to appear in mlists together with the noads; \TeX\ tells the difference
12590 by means of the |type| field, since a noad's |type| is always greater than
12591 that of a node. An mlist does not contain character nodes, hlist nodes, vlist
12592 nodes, math nodes, ligature nodes,
12593 or unset nodes; in particular, each mlist item appears in the
12594 variable-size part of |mem|, so the |type| field is always present.
12595
12596 @ Each noad is four or more words long. The first word contains the |type|
12597 and |subtype| and |link| fields that are already so familiar to us; the
12598 second, third, and fourth words are called the noad's |nucleus|, |subscr|,
12599 and |supscr| fields.
12600
12601 Consider, for example, the simple formula `\.{\$x\^2\$}', which would be
12602 parsed into an mlist containing a single element called an |ord_noad|.
12603 The |nucleus| of this noad is a representation of `\.x', the |subscr| is
12604 empty, and the |supscr| is a representation of `\.2'.
12605
12606 The |nucleus|, |subscr|, and |supscr| fields are further broken into
12607 subfields. If |p| points to a noad, and if |q| is one of its principal
12608 fields (e.g., |q==subscr(p)|), there are several possibilities for the
12609 subfields, depending on the |math_type| of |q|.
12610
12611 \yskip\hang|math_type(q)==math_char| means that |fam(q)| refers to one of
12612 the sixteen font families, and |character(q)| is the number of a character
12613 within a font of that family, as in a character node.
12614
12615 \yskip\hang|math_type(q)==math_text_char| is similar, but the character is
12616 unsubscripted and unsuperscripted and it is followed immediately by another
12617 character from the same font. (This |math_type| setting appears only
12618 briefly during the processing; it is used to suppress unwanted italic
12619 corrections.)
12620
12621 \yskip\hang|math_type(q)==empty| indicates a field with no value (the
12622 corresponding attribute of noad |p| is not present).
12623
12624 \yskip\hang|math_type(q)==sub_box| means that |info(q)| points to a box
12625 node (either an |hlist_node| or a |vlist_node|) that should be used as the
12626 value of the field. The |shift_amount| in the subsidiary box node is the
12627 amount by which that box will be shifted downward.
12628
12629 \yskip\hang|math_type(q)==sub_mlist| means that |info(q)| points to
12630 an mlist; the mlist must be converted to an hlist in order to obtain
12631 the value of this field.
12632
12633 \yskip\noindent In the latter case, we might have |info(q)==null|. This
12634 is not the same as |math_type(q)==empty|; for example, `\.{\$P\_\{\}\$}'
12635 and `\.{\$P\$}' produce different results (the former will not have the
12636 ``italic correction'' added to the width of |P|, but the ``script skip''
12637 will be added).
12638
12639 The definitions of subfields given here are evidently wasteful of space,
12640 since a halfword is being used for the |math_type| although only three
12641 bits would be needed. However, there are hardly ever many noads present at
12642 once, since they are soon converted to nodes that take up even more space,
12643 so we can afford to represent them in whatever way simplifies the
12644 programming.
12645
12646 @d noad_size 4 /*number of words in a normal noad*/
12647 @d nucleus(A) A+1 /*the |nucleus| field of a noad*/
12648 @d supscr(A) A+2 /*the |supscr| field of a noad*/
12649 @d subscr(A) A+3 /*the |subscr| field of a noad*/
12650 @d math_type(A) link(A) /*a |halfword| in |mem|*/
12651 @d fam font /*a |quarterword| in |mem|*/
12652 @d math_char 1 /*|math_type| when the attribute is simple*/
12653 @d sub_box 2 /*|math_type| when the attribute is a box*/
12654 @d sub_mlist 3 /*|math_type| when the attribute is a formula*/
12655 @d math_text_char 4 /*|math_type| when italic correction is dubious*/
12656
12657 @ Each portion of a formula is classified as Ord, Op, Bin, Rel, Open,
12658 Close, Punct, or Inner, for purposes of spacing and line breaking. An
12659 |ord_noad|, |op_noad|, |bin_noad|, |rel_noad|, |open_noad|, |close_noad|,
12660 |punct_noad|, or |inner_noad| is used to represent portions of the various
12661 types. For example, an `\.=' sign in a formula leads to the creation of a
12662 |rel_noad| whose |nucleus| field is a representation of an equals sign
12663 (usually |fam==0|, |character==075|). A formula preceded by \.{\\mathrel}
12664 also results in a |rel_noad|. When a |rel_noad| is followed by an
12665 |op_noad|, say, and possibly separated by one or more ordinary nodes (not
12666 noads), \TeX\ will insert a penalty node (with the current |rel_penalty|)
12667 just after the formula that corresponds to the |rel_noad|, unless there
12668 already was a penalty immediately following; and a ``thick space'' will be
12669 inserted just before the formula that corresponds to the |op_noad|.
12670
12671 A noad of type |ord_noad|, |op_noad|, \dots, |inner_noad| usually
12672 has a |subtype==normal|. The only exception is that an |op_noad| might
12673 have |subtype==limits| or |no_limits|, if the normal positioning of
12674 limits has been overridden for this operator.
12675
12676 @d ord_noad (unset_node+3) /*|type| of a noad classified Ord*/
12677 @d op_noad (ord_noad+1) /*|type| of a noad classified Op*/
12678 @d bin_noad (ord_noad+2) /*|type| of a noad classified Bin*/
12679 @d rel_noad (ord_noad+3) /*|type| of a noad classified Rel*/
12680 @d open_noad (ord_noad+4) /*|type| of a noad classified Open*/
12681 @d close_noad (ord_noad+5) /*|type| of a noad classified Close*/
12682 @d punct_noad (ord_noad+6) /*|type| of a noad classified Punct*/
12683 @d inner_noad (ord_noad+7) /*|type| of a noad classified Inner*/
12684 @d limits 1 /*|subtype| of |op_noad| whose scripts are to be above, below*/
12685 @d no_limits 2 /*|subtype| of |op_noad| whose scripts are to be normal*/
12686
12687 @ A |radical_noad| is five words long; the fifth word is the |left_delimiter|
12688 field, which usually represents a square root sign.
12689
12690 A |fraction_noad| is six words long; it has a |right_delimiter| field
12691 as well as a |left_delimiter|.
12692
12693 Delimiter fields are of type |four_quarters|, and they have four subfields
12694 called |small_fam|, |small_char|, |large_fam|, |large_char|. These subfields
12695 represent variable-size delimiters by giving the ``small'' and ``large''
12696 starting characters, as explained in Chapter~17 of {\sl The \TeX book}.
12697 @:TeXbook}{\sl The \TeX book@>
12698
12699 A |fraction_noad| is actually quite different from all other noads. Not
12700 only does it have six words, it has |thickness|, |denominator|, and
12701 |numerator| fields instead of |nucleus|, |subscr|, and |supscr|. The
12702 |thickness| is a scaled value that tells how thick to make a fraction
12703 rule; however, the special value |default_code| is used to stand for the
12704 |default_rule_thickness| of the current size. The |numerator| and
12705 |denominator| point to mlists that define a fraction; we always have
12706 $$\hbox{|math_type(numerator)==math_type(denominator)==sub_mlist|}.$$ The
12707 |left_delimiter| and |right_delimiter| fields specify delimiters that will
12708 be placed at the left and right of the fraction. In this way, a
12709 |fraction_noad| is able to represent all of \TeX's operators \.{\\over},
12710 \.{\\atop}, \.{\\above}, \.{\\overwithdelims}, \.{\\atopwithdelims}, and
12711 \.{\\abovewithdelims}.
12712
12713 @d left_delimiter(A) A+4 /*first delimiter field of a noad*/
12714 @d right_delimiter(A) A+5 /*second delimiter field of a fraction noad*/
12715 @d radical_noad (inner_noad+1) /*|type| of a noad for square roots*/
12716 @d radical_noad_size 5 /*number of |mem| words in a radical noad*/
12717 @d fraction_noad (radical_noad+1) /*|type| of a noad for generalized fractions*/
12718 @d fraction_noad_size 6 /*number of |mem| words in a fraction noad*/
12719 @d small_fam(A) mem[A].qqqq.b0 /*|fam| for ``small'' delimiter*/
12720 @d small_char(A) mem[A].qqqq.b1 /*|character| for ``small'' delimiter*/
12721 @d large_fam(A) mem[A].qqqq.b2 /*|fam| for ``large'' delimiter*/
12722 @d large_char(A) mem[A].qqqq.b3 /*|character| for ``large'' delimiter*/
12723 @d thickness(A) width(A) /*|thickness| field in a fraction noad*/
12724 @d default_code 010000000000 /*denotes |default_rule_thickness|*/
12725 @d numerator(A) supscr(A) /*|numerator| field in a fraction noad*/
12726 @d denominator(A) subscr(A) /*|denominator| field in a fraction noad*/
12727
12728 @ The global variable |empty_field| is set up for initialization of empty
12729 fields in new noads. Similarly, |null_delimiter| is for the initialization
12730 of delimiter fields.
12731
12732 @<Glob...@>=
12733 static two_halves @!empty_field;
12734 static four_quarters @!null_delimiter;
12735
12736 @ @<Set init...@>=
12737 empty_field.rh=empty;empty_field.lh=null;@/
12738 null_delimiter.b0=0;null_delimiter.b1=min_quarterword;@/
12739 null_delimiter.b2=0;null_delimiter.b3=min_quarterword;
12740
12741 @ The |new_noad| function creates an |ord_noad| that is completely null.
12742
12743 @p static pointer new_noad(void)
12744 {@+pointer p;
12745 p=get_node(noad_size);
12746 type(p)=ord_noad;subtype(p)=normal;
12747 mem[nucleus(p)].hh=empty_field;
12748 mem[subscr(p)].hh=empty_field;
12749 mem[supscr(p)].hh=empty_field;
12750 return p;
12751 }
12752
12753 @ A few more kinds of noads will complete the set: An |under_noad| has its
12754 nucleus underlined; an |over_noad| has it overlined. An |accent_noad| places
12755 an accent over its nucleus; the accent character appears as
12756 |fam(accent_chr(p))| and |character(accent_chr(p))|. A |vcenter_noad|
12757 centers its nucleus vertically with respect to the axis of the formula;
12758 in such noads we always have |math_type(nucleus(p))==sub_box|.
12759
12760 And finally, we have |left_noad| and |right_noad| types, to implement
12761 \TeX's \.{\\left} and \.{\\right} as well as \eTeX's \.{\\middle}.
12762 The |nucleus| of such noads is
12763 replaced by a |delimiter| field; thus, for example, `\.{\\left(}' produces
12764 a |left_noad| such that |delimiter(p)| holds the family and character
12765 codes for all left parentheses. A |left_noad| never appears in an mlist
12766 except as the first element, and a |right_noad| never appears in an mlist
12767 except as the last element; furthermore, we either have both a |left_noad|
12768 and a |right_noad|, or neither one is present. The |subscr| and |supscr|
12769 fields are always |empty| in a |left_noad| and a |right_noad|.
12770
12771 @d under_noad (fraction_noad+1) /*|type| of a noad for underlining*/
12772 @d over_noad (under_noad+1) /*|type| of a noad for overlining*/
12773 @d accent_noad (over_noad+1) /*|type| of a noad for accented subformulas*/
12774 @d accent_noad_size 5 /*number of |mem| words in an accent noad*/
12775 @d accent_chr(A) A+4 /*the |accent_chr| field of an accent noad*/
12776 @d vcenter_noad (accent_noad+1) /*|type| of a noad for \.{\\vcenter}*/
12777 @d left_noad (vcenter_noad+1) /*|type| of a noad for \.{\\left}*/
12778 @d right_noad (left_noad+1) /*|type| of a noad for \.{\\right}*/
12779 @d delimiter(A) nucleus(A) /*|delimiter| field in left and right noads*/
12780 @d middle_noad 1 /*|subtype| of right noad representing \.{\\middle}*/
12781 @d scripts_allowed(A) (type(A) >= ord_noad)&&(type(A) < left_noad)
12782
12783 @ Math formulas can also contain instructions like \.{\\textstyle} that
12784 override \TeX's normal style rules. A |style_node| is inserted into the
12785 data structure to record such instructions; it is three words long, so it
12786 is considered a node instead of a noad. The |subtype| is either |display_style|
12787 or |text_style| or |script_style| or |script_script_style|. The
12788 second and third words of a |style_node| are not used, but they are
12789 present because a |choice_node| is converted to a |style_node|.
12790
12791 \TeX\ uses even numbers 0, 2, 4, 6 to encode the basic styles
12792 |display_style|, \dots, |script_script_style|, and adds~1 to get the
12793 ``cramped'' versions of these styles. This gives a numerical order that
12794 is backwards from the convention of Appendix~G in {\sl The \TeX book\/};
12795 i.e., a smaller style has a larger numerical value.
12796 @:TeXbook}{\sl The \TeX book@>
12797
12798 @d style_node (unset_node+1) /*|type| of a style node*/
12799 @d style_node_size 3 /*number of words in a style node*/
12800 @d display_style 0 /*|subtype| for \.{\\displaystyle}*/
12801 @d text_style 2 /*|subtype| for \.{\\textstyle}*/
12802 @d script_style 4 /*|subtype| for \.{\\scriptstyle}*/
12803 @d script_script_style 6 /*|subtype| for \.{\\scriptscriptstyle}*/
12804 @d cramped 1 /*add this to an uncramped style if you want to cramp it*/
12805
12806 @p static pointer new_style(small_number @!s) /*create a style node*/
12807 {@+pointer p; /*the new node*/
12808 p=get_node(style_node_size);type(p)=style_node;
12809 subtype(p)=s;width(p)=0;depth(p)=0; /*the |width| and |depth| are not used*/
12810 return p;
12811 }
12812
12813 @ Finally, the \.{\\mathchoice} primitive creates a |choice_node|, which
12814 has special subfields |display_mlist|, |text_mlist|, |script_mlist|,
12815 and |script_script_mlist| pointing to the mlists for each style.
12816
12817 @d choice_node (unset_node+2) /*|type| of a choice node*/
12818 @d display_mlist(A) info(A+1) /*mlist to be used in display style*/
12819 @d text_mlist(A) link(A+1) /*mlist to be used in text style*/
12820 @d script_mlist(A) info(A+2) /*mlist to be used in script style*/
12821 @d script_script_mlist(A) link(A+2) /*mlist to be used in scriptscript style*/
12822
12823 @p static pointer new_choice(void) /*create a choice node*/
12824 {@+pointer p; /*the new node*/
12825 p=get_node(style_node_size);type(p)=choice_node;
12826 subtype(p)=0; /*the |subtype| is not used*/
12827 display_mlist(p)=null;text_mlist(p)=null;script_mlist(p)=null;
12828 script_script_mlist(p)=null;
12829 return p;
12830 }
12831
12832 @ Let's consider now the previously unwritten part of |show_node_list|
12833 that displays the things that can only be present in mlists; this
12834 program illustrates how to access the data structures just defined.
12835
12836 In the context of the following program, |p| points to a node or noad that
12837 should be displayed, and the current string contains the ``recursion history''
12838 that leads to this point. The recursion history consists of a dot for each
12839 outer level in which |p| is subsidiary to some node, or in which |p| is
12840 subsidiary to the |nucleus| field of some noad; the dot is replaced by
12841 `\.\_' or `\.\^' or `\./' or `\.\\' if |p| is descended from the |subscr|
12842 or |supscr| or |denominator| or |numerator| fields of noads. For example,
12843 the current string would be `\.{.\^.\_/}' if |p| points to the |ord_noad| for
12844 |x| in the (ridiculous) formula
12845 `\.{\$\\sqrt\{a\^\{\\mathinner\{b\_\{c\\over x+y\}\}\}\}\$}'.
12846
12847 @<Cases of |show_node_list| that arise...@>=
12848 case style_node: print_style(subtype(p));@+break;
12849 case choice_node: @<Display choice node |p|@>@;@+break;
12850 case ord_noad: case op_noad: case bin_noad:
12851 case rel_noad: case open_noad: case close_noad:
12852 case punct_noad: case inner_noad:
12853 case radical_noad: case over_noad: case under_noad:
12854 case vcenter_noad: case accent_noad:
12855 case left_noad: case right_noad: @<Display normal noad |p|@>@;@+break;
12856 case fraction_noad: @<Display fraction noad |p|@>@;@+break;
12857
12858 @ Here are some simple routines used in the display of noads.
12859
12860 @<Declare procedures needed for displaying the elements of mlists@>=
12861 static void print_fam_and_char(pointer @!p) /*prints family and character*/
12862 {@+print_esc("fam");print_int(fam(p));print_char(' ');
12863 print_ASCII(qo(character(p)));
12864 }
12865 @#
12866 static void print_delimiter(pointer @!p) /*prints a delimiter as 24-bit hex value*/
12867 {@+int a; /*accumulator*/
12868 a=small_fam(p)*256+qo(small_char(p));
12869 a=a*0x1000+large_fam(p)*256+qo(large_char(p));
12870 if (a < 0) print_int(a); /*this should never happen*/
12871 else print_hex(a);
12872 }
12873
12874 @ The next subroutine will descend to another level of recursion when a
12875 subsidiary mlist needs to be displayed. The parameter |c| indicates what
12876 character is to become part of the recursion history. An empty mlist is
12877 distinguished from a field with |math_type(p)==empty|, because these are
12878 not equivalent (as explained above).
12879 @^recursion@>
12880
12881 @<Declare procedures needed for displaying...@>=
12882 static void show_info(void); /*|show_node_list(info(temp_ptr))|*/
12883 static void print_subsidiary_data(pointer @!p, UTF8_code @!c)
12884 /*display a noad field*/
12885 {@+if (cur_length >= depth_threshold)
12886 {@+if (math_type(p)!=empty) print(" []");
12887 }
12888 else{@+append_char(c); /*include |c| in the recursion history*/
12889 temp_ptr=p; /*prepare for |show_info| if recursion is needed*/
12890 switch (math_type(p)) {
12891 case math_char: {@+print_ln();print_current_string();print_fam_and_char(p);
12892 } @+break;
12893 case sub_box: show_info();@+break; /*recursive call*/
12894 case sub_mlist: if (info(p)==null)
12895 {@+print_ln();print_current_string();print("{}");
12896 }
12897 else show_info();@+break; /*recursive call*/
12898 default:do_nothing; /*|empty|*/
12899 } @/
12900 flush_char; /*remove |c| from the recursion history*/
12901 }
12902 }
12903
12904 @ The inelegant introduction of |show_info| in the code above seems better
12905 than the alternative of using \PASCAL's strange |forward| declaration for a
12906 procedure with parameters. The \PASCAL\ convention about dropping parameters
12907 from a post-|forward| procedure is, frankly, so intolerable to the author
12908 of \TeX\ that he would rather stoop to communication via a global temporary
12909 variable. (A similar stoopidity occurred with respect to |hlist_out| and
12910 |vlist_out| above, and it will occur with respect to |mlist_to_hlist| below.)
12911 @^Knuth, Donald Ervin@>
12912 @:PASCAL}{\PASCAL@>
12913
12914 @p static void show_info(void) /*the reader will kindly forgive this*/
12915 {@+show_node_list(info(temp_ptr));
12916 }
12917
12918 @ @<Declare procedures needed for displaying...@>=
12919 static void print_style(int @!c)
12920 {@+switch (c/2) {
12921 case 0: print_esc("displaystyle");@+break; /*|display_style==0|*/
12922 case 1: print_esc("textstyle");@+break; /*|text_style==2|*/
12923 case 2: print_esc("scriptstyle");@+break; /*|script_style==4|*/
12924 case 3: print_esc("scriptscriptstyle");@+break; /*|script_script_style==6|*/
12925 default:print("Unknown style!");
12926 }
12927 }
12928
12929 @ @<Display choice node |p|@>=
12930 {@+print_esc("mathchoice");
12931 append_char('D');show_node_list(display_mlist(p));flush_char;
12932 append_char('T');show_node_list(text_mlist(p));flush_char;
12933 append_char('S');show_node_list(script_mlist(p));flush_char;
12934 append_char('s');show_node_list(script_script_mlist(p));flush_char;
12935 }
12936
12937 @ @<Display normal noad |p|@>=
12938 {@+switch (type(p)) {
12939 case ord_noad: print_esc("mathord");@+break;
12940 case op_noad: print_esc("mathop");@+break;
12941 case bin_noad: print_esc("mathbin");@+break;
12942 case rel_noad: print_esc("mathrel");@+break;
12943 case open_noad: print_esc("mathopen");@+break;
12944 case close_noad: print_esc("mathclose");@+break;
12945 case punct_noad: print_esc("mathpunct");@+break;
12946 case inner_noad: print_esc("mathinner");@+break;
12947 case over_noad: print_esc("overline");@+break;
12948 case under_noad: print_esc("underline");@+break;
12949 case vcenter_noad: print_esc("vcenter");@+break;
12950 case radical_noad: {@+print_esc("radical");print_delimiter(left_delimiter(p));
12951 } @+break;
12952 case accent_noad: {@+print_esc("accent");print_fam_and_char(accent_chr(p));
12953 } @+break;
12954 case left_noad: {@+print_esc("left");print_delimiter(delimiter(p));
12955 } @+break;
12956 case right_noad: {@+if (subtype(p)==normal) print_esc("right");
12957 else print_esc("middle");
12958 print_delimiter(delimiter(p));
12959 }
12960 }
12961 if (type(p) < left_noad)
12962 {@+if (subtype(p)!=normal)
12963 if (subtype(p)==limits) print_esc("limits");
12964 else print_esc("nolimits");
12965 print_subsidiary_data(nucleus(p),'.');
12966 }
12967 print_subsidiary_data(supscr(p),'^');
12968 print_subsidiary_data(subscr(p),'_');
12969 }
12970
12971 @ @<Display fraction noad |p|@>=
12972 {@+print_esc("fraction, thickness ");
12973 if (thickness(p)==default_code) print("= default");
12974 else print_scaled(thickness(p));
12975 if ((small_fam(left_delimiter(p))!=0)||@+
12976 (small_char(left_delimiter(p))!=min_quarterword)||@|
12977 (large_fam(left_delimiter(p))!=0)||@|
12978 (large_char(left_delimiter(p))!=min_quarterword))
12979 {@+print(", left-delimiter ");print_delimiter(left_delimiter(p));
12980 }
12981 if ((small_fam(right_delimiter(p))!=0)||@|
12982 (small_char(right_delimiter(p))!=min_quarterword)||@|
12983 (large_fam(right_delimiter(p))!=0)||@|
12984 (large_char(right_delimiter(p))!=min_quarterword))
12985 {@+print(", right-delimiter ");print_delimiter(right_delimiter(p));
12986 }
12987 print_subsidiary_data(numerator(p),'\\');
12988 print_subsidiary_data(denominator(p),'/');
12989 }
12990
12991 @ That which can be displayed can also be destroyed.
12992
12993 @<Cases of |flush_node_list| that arise...@>=
12994 case style_node: {@+free_node(p, style_node_size);goto done;
12995 }
12996 case choice_node: {@+flush_node_list(display_mlist(p));
12997 flush_node_list(text_mlist(p));
12998 flush_node_list(script_mlist(p));
12999 flush_node_list(script_script_mlist(p));
13000 free_node(p, style_node_size);goto done;
13001 }
13002 case ord_noad: case op_noad: case bin_noad:
13003 case rel_noad: case open_noad: case close_noad:
13004 case punct_noad: case inner_noad:
13005 case radical_noad: case over_noad: case under_noad:
13006 case vcenter_noad: case accent_noad: @t@>@;@/
13007 {@+if (math_type(nucleus(p)) >= sub_box)
13008 flush_node_list(info(nucleus(p)));
13009 if (math_type(supscr(p)) >= sub_box)
13010 flush_node_list(info(supscr(p)));
13011 if (math_type(subscr(p)) >= sub_box)
13012 flush_node_list(info(subscr(p)));
13013 if (type(p)==radical_noad) free_node(p, radical_noad_size);
13014 else if (type(p)==accent_noad) free_node(p, accent_noad_size);
13015 else free_node(p, noad_size);
13016 goto done;
13017 }
13018 case left_noad: case right_noad: {@+free_node(p, noad_size);goto done;
13019 }
13020 case fraction_noad: {@+flush_node_list(info(numerator(p)));
13021 flush_node_list(info(denominator(p)));
13022 free_node(p, fraction_noad_size);goto done;
13023 }
13024
13025 @* Subroutines for math mode.
13026 In order to convert mlists to hlists, i.e., noads to nodes, we need several
13027 subroutines that are conveniently dealt with now.
13028
13029 Let us first introduce the macros that make it easy to get at the parameters and
13030 other font information. A size code, which is a multiple of 16, is added to a
13031 family number to get an index into the table of internal font numbers
13032 for each combination of family and size. (Be alert: Size codes get
13033 larger as the type gets smaller.)
13034
13035 @d text_size 0 /*size code for the largest size in a family*/
13036 @d script_size 16 /*size code for the medium size in a family*/
13037 @d script_script_size 32 /*size code for the smallest size in a family*/
13038
13039 @<Basic printing procedures@>=
13040 static void print_size(int @!s)
13041 {@+if (s==text_size) print_esc("textfont");
13042 else if (s==script_size) print_esc("scriptfont");
13043 else print_esc("scriptscriptfont");
13044 }
13045
13046 @ Before an mlist is converted to an hlist, \TeX\ makes sure that
13047 the fonts in family~2 have enough parameters to be math-symbol
13048 fonts, and that the fonts in family~3 have enough parameters to be
13049 math-extension fonts. The math-symbol parameters are referred to by using the
13050 following macros, which take a size code as their parameter; for example,
13051 |num1(cur_size)| gives the value of the |num1| parameter for the current size.
13052 @^parameters for symbols@>
13053 @^font parameters@>
13054
13055 @d mathsy_end(A) fam_fnt(2+A)]].sc
13056 @d mathsy(A) font_info[A+param_base[mathsy_end
13057 @d math_x_height mathsy(5) /*height of `\.x'*/
13058 @d math_quad mathsy(6) /*\.{18mu}*/
13059 @d num1 mathsy(8) /*numerator shift-up in display styles*/
13060 @d num2 mathsy(9) /*numerator shift-up in non-display, non-\.{\\atop}*/
13061 @d num3 mathsy(10) /*numerator shift-up in non-display \.{\\atop}*/
13062 @d denom1 mathsy(11) /*denominator shift-down in display styles*/
13063 @d denom2 mathsy(12) /*denominator shift-down in non-display styles*/
13064 @d sup1 mathsy(13) /*superscript shift-up in uncramped display style*/
13065 @d sup2 mathsy(14) /*superscript shift-up in uncramped non-display*/
13066 @d sup3 mathsy(15) /*superscript shift-up in cramped styles*/
13067 @d sub1 mathsy(16) /*subscript shift-down if superscript is absent*/
13068 @d sub2 mathsy(17) /*subscript shift-down if superscript is present*/
13069 @d sup_drop mathsy(18) /*superscript baseline below top of large box*/
13070 @d sub_drop mathsy(19) /*subscript baseline below bottom of large box*/
13071 @d delim1 mathsy(20) /*size of \.{\\atopwithdelims} delimiters
13072 in display styles*/
13073 @d delim2 mathsy(21) /*size of \.{\\atopwithdelims} delimiters in non-displays*/
13074 @d axis_height mathsy(22) /*height of fraction lines above the baseline*/
13075 @d total_mathsy_params 22
13076
13077 @ The math-extension parameters have similar macros, but the size code is
13078 omitted (since it is always |cur_size| when we refer to such parameters).
13079 @^parameters for symbols@>
13080 @^font parameters@>
13081
13082 @d mathex(A) font_info[A+param_base[fam_fnt(3+cur_size)]].sc
13083 @d default_rule_thickness mathex(8) /*thickness of \.{\\over} bars*/
13084 @d big_op_spacing1 mathex(9) /*minimum clearance above a displayed op*/
13085 @d big_op_spacing2 mathex(10) /*minimum clearance below a displayed op*/
13086 @d big_op_spacing3 mathex(11) /*minimum baselineskip above displayed op*/
13087 @d big_op_spacing4 mathex(12) /*minimum baselineskip below displayed op*/
13088 @d big_op_spacing5 mathex(13) /*padding above and below displayed limits*/
13089 @d total_mathex_params 13
13090
13091 @ We also need to compute the change in style between mlists and their
13092 subsidiaries. The following macros define the subsidiary style for
13093 an overlined nucleus (|cramped_style|), for a subscript or a superscript
13094 (|sub_style| or |sup_style|), or for a numerator or denominator (|num_style|
13095 or |denom_style|).
13096
13097 @d cramped_style(A) 2*(A/2)+cramped /*cramp the style*/
13098 @d sub_style(A) 2*(A/4)+script_style+cramped /*smaller and cramped*/
13099 @d sup_style(A) 2*(A/4)+script_style+(A%2) /*smaller*/
13100 @d num_style(A) A+2-2*(A/6) /*smaller unless already script-script*/
13101 @d denom_style(A) 2*(A/2)+cramped+2-2*(A/6) /*smaller, cramped*/
13102
13103 @ When the style changes, the following piece of program computes associated
13104 information:
13105
13106 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>=
13107 {@+if (cur_style < script_style) cur_size=text_size;
13108 else cur_size=16*((cur_style-text_style)/2);
13109 cur_mu=x_over_n(math_quad(cur_size), 18);
13110 }
13111
13112 @ Here is a function that returns a pointer to a rule node having a given
13113 thickness |t|. The rule will extend horizontally to the boundary of the vlist
13114 that eventually contains it.
13115
13116 @p static pointer fraction_rule(scaled @!t)
13117 /*construct the bar for a fraction*/
13118 {@+pointer p; /*the new node*/
13119 p=new_rule();height(p)=t;depth(p)=0;return p;
13120 }
13121
13122 @ The |overbar| function returns a pointer to a vlist box that consists of
13123 a given box |b|, above which has been placed a kern of height |k| under a
13124 fraction rule of thickness |t| under additional space of height |t|.
13125
13126 @p static pointer overbar(pointer @!b, scaled @!k, scaled @!t)
13127 {@+pointer p, @!q; /*nodes being constructed*/
13128 p=new_kern(k);link(p)=b;q=fraction_rule(t);link(q)=p;
13129 p=new_kern(t);link(p)=q;return vpack(p, natural);
13130 }
13131
13132 @ The |var_delimiter| function, which finds or constructs a sufficiently
13133 large delimiter, is the most interesting of the auxiliary functions that
13134 currently concern us. Given a pointer |d| to a delimiter field in some noad,
13135 together with a size code |s| and a vertical distance |v|, this function
13136 returns a pointer to a box that contains the smallest variant of |d| whose
13137 height plus depth is |v| or more. (And if no variant is large enough, it
13138 returns the largest available variant.) In particular, this routine will
13139 construct arbitrarily large delimiters from extensible components, if
13140 |d| leads to such characters.
13141
13142 The value returned is a box whose |shift_amount| has been set so that
13143 the box is vertically centered with respect to the axis in the given size.
13144 If a built-up symbol is returned, the height of the box before shifting
13145 will be the height of its topmost component.
13146
13147 @p @t\4@>@<Declare subprocedures for |var_delimiter|@>@;
13148 static pointer var_delimiter(pointer @!d, small_number @!s, scaled @!v)
13149 {@+
13150 pointer b; /*the box that will be constructed*/
13151 internal_font_number @!f, @!g; /*best-so-far and tentative font codes*/
13152 int @!c, @!x, @!y; /*best-so-far and tentative character codes*/
13153 int @!m, @!n; /*the number of extensible pieces*/
13154 scaled @!u; /*height-plus-depth of a tentative character*/
13155 scaled @!w; /*largest height-plus-depth so far*/
13156 four_quarters @!q; /*character info*/
13157 four_quarters @!r; /*extensible pieces*/
13158 small_number @!z; /*runs through font family members*/
13159 bool @!large_attempt; /*are we trying the ``large'' variant?*/
13160 f=null_font;w=0;large_attempt=false;
13161 z=small_fam(d);x=small_char(d);
13162 loop@+{@+@<Look at the variants of |(z,x)|; set |f| and |c| whenever a better
13163 character is found; |goto found| as soon as a large enough variant is encountered@>;
13164 if (large_attempt) goto found; /*there were none large enough*/
13165 large_attempt=true;z=large_fam(d);x=large_char(d);
13166 }
13167 found: if (f!=null_font)
13168 @<Make variable |b| point to a box for |(f,c)|@>;
13169 else{@+b=new_null_box();
13170 width(b)=null_delimiter_space; /*use this width if no delimiter was found*/
13171 }
13172 shift_amount(b)=half(height(b)-depth(b))-axis_height(s);
13173 return b;
13174 }
13175
13176 @ The search process is complicated slightly by the facts that some of the
13177 characters might not be present in some of the fonts, and they might not
13178 be probed in increasing order of height.
13179
13180 @<Look at the variants of |(z,x)|; set |f| and |c|...@>=
13181 if ((z!=0)||(x!=min_quarterword))
13182 {@+z=z+s+16;
13183 @/do@+{z=z-16;g=fam_fnt(z);
13184 if (g!=null_font)
13185 @<Look at the list of characters starting with |x| in font |g|; set |f|
13186 and |c| whenever a better character is found; |goto found| as soon as a large
13187 enough variant is encountered@>;
13188 }@+ while (!(z < 16));
13189 }
13190
13191 @ @<Look at the list of characters starting with |x|...@>=
13192 {@+y=x;
13193 if ((qo(y) >= font_bc[g])&&(qo(y) <= font_ec[g]))
13194 {@+resume: q=char_info(g, y);
13195 if (char_exists(g,y))
13196 {@+if (char_tag(g,q)==ext_tag)
13197 {@+f=g;c=y;goto found;
13198 }
13199 u= height_plus_depth(g,y);
13200 if (u > w)
13201 {@+f=g;c=y;w=u;
13202 if (u >= v) goto found;
13203 }
13204 if (char_tag(g,q)==list_tag)
13205 {@+y=rem_byte(q);goto resume;
13206 }
13207 }
13208 }
13209 }
13210
13211 @ Here is a subroutine that creates a new box, whose list contains a
13212 single character, and whose width includes the italic correction for
13213 that character. The height or depth of the box will be negative, if
13214 the height or depth of the character is negative; thus, this routine
13215 may deliver a slightly different result than |hpack| would produce.
13216
13217 @<Declare subprocedures for |var_delimiter|@>=
13218 static pointer char_box(internal_font_number @!f, int @!c)
13219 {@+pointer @!b, @!p; /*the new box and its character node*/
13220 b=new_null_box();
13221 if (IS_X_FONT(f))
13222 { hb_codepoint_t glyph;
13223 if (x_glyph(f,c,&glyph))
13224 { scaled ph, pd;
13225 width(b)=x_glyph_width(f,glyph)+x_glyph_italic(f,glyph);
13226 x_glyph_height_depth(f,glyph,&ph,&pd);
13227 height(b)=ph;
13228 depth(b)=pd;
13229 }
13230 else
13231 width(b)=height(b)=depth(b)=0;
13232 }
13233 else
13234 { width(b)=char_width(f, c)+char_italic(f, c);
13235 height(b)=char_height(f, c);depth(b)=char_depth(f, c);
13236 }
13237 p=get_avail();character(p)=c;font(p)=f;list_ptr(b)=p;return b;
13238 }
13239
13240 @ When the following code is executed, |char_tag(f,q)| will be equal to
13241 |ext_tag| if and only if a built-up symbol is supposed to be returned.
13242
13243 @<Make variable |b| point to a box for |(f,c)|@>=
13244 if (char_tag(f,q)==ext_tag)
13245 @<Construct an extensible character in a new box |b|, using recipe |rem_byte(q)|
13246 and font |f|@>@;
13247 else b=char_box(f, c)
13248
13249 @ When we build an extensible character, it's handy to have the
13250 following subroutine, which puts a given character on top
13251 of the characters already in box |b|:
13252
13253 @<Declare subprocedures for |var_delimiter|@>=
13254 static void stack_into_box(pointer @!b, internal_font_number @!f,
13255 quarterword @!c)
13256 {@+pointer p; /*new node placed into |b|*/
13257 p=char_box(f, c);link(p)=list_ptr(b);list_ptr(b)=p;
13258 height(b)=height(p);
13259 }
13260
13261 @ Another handy subroutine computes the height plus depth of
13262 a given character:
13263
13264 @<Declare subprocedures for |var_delimiter|@>=
13265 static scaled height_plus_depth(internal_font_number @!f, quarterword @!c)
13266 { if (IS_X_FONT(f))
13267 { scaled hc,dc;
13268 x_char_height_depth(f, c,&hc, &dc);
13269 return hc+dc;
13270 }
13271 else
13272 return char_height(f, c)+char_depth(f, c);
13273 }
13274
13275 @ @<Construct an extensible...@>=
13276 {@+b=new_null_box();
13277 type(b)=vlist_node;
13278 r=font_info[exten_base[f]+rem_byte(q)].qqqq;@/
13279 @<Compute the minimum suitable height, |w|, and the corresponding number of
13280 extension steps, |n|; also set |width(b)|@>;
13281 c=ext_bot(r);
13282 if (c!=min_quarterword) stack_into_box(b, f, c);
13283 c=ext_rep(r);
13284 for (m=1; m<=n; m++) stack_into_box(b, f, c);
13285 c=ext_mid(r);
13286 if (c!=min_quarterword)
13287 {@+stack_into_box(b, f, c);c=ext_rep(r);
13288 for (m=1; m<=n; m++) stack_into_box(b, f, c);
13289 }
13290 c=ext_top(r);
13291 if (c!=min_quarterword) stack_into_box(b, f, c);
13292 depth(b)=w-height(b);
13293 }
13294
13295 @ The width of an extensible character is the width of the repeatable
13296 module. If this module does not have positive height plus depth,
13297 we don't use any copies of it, otherwise we use as few as possible
13298 (in groups of two if there is a middle part).
13299
13300 @<Compute the minimum suitable height, |w|, and...@>=
13301 c=ext_rep(r);u=height_plus_depth(f, c);
13302 w=0;q=char_info(f, c);width(b)=char_width(f, c)+char_italic(f, c);@/
13303 c=ext_bot(r);@+if (c!=min_quarterword) w=w+height_plus_depth(f, c);
13304 c=ext_mid(r);@+if (c!=min_quarterword) w=w+height_plus_depth(f, c);
13305 c=ext_top(r);@+if (c!=min_quarterword) w=w+height_plus_depth(f, c);
13306 n=0;
13307 if (u > 0) while (w < v)
13308 {@+w=w+u;incr(n);
13309 if (ext_mid(r)!=min_quarterword) w=w+u;
13310 }
13311
13312 @ The next subroutine is much simpler; it is used for numerators and
13313 denominators of fractions as well as for displayed operators and
13314 their limits above and below. It takes a given box~|b| and
13315 changes it so that the new box is centered in a box of width~|w|.
13316 The centering is done by putting \.{\\hss} glue at the left and right
13317 of the list inside |b|, then packaging the new box; thus, the
13318 actual box might not really be centered, if it already contains
13319 infinite glue.
13320
13321 The given box might contain a single character whose italic correction
13322 has been added to the width of the box; in this case a compensating
13323 kern is inserted.
13324
13325 @p static pointer rebox(pointer @!b, scaled @!w)
13326 {@+pointer p; /*temporary register for list manipulation*/
13327 internal_font_number @!f; /*font in a one-character box*/
13328 scaled @!v; /*width of a character without italic correction*/
13329 if ((width(b)!=w)&&(list_ptr(b)!=null))
13330 {@+if (type(b)==vlist_node) b=hpack(b, natural);
13331 p=list_ptr(b);
13332 if ((is_char_node(p))&&(link(p)==null))
13333 {@+f=font(p);v=char_width(f, character(p));
13334 if (v!=width(b)) link(p)=new_kern(width(b)-v);
13335 }
13336 list_ptr(b)=null; flush_node_list(b);
13337 b=new_glue(ss_glue);link(b)=p;
13338 while (link(p)!=null) p=link(p);
13339 link(p)=new_glue(ss_glue);
13340 return hpack(b, w, 0, 0, exactly, false);
13341 }
13342 else{@+width(b)=w;return b;
13343 }
13344 }
13345
13346 @ Here is a subroutine that creates a new glue specification from another
13347 one that is expressed in `\.{mu}', given the value of the math unit.
13348
13349 @d mu_mult(A) nx_plus_y(n, A, xn_over_d(A, f, 0200000))
13350
13351 @p static pointer math_glue(pointer @!g, scaled @!m)
13352 {@+pointer p; /*the new glue specification*/
13353 int @!n; /*integer part of |m|*/
13354 scaled @!f; /*fraction part of |m|*/
13355 n=x_over_n(m, 0200000);f=rem;@/
13356 if (f < 0)
13357 {@+decr(n);f=f+0200000;
13358 }
13359 p=get_node(glue_spec_size);
13360 width(p)=mu_mult(width(g)); /*convert \.{mu} to \.{pt}*/
13361 stretch_order(p)=stretch_order(g);
13362 if (stretch_order(p)==normal) stretch(p)=mu_mult(stretch(g));
13363 else stretch(p)=stretch(g);
13364 shrink_order(p)=shrink_order(g);
13365 if (shrink_order(p)==normal) shrink(p)=mu_mult(shrink(g));
13366 else shrink(p)=shrink(g);
13367 return p;
13368 }
13369
13370 @ The |math_kern| subroutine removes |mu_glue| from a kern node, given
13371 the value of the math unit.
13372
13373 @p static void math_kern(pointer @!p, scaled @!m)
13374 {@+int @!n; /*integer part of |m|*/
13375 scaled @!f; /*fraction part of |m|*/
13376 if (subtype(p)==mu_glue)
13377 {@+n=x_over_n(m, 0200000);f=rem;@/
13378 if (f < 0)
13379 {@+decr(n);f=f+0200000;
13380 }
13381 width(p)=mu_mult(width(p));subtype(p)=explicit;
13382 }
13383 }
13384
13385 @ Sometimes it is necessary to destroy an mlist. The following
13386 subroutine empties the current list, assuming that |abs(mode)==mmode|.
13387
13388 @p static void flush_math(void)
13389 {@+flush_node_list(link(head));flush_node_list(incompleat_noad);
13390 link(head)=null;tail=head;incompleat_noad=null;
13391 }
13392
13393 @* Typesetting math formulas.
13394 \TeX's most important routine for dealing with formulas is called
13395 |mlist_to_hlist|. After a formula has been scanned and represented as an
13396 mlist, this routine converts it to an hlist that can be placed into a box
13397 or incorporated into the text of a paragraph. There are three implicit
13398 parameters, passed in global variables: |cur_mlist| points to the first
13399 node or noad in the given mlist (and it might be |null|); |cur_style| is a
13400 style code; and |mlist_penalties| is |true| if penalty nodes for potential
13401 line breaks are to be inserted into the resulting hlist. After
13402 |mlist_to_hlist| has acted, |link(temp_head)| points to the translated hlist.
13403
13404 Since mlists can be inside mlists, the procedure is recursive. And since this
13405 is not part of \TeX's inner loop, the program has been written in a manner
13406 that stresses compactness over efficiency.
13407 @^recursion@>
13408
13409 @<Glob...@>=
13410 static pointer @!cur_mlist; /*beginning of mlist to be translated*/
13411 static small_number @!cur_style; /*style code at current place in the list*/
13412 static small_number @!cur_size; /*size code corresponding to |cur_style|*/
13413 static scaled @!cur_mu; /*the math unit width corresponding to |cur_size|*/
13414 static bool @!mlist_penalties; /*should |mlist_to_hlist| insert penalties?*/
13415
13416 @ The recursion in |mlist_to_hlist| is due primarily to a subroutine
13417 called |clean_box| that puts a given noad field into a box using a given
13418 math style; |mlist_to_hlist| can call |clean_box|, which can call
13419 |mlist_to_hlist|.
13420 @^recursion@>
13421
13422 The box returned by |clean_box| is ``clean'' in the
13423 sense that its |shift_amount| is zero.
13424
13425 @p static void mlist_to_hlist(void);@/
13426 static pointer clean_box(pointer @!p, small_number @!s)
13427 {@+
13428 pointer q; /*beginning of a list to be boxed*/
13429 small_number @!save_style; /*|cur_style| to be restored*/
13430 pointer @!x; /*box to be returned*/
13431 pointer @!r; /*temporary pointer*/
13432 switch (math_type(p)) {
13433 case math_char: {@+cur_mlist=new_noad();mem[nucleus(cur_mlist)]=mem[p];
13434 } @+break;
13435 case sub_box: {@+q=info(p);goto found;
13436 }
13437 case sub_mlist: cur_mlist=info(p);@+break;
13438 default:{@+q=new_null_box();goto found;
13439 }
13440 } @/
13441 save_style=cur_style;cur_style=s;mlist_penalties=false;@/
13442 mlist_to_hlist();q=link(temp_head); /*recursive call*/
13443 cur_style=save_style; /*restore the style*/
13444 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
13445 found: if (is_char_node(q)||(q==null)) x=hpack(q, natural);
13446 else if ((link(q)==null)&&(type(q) <= vlist_node)&&(shift_amount(q)==0))
13447 x=q; /*it's already clean*/
13448 else x=hpack(q, natural);
13449 @<Simplify a trivial box@>;
13450 return x;
13451 }
13452
13453 @ Here we save memory space in a common case.
13454
13455 @<Simplify a trivial box@>=
13456 q=list_ptr(x);
13457 if (is_char_node(q))
13458 {@+r=link(q);
13459 if (r!=null) if (link(r)==null) if (!is_char_node(r))
13460 if (type(r)==kern_node) /*unneeded italic correction*/
13461 {@+free_node(r, small_node_size);link(q)=null;
13462 }
13463 }
13464
13465 @ It is convenient to have a procedure that converts a |math_char|
13466 field to an ``unpacked'' form. The |fetch| routine sets |cur_f|, |cur_c|,
13467 and |cur_i| to the font code, character code, and character information bytes of
13468 a given noad field. It also takes care of issuing error messages for
13469 nonexistent characters; in such cases, |char_exists(cur_i)| will be |false|
13470 after |fetch| has acted, and the field will also have been reset to |empty|.
13471
13472 @p static void fetch(pointer @!a) /*unpack the |math_char| field |a|*/
13473 {@+cur_c=character(a);cur_f=fam_fnt(fam(a)+cur_size);
13474 if (cur_f==null_font)
13475 @<Complain about an undefined family and set |cur_i| null@>@;
13476 else{@+if ((qo(cur_c) >= font_bc[cur_f])&&(qo(cur_c) <= font_ec[cur_f]))
13477 { if (needs_loading(cur_f))
13478 { read_predefined_font(cur_f);
13479 cur_i=null_character;
13480 }
13481 else
13482 cur_i=char_info(cur_f, cur_c);
13483 }
13484 else cur_i=null_character;
13485 if (!(char_exists(cur_f,cur_c)))
13486 {@+char_warning(cur_f, qo(cur_c));
13487 math_type(a)=empty;cur_i=null_character;
13488 }
13489 }
13490 }
13491
13492 @ @<Complain about an undefined family...@>=
13493 {@+print_err("");print_size(cur_size);print_char(' ');
13494 print_int(fam(a));print(" is undefined (character ");
13495 print_ASCII(qo(cur_c));print_char(')');
13496 help4("Somewhere in the math formula just ended, you used the",@/
13497 "stated character from an undefined font family. For example,",@/
13498 "plain TeX doesn't allow \\it or \\sl in subscripts. Proceed,",@/
13499 "and I'll try to forget that I needed that character.");
13500 error();cur_i=null_character;math_type(a)=empty;
13501 }
13502
13503 @ The outputs of |fetch| are placed in global variables.
13504
13505 @<Glob...@>=
13506 static internal_font_number @!cur_f; /*the |font| field of a |math_char|*/
13507 static quarterword @!cur_c; /*the |character| field of a |math_char|*/
13508 static four_quarters @!cur_i; /*the |char_info| of a |math_char|,
13509 or a lig/kern instruction*/
13510
13511 @ We need to do a lot of different things, so |mlist_to_hlist| makes two
13512 passes over the given mlist.
13513
13514 The first pass does most of the processing: It removes ``mu'' spacing from
13515 glue, it recursively evaluates all subsidiary mlists so that only the
13516 top-level mlist remains to be handled, it puts fractions and square roots
13517 and such things into boxes, it attaches subscripts and superscripts, and
13518 it computes the overall height and depth of the top-level mlist so that
13519 the size of delimiters for a |left_noad| and a |right_noad| will be known.
13520 The hlist resulting from each noad is recorded in that noad's |new_hlist|
13521 field, an integer field that replaces the |nucleus| or |thickness|.
13522 @^recursion@>
13523
13524 The second pass eliminates all noads and inserts the correct glue and
13525 penalties between nodes.
13526
13527 @d new_hlist(A) mem[nucleus(A)].i /*the translation of an mlist*/
13528
13529 @ Here is the overall plan of |mlist_to_hlist|, and the list of its
13530 local variables.
13531
13532 @p @t\4@>@<Declare math construction procedures@>@;
13533 static void mlist_to_hlist(void)
13534 {@+
13535
13536 pointer mlist; /*beginning of the given list*/
13537 bool @!penalties; /*should penalty nodes be inserted?*/
13538 small_number @!style; /*the given style*/
13539 small_number @!save_style; /*holds |cur_style| during recursion*/
13540 pointer @!q; /*runs through the mlist*/
13541 pointer @!r; /*the most recent noad preceding |q|*/
13542 small_number @!r_type; /*the |type| of noad |r|, or |op_noad| if |r==null|*/
13543 small_number @!t; /*the effective |type| of noad |q| during the second pass*/
13544 pointer @!p, @!x, @!y, @!z; /*temporary registers for list construction*/
13545 int @!pen; /*a penalty to be inserted*/
13546 small_number @!s; /*the size of a noad to be deleted*/
13547 scaled @!max_h, @!max_d; /*maximum height and depth of the list translated so far*/
13548 scaled @!delta; /*offset between subscript and superscript*/
13549 mlist=cur_mlist;penalties=mlist_penalties;
13550 style=cur_style; /*tuck global parameters away as local variables*/
13551 q=mlist;r=null;r_type=op_noad;max_h=0;max_d=0;
13552 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
13553 while (q!=null) @<Process node-or-noad |q| as much as possible in preparation
13554 for the second pass of |mlist_to_hlist|, then move to the next item in the
13555 mlist@>;
13556 @<Convert \(a)a final |bin_noad| to an |ord_noad|@>;
13557 @<Make a second pass over the mlist, removing all noads and inserting the
13558 proper spacing and penalties@>;
13559 }
13560
13561 @ We use the fact that no character nodes appear in an mlist, hence
13562 the field |type(q)| is always present.
13563
13564 @<Process node-or-noad...@>=
13565 {@+@<Do first-pass processing based on |type(q)|; |goto done_with_noad| if
13566 a noad has been fully processed, |goto check_dimensions| if it has been translated
13567 into |new_hlist(q)|, or |goto done_with_node| if a node has been fully processed@>;
13568 check_dimensions: z=hpack(new_hlist(q), natural);
13569 if (height(z) > max_h) max_h=height(z);
13570 if (depth(z) > max_d) max_d=depth(z);
13571 list_ptr(z)=null; flush_node_list(z);
13572 done_with_noad: r=q;r_type=type(r);
13573 if (r_type==right_noad)
13574 {@+r_type=left_noad;cur_style=style;@<Set up the values...@>;
13575 }
13576 done_with_node: q=link(q);
13577 }
13578
13579 @ One of the things we must do on the first pass is change a |bin_noad| to
13580 an |ord_noad| if the |bin_noad| is not in the context of a binary operator.
13581 The values of |r| and |r_type| make this fairly easy.
13582
13583 @<Do first-pass processing...@>=
13584 reswitch: delta=0;
13585 switch (type(q)) {
13586 case bin_noad: switch (r_type) {
13587 case bin_noad: case op_noad: case rel_noad:
13588 case open_noad: case punct_noad: case left_noad:
13589 {@+type(q)=ord_noad;goto reswitch;
13590 }
13591 default:do_nothing;
13592 } @+break;
13593 case rel_noad: case close_noad: case punct_noad:
13594 case right_noad: {@+@t@>@;@/
13595 @<Convert \(a)a final |bin_noad| to an |ord_noad|@>;
13596 if (type(q)==right_noad) goto done_with_noad;
13597 } @+break;
13598 @t\4@>@<Cases for noads that can follow a |bin_noad|@>@;
13599 @t\4@>@<Cases for nodes that can appear in an mlist, after which we |goto
13600 done_with_node|@>@;
13601 default:confusion("mlist1");
13602 @:this can't happen mlist1}{\quad mlist1@>
13603 } @/
13604 @<Convert \(n)|nucleus(q)| to an hlist and attach the sub/superscripts@>@;
13605
13606 @ @<Convert \(a)a final |bin_noad| to an |ord_noad|@>=
13607 if (r_type==bin_noad) type(r)=ord_noad
13608
13609 @ @<Cases for nodes that can appear in an mlist...@>=
13610 case style_node: {@+cur_style=subtype(q);
13611 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
13612 goto done_with_node;
13613 }
13614 case choice_node: @<Change this node to a style node followed by the correct
13615 choice, then |goto done_with_node|@>@;
13616 case ins_node: case mark_node: case adjust_node:
13617 case whatsit_node: case penalty_node:
13618 case disc_node: goto done_with_node;
13619 case rule_node: {@+if (height(q) > max_h) max_h=height(q);
13620 if (depth(q) > max_d) max_d=depth(q);goto done_with_node;
13621 }
13622 case glue_node: {@+@<Convert \(m)math glue to ordinary glue@>;
13623 goto done_with_node;
13624 }
13625 case kern_node: {@+math_kern(q, cur_mu);goto done_with_node;
13626 }
13627
13628 @ @d choose_mlist(A) {@+p=A(q);A(q)=null;@+}
13629
13630 @<Change this node to a style node...@>=
13631 {@+switch (cur_style/2) {
13632 case 0: choose_mlist(display_mlist)@;@+break; /*|display_style==0|*/
13633 case 1: choose_mlist(text_mlist)@;@+break; /*|text_style==2|*/
13634 case 2: choose_mlist(script_mlist)@;@+break; /*|script_style==4|*/
13635 case 3: choose_mlist(script_script_mlist); /*|script_script_style==6|*/
13636 } /*there are no other cases*/
13637 flush_node_list(display_mlist(q));
13638 flush_node_list(text_mlist(q));
13639 flush_node_list(script_mlist(q));
13640 flush_node_list(script_script_mlist(q));@/
13641 type(q)=style_node;subtype(q)=cur_style;width(q)=0;depth(q)=0;
13642 if (p!=null)
13643 {@+z=link(q);link(q)=p;
13644 while (link(p)!=null) p=link(p);
13645 link(p)=z;
13646 }
13647 goto done_with_node;
13648 }
13649
13650 @ Conditional math glue (`\.{\\nonscript}') results in a |glue_node|
13651 pointing to |zero_glue|, with |subtype(q)==cond_math_glue|; in such a case
13652 the node following will be eliminated if it is a glue or kern node and if the
13653 current size is different from |text_size|. Unconditional math glue
13654 (`\.{\\muskip}') is converted to normal glue by multiplying the dimensions
13655 by |cur_mu|.
13656 @!@:non\_script\_}{\.{\\nonscript} primitive@>
13657
13658 @<Convert \(m)math glue to ordinary glue@>=
13659 if (subtype(q)==mu_glue)
13660 {@+x=glue_ptr(q);
13661 y=math_glue(x, cur_mu);delete_glue_ref(x);glue_ptr(q)=y;
13662 subtype(q)=normal;
13663 }
13664 else if ((cur_size!=text_size)&&(subtype(q)==cond_math_glue))
13665 {@+p=link(q);
13666 if (p!=null) if ((type(p)==glue_node)||(type(p)==kern_node))
13667 {@+link(q)=link(p);link(p)=null;flush_node_list(p);
13668 }
13669 }
13670
13671 @ @<Cases for noads that can follow a |bin_noad|@>=
13672 case left_noad: goto done_with_noad;
13673 case fraction_noad: {@+make_fraction(q);goto check_dimensions;
13674 }
13675 case op_noad: {@+delta=make_op(q);
13676 if (subtype(q)==limits) goto check_dimensions;
13677 } @+break;
13678 case ord_noad: make_ord(q);@+break;
13679 case open_noad: case inner_noad: do_nothing;@+break;
13680 case radical_noad: make_radical(q);@+break;
13681 case over_noad: make_over(q);@+break;
13682 case under_noad: make_under(q);@+break;
13683 case accent_noad: make_math_accent(q);@+break;
13684 case vcenter_noad: make_vcenter(q);@+break;
13685
13686 @ Most of the actual construction work of |mlist_to_hlist| is done
13687 by procedures with names
13688 like |make_fraction|, |make_radical|, etc. To illustrate
13689 the general setup of such procedures, let's begin with a couple of
13690 simple ones.
13691
13692 @<Declare math...@>=
13693 static void make_over(pointer @!q)
13694 {@+info(nucleus(q))=@|
13695 overbar(clean_box(nucleus(q), cramped_style(cur_style)),@|
13696 3*default_rule_thickness, default_rule_thickness);
13697 math_type(nucleus(q))=sub_box;
13698 }
13699
13700 @ @<Declare math...@>=
13701 static void make_under(pointer @!q)
13702 {@+pointer p, @!x, @!y; /*temporary registers for box construction*/
13703 scaled @!delta; /*overall height plus depth*/
13704 x=clean_box(nucleus(q), cur_style);
13705 p=new_kern(3*default_rule_thickness);link(x)=p;
13706 link(p)=fraction_rule(default_rule_thickness);
13707 y=vpack(x, natural);
13708 delta=height(y)+depth(y)+default_rule_thickness;
13709 height(y)=height(x);depth(y)=delta-height(y);
13710 info(nucleus(q))=y;math_type(nucleus(q))=sub_box;
13711 }
13712
13713 @ @<Declare math...@>=
13714 static void make_vcenter(pointer @!q)
13715 {@+pointer v; /*the box that should be centered vertically*/
13716 scaled @!delta; /*its height plus depth*/
13717 v=info(nucleus(q));
13718 if (type(v)!=vlist_node &&
13719 !(type(v)==whatsit_node && (subtype(v)==vset_node || subtype(v)==vpack_node)))
13720 confusion("vcenter");
13721 @:this can't happen vcenter}{\quad vcenter@>
13722 delta=height(v)+depth(v);
13723 height(v)=axis_height(cur_size)+half(delta);
13724 depth(v)=delta-height(v);
13725 }
13726
13727 @ According to the rules in the \.{DVI} file specifications, we ensure alignment
13728 @^square roots@>
13729 between a square root sign and the rule above its nucleus by assuming that the
13730 baseline of the square-root symbol is the same as the bottom of the rule. The
13731 height of the square-root symbol will be the thickness of the rule, and the
13732 depth of the square-root symbol should exceed or equal the height-plus-depth
13733 of the nucleus plus a certain minimum clearance~|clr|. The symbol will be
13734 placed so that the actual clearance is |clr| plus half the excess.
13735
13736 @<Declare math...@>=
13737 static void make_radical(pointer @!q)
13738 {@+pointer x, @!y; /*temporary registers for box construction*/
13739 scaled @!delta, @!clr; /*dimensions involved in the calculation*/
13740 x=clean_box(nucleus(q), cramped_style(cur_style));
13741 if (cur_style < text_style) /*display style*/
13742 clr=default_rule_thickness+(abs(math_x_height(cur_size))/4);
13743 else{@+clr=default_rule_thickness;clr=clr+(abs(clr)/4);
13744 }
13745 y=var_delimiter(left_delimiter(q), cur_size, height(x)+depth(x)+clr+
13746 default_rule_thickness);
13747 delta=depth(y)-(height(x)+depth(x)+clr);
13748 if (delta > 0) clr=clr+half(delta); /*increase the actual clearance*/
13749 shift_amount(y)=-(height(x)+clr);
13750 link(y)=overbar(x, clr, height(y));
13751 info(nucleus(q))=hpack(y, natural);math_type(nucleus(q))=sub_box;
13752 }
13753
13754 @ Slants are not considered when placing accents in math mode. The accenter is
13755 centered over the accentee, and the accent width is treated as zero with
13756 respect to the size of the final box.
13757
13758 @<Declare math...@>=
13759 static void make_math_accent(pointer @!q)
13760 {@+
13761 pointer p, @!x, @!y; /*temporary registers for box construction*/
13762 int @!a; /*address of lig/kern instruction*/
13763 quarterword @!c; /*accent character*/
13764 internal_font_number @!f; /*its font*/
13765 four_quarters @!i; /*its |char_info|*/
13766 scaled @!s; /*amount to skew the accent to the right*/
13767 scaled @!h; /*height of character being accented*/
13768 scaled @!delta; /*space to remove between accent and accentee*/
13769 scaled @!w; /*width of the accentee, not including sub/superscripts*/
13770 fetch(accent_chr(q));
13771 if (char_exists(cur_f,cur_c))
13772 {@+i=cur_i;c=cur_c;f=cur_f;@/
13773 @<Compute the amount of skew@>;
13774 x=clean_box(nucleus(q), cramped_style(cur_style));w=width(x);h=height(x);
13775 @<Switch to a larger accent if available and appropriate@>;
13776 if (h < x_height(f)) delta=h;@+else delta=x_height(f);
13777 if ((math_type(supscr(q))!=empty)||(math_type(subscr(q))!=empty))
13778 if (math_type(nucleus(q))==math_char)
13779 @<Swap the subscript and superscript into box |x|@>;
13780 y=char_box(f, c);
13781 shift_amount(y)=s+half(w-width(y));
13782 width(y)=0;p=new_kern(-delta);link(p)=x;link(y)=p;
13783 y=vpack(y, natural);width(y)=width(x);
13784 if (height(y) < h) @<Make the height of box |y| equal to |h|@>;
13785 info(nucleus(q))=y;
13786 math_type(nucleus(q))=sub_box;
13787 }
13788 }
13789
13790 @ @<Make the height of box |y|...@>=
13791 {@+p=new_kern(h-height(y));link(p)=list_ptr(y);list_ptr(y)=p;
13792 height(y)=h;
13793 }
13794
13795 @ @<Switch to a larger accent if available and appropriate@>=
13796 loop@+{@+if (char_tag(f,i)!=list_tag) goto done;
13797 y=rem_byte(i);
13798 i=char_info(f, y);
13799 if (!char_exists(f,y)) goto done;
13800 if (char_width(f, y) > w) goto done;
13801 c=y;
13802 }
13803 done:
13804
13805 @ @<Compute the amount of skew@>=
13806 s=0;
13807 if (math_type(nucleus(q))==math_char)
13808 {@+fetch(nucleus(q));
13809 if (char_tag(cur_f, cur_i)==lig_tag)
13810 {@+a=lig_kern_start(cur_f, cur_i);
13811 cur_i=font_info[a].qqqq;
13812 if (skip_byte(cur_i) > stop_flag)
13813 {@+a=lig_kern_restart(cur_f, cur_i);
13814 cur_i=font_info[a].qqqq;
13815 }
13816 loop@+{@+if (qo(next_char(cur_i))==skew_char[cur_f])
13817 {@+if (op_byte(cur_i) >= kern_flag)
13818 if (skip_byte(cur_i) <= stop_flag) s=char_kern(cur_f, cur_i);
13819 goto done1;
13820 }
13821 if (skip_byte(cur_i) >= stop_flag) goto done1;
13822 a=a+qo(skip_byte(cur_i))+1;
13823 cur_i=font_info[a].qqqq;
13824 }
13825 }
13826 }
13827 done1:
13828
13829 @ @<Swap the subscript and superscript into box |x|@>=
13830 {@+flush_node_list(x);x=new_noad();
13831 mem[nucleus(x)]=mem[nucleus(q)];
13832 mem[supscr(x)]=mem[supscr(q)];
13833 mem[subscr(x)]=mem[subscr(q)];@/
13834 mem[supscr(q)].hh=empty_field;
13835 mem[subscr(q)].hh=empty_field;@/
13836 math_type(nucleus(q))=sub_mlist;info(nucleus(q))=x;
13837 x=clean_box(nucleus(q), cur_style);delta=delta+height(x)-h;h=height(x);
13838 }
13839
13840 @ The |make_fraction| procedure is a bit different because it sets
13841 |new_hlist(q)| directly rather than making a sub-box.
13842
13843 @<Declare math...@>=
13844 static void make_fraction(pointer @!q)
13845 {@+pointer p, @!v, @!x, @!y, @!z; /*temporary registers for box construction*/
13846 scaled @!delta, @!delta1, @!delta2, @!shift_up, @!shift_down, @!clr;
13847 /*dimensions for box calculations*/
13848 if (thickness(q)==default_code) thickness(q)=default_rule_thickness;
13849 @<Create equal-width boxes |x| and |z| for the numerator and denominator,
13850 and compute the default amounts |shift_up| and |shift_down| by which they
13851 are displaced from the baseline@>;
13852 if (thickness(q)==0) @<Adjust \(s)|shift_up| and |shift_down| for the case
13853 of no fraction line@>@;
13854 else@<Adjust \(s)|shift_up| and |shift_down| for the case of a fraction line@>;
13855 @<Construct a vlist box for the fraction, according to |shift_up| and |shift_down|@>;
13856 @<Put the \(f)fraction into a box with its delimiters, and make |new_hlist(q)|
13857 point to it@>;
13858 }
13859
13860 @ @<Create equal-width boxes |x| and |z| for the numerator and denom...@>=
13861 x=clean_box(numerator(q), num_style(cur_style));
13862 z=clean_box(denominator(q), denom_style(cur_style));
13863 if (width(x) < width(z)) x=rebox(x, width(z));
13864 else z=rebox(z, width(x));
13865 if (cur_style < text_style) /*display style*/
13866 {@+shift_up=num1(cur_size);shift_down=denom1(cur_size);
13867 }
13868 else{@+shift_down=denom2(cur_size);
13869 if (thickness(q)!=0) shift_up=num2(cur_size);
13870 else shift_up=num3(cur_size);
13871 }
13872
13873 @ The numerator and denominator must be separated by a certain minimum
13874 clearance, called |clr| in the following program. The difference between
13875 |clr| and the actual clearance is twice |delta|.
13876
13877 @<Adjust \(s)|shift_up| and |shift_down| for the case of no fraction line@>=
13878 {@+if (cur_style < text_style) clr=7*default_rule_thickness;
13879 else clr=3*default_rule_thickness;
13880 delta=half(clr-((shift_up-depth(x))-(height(z)-shift_down)));
13881 if (delta > 0)
13882 {@+shift_up=shift_up+delta;
13883 shift_down=shift_down+delta;
13884 }
13885 }
13886
13887 @ In the case of a fraction line, the minimum clearance depends on the actual
13888 thickness of the line.
13889
13890 @<Adjust \(s)|shift_up| and |shift_down| for the case of a fraction line@>=
13891 {@+if (cur_style < text_style) clr=3*thickness(q);
13892 else clr=thickness(q);
13893 delta=half(thickness(q));
13894 delta1=clr-((shift_up-depth(x))-(axis_height(cur_size)+delta));
13895 delta2=clr-((axis_height(cur_size)-delta)-(height(z)-shift_down));
13896 if (delta1 > 0) shift_up=shift_up+delta1;
13897 if (delta2 > 0) shift_down=shift_down+delta2;
13898 }
13899
13900 @ @<Construct a vlist box for the fraction...@>=
13901 v=new_null_box();type(v)=vlist_node;
13902 height(v)=shift_up+height(x);depth(v)=depth(z)+shift_down;
13903 width(v)=width(x); /*this also equals |width(z)|*/
13904 if (thickness(q)==0)
13905 {@+p=new_kern((shift_up-depth(x))-(height(z)-shift_down));
13906 link(p)=z;
13907 }
13908 else{@+y=fraction_rule(thickness(q));@/
13909 p=new_kern((axis_height(cur_size)-delta)-@|(height(z)-shift_down));@/
13910 link(y)=p;link(p)=z;@/
13911 p=new_kern((shift_up-depth(x))-(axis_height(cur_size)+delta));
13912 link(p)=y;
13913 }
13914 link(x)=p;list_ptr(v)=x
13915
13916 @ @<Put the \(f)fraction into a box with its delimiters...@>=
13917 if (cur_style < text_style) delta=delim1(cur_size);
13918 else delta=delim2(cur_size);
13919 x=var_delimiter(left_delimiter(q), cur_size, delta);link(x)=v;@/
13920 z=var_delimiter(right_delimiter(q), cur_size, delta);link(v)=z;@/
13921 new_hlist(q)=hpack(x, natural)
13922
13923 @ If the nucleus of an |op_noad| is a single character, it is to be
13924 centered vertically with respect to the axis, after first being enlarged
13925 (via a character list in the font) if we are in display style. The normal
13926 convention for placing displayed limits is to put them above and below the
13927 operator in display style.
13928
13929 The italic correction is removed from the character if there is a subscript
13930 and the limits are not being displayed. The |make_op|
13931 routine returns the value that should be used as an offset between
13932 subscript and superscript.
13933
13934 After |make_op| has acted, |subtype(q)| will be |limits| if and only if
13935 the limits have been set above and below the operator. In that case,
13936 |new_hlist(q)| will already contain the desired final box.
13937
13938 @<Declare math...@>=
13939 static scaled make_op(pointer @!q)
13940 {@+scaled delta; /*offset between subscript and superscript*/
13941 pointer @!p, @!v, @!x, @!y, @!z; /*temporary registers for box construction*/
13942 quarterword @!c;@+four_quarters @!i; /*registers for character examination*/
13943 scaled @!shift_up, @!shift_down; /*dimensions for box calculation*/
13944 if ((subtype(q)==normal)&&(cur_style < text_style))
13945 subtype(q)=limits;
13946 if (math_type(nucleus(q))==math_char)
13947 {@+fetch(nucleus(q));
13948 if ((cur_style < text_style)&&(char_tag(cur_f, cur_i)==list_tag)) /*make it larger*/
13949 {@+c=rem_byte(cur_i);i=char_info(cur_f, c);
13950 if (char_exists(cur_f,c))
13951 {@+cur_c=c;cur_i=i;character(nucleus(q))=c;
13952 }
13953 }
13954 delta=char_italic(cur_f, cur_c);x=clean_box(nucleus(q), cur_style);
13955 if ((math_type(subscr(q))!=empty)&&(subtype(q)!=limits))
13956 width(x)=width(x)-delta; /*remove italic correction*/
13957 shift_amount(x)=half(height(x)-depth(x))-axis_height(cur_size);
13958 /*center vertically*/
13959 math_type(nucleus(q))=sub_box;info(nucleus(q))=x;
13960 }
13961 else delta=0;
13962 if (subtype(q)==limits)
13963 @<Construct a box with limits above and below it, skewed by |delta|@>;
13964 return delta;
13965 }
13966
13967 @ The following program builds a vlist box |v| for displayed limits. The
13968 width of the box is not affected by the fact that the limits may be skewed.
13969
13970 @<Construct a box with limits above and below it...@>=
13971 {@+x=clean_box(supscr(q), sup_style(cur_style));
13972 y=clean_box(nucleus(q), cur_style);
13973 z=clean_box(subscr(q), sub_style(cur_style));
13974 v=new_null_box();type(v)=vlist_node;width(v)=width(y);
13975 if (width(x) > width(v)) width(v)=width(x);
13976 if (width(z) > width(v)) width(v)=width(z);
13977 x=rebox(x, width(v));y=rebox(y, width(v));z=rebox(z, width(v));@/
13978 shift_amount(x)=half(delta);shift_amount(z)=-shift_amount(x);
13979 height(v)=height(y);depth(v)=depth(y);
13980 @<Attach the limits to |y| and adjust |height(v)|, |depth(v)| to account for
13981 their presence@>;
13982 new_hlist(q)=v;
13983 }
13984
13985 @ We use |shift_up| and |shift_down| in the following program for the
13986 amount of glue between the displayed operator |y| and its limits |x| and
13987 |z|. The vlist inside box |v| will consist of |x| followed by |y| followed
13988 by |z|, with kern nodes for the spaces between and around them.
13989
13990 @<Attach the limits to |y| and adjust |height(v)|, |depth(v)|...@>=
13991 if (math_type(supscr(q))==empty)
13992 {@+list_ptr(x)=null; flush_node_list(x);list_ptr(v)=y;
13993 }
13994 else{@+shift_up=big_op_spacing3-depth(x);
13995 if (shift_up < big_op_spacing1) shift_up=big_op_spacing1;
13996 p=new_kern(shift_up);link(p)=y;link(x)=p;@/
13997 p=new_kern(big_op_spacing5);link(p)=x;list_ptr(v)=p;
13998 height(v)=height(v)+big_op_spacing5+height(x)+depth(x)+shift_up;
13999 }
14000 if (math_type(subscr(q))==empty)@/
14001 {@+list_ptr(z)=null;@+flush_node_list(z);@+}
14002 else{@+shift_down=big_op_spacing4-height(z);
14003 if (shift_down < big_op_spacing2) shift_down=big_op_spacing2;
14004 p=new_kern(shift_down);link(y)=p;link(p)=z;@/
14005 p=new_kern(big_op_spacing5);link(z)=p;
14006 depth(v)=depth(v)+big_op_spacing5+height(z)+depth(z)+shift_down;
14007 }
14008
14009 @ A ligature found in a math formula does not create a |ligature_node|, because
14010 there is no question of hyphenation afterwards; the ligature will simply be
14011 stored in an ordinary |char_node|, after residing in an |ord_noad|.
14012
14013 The |math_type| is converted to |math_text_char| here if we would not want to
14014 apply an italic correction to the current character unless it belongs
14015 to a math font (i.e., a font with |space==0|).
14016
14017 No boundary characters enter into these ligatures.
14018
14019 @<Declare math...@>=
14020 static void make_ord(pointer @!q)
14021 {@+
14022 int a; /*address of lig/kern instruction*/
14023 pointer @!p, @!r; /*temporary registers for list manipulation*/
14024 restart: @t@>@;@/
14025 if (math_type(subscr(q))==empty) if (math_type(supscr(q))==empty)
14026 if (math_type(nucleus(q))==math_char)
14027 {@+p=link(q);
14028 if (p!=null) if ((type(p) >= ord_noad)&&(type(p) <= punct_noad))
14029 if (math_type(nucleus(p))==math_char)
14030 if (fam(nucleus(p))==fam(nucleus(q)))
14031 {@+math_type(nucleus(q))=math_text_char;
14032 fetch(nucleus(q));
14033 if (char_tag(cur_f, cur_i)==lig_tag)
14034 {@+a=lig_kern_start(cur_f, cur_i);
14035 cur_c=character(nucleus(p));
14036 cur_i=font_info[a].qqqq;
14037 if (skip_byte(cur_i) > stop_flag)
14038 {@+a=lig_kern_restart(cur_f, cur_i);
14039 cur_i=font_info[a].qqqq;
14040 }
14041 loop@+{@+@<If instruction |cur_i| is a kern with |cur_c|, attach the
14042 kern after~|q|; or if it is a ligature with |cur_c|, combine noads |q| and~|p|
14043 appropriately; then |return| if the cursor has moved past a noad, or |goto
14044 restart|@>;
14045 if (skip_byte(cur_i) >= stop_flag) return;
14046 a=a+qo(skip_byte(cur_i))+1;
14047 cur_i=font_info[a].qqqq;
14048 }
14049 }
14050 }
14051 }
14052 }
14053
14054 @ Note that a ligature between an |ord_noad| and another kind of noad
14055 is replaced by an |ord_noad|, when the two noads collapse into one.
14056 But we could make a parenthesis (say) change shape when it follows
14057 certain letters. Presumably a font designer will define such
14058 ligatures only when this convention makes sense.
14059
14060 \chardef\@@='174 % vertical line to indicate character retention
14061
14062 @<If instruction |cur_i| is a kern with |cur_c|,...@>=
14063 if (next_char(cur_i)==cur_c) if (skip_byte(cur_i) <= stop_flag)
14064 if (op_byte(cur_i) >= kern_flag)
14065 {@+p=new_kern(char_kern(cur_f, cur_i));
14066 link(p)=link(q);link(q)=p;return;
14067 }
14068 else{@+check_interrupt; /*allow a way out of infinite ligature loop*/
14069 switch (op_byte(cur_i)) {
14070 case qi(1): case qi(5): character(nucleus(q))=rem_byte(cur_i);@+break; /*\.{=:\@@}, \.{=:\@@>}*/
14071 case qi(2): case qi(6): character(nucleus(p))=rem_byte(cur_i);@+break; /*\.{\@@=:}, \.{\@@=:>}*/
14072 case qi(3): case qi(7): case qi(11): {@+r=new_noad(); /*\.{\@@=:\@@}, \.{\@@=:\@@>}, \.{\@@=:\@@>>}*/
14073 character(nucleus(r))=rem_byte(cur_i);
14074 fam(nucleus(r))=fam(nucleus(q));@/
14075 link(q)=r;link(r)=p;
14076 if (op_byte(cur_i) < qi(11)) math_type(nucleus(r))=math_char;
14077 else math_type(nucleus(r))=math_text_char; /*prevent combination*/
14078 } @+break;
14079 default:{@+link(q)=link(p);
14080 character(nucleus(q))=rem_byte(cur_i); /*\.{=:}*/
14081 mem[subscr(q)]=mem[subscr(p)];mem[supscr(q)]=mem[supscr(p)];@/
14082 free_node(p, noad_size);
14083 }
14084 }
14085 if (op_byte(cur_i) > qi(3)) return;
14086 math_type(nucleus(q))=math_char;goto restart;
14087 }
14088
14089 @ When we get to the following part of the program, we have ``fallen through''
14090 from cases that did not lead to |check_dimensions| or |done_with_noad| or
14091 |done_with_node|. Thus, |q|~points to a noad whose nucleus may need to be
14092 converted to an hlist, and whose subscripts and superscripts need to be
14093 appended if they are present.
14094
14095 If |nucleus(q)| is not a |math_char|, the variable |delta| is the amount
14096 by which a superscript should be moved right with respect to a subscript
14097 when both are present.
14098 @^subscripts@>
14099 @^superscripts@>
14100
14101 @<Convert \(n)|nucleus(q)| to an hlist and attach the sub/superscripts@>=
14102 switch (math_type(nucleus(q))) {
14103 case math_char: case math_text_char:
14104 @<Create a character node |p| for |nucleus(q)|, possibly followed by a kern
14105 node for the italic correction, and set |delta| to the italic correction if
14106 a subscript is present@>@;@+break;
14107 case empty: p=null;@+break;
14108 case sub_box: p=info(nucleus(q));@+break;
14109 case sub_mlist: {@+cur_mlist=info(nucleus(q));save_style=cur_style;
14110 mlist_penalties=false;mlist_to_hlist(); /*recursive call*/
14111 @^recursion@>
14112 cur_style=save_style;@<Set up the values...@>;
14113 p=hpack(link(temp_head), natural);
14114 } @+break;
14115 default:confusion("mlist2");
14116 @:this can't happen mlist2}{\quad mlist2@>
14117 } @/
14118 new_hlist(q)=p;
14119 if ((math_type(subscr(q))==empty)&&(math_type(supscr(q))==empty))
14120 goto check_dimensions;
14121 make_scripts(q, delta)
14122
14123 @ @<Create a character node |p| for |nucleus(q)|...@>=
14124 {@+fetch(nucleus(q));
14125 if (char_exists(cur_f,cur_c))
14126 {@+delta=char_italic(cur_f, cur_c);p=new_character(cur_f, qo(cur_c));
14127 if ((math_type(nucleus(q))==math_text_char)&&(space(cur_f)!=0))
14128 delta=0; /*no italic correction in mid-word of text font*/
14129 if ((math_type(subscr(q))==empty)&&(delta!=0))
14130 {@+link(p)=new_kern(delta);delta=0;
14131 }
14132 }
14133 else p=null;
14134 }
14135
14136 @ The purpose of |make_scripts(q, delta)| is to attach the subscript and/or
14137 superscript of noad |q| to the list that starts at |new_hlist(q)|,
14138 given that the subscript and superscript aren't both empty. The superscript
14139 will appear to the right of the subscript by a given distance |delta|.
14140
14141 We set |shift_down| and |shift_up| to the minimum amounts to shift the
14142 baseline of subscripts and superscripts based on the given nucleus.
14143
14144 @<Declare math...@>=
14145 static void make_scripts(pointer @!q, scaled @!delta)
14146 {@+pointer p, @!x, @!y, @!z; /*temporary registers for box construction*/
14147 scaled @!shift_up, @!shift_down, @!clr; /*dimensions in the calculation*/
14148 small_number @!t; /*subsidiary size code*/
14149 p=new_hlist(q);
14150 if (is_char_node(p))
14151 {@+shift_up=0;shift_down=0;
14152 }
14153 else{@+z=hpack(p, natural);
14154 if (cur_style < script_style) t=script_size;@+else t=script_script_size;
14155 shift_up=height(z)-sup_drop(t);
14156 shift_down=depth(z)+sub_drop(t);
14157 list_ptr(z)=null;flush_node_list(z);
14158 }
14159 if (math_type(supscr(q))==empty)
14160 @<Construct a subscript box |x| when there is no superscript@>@;
14161 else{@+@<Construct a superscript box |x|@>;
14162 if (math_type(subscr(q))==empty) shift_amount(x)=-shift_up;
14163 else@<Construct a sub/superscript combination box |x|, with the superscript
14164 offset by |delta|@>;
14165 }
14166 if (new_hlist(q)==null) new_hlist(q)=x;
14167 else{@+p=new_hlist(q);
14168 while (link(p)!=null) p=link(p);
14169 link(p)=x;
14170 }
14171 }
14172
14173 @ When there is a subscript without a superscript, the top of the subscript
14174 should not exceed the baseline plus four-fifths of the x-height.
14175
14176 @<Construct a subscript box |x| when there is no superscript@>=
14177 {@+x=clean_box(subscr(q), sub_style(cur_style));
14178 width(x)=width(x)+script_space;
14179 if (shift_down < sub1(cur_size)) shift_down=sub1(cur_size);
14180 clr=height(x)-(abs(math_x_height(cur_size)*4)/5);
14181 if (shift_down < clr) shift_down=clr;
14182 shift_amount(x)=shift_down;
14183 }
14184
14185 @ The bottom of a superscript should never descend below the baseline plus
14186 one-fourth of the x-height.
14187
14188 @<Construct a superscript box |x|@>=
14189 {@+x=clean_box(supscr(q), sup_style(cur_style));
14190 width(x)=width(x)+script_space;
14191 if (odd(cur_style)) clr=sup3(cur_size);
14192 else if (cur_style < text_style) clr=sup1(cur_size);
14193 else clr=sup2(cur_size);
14194 if (shift_up < clr) shift_up=clr;
14195 clr=depth(x)+(abs(math_x_height(cur_size))/4);
14196 if (shift_up < clr) shift_up=clr;
14197 }
14198
14199 @ When both subscript and superscript are present, the subscript must be
14200 separated from the superscript by at least four times |default_rule_thickness|.
14201 If this condition would be violated, the subscript moves down, after which
14202 both subscript and superscript move up so that the bottom of the superscript
14203 is at least as high as the baseline plus four-fifths of the x-height.
14204
14205 @<Construct a sub/superscript combination box |x|...@>=
14206 {@+y=clean_box(subscr(q), sub_style(cur_style));
14207 width(y)=width(y)+script_space;
14208 if (shift_down < sub2(cur_size)) shift_down=sub2(cur_size);
14209 clr=4*default_rule_thickness-
14210 ((shift_up-depth(x))-(height(y)-shift_down));
14211 if (clr > 0)
14212 {@+shift_down=shift_down+clr;
14213 clr=(abs(math_x_height(cur_size)*4)/5)-(shift_up-depth(x));
14214 if (clr > 0)
14215 {@+shift_up=shift_up+clr;
14216 shift_down=shift_down-clr;
14217 }
14218 }
14219 shift_amount(x)=delta; /*superscript is |delta| to the right of the subscript*/
14220 p=new_kern((shift_up-depth(x))-(height(y)-shift_down));link(x)=p;link(p)=y;
14221 x=vpack(x, natural);shift_amount(x)=shift_down;
14222 }
14223
14224 @ We have now tied up all the loose ends of the first pass of |mlist_to_hlist|.
14225 The second pass simply goes through and hooks everything together with the
14226 proper glue and penalties. It also handles the |left_noad| and |right_noad| that
14227 might be present, since |max_h| and |max_d| are now known. Variable |p| points
14228 to a node at the current end of the final hlist.
14229
14230 @<Make a second pass over the mlist,...@>=
14231 p=temp_head;link(p)=null;q=mlist;r_type=0;cur_style=style;
14232 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
14233 while (q!=null)
14234 {@+@<If node |q| is a style node, change the style and |goto delete_q|;
14235 otherwise if it is not a noad, put it into the hlist, advance |q|, and |goto
14236 done|; otherwise set |s| to the size of noad |q|, set |t| to the associated
14237 type (|ord_noad.. inner_noad|), and set |pen| to the associated penalty@>;
14238 @<Append inter-element spacing based on |r_type| and |t|@>;
14239 @<Append any |new_hlist| entries for |q|, and any appropriate penalties@>;
14240 if (type(q)==right_noad) t=open_noad;
14241 r_type=t;
14242 delete_q: r=q;q=link(q);free_node(r, s);
14243 done: ;}
14244
14245 @ Just before doing the big |case| switch in the second pass, the program
14246 sets up default values so that most of the branches are short.
14247
14248 @<If node |q| is a style node, change the style...@>=
14249 t=ord_noad;s=noad_size;pen=inf_penalty;
14250 switch (type(q)) {
14251 case op_noad: case open_noad: case close_noad:
14252 case punct_noad: case inner_noad: t=type(q);@+break;
14253 case bin_noad: {@+t=bin_noad;pen=bin_op_penalty;
14254 } @+break;
14255 case rel_noad: {@+t=rel_noad;pen=rel_penalty;
14256 } @+break;
14257 case ord_noad: case vcenter_noad: case over_noad:
14258 case under_noad: do_nothing;@+break;
14259 case radical_noad: s=radical_noad_size;@+break;
14260 case accent_noad: s=accent_noad_size;@+break;
14261 case fraction_noad: s=fraction_noad_size;@+break;
14262 case left_noad: case right_noad: t=make_left_right(q, style, max_d, max_h);@+break;
14263 case style_node: @<Change the current style and |goto delete_q|@>@;
14264 case whatsit_node: case penalty_node:
14265 case rule_node: case disc_node: case adjust_node:
14266 case ins_node: case mark_node:
14267 case glue_node: case kern_node: @t@>@;@/
14268 {@+link(p)=q;p=q;q=link(q);link(p)=null;goto done;
14269 }
14270 default:confusion("mlist3");
14271 @:this can't happen mlist3}{\quad mlist3@>
14272 }
14273
14274 @ The |make_left_right| function constructs a left or right delimiter of
14275 the required size and returns the value |open_noad| or |close_noad|. The
14276 |right_noad| and |left_noad| will both be based on the original |style|,
14277 so they will have consistent sizes.
14278
14279 We use the fact that |right_noad-left_noad==close_noad-open_noad|.
14280
14281 @<Declare math...@>=
14282 static small_number make_left_right(pointer @!q, small_number @!style,
14283 scaled @!max_d, scaled @!max_h)
14284 {@+scaled delta, @!delta1, @!delta2; /*dimensions used in the calculation*/
14285 cur_style=style;@<Set up the values...@>;
14286 delta2=max_d+axis_height(cur_size);
14287 delta1=max_h+max_d-delta2;
14288 if (delta2 > delta1) delta1=delta2; /*|delta1| is max distance from axis*/
14289 delta=(delta1/500)*delimiter_factor;
14290 delta2=delta1+delta1-delimiter_shortfall;
14291 if (delta < delta2) delta=delta2;
14292 new_hlist(q)=var_delimiter(delimiter(q), cur_size, delta);
14293 return type(q)-(left_noad-open_noad); /*|open_noad| or |close_noad|*/
14294 }
14295
14296 @ @<Change the current style and |goto delete_q|@>=
14297 {@+cur_style=subtype(q);s=style_node_size;
14298 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
14299 goto delete_q;
14300 }
14301
14302 @ The inter-element spacing in math formulas depends on an $8\times8$ table that
14303 \TeX\ preloads as a 64-digit string. The elements of this string have the
14304 following significance:
14305 $$\vbox{\halign{#\hfil\cr
14306 \.0 means no space;\cr
14307 \.1 means a conditional thin space (\.{\\nonscript\\mskip\\thinmuskip});\cr
14308 \.2 means a thin space (\.{\\mskip\\thinmuskip});\cr
14309 \.3 means a conditional medium space
14310 (\.{\\nonscript\\mskip\\medmuskip});\cr
14311 \.4 means a conditional thick space
14312 (\.{\\nonscript\\mskip\\thickmuskip});\cr
14313 \.* means an impossible case.\cr}}$$
14314 This is all pretty cryptic, but {\sl The \TeX book\/} explains what is
14315 supposed to happen, and the string makes it happen.
14316 @:TeXbook}{\sl The \TeX book@>
14317
14318 A global variable |magic_offset| is computed so that if |a| and |b| are
14319 in the range |ord_noad dotdot inner_noad|, then |str_pool[a*8+b+magic_offset]|
14320 is the digit for spacing between noad types |a| and |b|.
14321
14322 If \PASCAL\ had provided a good way to preload constant arrays, this part of
14323 the program would not have been so strange.
14324 @:PASCAL}{\PASCAL@>
14325
14326 @d math_spacing @;@/
14327 @t\hskip-35pt@>
14328 "0234000122*4000133**3**344*0400400*000000234000111*1111112341011"
14329 @t$ \hskip-35pt$@>
14330
14331 @ @<Glob...@>=
14332 static const int @!magic_offset=-9*ord_noad; /*used to find inter-element spacing*/
14333
14334 @ @<Append inter-element spacing based on |r_type| and |t|@>=
14335 if (r_type > 0) /*not the first noad*/
14336 {@+switch (math_spacing[r_type*8+t+magic_offset]) {
14337 case '0': x=0;@+break;
14338 case '1': if (cur_style < script_style) x=thin_mu_skip_code;@+else x=0;@+break;
14339 case '2': x=thin_mu_skip_code;@+break;
14340 case '3': if (cur_style < script_style) x=med_mu_skip_code;@+else x=0;@+break;
14341 case '4': if (cur_style < script_style) x=thick_mu_skip_code;@+else x=0;@+break;
14342 default:confusion("mlist4");
14343 @:this can't happen mlist4}{\quad mlist4@>
14344 }
14345 if (x!=0)
14346 {@+y=math_glue(glue_par(x), cur_mu);
14347 z=new_glue(y);glue_ref_count(y)=null;link(p)=z;p=z;@/
14348 subtype(z)=x+1; /*store a symbolic subtype*/
14349 }
14350 }
14351
14352 @ We insert a penalty node after the hlist entries of noad |q| if |pen|
14353 is not an ``infinite'' penalty, and if the node immediately following |q|
14354 is not a penalty node or a |rel_noad| or absent entirely.
14355
14356 @<Append any |new_hlist| entries for |q|, and any appropriate penalties@>=
14357 if (new_hlist(q)!=null)
14358 {@+link(p)=new_hlist(q);
14359 @/do@+{p=link(p);
14360 }@+ while (!(link(p)==null));
14361 }
14362 if (penalties) if (link(q)!=null) if (pen < inf_penalty)
14363 {@+r_type=type(link(q));
14364 if (r_type!=penalty_node) if (r_type!=rel_noad)
14365 {@+z=new_penalty(pen);link(p)=z;p=z;
14366 }
14367 }
14368
14369 @* Alignment.
14370 It's sort of a miracle whenever \.{\\halign} and \.{\\valign} work, because
14371 they cut across so many of the control structures of \TeX.
14372
14373 Therefore the
14374 present page is probably not the best place for a beginner to start reading
14375 this program; it is better to master everything else first.
14376
14377 Let us focus our thoughts on an example of what the input might be, in order
14378 to get some idea about how the alignment miracle happens. The example doesn't
14379 do anything useful, but it is sufficiently general to indicate all of the
14380 special cases that must be dealt with; please do not be disturbed by its
14381 apparent complexity and meaninglessness.
14382 $$\vbox{\halign{\.{#}\hfil\cr
14383 {}\\tabskip 2pt plus 3pt\cr
14384 {}\\halign to 300pt\{u1\#v1\&\cr
14385 \hskip 50pt\\tabskip 1pt plus 1fil u2\#v2\&\cr
14386 \hskip 50pt u3\#v3\\cr\cr
14387 \hskip 25pt a1\&\\omit a2\&\\vrule\\cr\cr
14388 \hskip 25pt \\noalign\{\\vskip 3pt\}\cr
14389 \hskip 25pt b1\\span b2\\cr\cr
14390 \hskip 25pt \\omit\&c2\\span\\omit\\cr\}\cr}}$$
14391 Here's what happens:
14392
14393 \yskip
14394 (0) When `\.{\\halign to 300pt\{}' is scanned, the |scan_spec| routine
14395 places the 300pt dimension onto the |save_stack|, and an |align_group|
14396 code is placed above it. This will make it possible to complete the alignment
14397 when the matching `\.\}' is found.
14398
14399 (1) The preamble is scanned next. Macros in the preamble are not expanded,
14400 @^preamble@>
14401 except as part of a tabskip specification. For example, if \.{u2} had been
14402 a macro in the preamble above, it would have been expanded, since \TeX\
14403 must look for `\.{minus...}' as part of the tabskip glue. A ``preamble list''
14404 is constructed based on the user's preamble; in our case it contains the
14405 following seven items:
14406 $$\vbox{\halign{\.{#}\hfil\qquad&(#)\hfil\cr
14407 {}\\glue 2pt plus 3pt&the tabskip preceding column 1\cr
14408 {}\\alignrecord, width $-\infty$&preamble info for column 1\cr
14409 {}\\glue 2pt plus 3pt&the tabskip between columns 1 and 2\cr
14410 {}\\alignrecord, width $-\infty$&preamble info for column 2\cr
14411 {}\\glue 1pt plus 1fil&the tabskip between columns 2 and 3\cr
14412 {}\\alignrecord, width $-\infty$&preamble info for column 3\cr
14413 {}\\glue 1pt plus 1fil&the tabskip following column 3\cr}}$$
14414 These ``alignrecord'' entries have the same size as an |unset_node|,
14415 since they will later be converted into such nodes. However, at the
14416 moment they have no |type| or |subtype| fields; they have |info| fields
14417 instead, and these |info| fields are initially set to the value |end_span|,
14418 for reasons explained below. Furthermore, the alignrecord nodes have no
14419 |height| or |depth| fields; these are renamed |u_part| and |v_part|,
14420 and they point to token lists for the templates of the alignment.
14421 For example, the |u_part| field in the first alignrecord points to the
14422 token list `\.{u1}', i.e., the template preceding the `\.\#' for column~1.
14423
14424 (2) \TeX\ now looks at what follows the \.{\\cr} that ended the preamble.
14425 It is not `\.{\\noalign}' or `\.{\\omit}', so this input is put back to
14426 be read again, and the template `\.{u1}' is fed to the scanner. Just
14427 before reading `\.{u1}', \TeX\ goes into restricted horizontal mode.
14428 Just after reading `\.{u1}', \TeX\ will see `\.{a1}', and then (when the
14429 {\.\&} is sensed) \TeX\ will see `\.{v1}'. Then \TeX\ scans an |endv|
14430 token, indicating the end of a column. At this point an |unset_node| is
14431 created, containing the contents of the current hlist (i.e., `\.{u1a1v1}').
14432 The natural width of this unset node replaces the |width| field of the
14433 alignrecord for column~1; in general, the alignrecords will record the
14434 maximum natural width that has occurred so far in a given column.
14435
14436 (3) Since `\.{\\omit}' follows the `\.\&', the templates for column~2
14437 are now bypassed. Again \TeX\ goes into restricted horizontal mode and
14438 makes an |unset_node| from the resulting hlist; but this time the
14439 hlist contains simply `\.{a2}'. The natural width of the new unset box
14440 is remembered in the |width| field of the alignrecord for column~2.
14441
14442 (4) A third |unset_node| is created for column 3, using essentially the
14443 mechanism that worked for column~1; this unset box contains `\.{u3\\vrule
14444 v3}'. The vertical rule in this case has running dimensions that will later
14445 extend to the height and depth of the whole first row, since each |unset_node|
14446 in a row will eventually inherit the height and depth of its enclosing box.
14447
14448 (5) The first row has now ended; it is made into a single unset box
14449 comprising the following seven items:
14450 $$\vbox{\halign{\hbox to 325pt{\qquad\.{#}\hfil}\cr
14451 {}\\glue 2pt plus 3pt\cr
14452 {}\\unsetbox for 1 column: u1a1v1\cr
14453 {}\\glue 2pt plus 3pt\cr
14454 {}\\unsetbox for 1 column: a2\cr
14455 {}\\glue 1pt plus 1fil\cr
14456 {}\\unsetbox for 1 column: u3\\vrule v3\cr
14457 {}\\glue 1pt plus 1fil\cr}}$$
14458 The width of this unset row is unimportant, but it has the correct height
14459 and depth, so the correct baselineskip glue will be computed as the row
14460 is inserted into a vertical list.
14461
14462 (6) Since `\.{\\noalign}' follows the current \.{\\cr}, \TeX\ appends
14463 additional material (in this case \.{\\vskip 3pt}) to the vertical list.
14464 While processing this material, \TeX\ will be in internal vertical
14465 mode, and |no_align_group| will be on |save_stack|.
14466
14467 (7) The next row produces an unset box that looks like this:
14468 $$\vbox{\halign{\hbox to 325pt{\qquad\.{#}\hfil}\cr
14469 {}\\glue 2pt plus 3pt\cr
14470 {}\\unsetbox for 2 columns: u1b1v1u2b2v2\cr
14471 {}\\glue 1pt plus 1fil\cr
14472 {}\\unsetbox for 1 column: {\rm(empty)}\cr
14473 {}\\glue 1pt plus 1fil\cr}}$$
14474 The natural width of the unset box that spans columns 1~and~2 is stored
14475 in a ``span node,'' which we will explain later; the |info| field of the
14476 alignrecord for column~1 now points to the new span node, and the |info|
14477 of the span node points to |end_span|.
14478
14479 (8) The final row produces the unset box
14480 $$\vbox{\halign{\hbox to 325pt{\qquad\.{#}\hfil}\cr
14481 {}\\glue 2pt plus 3pt\cr
14482 {}\\unsetbox for 1 column: {\rm(empty)}\cr
14483 {}\\glue 2pt plus 3pt\cr
14484 {}\\unsetbox for 2 columns: u2c2v2\cr
14485 {}\\glue 1pt plus 1fil\cr}}$$
14486 A new span node is attached to the alignrecord for column 2.
14487
14488 (9) The last step is to compute the true column widths and to change all the
14489 unset boxes to hboxes, appending the whole works to the vertical list that
14490 encloses the \.{\\halign}. The rules for deciding on the final widths of
14491 each unset column box will be explained below.
14492
14493 \yskip\noindent
14494 Note that as \.{\\halign} is being processed, we fearlessly give up control
14495 to the rest of \TeX. At critical junctures, an alignment routine is
14496 called upon to step in and do some little action, but most of the time
14497 these routines just lurk in the background. It's something like
14498 post-hypnotic suggestion.
14499
14500 @ We have mentioned that alignrecords contain no |height| or |depth| fields.
14501 Their |glue_sign| and |glue_order| are pre-empted as well, since it
14502 is necessary to store information about what to do when a template ends.
14503 This information is called the |extra_info| field.
14504
14505 @d u_part(A) mem[A+height_offset].i /*pointer to \<u_j> token list*/
14506 @d v_part(A) mem[A+depth_offset].i /*pointer to \<v_j> token list*/
14507 @d extra_info(A) info(A+list_offset) /*info to remember during template*/
14508
14509 @ Alignments can occur within alignments, so a small stack is used to access
14510 the alignrecord information. At each level we have a |preamble| pointer,
14511 indicating the beginning of the preamble list; a |cur_align| pointer,
14512 indicating the current position in the preamble list; a |cur_span| pointer,
14513 indicating the value of |cur_align| at the beginning of a sequence of
14514 spanned columns; a |cur_loop| pointer, indicating the tabskip glue before
14515 an alignrecord that should be copied next if the current list is extended;
14516 and the |align_state| variable, which indicates the nesting of braces so
14517 that \.{\\cr} and \.{\\span} and tab marks are properly intercepted.
14518 There also are pointers |cur_head| and |cur_tail| to the head and tail
14519 of a list of adjustments being moved out from horizontal mode to
14520 vertical~mode.
14521
14522 The current values of these seven quantities appear in global variables;
14523 when they have to be pushed down, they are stored in 5-word nodes, and
14524 |align_ptr| points to the topmost such node.
14525
14526 @d preamble link(align_head) /*the current preamble list*/
14527 @d align_stack_node_size 5 /*number of |mem| words to save alignment states*/
14528
14529 @<Glob...@>=
14530 static pointer @!cur_align; /*current position in preamble list*/
14531 static pointer @!cur_span; /*start of currently spanned columns in preamble list*/
14532 static pointer @!cur_loop; /*place to copy when extending a periodic preamble*/
14533 static pointer @!align_ptr; /*most recently pushed-down alignment stack node*/
14534 static pointer @!cur_head, @!cur_tail; /*adjustment list pointers*/
14535
14536 @ The |align_state| and |preamble| variables are initialized elsewhere.
14537
14538 @<Set init...@>=
14539 align_ptr=null;cur_align=null;cur_span=null;cur_loop=null;
14540 cur_head=null;cur_tail=null;
14541
14542 @ Alignment stack maintenance is handled by a pair of trivial routines
14543 called |push_alignment| and |pop_alignment|.
14544
14545 @p static void push_alignment(void)
14546 {@+pointer p; /*the new alignment stack node*/
14547 p=get_node(align_stack_node_size);
14548 link(p)=align_ptr;info(p)=cur_align;
14549 llink(p)=preamble;rlink(p)=cur_span;
14550 mem[p+2].i=cur_loop;mem[p+3].i=align_state;
14551 info(p+4)=cur_head;link(p+4)=cur_tail;
14552 align_ptr=p;
14553 cur_head=get_avail();
14554 }
14555 @#
14556 static void pop_alignment(void)
14557 {@+pointer p; /*the top alignment stack node*/
14558 free_avail(cur_head);
14559 p=align_ptr;
14560 cur_tail=link(p+4);cur_head=info(p+4);
14561 align_state=mem[p+3].i;cur_loop=mem[p+2].i;
14562 cur_span=rlink(p);preamble=llink(p);
14563 cur_align=info(p);align_ptr=link(p);
14564 free_node(p, align_stack_node_size);
14565 }
14566
14567 @ \TeX\ has eight procedures that govern alignments: |init_align| and
14568 |fin_align| are used at the very beginning and the very end; |init_row| and
14569 |fin_row| are used at the beginning and end of individual rows; |init_span|
14570 is used at the beginning of a sequence of spanned columns (possibly involving
14571 only one column); |init_col| and |fin_col| are used at the beginning and
14572 end of individual columns; and |align_peek| is used after \.{\\cr} to see
14573 whether the next item is \.{\\noalign}.
14574
14575 We shall consider these routines in the order they are first used during
14576 the course of a complete \.{\\halign}, namely |init_align|, |align_peek|,
14577 |init_row|, |init_span|, |init_col|, |fin_col|, |fin_row|, |fin_align|.
14578
14579 @ When \.{\\halign} or \.{\\valign} has been scanned in an appropriate
14580 mode, \TeX\ calls |init_align|, whose task is to get everything off to a
14581 good start. This mostly involves scanning the preamble and putting its
14582 information into the preamble list.
14583 @^preamble@>
14584
14585 @p @t\4@>@<Declare the procedure called |get_preamble_token|@>@t@>@/
14586 static void align_peek(void);@/
14587 static void normal_paragraph(void);@/
14588 static void init_align(void)
14589 {@+
14590 pointer save_cs_ptr; /*|warning_index| value for error messages*/
14591 pointer @!p; /*for short-term temporary use*/
14592 save_cs_ptr=cur_cs; /*\.{\\halign} or \.{\\valign}, usually*/
14593 push_alignment();align_state=-1000000; /*enter a new alignment level*/
14594 @<Check for improper alignment in displayed math@>;
14595 push_nest(); /*enter a new semantic level*/
14596 @<Change current mode to |-vmode| for \.{\\halign}, |-hmode| for \.{\\valign}@>;
14597 scan_spec(align_group, false);@/
14598 @<Scan the preamble and record it in the |preamble| list@>;
14599 new_save_level(align_group);
14600 if (every_cr!=null) begin_token_list(every_cr, every_cr_text);
14601 align_peek(); /*look for \.{\\noalign} or \.{\\omit}*/
14602 }
14603
14604 @ In vertical modes, |prev_depth| already has the correct value. But
14605 if we are in |mmode| (displayed formula mode), we reach out to the
14606 enclosing vertical mode for the |prev_depth| value that produces the
14607 correct baseline calculations.
14608
14609 @<Change current mode...@>=
14610 if (mode==mmode)
14611 {@+mode=-vmode;prev_depth=nest[nest_ptr-2].aux_field.sc;
14612 }
14613 else if (mode > 0) negate(mode)
14614
14615 @ When \.{\\halign} is used as a displayed formula, there should be
14616 no other pieces of mlists present.
14617
14618 @<Check for improper alignment in displayed math@>=
14619 if ((mode==mmode)&&((tail!=head)||(incompleat_noad!=null)))
14620 {@+print_err("Improper ");print_esc("halign");print(" inside $$'s");
14621 @.Improper \\halign...@>
14622 help3("Displays can use special alignments (like \\eqalignno)",@/
14623 "only if nothing but the alignment itself is between $$'s.",@/
14624 "So I've deleted the formulas that preceded this alignment.");
14625 error();flush_math();
14626 }
14627
14628 @ @<Scan the preamble and record it in the |preamble| list@>=
14629 preamble=null;cur_align=align_head;cur_loop=null;scanner_status=aligning;
14630 warning_index=save_cs_ptr;align_state=-1000000;
14631 /*at this point, |cur_cmd==left_brace|*/
14632 loop@+{@+@<Append the current tabskip glue to the preamble list@>;
14633 if (cur_cmd==car_ret) goto done; /*\.{\\cr} ends the preamble*/
14634 @<Scan preamble text until |cur_cmd| is |tab_mark| or |car_ret|, looking
14635 for changes in the tabskip glue; append an alignrecord to the preamble list@>;
14636 }
14637 done: scanner_status=normal
14638
14639 @ @<Append the current tabskip glue to the preamble list@>=
14640 link(cur_align)=new_param_glue(tab_skip_code);
14641 cur_align=link(cur_align)
14642
14643 @ @<Scan preamble text until |cur_cmd| is |tab_mark| or |car_ret|...@>=
14644 @<Scan the template \<u_j>, putting the resulting token list in |hold_head|@>;
14645 link(cur_align)=new_null_box();cur_align=link(cur_align); /*a new alignrecord*/
14646 info(cur_align)=end_span;width(cur_align)=null_flag;
14647 u_part(cur_align)=link(hold_head);
14648 @<Scan the template \<v_j>, putting the resulting token list in |hold_head|@>;
14649 v_part(cur_align)=link(hold_head)
14650
14651 @ We enter `\.{\\span}' into |eqtb| with |tab_mark| as its command code,
14652 and with |span_code| as the command modifier. This makes \TeX\ interpret it
14653 essentially the same as an alignment delimiter like `\.\&', yet it is
14654 recognizably different when we need to distinguish it from a normal delimiter.
14655 It also turns out to be useful to give a special |cr_code| to `\.{\\cr}',
14656 and an even larger |cr_cr_code| to `\.{\\crcr}'.
14657
14658 The end of a template is represented by two ``frozen'' control sequences
14659 called \.{\\endtemplate}. The first has the command code |end_template|, which
14660 is | > outer_call|, so it will not easily disappear in the presence of errors.
14661 The |get_x_token| routine converts the first into the second, which has |endv|
14662 as its command code.
14663
14664 @d span_code 256 /*distinct from any character*/
14665 @d cr_code 257 /*distinct from |span_code| and from any character*/
14666 @d cr_cr_code (cr_code+1) /*this distinguishes \.{\\crcr} from \.{\\cr}*/
14667 @d end_template_token cs_token_flag+frozen_end_template
14668
14669 @<Put each of \TeX's primitives into the hash table@>=
14670 primitive("span", tab_mark, span_code);@/
14671 @!@:span\_}{\.{\\span} primitive@>
14672 primitive("cr", car_ret, cr_code);
14673 @!@:cr\_}{\.{\\cr} primitive@>
14674 text(frozen_cr)=text(cur_val);eqtb[frozen_cr]=eqtb[cur_val];@/
14675 primitive("crcr", car_ret, cr_cr_code);
14676 @!@:cr\_cr\_}{\.{\\crcr} primitive@>
14677 text(frozen_end_template)=text(frozen_endv)=s_no("endtemplate");
14678 @.endtemplate@>
14679 eq_type(frozen_endv)=endv;equiv(frozen_endv)=null_list;
14680 eq_level(frozen_endv)=level_one;@/
14681 eqtb[frozen_end_template]=eqtb[frozen_endv];
14682 eq_type(frozen_end_template)=end_template;
14683
14684 @ @<Cases of |print_cmd_chr|...@>=
14685 case tab_mark: if (chr_code==span_code) print_esc("span");
14686 else chr_cmd("alignment tab character ")@;@+break;
14687 case car_ret: if (chr_code==cr_code) print_esc("cr");
14688 else print_esc("crcr");@+break;
14689
14690 @ The preamble is copied directly, except that \.{\\tabskip} causes a change
14691 to the tabskip glue, thereby possibly expanding macros that immediately
14692 follow it. An appearance of \.{\\span} also causes such an expansion.
14693
14694 Note that if the preamble contains `\.{\\global\\tabskip}', the `\.{\\global}'
14695 token survives in the preamble and the `\.{\\tabskip}' defines new
14696 tabskip glue (locally).
14697
14698 @<Declare the procedure called |get_preamble_token|@>=
14699 static void get_preamble_token(void)
14700 {@+
14701 restart: get_token();
14702 while ((cur_chr==span_code)&&(cur_cmd==tab_mark))
14703 {@+get_token(); /*this token will be expanded once*/
14704 if (cur_cmd > max_command)
14705 {@+expand();get_token();
14706 }
14707 }
14708 if (cur_cmd==endv)
14709 fatal_error("(interwoven alignment preambles are not allowed)");
14710 @.interwoven alignment preambles...@>
14711 if ((cur_cmd==assign_glue)&&(cur_chr==glue_base+tab_skip_code))
14712 {@+scan_optional_equals();scan_glue(glue_val);
14713 if (global_defs > 0) geq_define(glue_base+tab_skip_code, glue_ref, cur_val);
14714 else eq_define(glue_base+tab_skip_code, glue_ref, cur_val);
14715 goto restart;
14716 }
14717 }
14718
14719 @ Spaces are eliminated from the beginning of a template.
14720
14721 @<Scan the template \<u_j>...@>=
14722 p=hold_head;link(p)=null;
14723 loop@+{@+get_preamble_token();
14724 if (cur_cmd==mac_param) goto done1;
14725 if ((cur_cmd <= car_ret)&&(cur_cmd >= tab_mark)&&(align_state==-1000000))
14726 if ((p==hold_head)&&(cur_loop==null)&&(cur_cmd==tab_mark)
14727 ) cur_loop=cur_align;
14728 else{@+print_err("Missing # inserted in alignment preamble");
14729 @.Missing \# inserted...@>
14730 help3("There should be exactly one # between &'s, when an",@/
14731 "\\halign or \\valign is being set up. In this case you had",@/
14732 "none, so I've put one in; maybe that will work.");
14733 back_error();goto done1;
14734 }
14735 else if ((cur_cmd!=spacer)||(p!=hold_head))
14736 {@+link(p)=get_avail();p=link(p);info(p)=cur_tok;
14737 }
14738 }
14739 done1:
14740
14741 @ @<Scan the template \<v_j>...@>=
14742 p=hold_head;link(p)=null;
14743 loop@+{@+resume: get_preamble_token();
14744 if ((cur_cmd <= car_ret)&&(cur_cmd >= tab_mark)&&(align_state==-1000000))
14745 goto done2;
14746 if (cur_cmd==mac_param)
14747 {@+print_err("Only one # is allowed per tab");
14748 @.Only one \# is allowed...@>
14749 help3("There should be exactly one # between &'s, when an",@/
14750 "\\halign or \\valign is being set up. In this case you had",@/
14751 "more than one, so I'm ignoring all but the first.");
14752 error();goto resume;
14753 }
14754 link(p)=get_avail();p=link(p);info(p)=cur_tok;
14755 }
14756 done2: link(p)=get_avail();p=link(p);
14757 info(p)=end_template_token /*put \.{\\endtemplate} at the end*/
14758
14759 @ The tricky part about alignments is getting the templates into the
14760 scanner at the right time, and recovering control when a row or column
14761 is finished.
14762
14763 We usually begin a row after each \.{\\cr} has been sensed, unless that
14764 \.{\\cr} is followed by \.{\\noalign} or by the right brace that terminates
14765 the alignment. The |align_peek| routine is used to look ahead and do
14766 the right thing; it either gets a new row started, or gets a \.{\\noalign}
14767 started, or finishes off the alignment.
14768
14769 @<Declare the procedure called |align_peek|@>=
14770 static void align_peek(void)
14771 {@+
14772 restart: align_state=1000000;
14773 @/do@+{get_x_or_protected();
14774 }@+ while (!(cur_cmd!=spacer));
14775 if (cur_cmd==no_align)
14776 {@+scan_left_brace();new_save_level(no_align_group);
14777 if (mode==-vmode) normal_paragraph();
14778 }
14779 else if (cur_cmd==right_brace) fin_align();
14780 else if ((cur_cmd==car_ret)&&(cur_chr==cr_cr_code))
14781 goto restart; /*ignore \.{\\crcr}*/
14782 else{@+init_row(); /*start a new row*/
14783 init_col(); /*start a new column and replace what we peeked at*/
14784 }
14785 }
14786
14787 @ To start a row (i.e., a `row' that rhymes with `dough' but not with `bough'),
14788 we enter a new semantic level, copy the first tabskip glue, and change
14789 from internal vertical mode to restricted horizontal mode or vice versa.
14790 The |space_factor| and |prev_depth| are not used on this semantic level,
14791 but we clear them to zero just to be tidy.
14792
14793 @p @t\4@>@<Declare the procedure called |init_span|@>@t@>@/
14794 static void init_row(void)
14795 {@+push_nest();mode=(-hmode-vmode)-mode;
14796 if (mode==-hmode) space_factor=0;@+else prev_depth=0;
14797 tail_append(new_glue(glue_ptr(preamble)));
14798 subtype(tail)=tab_skip_code+1;@/
14799 cur_align=link(preamble);cur_tail=cur_head;init_span(cur_align);
14800 }
14801
14802 @ The parameter to |init_span| is a pointer to the alignrecord where the
14803 next column or group of columns will begin. A new semantic level is
14804 entered, so that the columns will generate a list for subsequent packaging.
14805
14806 @<Declare the procedure called |init_span|@>=
14807 static void init_span(pointer @!p)
14808 {@+push_nest();
14809 if (mode==-hmode) space_factor=1000;
14810 else{@+prev_depth=ignore_depth;normal_paragraph();
14811 }
14812 cur_span=p;
14813 }
14814
14815 @ When a column begins, we assume that |cur_cmd| is either |omit| or else
14816 the current token should be put back into the input until the \<u_j>
14817 template has been scanned. (Note that |cur_cmd| might be |tab_mark| or
14818 |car_ret|.) We also assume that |align_state| is approximately 1000000 at
14819 this time. We remain in the same mode, and start the template if it is
14820 called for.
14821
14822 @p static void init_col(void)
14823 {@+extra_info(cur_align)=cur_cmd;
14824 if (cur_cmd==omit) align_state=0;
14825 else{@+back_input();begin_token_list(u_part(cur_align), u_template);
14826 } /*now |align_state==1000000|*/
14827 }
14828
14829 @ The scanner sets |align_state| to zero when the \<u_j> template ends. When
14830 a subsequent \.{\\cr} or \.{\\span} or tab mark occurs with |align_state==0|,
14831 the scanner activates the following code, which fires up the \<v_j> template.
14832 We need to remember the |cur_chr|, which is either |cr_cr_code|, |cr_code|,
14833 |span_code|, or a character code, depending on how the column text has ended.
14834
14835 This part of the program had better not be activated when the preamble
14836 to another alignment is being scanned, or when no alignment preamble is active.
14837
14838 @<Insert the \(v)\<v_j>...@>=
14839 {@+if ((scanner_status==aligning)||(cur_align==null))
14840 fatal_error("(interwoven alignment preambles are not allowed)");
14841 @.interwoven alignment preambles...@>
14842 cur_cmd=extra_info(cur_align);extra_info(cur_align)=cur_chr;
14843 if (cur_cmd==omit) begin_token_list(omit_template, v_template);
14844 else begin_token_list(v_part(cur_align), v_template);
14845 align_state=1000000;goto restart;
14846 }
14847
14848 @ The token list |omit_template| just referred to is a constant token
14849 list that contains the special control sequence \.{\\endtemplate} only.
14850
14851 @<Initialize the special...@>=
14852 info(omit_template)=end_template_token; /*|link(omit_template)==null|*/
14853
14854 @ When the |endv| command at the end of a \<v_j> template comes through the
14855 scanner, things really start to happen; and it is the |fin_col| routine
14856 that makes them happen. This routine returns |true| if a row as well as a
14857 column has been finished.
14858
14859 @p static bool fin_col(void)
14860 {@+
14861 pointer p; /*the alignrecord after the current one*/
14862 pointer @!q, @!r; /*temporary pointers for list manipulation*/
14863 pointer @!s; /*a new span node*/
14864 pointer @!u; /*a new unset box*/
14865 scaled @!w; /*natural width*/
14866 glue_ord @!o; /*order of infinity*/
14867 halfword @!n; /*span counter*/
14868 if (cur_align==null) confusion("endv");
14869 q=link(cur_align);@+if (q==null) confusion("endv");
14870 @:this can't happen endv}{\quad endv@>
14871 if (align_state < 500000)
14872 fatal_error("(interwoven alignment preambles are not allowed)");
14873 @.interwoven alignment preambles...@>
14874 p=link(q);
14875 @<If the preamble list has been traversed, check that the row has ended@>;
14876 if (extra_info(cur_align)!=span_code)
14877 {@+unsave();new_save_level(align_group);@/
14878 @<Package an unset box for the current column and record its width@>;
14879 @<Copy the tabskip glue between columns@>;
14880 if (extra_info(cur_align) >= cr_code)
14881 {@+return true;
14882 }
14883 init_span(p);
14884 }
14885 align_state=1000000;
14886 @/do@+{get_x_or_protected();
14887 }@+ while (!(cur_cmd!=spacer));
14888 cur_align=p;
14889 init_col();return false;
14890 }
14891
14892 @ @<If the preamble list has been traversed, check that the row has ended@>=
14893 if ((p==null)&&(extra_info(cur_align) < cr_code))
14894 if (cur_loop!=null) @<Lengthen the preamble periodically@>@;
14895 else{@+print_err("Extra alignment tab has been changed to ");
14896 @.Extra alignment tab...@>
14897 print_esc("cr");
14898 help3("You have given more \\span or & marks than there were",@/
14899 "in the preamble to the \\halign or \\valign now in progress.",@/
14900 "So I'll assume that you meant to type \\cr instead.");
14901 extra_info(cur_align)=cr_code;error();
14902 }
14903
14904 @ @<Lengthen the preamble...@>=
14905 {@+link(q)=new_null_box();p=link(q); /*a new alignrecord*/
14906 info(p)=end_span;width(p)=null_flag;cur_loop=link(cur_loop);
14907 @<Copy the templates from node |cur_loop| into node |p|@>;
14908 cur_loop=link(cur_loop);
14909 link(p)=new_glue(glue_ptr(cur_loop));
14910 subtype(link(p))=tab_skip_code+1;
14911 }
14912
14913 @ @<Copy the templates from node |cur_loop| into node |p|@>=
14914 q=hold_head;r=u_part(cur_loop);
14915 while (r!=null)
14916 {@+link(q)=get_avail();q=link(q);info(q)=info(r);r=link(r);
14917 }
14918 link(q)=null;u_part(p)=link(hold_head);
14919 q=hold_head;r=v_part(cur_loop);
14920 while (r!=null)
14921 {@+link(q)=get_avail();q=link(q);info(q)=info(r);r=link(r);
14922 }
14923 link(q)=null;v_part(p)=link(hold_head)
14924
14925 @ @<Copy the tabskip glue...@>=
14926 tail_append(new_glue(glue_ptr(link(cur_align))));
14927 subtype(tail)=tab_skip_code+1
14928
14929 @ @<Package an unset...@>=
14930 {@+if (mode==-hmode)
14931 {@+adjust_tail=cur_tail;u=hpack(link(head), natural);
14932 if (type(u)==hlist_node) w=width(u);
14933 else
14934 #if 0
14935 w=max_dimen+1;
14936 #else
14937 w = width(u);
14938 #endif
14939 cur_tail=adjust_tail;adjust_tail=null;
14940 }
14941 else{@+u=vpackage(link(head), natural, 0);
14942 if (type(u)==vlist_node) w=height(u);
14943 else w=max_dimen+1;
14944 }
14945 n=min_quarterword; /*this represents a span count of 1*/
14946 if (cur_span!=cur_align) @<Update width entry for spanned columns@>@;
14947 else if (w > width(cur_align)) width(cur_align)=w;
14948 if (type(u)==whatsit_node)
14949 { if (subtype(u)==hset_node ||subtype(u)==vset_node) type(u)=unset_set_node;
14950 else type(u)=unset_pack_node;
14951 span_count(u)=n;
14952 }
14953 else if (type(u)==hlist_node ||type(u)==vlist_node)
14954 { type(u)=unset_node;span_count(u)=n;
14955 @<Determine the stretch order@>;
14956 glue_order(u)=o;glue_stretch(u)=total_stretch[o];@/
14957 @<Determine the shrink order@>;
14958 glue_sign(u)=o;glue_shrink(u)=total_shrink[o];@/
14959 }
14960 pop_nest();link(tail)=u;tail=u;
14961 }
14962
14963 @ A span node is a 2-word record containing |width|, |info|, and |link|
14964 fields. The |link| field is not really a link, it indicates the number of
14965 spanned columns; the |info| field points to a span node for the same
14966 starting column, having a greater extent of spanning, or to |end_span|,
14967 which has the largest possible |link| field; the |width| field holds the
14968 largest natural width corresponding to a particular set of spanned columns.
14969
14970 A list of the maximum widths so far, for spanned columns starting at a
14971 given column, begins with the |info| field of the alignrecord for that
14972 column.
14973
14974 @d span_node_size 2 /*number of |mem| words for a span node*/
14975
14976 @<Initialize the special list heads...@>=
14977 link(end_span)=max_quarterword+1;info(end_span)=null;
14978
14979 @ @<Update width entry for spanned columns@>=
14980 {@+q=cur_span;
14981 @/do@+{incr(n);q=link(link(q));
14982 }@+ while (!(q==cur_align));
14983 if (n > max_quarterword) confusion("256 spans"); /*this can happen, but won't*/
14984 @^system dependencies@>
14985 @:this can't happen 256 spans}{\quad 256 spans@>
14986 q=cur_span;while (link(info(q)) < n) q=info(q);
14987 if (link(info(q)) > n)
14988 {@+s=get_node(span_node_size);info(s)=info(q);link(s)=n;
14989 info(q)=s;width(s)=w;
14990 }
14991 else if (width(info(q)) < w) width(info(q))=w;
14992 }
14993
14994 @ At the end of a row, we append an unset box to the current vlist (for
14995 \.{\\halign}) or the current hlist (for \.{\\valign}). This unset box
14996 contains the unset boxes for the columns, separated by the tabskip glue.
14997 Everything will be set later.
14998
14999 @p static void fin_row(void)
15000 {@+pointer p; /*the new unset box*/
15001 if (mode==-hmode)
15002 {@+p=hpack(link(head), natural);
15003 pop_nest();append_to_vlist(p);
15004 if (cur_head!=cur_tail)
15005 {@+link(tail)=link(cur_head);tail=cur_tail;
15006 }
15007 }
15008 else{@+p=vpack(link(head), natural);pop_nest();
15009 link(tail)=p;tail=p;space_factor=1000;
15010 }
15011 type(p)=unset_node;glue_stretch(p)=0;
15012 if (every_cr!=null) begin_token_list(every_cr, every_cr_text);
15013 align_peek();
15014 } /*note that |glue_shrink(p)==0| since |glue_shrink====shift_amount|*/
15015
15016 @ Finally, we will reach the end of the alignment, and we can breathe a
15017 sigh of relief that memory hasn't overflowed. All the unset boxes will now be
15018 set so that the columns line up, taking due account of spanned columns.
15019
15020 @p static void do_assignments(void);@/
15021 static void resume_after_display(void);@/
15022 static void build_page(void);@/
15023 static void fin_align(void)
15024 {@+pointer @!p, @!q, @!r, @!s, @!u, @!v; /*registers for the list operations*/
15025 scaled @!t, @!w; /*width of column*/
15026 bool x=false; /* indicates an extended alignment */
15027 scaled @!o; /*shift offset for unset boxes*/
15028 halfword @!n; /*matching span amount*/
15029 scaled @!rule_save; /*temporary storage for |overfull_rule|*/
15030 memory_word @!aux_save; /*temporary storage for |aux|*/
15031 if (cur_group!=align_group) confusion("align1");
15032 @:this can't happen align}{\quad align@>
15033 unsave(); /*that |align_group| was for individual entries*/
15034 if (cur_group!=align_group) confusion("align0");
15035 unsave(); /*that |align_group| was for the whole alignment*/
15036 if (nest[nest_ptr-1].mode_field==mmode) o=display_indent;
15037 else o=0;
15038 @<Go through the preamble list, determining the column widths and changing
15039 the alignrecords to dummy unset boxes@>;
15040 if (x)
15041 { @<Handle an alignment that depends on |hsize| or |vsize|@>@;
15042 pop_alignment();
15043 }
15044 else
15045 { @<Package the preamble list, to determine the actual tabskip glue amounts,
15046 and let |p| point to this prototype box@>;
15047 @<Set the glue in all the unset boxes of the current list@>;
15048 flush_node_list(p);pop_alignment();
15049 }
15050 @<Insert the \(c)current list into its environment@>;
15051 } @/
15052 @t\4@>@<Declare the procedure called |align_peek|@>@;
15053 @ @<Handle an alignment that depends on |hsize| or |vsize|@>=
15054 pointer r=get_node(align_node_size);
15055 save_ptr=save_ptr-2;pack_begin_line=-mode_line;
15056
15057 type(r)=whatsit_node; subtype(r)=align_node;
15058 align_preamble(r)=preamble;
15059 align_list(r)=link(head);
15060 align_extent(r)=new_xdimen(saved(1),saved_hfactor(1),saved_vfactor(1));
15061 align_m(r)= saved(0);
15062 align_v(r)= (mode!=-vmode);
15063 link(head)=r; tail=r;
15064 pack_begin_line=0;
15065
15066 @ It's time now to dismantle the preamble list and to compute the column
15067 widths. Let $w_{ij}$ be the maximum of the natural widths of all entries
15068 that span columns $i$ through $j$, inclusive. The alignrecord for column~$i$
15069 contains $w_{ii}$ in its |width| field, and there is also a linked list of
15070 the nonzero $w_{ij}$ for increasing $j$, accessible via the |info| field;
15071 these span nodes contain the value $j-i+|min_quarterword|$ in their
15072 |link| fields. The values of $w_{ii}$ were initialized to |null_flag|, which
15073 we regard as $-\infty$.
15074
15075 The final column widths are defined by the formula
15076 $$w_j=\max_{1\le i\le j}\biggl( w_{ij}-\sum_{i\le k<j}(t_k+w_k)\biggr),$$
15077 where $t_k$ is the natural width of the tabskip glue between columns
15078 $k$ and~$k+1$. However, if $w_{ij}=-\infty$ for all |i| in the range
15079 |1 <= i <= j| (i.e., if every entry that involved column~|j| also involved
15080 column~|j+1|), we let $w_j=0$, and we zero out the tabskip glue after
15081 column~|j|.
15082
15083 \TeX\ computes these values by using the following scheme: First $w_1=w_{11}$.
15084 Then replace $w_{2j}$ by $\max(w_{2j},w_{1j}-t_1-w_1)$, for all $j>1$.
15085 Then $w_2=w_{22}$. Then replace $w_{3j}$ by $\max(w_{3j},w_{2j}-t_2-w_2)$
15086 for all $j>2$; and so on. If any $w_j$ turns out to be $-\infty$, its
15087 value is changed to zero and so is the next tabskip.
15088
15089 @<Go through the preamble list,...@>=
15090 q=link(preamble);
15091 @/do@+{flush_list(u_part(q));flush_list(v_part(q));
15092 p=link(link(q));
15093 if (width(q)==null_flag)
15094 @<Nullify |width(q)| and the tabskip glue following this column@>;
15095 if (info(q)!=end_span)
15096 @<Merge the widths in the span nodes of |q| with those of |p|, destroying
15097 the span nodes of |q|@>;
15098 type(q)=unset_node;span_count(q)=min_quarterword;height(q)=0;
15099 depth(q)=0;glue_order(q)=normal;glue_sign(q)=normal;
15100 glue_stretch(q)=0;glue_shrink(q)=0;
15101 #if 0 /* Table nodes are not implemented in the 1.2 viewer */
15102 if (width(q)>max_dimen) x=true;
15103 #endif
15104 q=p;
15105 }@+ while (!(q==null))
15106
15107 @ @<Nullify |width(q)| and the tabskip glue following this column@>=
15108 {@+width(q)=0;r=link(q);s=glue_ptr(r);
15109 if (s!=zero_glue)
15110 {@+add_glue_ref(zero_glue);delete_glue_ref(s);
15111 glue_ptr(r)=zero_glue;
15112 }
15113 }
15114
15115 @ Merging of two span-node lists is a typical exercise in the manipulation of
15116 linearly linked data structures. The essential invariant in the following
15117 |@/do@+{| loop is that we want to dispense with node |r|, in |q|'s list,
15118 and |u| is its successor; all nodes of |p|'s list up to and including |s|
15119 have been processed, and the successor of |s| matches |r| or precedes |r|
15120 or follows |r|, according as |link(r)==n| or |link(r) > n| or |link(r) < n|.
15121
15122 @<Merge the widths...@>=
15123 {@+t=width(q)+width(glue_ptr(link(q)));
15124 r=info(q);s=end_span;info(s)=p;n=min_quarterword+1;
15125 @/do@+{width(r)=width(r)-t;u=info(r);
15126 while (link(r) > n)
15127 {@+s=info(s);n=link(info(s))+1;
15128 }
15129 if (link(r) < n)
15130 {@+info(r)=info(s);info(s)=r;decr(link(r));s=r;
15131 }
15132 else{@+if (width(r) > width(info(s))) width(info(s))=width(r);
15133 free_node(r, span_node_size);
15134 }
15135 r=u;
15136 }@+ while (!(r==end_span));
15137 }
15138
15139 @ Now the preamble list has been converted to a list of alternating unset
15140 boxes and tabskip glue, where the box widths are equal to the final
15141 column sizes. In case of \.{\\valign}, we change the widths to heights,
15142 so that a correct error message will be produced if the alignment is
15143 overfull or underfull.
15144
15145 @<Package the preamble list...@>=
15146 save_ptr=save_ptr-2;pack_begin_line=-mode_line;
15147 if (mode==-vmode)
15148 {@+rule_save=overfull_rule;
15149 overfull_rule=0; /*prevent rule from being packaged*/
15150 p=hpack(preamble, saved(1), saved_hfactor(1), saved_vfactor(1), saved(0), false);overfull_rule=rule_save;
15151 }
15152 else{@+q=link(preamble);
15153 @/do@+{height(q)=width(q);width(q)=0;q=link(link(q));
15154 }@+ while (!(q==null));
15155 p=vpack(preamble, saved(1), saved_hfactor(1), saved_vfactor(1), saved(0), false);
15156 q=link(preamble);
15157 @/do@+{width(q)=height(q);height(q)=0;q=link(link(q));
15158 }@+ while (!(q==null));
15159 }
15160 pack_begin_line=0
15161
15162 @ @<Set the glue in all the unset...@>=
15163 q=link(head);s=head;
15164 while (q!=null)
15165 {@+if (!is_char_node(q))
15166 if (type(q)==unset_node)
15167 @<Set the unset box |q| and the unset boxes in it@>@;
15168 else if (type(q)==rule_node)
15169 @<Make the running dimensions in rule |q| extend to the boundaries of
15170 the alignment@>;
15171 s=q;q=link(q);
15172 }
15173
15174 @ @<Make the running dimensions in rule |q| extend...@>=
15175 {@+if (is_running(width(q))) width(q)=width(p);
15176 if (is_running(height(q))) height(q)=height(p);
15177 if (is_running(depth(q))) depth(q)=depth(p);
15178 if (o!=0)
15179 {@+r=link(q);link(q)=null;q=hpack(q, natural);
15180 shift_amount(q)=o;link(q)=r;link(s)=q;
15181 }
15182 }
15183
15184 @ The unset box |q| represents a row that contains one or more unset boxes,
15185 depending on how soon \.{\\cr} occurred in that row.
15186
15187 @<Set the unset box |q| and the unset boxes in it@>=
15188 {@+if (mode==-vmode)
15189 {@+type(q)=hlist_node;width(q)=width(p);
15190 }
15191 else{@+type(q)=vlist_node;height(q)=height(p);
15192 }
15193 glue_order(q)=glue_order(p);glue_sign(q)=glue_sign(p);
15194 glue_set(q)=glue_set(p);shift_amount(q)=o;
15195 r=link(list_ptr(q));s=link(list_ptr(p));
15196 @/do@+{@<Set the glue in node |r| and change it from an unset node@>;
15197 r=link(link(r));s=link(link(s));
15198 }@+ while (!(r==null));
15199 }
15200
15201 @ A box made from spanned columns will be followed by tabskip glue nodes and
15202 by empty boxes as if there were no spanning. This permits perfect alignment
15203 of subsequent entries, and it prevents values that depend on floating point
15204 arithmetic from entering into the dimensions of any boxes.
15205
15206 @<Set the glue in node |r|...@>=
15207 n=span_count(r);t=width(s);w=t;u=hold_head;
15208 while (n > min_quarterword)
15209 {@+decr(n);
15210 @<Append tabskip glue and an empty box to list |u|, and update |s| and |t|
15211 as the prototype nodes are passed@>;
15212 }
15213 if (mode==-vmode)
15214 @<Make the unset node |r| into an |hlist_node| of width |w|, setting the
15215 glue as if the width were |t|@>@;
15216 else@<Make the unset node |r| into a |vlist_node| of height |w|, setting the
15217 glue as if the height were |t|@>;
15218 shift_amount(r)=0;
15219 if (u!=hold_head) /*append blank boxes to account for spanned nodes*/
15220 {@+link(u)=link(r);link(r)=link(hold_head);r=u;
15221 }
15222
15223 @ @<Append tabskip glue and an empty box to list |u|...@>=
15224 s=link(s);v=glue_ptr(s);link(u)=new_glue(v);u=link(u);
15225 subtype(u)=tab_skip_code+1;t=t+width(v);
15226 if (glue_sign(p)==stretching)
15227 {@+if (stretch_order(v)==glue_order(p))
15228 t=t+round(unfix(glue_set(p))*stretch(v));
15229 @^real multiplication@>
15230 }
15231 else if (glue_sign(p)==shrinking)
15232 {@+if (shrink_order(v)==glue_order(p))
15233 t=t-round(unfix(glue_set(p))*shrink(v));
15234 }
15235 s=link(s);link(u)=new_null_box();u=link(u);t=t+width(s);
15236 if (mode==-vmode) width(u)=width(s);@+else
15237 {@+type(u)=vlist_node;height(u)=width(s);
15238 }
15239
15240 @ @<Make the unset node |r| into an |hlist_node| of width |w|...@>=
15241 {@+height(r)=height(q);depth(r)=depth(q);
15242 if (t==width(r))
15243 {@+glue_sign(r)=normal;glue_order(r)=normal;
15244 set_glue_ratio_zero(glue_set(r));
15245 }
15246 else if (t > width(r))
15247 {@+glue_sign(r)=stretching;
15248 if (glue_stretch(r)==0) set_glue_ratio_zero(glue_set(r));
15249 else glue_set(r)=fix((t-width(r))/(double)glue_stretch(r));
15250 @^real division@>
15251 }
15252 else{@+glue_order(r)=glue_sign(r);glue_sign(r)=shrinking;
15253 if (glue_shrink(r)==0) set_glue_ratio_zero(glue_set(r));
15254 else if ((glue_order(r)==normal)&&(width(r)-t > glue_shrink(r)))
15255 set_glue_ratio_one(glue_set(r));
15256 else glue_set(r)=fix((width(r)-t)/(double)glue_shrink(r));
15257 }
15258 width(r)=w;type(r)=hlist_node;
15259 }
15260
15261 @ @<Make the unset node |r| into a |vlist_node| of height |w|...@>=
15262 {@+width(r)=width(q);
15263 if (t==height(r))
15264 {@+glue_sign(r)=normal;glue_order(r)=normal;
15265 set_glue_ratio_zero(glue_set(r));
15266 }
15267 else if (t > height(r))
15268 {@+glue_sign(r)=stretching;
15269 if (glue_stretch(r)==0) set_glue_ratio_zero(glue_set(r));
15270 else glue_set(r)=fix((t-height(r))/(double)glue_stretch(r));
15271 @^real division@>
15272 }
15273 else{@+glue_order(r)=glue_sign(r);glue_sign(r)=shrinking;
15274 if (glue_shrink(r)==0) set_glue_ratio_zero(glue_set(r));
15275 else if ((glue_order(r)==normal)&&(height(r)-t > glue_shrink(r)))
15276 set_glue_ratio_one(glue_set(r));
15277 else glue_set(r)=fix((height(r)-t)/(double)glue_shrink(r));
15278 }
15279 height(r)=w;type(r)=vlist_node;
15280 }
15281
15282 @ We now have a completed alignment, in the list that starts at |head|
15283 and ends at |tail|. This list will be merged with the one that encloses
15284 it. (In case the enclosing mode is |mmode|, for displayed formulas,
15285 we will need to insert glue before and after the display; that part of the
15286 program will be deferred until we're more familiar with such operations.)
15287
15288 In restricted horizontal mode, the |clang| part of |aux| is undefined;
15289 an over-cautious \PASCAL\ runtime system may complain about this.
15290 @^dirty \PASCAL@>
15291
15292 @<Insert the \(c)current list into its environment@>=
15293 aux_save=aux;p=link(head);q=tail;pop_nest();
15294 if (mode==mmode) @<Finish an alignment in a display@>@;
15295 else{@+aux=aux_save;link(tail)=p;
15296 if (p!=null) tail=q;
15297 if (mode==vmode) build_page();
15298 }
15299
15300 @* Breaking paragraphs into lines.
15301 We come now to what is probably the most interesting algorithm of \TeX:
15302 the mechanism for choosing the ``best possible'' breakpoints that yield
15303 the individual lines of a paragraph. \TeX's line-breaking algorithm takes
15304 a given horizontal list and converts it to a sequence of boxes that are
15305 appended to the current vertical list. In the course of doing this, it
15306 creates a special data structure containing three kinds of records that are
15307 not used elsewhere in \TeX. Such nodes are created while a paragraph is
15308 being processed, and they are destroyed afterwards; thus, the other parts
15309 of \TeX\ do not need to know anything about how line-breaking is done.
15310
15311 The method used here is based on an approach devised by Michael F. Plass and
15312 @^Plass, Michael Frederick@>
15313 @^Knuth, Donald Ervin@>
15314 the author in 1977, subsequently generalized and improved by the same two
15315 people in 1980. A detailed discussion appears in {\sl Software---Practice
15316 and Experience \bf11} (1981), 1119--1184, where it is shown that the
15317 line-breaking problem can be regarded as a special case of the problem of
15318 computing the shortest path in an acyclic network. The cited paper includes
15319 numerous examples and describes the history of line breaking as it has been
15320 practiced by printers through the ages. The present implementation adds two
15321 new ideas to the algorithm of 1980: Memory space requirements are considerably
15322 reduced by using smaller records for inactive nodes than for active ones,
15323 and arithmetic overflow is avoided by using ``delta distances'' instead of
15324 keeping track of the total distance from the beginning of the paragraph to the
15325 current point.
15326
15327 @ The |line_break| procedure should be invoked only in horizontal mode; it
15328 leaves that mode and places its output into the current vlist of the
15329 enclosing vertical mode (or internal vertical mode).
15330 There is one explicit parameter: |final_widow_penalty| is the amount of
15331 additional penalty to be inserted before the final line of the paragraph.
15332
15333 There are also a number of implicit parameters: The hlist to be broken
15334 starts at |link(head)|, and it is nonempty. The value of |prev_graf| in the
15335 enclosing semantic level tells where the paragraph should begin in the
15336 sequence of line numbers, in case hanging indentation or \.{\\parshape}
15337 is in use; |prev_graf| is zero unless this paragraph is being continued
15338 after a displayed formula. Other implicit parameters, such as the
15339 |par_shape_ptr| and various penalties to use for hyphenation, etc., appear
15340 in |eqtb|.
15341
15342 After |line_break| has acted, it will have updated the current vlist and the
15343 value of |prev_graf|. Furthermore, the global variable |just_box| will
15344 point to the final box created by |line_break|, so that the width of this
15345 line can be ascertained when it is necessary to decide whether to use
15346 |above_display_skip| or |above_display_short_skip| before a displayed formula.
15347
15348 @<Glob...@>=
15349 static pointer @!just_box; /*the |hlist_node| for the last line of the new paragraph*/
15350
15351 @ Since |line_break| is a rather lengthy procedure---sort of a small world unto
15352 itself---we must build it up little by little, somewhat more cautiously
15353 than we have done with the simpler procedures of \TeX. Here is the
15354 general outline.
15355
15356 @p @t\4@>@<Declare subprocedures for |line_break|@>@;
15357 static void line_break(int @!final_widow_penalty)
15358 {@+
15359 @<Local variables for line breaking@>@;
15360 pack_begin_line=mode_line; /*this is for over/underfull box messages*/
15361 @<Get ready to start line breaking@>;
15362 @<Find optimal breakpoints@>;
15363 @<Break the paragraph at the chosen breakpoints, justify the resulting lines
15364 to the correct widths, and append them to the current vertical list@>;
15365 @<Clean up the memory by removing the break nodes@>;
15366 pack_begin_line=0;
15367 }
15368 @#
15369 @t\4@>@<Declare \eTeX\ procedures for use by |main_control|@>@;
15370
15371 @ The first task is to move the list from |head| to |temp_head| and go
15372 into the enclosing semantic level. We also append the \.{\\parfillskip}
15373 glue to the end of the paragraph, removing a space (or other glue node) if
15374 it was there, since spaces usually precede blank lines and instances of
15375 `\.{\$\$}'. The |par_fill_skip| is preceded by an infinite penalty, so
15376 it will never be considered as a potential breakpoint.
15377
15378 This code assumes that a |glue_node| and a |penalty_node| occupy the
15379 same number of |mem|~words.
15380 @^data structure assumptions@>
15381
15382 @<Get ready to start...@>=
15383 link(temp_head)=link(head);
15384 if (is_char_node(tail)) tail_append(new_penalty(inf_penalty))@;
15385 else if (type(tail)!=glue_node) tail_append(new_penalty(inf_penalty))@;
15386 else{@+type(tail)=penalty_node;delete_glue_ref(glue_ptr(tail));
15387 flush_node_list(leader_ptr(tail));penalty(tail)=inf_penalty;
15388 }
15389 link(tail)=new_param_glue(par_fill_skip_code);
15390 init_cur_lang=prev_graf%0200000;
15391 init_l_hyf=prev_graf/020000000;
15392 init_r_hyf=(prev_graf/0200000)%0100;
15393 pop_nest();
15394
15395 @ When looking for optimal line breaks, \TeX\ creates a ``break node'' for
15396 each break that is {\sl feasible}, in the sense that there is a way to end
15397 a line at the given place without requiring any line to stretch more than
15398 a given tolerance. A break node is characterized by three things: the position
15399 of the break (which is a pointer to a |glue_node|, |math_node|, |penalty_node|,
15400 or |disc_node|); the ordinal number of the line that will follow this
15401 breakpoint; and the fitness classification of the line that has just
15402 ended, i.e., |tight_fit|, |decent_fit|, |loose_fit|, or |very_loose_fit|.
15403
15404 @d tight_fit 3 /*fitness classification for lines shrinking 0.5 to 1.0 of their
15405 shrinkability*/
15406 @d loose_fit 1 /*fitness classification for lines stretching 0.5 to 1.0 of their
15407 stretchability*/
15408 @d very_loose_fit 0 /*fitness classification for lines stretching more than
15409 their stretchability*/
15410 @d decent_fit 2 /*fitness classification for all other lines*/
15411
15412 @ The algorithm essentially determines the best possible way to achieve
15413 each feasible combination of position, line, and fitness. Thus, it answers
15414 questions like, ``What is the best way to break the opening part of the
15415 paragraph so that the fourth line is a tight line ending at such-and-such
15416 a place?'' However, the fact that all lines are to be the same length
15417 after a certain point makes it possible to regard all sufficiently large
15418 line numbers as equivalent, when the looseness parameter is zero, and this
15419 makes it possible for the algorithm to save space and time.
15420
15421 An ``active node'' and a ``passive node'' are created in |mem| for each
15422 feasible breakpoint that needs to be considered. Active nodes are three
15423 words long and passive nodes are two words long. We need active nodes only
15424 for breakpoints near the place in the paragraph that is currently being
15425 examined, so they are recycled within a comparatively short time after
15426 they are created.
15427
15428 @ An active node for a given breakpoint contains six fields:
15429
15430 \yskip\hang|link| points to the next node in the list of active nodes; the
15431 last active node has |link==last_active|.
15432
15433 \yskip\hang|break_node| points to the passive node associated with this
15434 breakpoint.
15435
15436 \yskip\hang|line_number| is the number of the line that follows this
15437 breakpoint.
15438
15439 \yskip\hang|fitness| is the fitness classification of the line ending at this
15440 breakpoint.
15441
15442 \yskip\hang|type| is either |hyphenated| or |unhyphenated|, depending on
15443 whether this breakpoint is a |disc_node|.
15444
15445 \yskip\hang|total_demerits| is the minimum possible sum of demerits over all
15446 lines leading from the beginning of the paragraph to this breakpoint.
15447
15448 \yskip\noindent
15449 The value of |link(active)| points to the first active node on a linked list
15450 of all currently active nodes. This list is in order by |line_number|,
15451 except that nodes with |line_number > easy_line| may be in any order relative
15452 to each other.
15453
15454 @d active_node_size 3 /*number of words in active nodes*/
15455 @d fitness(A) subtype(A) /*|very_loose_fit dotdot tight_fit| on final line for this break*/
15456 @d break_node(A) rlink(A) /*pointer to the corresponding passive node*/
15457 @d line_number(A) llink(A) /*line that begins at this breakpoint*/
15458 @d total_demerits(A) mem[A+2].i /*the quantity that \TeX\ minimizes*/
15459 @d unhyphenated 0 /*the |type| of a normal active break node*/
15460 @d hyphenated 1 /*the |type| of an active node that breaks at a |disc_node|*/
15461 @d last_active active /*the active list ends where it begins*/
15462
15463 @ @<Initialize the special list heads...@>=
15464 type(last_active)=hyphenated;line_number(last_active)=max_halfword;
15465 subtype(last_active)=0; /*the |subtype| is never examined by the algorithm*/
15466
15467 @ The passive node for a given breakpoint contains only four fields:
15468
15469 \yskip\hang|link| points to the passive node created just before this one,
15470 if any, otherwise it is |null|.
15471
15472 \yskip\hang|cur_break| points to the position of this breakpoint in the
15473 horizontal list for the paragraph being broken.
15474
15475 \yskip\hang|prev_break| points to the passive node that should precede this
15476 one in an optimal path to this breakpoint.
15477
15478 \yskip\hang|serial| is equal to |n| if this passive node is the |n|th
15479 one created during the current pass. (This field is used only when
15480 printing out detailed statistics about the line-breaking calculations.)
15481
15482 \yskip\noindent
15483 There is a global variable called |passive| that points to the most
15484 recently created passive node. Another global variable, |printed_node|,
15485 is used to help print out the paragraph when detailed information about
15486 the line-breaking computation is being displayed.
15487
15488 @d passive_node_size 2 /*number of words in passive nodes*/
15489 @d cur_break(A) rlink(A) /*in passive node, points to position of this breakpoint*/
15490 @d prev_break(A) llink(A) /*points to passive node that should precede this one*/
15491 @d serial(A) info(A) /*serial number for symbolic identification*/
15492
15493 @<Glob...@>=
15494 static pointer @!passive; /*most recent node on passive list*/
15495 static pointer @!printed_node; /*most recent node that has been printed*/
15496 static halfword @!pass_number; /*the number of passive nodes allocated on this pass*/
15497
15498 @ The active list also contains ``delta'' nodes that help the algorithm
15499 compute the badness of individual lines. Such nodes appear only between two
15500 active nodes, and they have |type==delta_node|. If |p| and |r| are active nodes
15501 and if |q| is a delta node between them, so that |link(p)==q| and |link(q)==r|,
15502 then |q| tells the space difference between lines in the horizontal list that
15503 start after breakpoint |p| and lines that start after breakpoint |r|. In
15504 other words, if we know the length of the line that starts after |p| and
15505 ends at our current position, then the corresponding length of the line that
15506 starts after |r| is obtained by adding the amounts in node~|q|. A delta node
15507 contains six scaled numbers, since it must record the net change in glue
15508 stretchability with respect to all orders of infinity. The natural width
15509 difference appears in |mem[q+1].sc|; the stretch differences in units of
15510 pt, fil, fill, and filll appear in |mem[q+2 dotdot q+5].sc|; and the shrink difference
15511 appears in |mem[q+6].sc|. The |subtype| field of a delta node is not used.
15512
15513 @d delta_node_size 7 /*number of words in a delta node*/
15514 @d delta_node 2 /*|type| field in a delta node*/
15515
15516 @ As the algorithm runs, it maintains a set of six delta-like registers
15517 for the length of the line following the first active breakpoint to the
15518 current position in the given hlist. When it makes a pass through the
15519 active list, it also maintains a similar set of six registers for the
15520 length following the active breakpoint of current interest. A third set
15521 holds the length of an empty line (namely, the sum of \.{\\leftskip} and
15522 \.{\\rightskip}); and a fourth set is used to create new delta nodes.
15523
15524 When we pass a delta node we want to do operations like
15525 $$\hbox{\ignorespaces|for
15526 k=1 to 6 do cur_active_width[k]=cur_active_width[k]+mem[q+k].sc|};$$ and we
15527 want to do this without the overhead of |for| loops. The |do_all_six|
15528 macro makes such six-tuples convenient.
15529
15530 @d do_all_six(A) A(1);A(2);A(3);A(4);A(5);A(6)
15531
15532 @<Glob...@>=
15533 static scaled @!active_width0[6], *const @!active_width = @!active_width0-1;
15534 /*distance from first active node to~|cur_p|*/
15535 static scaled @!cur_active_width0[6],
15536 *const @!cur_active_width = @!cur_active_width0-1; /*distance from current active node*/
15537 static scaled @!background0[6], *const @!background = @!background0-1; /*length of an ``empty'' line*/
15538 static scaled @!break_width0[6], *const @!break_width = @!break_width0-1; /*length being computed after current break*/
15539
15540 @ Let's state the principles of the delta nodes more precisely and concisely,
15541 so that the following programs will be less obscure. For each legal
15542 breakpoint~|p| in the paragraph, we define two quantities $\alpha(p)$ and
15543 $\beta(p)$ such that the length of material in a line from breakpoint~|p|
15544 to breakpoint~|q| is $\gamma+\beta(q)-\alpha(p)$, for some fixed $\gamma$.
15545 Intuitively, $\alpha(p)$ and $\beta(q)$ are the total length of material from
15546 the beginning of the paragraph to a point ``after'' a break at |p| and to a
15547 point ``before'' a break at |q|; and $\gamma$ is the width of an empty line,
15548 namely the length contributed by \.{\\leftskip} and \.{\\rightskip}.
15549
15550 Suppose, for example, that the paragraph consists entirely of alternating
15551 boxes and glue skips; let the boxes have widths $x_1\ldots x_n$ and
15552 let the skips have widths $y_1\ldots y_n$, so that the paragraph can be
15553 represented by $x_1y_1\ldots x_ny_n$. Let $p_i$ be the legal breakpoint
15554 at $y_i$; then $\alpha(p_i)=x_1+y_1+\cdots+x_i+y_i$, and $\beta(p_i)=
15555 x_1+y_1+\cdots+x_i$. To check this, note that the length of material from
15556 $p_2$ to $p_5$, say, is $\gamma+x_3+y_3+x_4+y_4+x_5=\gamma+\beta(p_5)
15557 -\alpha(p_2)$.
15558
15559 The quantities $\alpha$, $\beta$, $\gamma$ involve glue stretchability and
15560 shrinkability as well as a natural width. If we were to compute $\alpha(p)$
15561 and $\beta(p)$ for each |p|, we would need multiple precision arithmetic, and
15562 the multiprecise numbers would have to be kept in the active nodes.
15563 \TeX\ avoids this problem by working entirely with relative differences
15564 or ``deltas.'' Suppose, for example, that the active list contains
15565 $a_1\,\delta_1\,a_2\,\delta_2\,a_3$, where the |a|'s are active breakpoints
15566 and the $\delta$'s are delta nodes. Then $\delta_1=\alpha(a_1)-\alpha(a_2)$
15567 and $\delta_2=\alpha(a_2)-\alpha(a_3)$. If the line breaking algorithm is
15568 currently positioned at some other breakpoint |p|, the |active_width| array
15569 contains the value $\gamma+\beta(p)-\alpha(a_1)$. If we are scanning through
15570 the list of active nodes and considering a tentative line that runs from
15571 $a_2$ to~|p|, say, the |cur_active_width| array will contain the value
15572 $\gamma+\beta(p)-\alpha(a_2)$. Thus, when we move from $a_2$ to $a_3$,
15573 we want to add $\alpha(a_2)-\alpha(a_3)$ to |cur_active_width|; and this
15574 is just $\delta_2$, which appears in the active list between $a_2$ and
15575 $a_3$. The |background| array contains $\gamma$. The |break_width| array
15576 will be used to calculate values of new delta nodes when the active
15577 list is being updated.
15578
15579 @ Glue nodes in a horizontal list that is being paragraphed are not supposed to
15580 include ``infinite'' shrinkability; that is why the algorithm maintains
15581 four registers for stretching but only one for shrinking. If the user tries to
15582 introduce infinite shrinkability, the shrinkability will be reset to finite
15583 and an error message will be issued. A boolean variable |no_shrink_error_yet|
15584 prevents this error message from appearing more than once per paragraph.
15585
15586 @d check_shrinkage(A) if ((shrink_order(A)!=normal)&&(shrink(A)!=0))
15587 {@+A=finite_shrink(A);
15588 }
15589
15590 @<Glob...@>=
15591 static bool @!no_shrink_error_yet; /*have we complained about infinite shrinkage?*/
15592
15593 @ @<Declare subprocedures for |line_break|@>=
15594 static pointer finite_shrink(pointer @!p) /*recovers from infinite shrinkage*/
15595 {@+pointer q; /*new glue specification*/
15596 if (no_shrink_error_yet)
15597 {@+no_shrink_error_yet=false;
15598 #ifdef @!STAT
15599 if (tracing_paragraphs > 0) end_diagnostic(true);
15600 #endif
15601 @;
15602 print_err("Infinite glue shrinkage found in a paragraph");
15603 @.Infinite glue shrinkage...@>
15604 help5("The paragraph just ended includes some glue that has",@/
15605 "infinite shrinkability, e.g., `\\hskip 0pt minus 1fil'.",@/
15606 "Such glue doesn't belong there---it allows a paragraph",@/
15607 "of any length to fit on one line. But it's safe to proceed,",@/
15608 "since the offensive shrinkability has been made finite.");
15609 error();
15610 #ifdef @!STAT
15611 if (tracing_paragraphs > 0) begin_diagnostic();
15612 #endif
15613 @;
15614 }
15615 q=new_spec(p);shrink_order(q)=normal;
15616 delete_glue_ref(p);return q;
15617 }
15618
15619 @ @<Get ready to start...@>=
15620 no_shrink_error_yet=true;@/
15621 check_shrinkage(left_skip);check_shrinkage(right_skip);@/
15622 q=left_skip;r=right_skip;background[1]=width(q)+width(r);@/
15623 background[2]=0;background[3]=0;background[4]=0;background[5]=0;@/
15624 background[2+stretch_order(q)]=stretch(q);@/
15625 background[2+stretch_order(r)]=@|background[2+stretch_order(r)]+stretch(r);@/
15626 background[6]=shrink(q)+shrink(r);
15627
15628 @ A pointer variable |cur_p| runs through the given horizontal list as we look
15629 for breakpoints. This variable is global, since it is used both by |line_break|
15630 and by its subprocedure |try_break|.
15631
15632 Another global variable called |threshold| is used to determine the feasibility
15633 of individual lines: Breakpoints are feasible if there is a way to reach
15634 them without creating lines whose badness exceeds |threshold|. (The
15635 badness is compared to |threshold| before penalties are added, so that
15636 penalty values do not affect the feasibility of breakpoints, except that
15637 no break is allowed when the penalty is 10000 or more.) If |threshold|
15638 is 10000 or more, all legal breaks are considered feasible, since the
15639 |badness| function specified above never returns a value greater than~10000.
15640
15641 Up to three passes might be made through the paragraph in an attempt to find at
15642 least one set of feasible breakpoints. On the first pass, we have
15643 |threshold==pretolerance| and |second_pass==final_pass==false|.
15644 If this pass fails to find a
15645 feasible solution, |threshold| is set to |tolerance|, |second_pass| is set
15646 |true|, and an attempt is made to hyphenate as many words as possible.
15647 If that fails too, we add |emergency_stretch| to the background
15648 stretchability and set |final_pass==true|.
15649
15650 @<Glob...@>=
15651 static pointer @!cur_p; /*the current breakpoint under consideration*/
15652 static bool @!second_pass; /*is this our second attempt to break this paragraph?*/
15653 static bool @!final_pass; /*is this our final attempt to break this paragraph?*/
15654 static int @!threshold; /*maximum badness on feasible lines*/
15655
15656 @ The heart of the line-breaking procedure is `|try_break|', a subroutine
15657 that tests if the current breakpoint |cur_p| is feasible, by running
15658 through the active list to see what lines of text can be made from active
15659 nodes to~|cur_p|. If feasible breaks are possible, new break nodes are
15660 created. If |cur_p| is too far from an active node, that node is
15661 deactivated.
15662
15663 The parameter |pi| to |try_break| is the penalty associated
15664 with a break at |cur_p|; we have |pi==eject_penalty| if the break is forced,
15665 and |pi==inf_penalty| if the break is illegal.
15666
15667 The other parameter, |break_type|, is set to |hyphenated| or |unhyphenated|,
15668 depending on whether or not the current break is at a |disc_node|. The
15669 end of a paragraph is also regarded as `|hyphenated|'; this case is
15670 distinguishable by the condition |cur_p==null|.
15671
15672 @d copy_to_cur_active(A) cur_active_width[A]=active_width[A]
15673 @<Declare subprocedures for |line_break|@>=
15674 static void try_break(int @!pi, small_number @!break_type)
15675 {@+
15676 pointer r; /*runs through the active list*/
15677 pointer @!prev_r; /*stays a step behind |r|*/
15678 halfword @!old_l; /*maximum line number in current equivalence class of lines*/
15679 bool @!no_break_yet; /*have we found a feasible break at |cur_p|?*/
15680 @<Other local variables for |try_break|@>@;
15681 @<Make sure that |pi| is in the proper range@>;
15682 no_break_yet=true;prev_r=active;old_l=0;
15683 do_all_six(copy_to_cur_active);
15684 loop@+{@+resume: r=link(prev_r);
15685 @<If node |r| is of type |delta_node|, update |cur_active_width|, set |prev_r|
15686 and |prev_prev_r|, then |goto resume|@>;
15687 @<If a line number class has ended, create new active nodes for the best
15688 feasible breaks in that class; then |return| if |r=last_active|, otherwise
15689 compute the new |line_width|@>;
15690 @<Consider the demerits for a line from |r| to |cur_p|; deactivate node
15691 |r| if it should no longer be active; then |goto resume| if a line from
15692 |r| to |cur_p| is infeasible, otherwise record a new feasible break@>;
15693 }
15694 end: ;
15695 #ifdef @!STAT
15696 @<Update the value of |printed_node| for symbolic displays@>;
15697 #endif
15698 @;
15699 }
15700
15701 @ @<Other local variables for |try_break|@>=
15702 pointer @!prev_prev_r; /*a step behind |prev_r|, if |type(prev_r)==delta_node|*/
15703 pointer @!s; /*runs through nodes ahead of |cur_p|*/
15704 pointer @!q; /*points to a new node being created*/
15705 pointer @!v; /*points to a glue specification or a node ahead of |cur_p|*/
15706 int @!t; /*node count, if |cur_p| is a discretionary node*/
15707 internal_font_number @!f; /*used in character width calculation*/
15708 halfword @!l; /*line number of current active node*/
15709 bool @!node_r_stays_active; /*should node |r| remain in the active list?*/
15710 scaled @!line_width; /*the current line will be justified to this width*/
15711 int @!fit_class; /*possible fitness class of test line*/
15712 halfword @!b; /*badness of test line*/
15713 int @!d; /*demerits of test line*/
15714 bool @!artificial_demerits; /*has |d| been forced to zero?*/
15715 #ifdef @!STAT
15716 pointer @!save_link; /*temporarily holds value of |link(cur_p)|*/
15717 #endif
15718 scaled @!shortfall; /*used in badness calculations*/
15719
15720 @ @<Make sure that |pi| is in the proper range@>=
15721 if (abs(pi) >= inf_penalty)
15722 if (pi > 0) goto end; /*this breakpoint is inhibited by infinite penalty*/
15723 else pi=eject_penalty /*this breakpoint will be forced*/
15724
15725 @ The following code uses the fact that |type(last_active)!=delta_node|.
15726
15727 @d update_width(A) @|
15728 cur_active_width[A]=cur_active_width[A]+mem[r+A].sc
15729
15730 @<If node |r|...@>=
15731 @^inner loop@>
15732 if (type(r)==delta_node)
15733 {@+do_all_six(update_width);
15734 prev_prev_r=prev_r;prev_r=r;goto resume;
15735 }
15736
15737 @ As we consider various ways to end a line at |cur_p|, in a given line number
15738 class, we keep track of the best total demerits known, in an array with
15739 one entry for each of the fitness classifications. For example,
15740 |minimal_demerits[tight_fit]| contains the fewest total demerits of feasible
15741 line breaks ending at |cur_p| with a |tight_fit| line; |best_place[tight_fit]|
15742 points to the passive node for the break before~|cur_p| that achieves such
15743 an optimum; and |best_pl_line[tight_fit]| is the |line_number| field in the
15744 active node corresponding to |best_place[tight_fit]|. When no feasible break
15745 sequence is known, the |minimal_demerits| entries will be equal to
15746 |awful_bad|, which is $2^{30}-1$. Another variable, |minimum_demerits|,
15747 keeps track of the smallest value in the |minimal_demerits| array.
15748
15749 @d awful_bad 07777777777 /*more than a billion demerits*/
15750
15751 @<Global...@>=
15752 static int @!minimal_demerits0[tight_fit-very_loose_fit+1],
15753 *const @!minimal_demerits = @!minimal_demerits0-very_loose_fit; /*best total
15754 demerits known for current line class and position, given the fitness*/
15755 static int @!minimum_demerits; /*best total demerits known for current line class
15756 and position*/
15757 static pointer @!best_place0[tight_fit-very_loose_fit+1],
15758 *const @!best_place = @!best_place0-very_loose_fit; /*how to achieve
15759 |minimal_demerits|*/
15760 static halfword @!best_pl_line0[tight_fit-very_loose_fit+1],
15761 *const @!best_pl_line = @!best_pl_line0-very_loose_fit; /*corresponding
15762 line number*/
15763
15764 @ @<Get ready to start...@>=
15765 minimum_demerits=awful_bad;
15766 minimal_demerits[tight_fit]=awful_bad;
15767 minimal_demerits[decent_fit]=awful_bad;
15768 minimal_demerits[loose_fit]=awful_bad;
15769 minimal_demerits[very_loose_fit]=awful_bad;
15770
15771 @ The first part of the following code is part of \TeX's inner loop, so
15772 we don't want to waste any time. The current active node, namely node |r|,
15773 contains the line number that will be considered next. At the end of the
15774 list we have arranged the data structure so that |r==last_active| and
15775 |line_number(last_active) > old_l|.
15776 @^inner loop@>
15777
15778 @<If a line number class...@>=
15779 {@+l=line_number(r);
15780 if (l > old_l)
15781 {@+ /*now we are no longer in the inner loop*/
15782 if ((minimum_demerits < awful_bad)&&@|
15783 ((old_l!=easy_line)||(r==last_active)))
15784 @<Create new active nodes for the best feasible breaks just found@>;
15785 if (r==last_active) goto end;
15786 @<Compute the new line width@>;
15787 }
15788 }
15789
15790 @ It is not necessary to create new active nodes having |minimal_demerits|
15791 greater than
15792 |minimum_demerits+abs(adj_demerits)|, since such active nodes will never
15793 be chosen in the final paragraph breaks. This observation allows us to
15794 omit a substantial number of feasible breakpoints from further consideration.
15795
15796 @<Create new active nodes...@>=
15797 {@+if (no_break_yet) @<Compute the values of |break_width|@>;
15798 @<Insert a delta node to prepare for breaks at |cur_p|@>;
15799 if (abs(adj_demerits) >= awful_bad-minimum_demerits)
15800 minimum_demerits=awful_bad-1;
15801 else minimum_demerits=minimum_demerits+abs(adj_demerits);
15802 for (fit_class=very_loose_fit; fit_class<=tight_fit; fit_class++)
15803 {@+if (minimal_demerits[fit_class] <= minimum_demerits)
15804 @<Insert a new active node from |best_place[fit_class]| to |cur_p|@>;
15805 minimal_demerits[fit_class]=awful_bad;
15806 }
15807 minimum_demerits=awful_bad;
15808 @<Insert a delta node to prepare for the next active node@>;
15809 }
15810
15811 @ When we insert a new active node for a break at |cur_p|, suppose this
15812 new node is to be placed just before active node |a|; then we essentially
15813 want to insert `$\delta\,|cur_p|\,\delta^\prime$' before |a|, where
15814 $\delta=\alpha(a)-\alpha(|cur_p|)$ and $\delta^\prime=\alpha(|cur_p|)-\alpha(a)$
15815 in the notation explained above. The |cur_active_width| array now holds
15816 $\gamma+\beta(|cur_p|)-\alpha(a)$; so $\delta$ can be obtained by
15817 subtracting |cur_active_width| from the quantity $\gamma+\beta(|cur_p|)-
15818 \alpha(|cur_p|)$. The latter quantity can be regarded as the length of a
15819 line ``from |cur_p| to |cur_p|''; we call it the |break_width| at |cur_p|.
15820
15821 The |break_width| is usually negative, since it consists of the background
15822 (which is normally zero) minus the width of nodes following~|cur_p| that are
15823 eliminated after a break. If, for example, node |cur_p| is a glue node, the
15824 width of this glue is subtracted from the background; and we also look
15825 ahead to eliminate all subsequent glue and penalty and kern and math
15826 nodes, subtracting their widths as well.
15827
15828 Kern nodes do not disappear at a line break unless they are |explicit|.
15829
15830 @d set_break_width_to_background(A) break_width[A]=background[A]
15831
15832 @<Compute the values of |break...@>=
15833 {@+no_break_yet=false;do_all_six(set_break_width_to_background);
15834 s=cur_p;
15835 if (break_type > unhyphenated) if (cur_p!=null)
15836 @<Compute the discretionary |break_width| values@>;
15837 while (s!=null)
15838 {@+if (is_char_node(s)) goto done;
15839 switch (type(s)) {
15840 case glue_node: @<Subtract glue from |break_width|@>@;@+break;
15841 case penalty_node: do_nothing;@+break;
15842 case math_node: break_width[1]=break_width[1]-width(s);@+break;
15843 case kern_node: if (subtype(s)!=explicit) goto done;
15844 else break_width[1]=break_width[1]-width(s);@+break;
15845 default:goto done;
15846 } @/
15847 s=link(s);
15848 }
15849 done: ;}
15850
15851 @ @<Subtract glue from |break...@>=
15852 {@+v=glue_ptr(s);break_width[1]=break_width[1]-width(v);
15853 break_width[2+stretch_order(v)]=break_width[2+stretch_order(v)]-stretch(v);
15854 break_width[6]=break_width[6]-shrink(v);
15855 }
15856
15857 @ When |cur_p| is a discretionary break, the length of a line ``from |cur_p| to
15858 |cur_p|'' has to be defined properly so that the other calculations work out.
15859 Suppose that the pre-break text at |cur_p| has length $l_0$, the post-break
15860 text has length $l_1$, and the replacement text has length |l|. Suppose
15861 also that |q| is the node following the replacement text. Then length of a
15862 line from |cur_p| to |q| will be computed as $\gamma+\beta(q)-\alpha(|cur_p|)$,
15863 where $\beta(q)=\beta(|cur_p|)-l_0+l$. The actual length will be the background
15864 plus $l_1$, so the length from |cur_p| to |cur_p| should be $\gamma+l_0+l_1-l$.
15865 If the post-break text of the discretionary is empty, a break may also
15866 discard~|q|; in that unusual case we subtract the length of~|q| and any
15867 other nodes that will be discarded after the discretionary break.
15868
15869 The value of $l_0$ need not be computed, since |line_break| will put
15870 it into the global variable |disc_width| before calling |try_break|.
15871
15872 @<Glob...@>=
15873 static scaled @!disc_width; /*the length of discretionary material preceding a break*/
15874
15875 @ @<Compute the discretionary |break...@>=
15876 {@+t=replace_count(cur_p);v=cur_p;s=post_break(cur_p);
15877 while (t > 0)
15878 {@+decr(t);v=link(v);
15879 @<Subtract the width of node |v| from |break_width|@>;
15880 }
15881 while (s!=null)
15882 {@+@<Add the width of node |s| to |break_width|@>;
15883 s=link(s);
15884 }
15885 break_width[1]=break_width[1]+disc_width;
15886 if (post_break(cur_p)==null) s=link(v);
15887 /*nodes may be discardable after the break*/
15888 }
15889
15890 @ Replacement texts and discretionary texts are supposed to contain
15891 only character nodes, kern nodes, ligature nodes, and box or rule nodes.
15892
15893 @<Subtract the width of node |v|...@>=
15894 if (is_char_node(v))
15895 {@+f=font(v);
15896 break_width[1]=break_width[1]-char_width(f, character(v));
15897 }
15898 else switch (type(v)) {
15899 case ligature_node: {@+f=font(lig_char(v));@/
15900 break_width[1]=@|break_width[1]-
15901 char_width(f, character(lig_char(v)));
15902 } @+break;
15903 case hlist_node: case vlist_node: case rule_node:
15904 case kern_node:
15905 break_width[1]=break_width[1]-width(v);@+break;
15906 default:confusion("disc1");
15907 @:this can't happen disc1}{\quad disc1@>
15908 }
15909
15910 @ @<Add the width of node |s| to |b...@>=
15911 if (is_char_node(s))
15912 {@+f=font(s);
15913 break_width[1]=@|break_width[1]+char_width(f, character(s));
15914 }
15915 else switch (type(s)) {
15916 case ligature_node: {@+f=font(lig_char(s));
15917 break_width[1]=break_width[1]+
15918 char_width(f, character(lig_char(s)));
15919 } @+break;
15920 case hlist_node: case vlist_node: case rule_node:
15921 case kern_node:
15922 break_width[1]=break_width[1]+width(s);@+break;
15923 default:confusion("disc2");
15924 @:this can't happen disc2}{\quad disc2@>
15925 }
15926
15927 @ We use the fact that |type(active)!=delta_node|.
15928
15929 @d convert_to_break_width(A) @|
15930 mem[prev_r+A].sc=@|@t\hskip10pt@>mem[prev_r+A].sc
15931 -cur_active_width[A]+break_width[A]
15932 @d store_break_width(A) active_width[A]=break_width[A]
15933 @d new_delta_to_break_width(A) @|
15934 mem[q+A].sc=break_width[A]-cur_active_width[A]
15935
15936 @<Insert a delta node to prepare for breaks at |cur_p|@>=
15937 if (type(prev_r)==delta_node) /*modify an existing delta node*/
15938 {@+do_all_six(convert_to_break_width);
15939 }
15940 else if (prev_r==active) /*no delta node needed at the beginning*/
15941 {@+do_all_six(store_break_width);
15942 }
15943 else{@+q=get_node(delta_node_size);link(q)=r;type(q)=delta_node;@/
15944 subtype(q)=0; /*the |subtype| is not used*/
15945 do_all_six(new_delta_to_break_width);
15946 link(prev_r)=q;prev_prev_r=prev_r;prev_r=q;
15947 }
15948
15949 @ When the following code is performed, we will have just inserted at
15950 least one active node before |r|, so |type(prev_r)!=delta_node|.
15951
15952 @d new_delta_from_break_width(A) @|mem[q+A].sc=
15953 cur_active_width[A]-break_width[A]
15954
15955 @<Insert a delta node to prepare for the next active node@>=
15956 if (r!=last_active)
15957 {@+q=get_node(delta_node_size);link(q)=r;type(q)=delta_node;@/
15958 subtype(q)=0; /*the |subtype| is not used*/
15959 do_all_six(new_delta_from_break_width);
15960 link(prev_r)=q;prev_prev_r=prev_r;prev_r=q;
15961 }
15962
15963 @ When we create an active node, we also create the corresponding
15964 passive node.
15965
15966 @<Insert a new active node from |best_place[fit_class]| to |cur_p|@>=
15967 {@+q=get_node(passive_node_size);
15968 link(q)=passive;passive=q;cur_break(q)=cur_p;
15969 #ifdef @!STAT
15970 incr(pass_number);serial(q)=pass_number;
15971 #endif
15972 @;@/
15973 prev_break(q)=best_place[fit_class];@/
15974 q=get_node(active_node_size);break_node(q)=passive;
15975 line_number(q)=best_pl_line[fit_class]+1;
15976 fitness(q)=fit_class;type(q)=break_type;
15977 total_demerits(q)=minimal_demerits[fit_class];
15978 link(q)=r;link(prev_r)=q;prev_r=q;
15979 #ifdef @!STAT
15980 if (tracing_paragraphs > 0)
15981 @<Print a symbolic description of the new break node@>;
15982 #endif
15983 @;@/
15984 }
15985
15986 @ @<Print a symbolic description of the new break node@>=
15987 {@+print_nl("@@@@");print_int(serial(passive));
15988 @.\AT\AT@>
15989 print(": line ");print_int(line_number(q)-1);
15990 print_char('.');print_int(fit_class);
15991 if (break_type==hyphenated) print_char('-');
15992 print(" t=");print_int(total_demerits(q));
15993 print(" -> @@@@");
15994 if (prev_break(passive)==null) print_char('0');
15995 else print_int(serial(prev_break(passive)));
15996 }
15997
15998 @ The length of lines depends on whether the user has specified
15999 \.{\\parshape} or \.{\\hangindent}. If |par_shape_ptr| is not null, it
16000 points to a $(2n+1)$-word record in |mem|, where the |info| in the first
16001 word contains the value of |n|, and the other $2n$ words contain the left
16002 margins and line lengths for the first |n| lines of the paragraph; the
16003 specifications for line |n| apply to all subsequent lines. If
16004 |par_shape_ptr==null|, the shape of the paragraph depends on the value of
16005 |n==hang_after|; if |n >= 0|, hanging indentation takes place on lines |n+1|,
16006 |n+2|, \dots, otherwise it takes place on lines 1, \dots, $\vert
16007 n\vert$. When hanging indentation is active, the left margin is
16008 |hang_indent|, if |hang_indent >= 0|, else it is 0; the line length is
16009 $|hsize|-\vert|hang_indent|\vert$. The normal setting is
16010 |par_shape_ptr==null|, |hang_after==1|, and |hang_indent==0|.
16011 Note that if |hang_indent==0|, the value of |hang_after| is irrelevant.
16012 @^length of lines@> @^hanging indentation@>
16013
16014 @<Glob...@>=
16015 static halfword @!easy_line; /*line numbers | > easy_line| are equivalent in break nodes*/
16016 static halfword @!last_special_line; /*line numbers | > last_special_line| all have
16017 the same width*/
16018 static scaled @!first_width; /*the width of all lines | <= last_special_line|, if
16019 no \.{\\parshape} has been specified*/
16020 static scaled @!second_width; /*the width of all lines | > last_special_line|*/
16021 static scaled @!first_indent; /*left margin to go with |first_width|*/
16022 static scaled @!second_indent; /*left margin to go with |second_width|*/
16023
16024 @ We compute the values of |easy_line| and the other local variables relating
16025 to line length when the |line_break| procedure is initializing itself.
16026
16027 @<Get ready to start...@>=
16028 if (par_shape_ptr==null)
16029 if (hang_indent==0)
16030 {@+last_special_line=0;second_width=hsize;
16031 second_indent=0;
16032 }
16033 else@<Set line length parameters in preparation for hanging indentation@>@;
16034 else{@+last_special_line=info(par_shape_ptr)-1;
16035 second_width=mem[par_shape_ptr+2*(last_special_line+1)].sc;
16036 second_indent=mem[par_shape_ptr+2*last_special_line+1].sc;
16037 }
16038 if (looseness==0) easy_line=last_special_line;
16039 else easy_line=max_halfword
16040
16041 @ @<Set line length parameters in preparation for hanging indentation@>=
16042 {@+last_special_line=abs(hang_after);
16043 if (hang_after < 0)
16044 {@+first_width=hsize-abs(hang_indent);
16045 if (hang_indent >= 0) first_indent=hang_indent;
16046 else first_indent=0;
16047 second_width=hsize;second_indent=0;
16048 }
16049 else{@+first_width=hsize;first_indent=0;
16050 second_width=hsize-abs(hang_indent);
16051 if (hang_indent >= 0) second_indent=hang_indent;
16052 else second_indent=0;
16053 }
16054 }
16055
16056 @ When we come to the following code, we have just encountered the first
16057 active node~|r| whose |line_number| field contains |l|. Thus we want to
16058 compute the length of the $l\mskip1mu$th line of the current paragraph. Furthermore,
16059 we want to set |old_l| to the last number in the class of line numbers
16060 equivalent to~|l|.
16061
16062 @<Compute the new line width@>=
16063 if (l > easy_line)
16064 {@+line_width=second_width;old_l=max_halfword-1;
16065 }
16066 else{@+old_l=l;
16067 if (l > last_special_line) line_width=second_width;
16068 else if (par_shape_ptr==null) line_width=first_width;
16069 else line_width=mem[par_shape_ptr+2*l@,].sc;
16070 }
16071
16072 @ The remaining part of |try_break| deals with the calculation of
16073 demerits for a break from |r| to |cur_p|.
16074
16075 The first thing to do is calculate the badness, |b|. This value will always
16076 be between zero and |inf_bad+1|; the latter value occurs only in the
16077 case of lines from |r| to |cur_p| that cannot shrink enough to fit the necessary
16078 width. In such cases, node |r| will be deactivated.
16079 We also deactivate node~|r| when a break at~|cur_p| is forced, since future
16080 breaks must go through a forced break.
16081
16082 @<Consider the demerits for a line from |r| to |cur_p|...@>=
16083 {@+artificial_demerits=false;@/
16084 @^inner loop@>
16085 shortfall=line_width-cur_active_width[1]; /*we're this much too short*/
16086 if (shortfall > 0)
16087 @<Set the value of |b| to the badness for stretching the line, and compute
16088 the corresponding |fit_class|@>@;
16089 else@<Set the value of |b| to the badness for shrinking the line, and compute
16090 the corresponding |fit_class|@>;
16091 if ((b > inf_bad)||(pi==eject_penalty))
16092 @<Prepare to deactivate node~|r|, and |goto deactivate| unless there is
16093 a reason to consider lines of text from |r| to |cur_p|@>@;
16094 else{@+prev_r=r;
16095 if (b > threshold) goto resume;
16096 node_r_stays_active=true;
16097 }
16098 @<Record a new feasible break@>;
16099 if (node_r_stays_active) goto resume; /*|prev_r| has been set to |r|*/
16100 deactivate: @<Deactivate node |r|@>;
16101 }
16102
16103 @ When a line must stretch, the available stretchability can be found in the
16104 subarray |cur_active_width[2 dotdot 5]|, in units of points, fil, fill, and filll.
16105
16106 The present section is part of \TeX's inner loop, and it is most often performed
16107 when the badness is infinite; therefore it is worth while to make a quick
16108 test for large width excess and small stretchability, before calling the
16109 |badness| subroutine.
16110 @^inner loop@>
16111
16112 @<Set the value of |b| to the badness for stretching...@>=
16113 if ((cur_active_width[3]!=0)||(cur_active_width[4]!=0)||@|
16114 (cur_active_width[5]!=0))
16115 {@+b=0;fit_class=decent_fit; /*infinite stretch*/
16116 }
16117 else{@+if (shortfall > 7230584) if (cur_active_width[2] < 1663497)
16118 {@+b=inf_bad;fit_class=very_loose_fit;goto done1;
16119 }
16120 b=badness(shortfall, cur_active_width[2]);
16121 if (b > 12)
16122 if (b > 99) fit_class=very_loose_fit;
16123 else fit_class=loose_fit;
16124 else fit_class=decent_fit;
16125 done1: ;
16126 }
16127
16128 @ Shrinkability is never infinite in a paragraph;
16129 we can shrink the line from |r| to |cur_p| by at most |cur_active_width[6]|.
16130
16131 @<Set the value of |b| to the badness for shrinking...@>=
16132 {@+if (-shortfall > cur_active_width[6]) b=inf_bad+1;
16133 else b=badness(-shortfall, cur_active_width[6]);
16134 if (b > 12) fit_class=tight_fit;@+else fit_class=decent_fit;
16135 }
16136
16137 @ During the final pass, we dare not lose all active nodes, lest we lose
16138 touch with the line breaks already found. The code shown here makes sure
16139 that such a catastrophe does not happen, by permitting overfull boxes as
16140 a last resort. This particular part of \TeX\ was a source of several subtle
16141 bugs before the correct program logic was finally discovered; readers
16142 who seek to ``improve'' \TeX\ should therefore think thrice before daring
16143 to make any changes here.
16144 @^overfull boxes@>
16145
16146 @<Prepare to deactivate node~|r|, and |goto deactivate| unless...@>=
16147 {@+if (final_pass&&(minimum_demerits==awful_bad)&&@|
16148 (link(r)==last_active)&&
16149 (prev_r==active))
16150 artificial_demerits=true; /*set demerits zero, this break is forced*/
16151 else if (b > threshold) goto deactivate;
16152 node_r_stays_active=false;
16153 }
16154
16155 @ When we get to this part of the code, the line from |r| to |cur_p| is
16156 feasible, its badness is~|b|, and its fitness classification is |fit_class|.
16157 We don't want to make an active node for this break yet, but we will
16158 compute the total demerits and record them in the |minimal_demerits| array,
16159 if such a break is the current champion among all ways to get to |cur_p|
16160 in a given line-number class and fitness class.
16161
16162 @<Record a new feasible break@>=
16163 if (artificial_demerits) d=0;
16164 else@<Compute the demerits, |d|, from |r| to |cur_p|@>;
16165 #ifdef @!STAT
16166 if (tracing_paragraphs > 0)
16167 @<Print a symbolic description of this feasible break@>;
16168 #endif
16169 @;@/
16170 d=d+total_demerits(r); /*this is the minimum total demerits
16171 from the beginning to |cur_p| via |r|*/
16172 if (d <= minimal_demerits[fit_class])
16173 {@+minimal_demerits[fit_class]=d;
16174 best_place[fit_class]=break_node(r);best_pl_line[fit_class]=l;
16175 if (d < minimum_demerits) minimum_demerits=d;
16176 }
16177
16178 @ @<Print a symbolic description of this feasible break@>=
16179 {@+if (printed_node!=cur_p)
16180 @<Print the list between |printed_node| and |cur_p|, then set |printed_node:=cur_p|@>;
16181 print_nl("@@");
16182 @.\AT@>
16183 if (cur_p==null) print_esc("par");
16184 else if (type(cur_p)!=glue_node)
16185 {@+if (type(cur_p)==penalty_node) print_esc("penalty");
16186 else if (type(cur_p)==disc_node) print_esc("discretionary");
16187 else if (type(cur_p)==kern_node) print_esc("kern");
16188 else print_esc("math");
16189 }
16190 print(" via @@@@");
16191 if (break_node(r)==null) print_char('0');
16192 else print_int(serial(break_node(r)));
16193 print(" b=");
16194 if (b > inf_bad) print_char('*');@+else print_int(b);
16195 @.*\relax@>
16196 print(" p=");print_int(pi);print(" d=");
16197 if (artificial_demerits) print_char('*');@+else print_int(d);
16198 }
16199
16200 @ @<Print the list between |printed_node| and |cur_p|...@>=
16201 {@+print_nl("");
16202 if (cur_p==null) short_display(link(printed_node));
16203 else{@+save_link=link(cur_p);
16204 link(cur_p)=null;print_nl("");short_display(link(printed_node));
16205 link(cur_p)=save_link;
16206 }
16207 printed_node=cur_p;
16208 }
16209
16210 @ When the data for a discretionary break is being displayed, we will have
16211 printed the |pre_break| and |post_break| lists; we want to skip over the
16212 third list, so that the discretionary data will not appear twice. The
16213 following code is performed at the very end of |try_break|.
16214
16215 @<Update the value of |printed_node|...@>=
16216 if (cur_p==printed_node) if (cur_p!=null) if (type(cur_p)==disc_node)
16217 {@+t=replace_count(cur_p);
16218 while (t > 0)
16219 {@+decr(t);printed_node=link(printed_node);
16220 }
16221 }
16222
16223 @ @<Compute the demerits, |d|, from |r| to |cur_p|@>=
16224 {@+d=line_penalty+b;
16225 if (abs(d) >= 10000) d=100000000;@+else d=d*d;
16226 if (pi!=0)
16227 if (pi > 0) d=d+pi*pi;
16228 else if (pi > eject_penalty) d=d-pi*pi;
16229 if ((break_type==hyphenated)&&(type(r)==hyphenated))
16230 if (cur_p!=null) d=d+double_hyphen_demerits;
16231 else d=d+final_hyphen_demerits;
16232 if (abs(fit_class-fitness(r)) > 1) d=d+adj_demerits;
16233 }
16234
16235 @ When an active node disappears, we must delete an adjacent delta node if the
16236 active node was at the beginning or the end of the active list, or if it
16237 was surrounded by delta nodes. We also must preserve the property that
16238 |cur_active_width| represents the length of material from |link(prev_r)|
16239 to~|cur_p|.
16240
16241 @d combine_two_deltas(A) @|mem[prev_r+A].sc=mem[prev_r+A].sc+mem[r+A].sc
16242 @d downdate_width(A) @|cur_active_width[A]=cur_active_width[A]-
16243 mem[prev_r+A].sc
16244
16245 @<Deactivate node |r|@>=
16246 link(prev_r)=link(r);free_node(r, active_node_size);
16247 if (prev_r==active) @<Update the active widths, since the first active node
16248 has been deleted@>@;
16249 else if (type(prev_r)==delta_node)
16250 {@+r=link(prev_r);
16251 if (r==last_active)
16252 {@+do_all_six(downdate_width);
16253 link(prev_prev_r)=last_active;
16254 free_node(prev_r, delta_node_size);prev_r=prev_prev_r;
16255 }
16256 else if (type(r)==delta_node)
16257 {@+do_all_six(update_width);
16258 do_all_six(combine_two_deltas);
16259 link(prev_r)=link(r);free_node(r, delta_node_size);
16260 }
16261 }
16262
16263 @ The following code uses the fact that |type(last_active)!=delta_node|. If the
16264 active list has just become empty, we do not need to update the
16265 |active_width| array, since it will be initialized when an active
16266 node is next inserted.
16267
16268 @d update_active(A) active_width[A]=active_width[A]+mem[r+A].sc
16269
16270 @<Update the active widths,...@>=
16271 {@+r=link(active);
16272 if (type(r)==delta_node)
16273 {@+do_all_six(update_active);
16274 do_all_six(copy_to_cur_active);
16275 link(active)=link(r);free_node(r, delta_node_size);
16276 }
16277 }
16278
16279 @* Breaking paragraphs into lines, continued.
16280 So far we have gotten a little way into the |line_break| routine, having
16281 covered its important |try_break| subroutine. Now let's consider the
16282 rest of the process.
16283
16284 The main loop of |line_break| traverses the given hlist,
16285 starting at |link(temp_head)|, and calls |try_break| at each legal
16286 breakpoint. A variable called |auto_breaking| is set to true except
16287 within math formulas, since glue nodes are not legal breakpoints when
16288 they appear in formulas.
16289
16290 The current node of interest in the hlist is pointed to by |cur_p|. Another
16291 variable, |prev_p|, is usually one step behind |cur_p|, but the real
16292 meaning of |prev_p| is this: If |type(cur_p)==glue_node| then |cur_p| is a legal
16293 breakpoint if and only if |auto_breaking| is true and |prev_p| does not
16294 point to a glue node, penalty node, explicit kern node, or math node.
16295
16296 The following declarations provide for a few other local variables that are
16297 used in special calculations.
16298
16299 @<Local variables for line breaking@>=
16300 bool @!auto_breaking; /*is node |cur_p| outside a formula?*/
16301 pointer @!prev_p; /*helps to determine when glue nodes are breakpoints*/
16302 pointer @!q, @!r, @!s; /*miscellaneous nodes of temporary interest*/
16303 internal_font_number @!f; /*used when calculating character widths*/
16304
16305 @ The `\ignorespaces|loop|\unskip' in the following code is performed at most
16306 thrice per call of |line_break|, since it is actually a pass over the
16307 entire paragraph.
16308
16309 @<Find optimal breakpoints@>=
16310 threshold=pretolerance;
16311 if (threshold >= 0)
16312 {
16313 #ifdef @!STAT
16314 if (tracing_paragraphs > 0)
16315 {@+begin_diagnostic();print_nl("@@firstpass");@+} @;
16316 #endif
16317 @;@/
16318 second_pass=false;final_pass=false;
16319 }
16320 else{@+threshold=tolerance;second_pass=true;
16321 final_pass=(emergency_stretch <= 0);
16322 #ifdef @!STAT
16323 if (tracing_paragraphs > 0) begin_diagnostic();
16324 #endif
16325 @;
16326 }
16327 loop@+{@+if (threshold > inf_bad) threshold=inf_bad;
16328 if (second_pass) @<Initialize for hyphenating a paragraph@>;
16329 @<Create an active breakpoint representing the beginning of the paragraph@>;
16330 cur_p=link(temp_head);auto_breaking=true;@/
16331 prev_p=cur_p; /*glue at beginning is not a legal breakpoint*/
16332 while ((cur_p!=null)&&(link(active)!=last_active))
16333 @<Call |try_break| if |cur_p| is a legal breakpoint; on the second pass,
16334 also try to hyphenate the next word, if |cur_p| is a glue node; then advance
16335 |cur_p| to the next node of the paragraph that could possibly be a legal breakpoint@>;
16336 if (cur_p==null)
16337 @<Try the final line break at the end of the paragraph, and |goto done|
16338 if the desired breakpoints have been found@>;
16339 @<Clean up the memory by removing the break nodes@>;
16340 if (!second_pass)
16341 {
16342 #ifdef @!STAT
16343 if (tracing_paragraphs > 0) print_nl("@@secondpass");@;
16344 #endif
16345 threshold=tolerance;second_pass=true;final_pass=(emergency_stretch <= 0);
16346 } /*if at first you don't succeed, \dots*/
16347 else{
16348 #ifdef @!STAT
16349 if (tracing_paragraphs > 0)
16350 print_nl("@@emergencypass");@;
16351 #endif
16352 background[2]=background[2]+emergency_stretch;final_pass=true;
16353 }
16354 }
16355 done:
16356 #ifdef @!STAT
16357 if (tracing_paragraphs > 0)
16358 {@+end_diagnostic(true);normalize_selector();
16359 }
16360 #endif
16361
16362 @ The active node that represents the starting point does not need a
16363 corresponding passive node.
16364
16365 @d store_background(A) active_width[A]=background[A]
16366
16367 @<Create an active breakpoint representing the beginning of the paragraph@>=
16368 q=get_node(active_node_size);
16369 type(q)=unhyphenated;fitness(q)=decent_fit;
16370 link(q)=last_active;break_node(q)=null;
16371 line_number(q)=prev_graf+1;total_demerits(q)=0;link(active)=q;
16372 do_all_six(store_background);@/
16373 passive=null;printed_node=temp_head;pass_number=0;
16374 font_in_short_display=null_font
16375
16376 @ @<Clean...@>=
16377 q=link(active);
16378 while (q!=last_active)
16379 {@+cur_p=link(q);
16380 if (type(q)==delta_node) free_node(q, delta_node_size);
16381 else free_node(q, active_node_size);
16382 q=cur_p;
16383 }
16384 q=passive;
16385 while (q!=null)
16386 {@+cur_p=link(q);
16387 free_node(q, passive_node_size);
16388 q=cur_p;
16389 }
16390
16391 @ Here is the main switch in the |line_break| routine, where legal breaks
16392 are determined. As we move through the hlist, we need to keep the |active_width|
16393 array up to date, so that the badness of individual lines is readily calculated
16394 by |try_break|. It is convenient to use the short name |act_width| for
16395 the component of active width that represents real width as opposed to glue.
16396
16397 @d act_width active_width[1] /*length from first active node to current node*/
16398 @d kern_break {@+if (!is_char_node(link(cur_p))&&auto_breaking)
16399 if (type(link(cur_p))==glue_node) try_break(0, unhyphenated);
16400 act_width=act_width+width(cur_p);
16401 }
16402
16403 @<Call |try_break| if |cur_p| is a legal breakpoint...@>=
16404 {@+if (is_char_node(cur_p))
16405 @<Advance \(c)|cur_p| to the node following the present string of characters@>;
16406 switch (type(cur_p)) {
16407 case hlist_node: case vlist_node: case rule_node: act_width=act_width+width(cur_p);@+break;
16408 case whatsit_node: @<Advance \(p)past a whatsit node in the \(l)|line_break|
16409 loop@>@;@+break;
16410 case glue_node: {@+@<If node |cur_p| is a legal breakpoint, call |try_break|;
16411 then update the active widths by including the glue in |glue_ptr(cur_p)|@>;
16412 if (second_pass&&auto_breaking)
16413 hyphenate_word();
16414 } @+break;
16415 case kern_node: if (subtype(cur_p)==explicit) kern_break@;
16416 else act_width=act_width+width(cur_p);@+break;
16417 case ligature_node: {@+f=font(lig_char(cur_p));
16418 act_width=act_width+char_width(f, character(lig_char(cur_p)));
16419 } @+break;
16420 case disc_node: @<Try to break after a discretionary fragment, then |goto
16421 done5|@>@;
16422 case math_node: {@+auto_breaking=(subtype(cur_p)==after);kern_break;
16423 } @+break;
16424 case penalty_node: try_break(penalty(cur_p), unhyphenated);@+break;
16425 case mark_node: case ins_node: case adjust_node: do_nothing;@+break;
16426 default:confusion("paragraph");
16427 @:this can't happen paragraph}{\quad paragraph@>
16428 } @/
16429 prev_p=cur_p;cur_p=link(cur_p);
16430 done5: ;}
16431
16432 @ The code that passes over the characters of words in a paragraph is
16433 part of \TeX's inner loop, so it has been streamlined for speed. We use
16434 the fact that `\.{\\parfillskip}' glue appears at the end of each paragraph;
16435 it is therefore unnecessary to check if |link(cur_p)==null| when |cur_p| is a
16436 character node.
16437 @^inner loop@>
16438
16439 @<Advance \(c)|cur_p| to the node following the present string...@>=
16440 {@+prev_p=cur_p;
16441 @/do@+{f=font(cur_p);
16442 act_width=act_width+char_width(f, character(cur_p));
16443 cur_p=link(cur_p);
16444 }@+ while (!(!is_char_node(cur_p)));
16445 }
16446
16447 @ When node |cur_p| is a glue node, we look at |prev_p| to see whether or not
16448 a breakpoint is legal at |cur_p|, as explained above.
16449
16450 @<If node |cur_p| is a legal breakpoint, call...@>=
16451 if (auto_breaking)
16452 {@+if (is_char_node(prev_p)) try_break(0, unhyphenated);
16453 else if (precedes_break(prev_p)) try_break(0, unhyphenated);
16454 else if ((type(prev_p)==kern_node)&&(subtype(prev_p)!=explicit))
16455 try_break(0, unhyphenated);
16456 }
16457 check_shrinkage(glue_ptr(cur_p));q=glue_ptr(cur_p);
16458 act_width=act_width+width(q);@|
16459 active_width[2+stretch_order(q)]=@|
16460 active_width[2+stretch_order(q)]+stretch(q);@/
16461 active_width[6]=active_width[6]+shrink(q)
16462
16463 @ The following code knows that discretionary texts contain
16464 only character nodes, kern nodes, box nodes, rule nodes, and ligature nodes.
16465
16466 @<Try to break after a discretionary fragment...@>=
16467 {@+s=pre_break(cur_p);disc_width=0;
16468 if (s==null) try_break(ex_hyphen_penalty, hyphenated);
16469 else{@+@/do@+{@<Add the width of node |s| to |disc_width|@>;
16470 s=link(s);
16471 }@+ while (!(s==null));
16472 act_width=act_width+disc_width;
16473 try_break(hyphen_penalty, hyphenated);
16474 act_width=act_width-disc_width;
16475 }
16476 r=replace_count(cur_p);s=link(cur_p);
16477 while (r > 0)
16478 {@+@<Add the width of node |s| to |act_width|@>;
16479 decr(r);s=link(s);
16480 }
16481 prev_p=cur_p;cur_p=s;goto done5;
16482 }
16483
16484 @ @<Add the width of node |s| to |disc_width|@>=
16485 if (is_char_node(s))
16486 {@+f=font(s);
16487 disc_width=disc_width+char_width(f, character(s));
16488 }
16489 else switch (type(s)) {
16490 case ligature_node: {@+f=font(lig_char(s));
16491 disc_width=disc_width+
16492 char_width(f, character(lig_char(s)));
16493 } @+break;
16494 case hlist_node: case vlist_node: case rule_node:
16495 case kern_node:
16496 disc_width=disc_width+width(s);@+break;
16497 default:confusion("disc3");
16498 @:this can't happen disc3}{\quad disc3@>
16499 }
16500
16501 @ @<Add the width of node |s| to |act_width|@>=
16502 if (is_char_node(s))
16503 {@+f=font(s);
16504 act_width=act_width+char_width(f, character(s));
16505 }
16506 else switch (type(s)) {
16507 case ligature_node: {@+f=font(lig_char(s));
16508 act_width=act_width+
16509 char_width(f, character(lig_char(s)));
16510 } @+break;
16511 case hlist_node: case vlist_node: case rule_node:
16512 case kern_node:
16513 act_width=act_width+width(s);@+break;
16514 default:confusion("disc4");
16515 @:this can't happen disc4}{\quad disc4@>
16516 }
16517
16518 @ The forced line break at the paragraph's end will reduce the list of
16519 breakpoints so that all active nodes represent breaks at |cur_p==null|.
16520 On the first pass, we insist on finding an active node that has the
16521 correct ``looseness.'' On the final pass, there will be at least one active
16522 node, and we will match the desired looseness as well as we can.
16523
16524 The global variable |best_bet| will be set to the active node for the best
16525 way to break the paragraph, and a few other variables are used to
16526 help determine what is best.
16527
16528 @<Glob...@>=
16529 static pointer @!best_bet; /*use this passive node and its predecessors*/
16530 static int @!fewest_demerits; /*the demerits associated with |best_bet|*/
16531 static halfword @!best_line; /*line number following the last line of the new paragraph*/
16532 static int @!actual_looseness; /*the difference between |line_number(best_bet)|
16533 and the optimum |best_line|*/
16534 static int @!line_diff; /*the difference between the current line number and
16535 the optimum |best_line|*/
16536
16537 @ @<Try the final line break at the end of the paragraph...@>=
16538 {@+try_break(eject_penalty, hyphenated);
16539 if (link(active)!=last_active)
16540 {@+@<Find an active node with fewest demerits@>;
16541 if (looseness==0) goto done;
16542 @<Find the best active node for the desired looseness@>;
16543 if ((actual_looseness==looseness)||final_pass) goto done;
16544 }
16545 }
16546
16547 @ @<Find an active node...@>=
16548 r=link(active);fewest_demerits=awful_bad;
16549 @/do@+{if (type(r)!=delta_node) if (total_demerits(r) < fewest_demerits)
16550 {@+fewest_demerits=total_demerits(r);best_bet=r;
16551 }
16552 r=link(r);
16553 }@+ while (!(r==last_active));
16554 best_line=line_number(best_bet)
16555
16556 @ The adjustment for a desired looseness is a slightly more complicated
16557 version of the loop just considered. Note that if a paragraph is broken
16558 into segments by displayed equations, each segment will be subject to the
16559 looseness calculation, independently of the other segments.
16560
16561 @<Find the best active node...@>=
16562 {@+r=link(active);actual_looseness=0;
16563 @/do@+{if (type(r)!=delta_node)
16564 {@+line_diff=line_number(r)-best_line;
16565 if (((line_diff < actual_looseness)&&(looseness <= line_diff))||@|
16566 ((line_diff > actual_looseness)&&(looseness >= line_diff)))
16567 {@+best_bet=r;actual_looseness=line_diff;
16568 fewest_demerits=total_demerits(r);
16569 }
16570 else if ((line_diff==actual_looseness)&&@|
16571 (total_demerits(r) < fewest_demerits))
16572 {@+best_bet=r;fewest_demerits=total_demerits(r);
16573 }
16574 }
16575 r=link(r);
16576 }@+ while (!(r==last_active));
16577 best_line=line_number(best_bet);
16578 }
16579
16580 @ Once the best sequence of breakpoints has been found (hurray), we call on the
16581 procedure |post_line_break| to finish the remainder of the work.
16582 (By introducing this subprocedure, we are able to keep |line_break|
16583 from getting extremely long.)
16584
16585 @<Break the paragraph at the chosen...@>=
16586 post_line_break(final_widow_penalty)
16587
16588 @ The total number of lines that will be set by |post_line_break|
16589 is |best_line-prev_graf-1|. The last breakpoint is specified by
16590 |break_node(best_bet)|, and this passive node points to the other breakpoints
16591 via the |prev_break| links. The finishing-up phase starts by linking the
16592 relevant passive nodes in forward order, changing |prev_break| to
16593 |next_break|. (The |next_break| fields actually reside in the same memory
16594 space as the |prev_break| fields did, but we give them a new name because
16595 of their new significance.) Then the lines are justified, one by one.
16596
16597 @d next_break prev_break /*new name for |prev_break| after links are reversed*/
16598
16599 @<Declare subprocedures for |line_break|@>=
16600 static void post_line_break(int @!final_widow_penalty)
16601 {@+
16602 pointer q, @!r, @!s; /*temporary registers for list manipulation*/
16603 bool @!disc_break; /*was the current break at a discretionary node?*/
16604 bool @!post_disc_break; /*and did it have a nonempty post-break part?*/
16605 scaled @!cur_width; /*width of line number |cur_line|*/
16606 scaled @!cur_indent; /*left margin of line number |cur_line|*/
16607 quarterword @!t; /*used for replacement counts in discretionary nodes*/
16608 int @!pen; /*use when calculating penalties between lines*/
16609 halfword @!cur_line; /*the current line number being justified*/
16610 @<Reverse the links of the relevant passive nodes, setting |cur_p| to the
16611 first breakpoint@>;
16612 cur_line=prev_graf+1;
16613 @<initialize the color stack@>@;
16614 @/do@+{@<Justify the line ending at breakpoint |cur_p|, and append it to the
16615 current vertical list, together with associated penalties and other insertions@>;
16616 incr(cur_line);cur_p=next_break(cur_p);
16617 if (cur_p!=null) if (!post_disc_break)
16618 @<Prune unwanted nodes at the beginning of the next line@>;
16619 }@+ while (!(cur_p==null));
16620 if ((cur_line!=best_line)||(link(temp_head)!=null))
16621 confusion("line breaking");
16622 @:this can't happen line breaking}{\quad line breaking@>
16623 prev_graf=best_line-1;
16624 }
16625
16626 @ The job of reversing links in a list is conveniently regarded as the job
16627 of taking items off one stack and putting them on another. In this case we
16628 take them off a stack pointed to by |q| and having |prev_break| fields;
16629 we put them on a stack pointed to by |cur_p| and having |next_break| fields.
16630 Node |r| is the passive node being moved from stack to stack.
16631
16632 @<Reverse the links of the relevant passive nodes...@>=
16633 q=break_node(best_bet);cur_p=null;
16634 @/do@+{r=q;q=prev_break(q);next_break(r)=cur_p;cur_p=r;
16635 }@+ while (!(q==null))
16636
16637 @ Glue and penalty and kern and math nodes are deleted at the beginning of
16638 a line, except in the anomalous case that the node to be deleted is actually
16639 one of the chosen breakpoints. Otherwise
16640 the pruning done here is designed to match
16641 the lookahead computation in |try_break|, where the |break_width| values
16642 are computed for non-discretionary breakpoints.
16643
16644 @<Prune unwanted nodes at the beginning of the next line@>=
16645 {@+r=temp_head;
16646 loop@+{@+q=link(r);
16647 if (q==cur_break(cur_p)) goto done1;
16648 /*|cur_break(cur_p)| is the next breakpoint*/
16649 /*now |q| cannot be |null|*/
16650 if (is_char_node(q)) goto done1;
16651 if (non_discardable(q)) goto done1;
16652 if (type(q)==kern_node) if (subtype(q)!=explicit) goto done1;
16653 r=q; /*now |type(q)==glue_node|, |kern_node|, |math_node|, or |penalty_node|*/
16654 }
16655 done1: if (r!=temp_head)
16656 {@+link(r)=null;flush_node_list(link(temp_head));
16657 link(temp_head)=q;
16658 }
16659 }
16660
16661 @ The current line to be justified appears in a horizontal list starting
16662 at |link(temp_head)| and ending at |cur_break(cur_p)|. If |cur_break(cur_p)| is
16663 a glue node, we reset the glue to equal the |right_skip| glue; otherwise
16664 we append the |right_skip| glue at the right. If |cur_break(cur_p)| is a
16665 discretionary node, we modify the list so that the discretionary break
16666 is compulsory, and we set |disc_break| to |true|. We also append
16667 the |left_skip| glue at the left of the line, unless it is zero.
16668
16669 @<Justify the line ending at breakpoint |cur_p|, and append it...@>=
16670 @<Modify the end of the line to reflect the nature of the break and to include
16671 \.{\\rightskip}; also set the proper value of |disc_break|@>;
16672 @<Put the \(l)\.{\\leftskip} glue at the left and detach this line@>;
16673 @<Call the packaging subroutine, setting |just_box| to the justified box@>;
16674 @<Append the new box to the current vertical list, followed by the list of
16675 special nodes taken out of the box by the packager@>;
16676 @<Append a penalty node, if a nonzero penalty is appropriate@>@;
16677
16678 @ At the end of the following code, |q| will point to the final node on the
16679 list about to be justified.
16680
16681 @<Modify the end of the line...@>=
16682 q=cur_break(cur_p);disc_break=false;post_disc_break=false;
16683 if (q!=null) /*|q| cannot be a |char_node|*/
16684 if (type(q)==glue_node)
16685 {@+delete_glue_ref(glue_ptr(q));
16686 glue_ptr(q)=right_skip;
16687 subtype(q)=right_skip_code+1;add_glue_ref(right_skip);
16688 goto done;
16689 }
16690 else{@+if (type(q)==disc_node)
16691 @<Change discretionary to compulsory and set |disc_break:=true|@>@;
16692 else if ((type(q)==math_node)||(type(q)==kern_node)) width(q)=0;
16693 }
16694 else{@+q=temp_head;
16695 while (link(q)!=null) q=link(q);
16696 }
16697 @<Put the \(r)\.{\\rightskip} glue after node |q|@>;
16698 done:
16699
16700 @ @<Change discretionary to compulsory...@>=
16701 {@+t=replace_count(q);
16702 @<Destroy the |t| nodes following |q|, and make |r| point to the following
16703 node@>;
16704 if (post_break(q)!=null) @<Transplant the post-break list@>;
16705 if (pre_break(q)!=null) @<Transplant the pre-break list@>;
16706 link(q)=r;disc_break=true;
16707 }
16708
16709 @ @<Destroy the |t| nodes following |q|...@>=
16710 if (t==0) r=link(q);
16711 else{@+r=q;
16712 while (t > 1)
16713 {@+r=link(r);decr(t);
16714 }
16715 s=link(r);
16716 r=link(s);link(s)=null;
16717 flush_node_list(link(q));set_replace_count(q,0);
16718 }
16719
16720 @ We move the post-break list from inside node |q| to the main list by
16721 re\-attaching it just before the present node |r|, then resetting |r|.
16722
16723 @<Transplant the post-break list@>=
16724 {@+s=post_break(q);
16725 while (link(s)!=null) s=link(s);
16726 link(s)=r;r=post_break(q);post_break(q)=null;post_disc_break=true;
16727 }
16728
16729 @ We move the pre-break list from inside node |q| to the main list by
16730 re\-attaching it just after the present node |q|, then resetting |q|.
16731
16732 @<Transplant the pre-break list@>=
16733 {@+s=pre_break(q);link(q)=s;
16734 while (link(s)!=null) s=link(s);
16735 pre_break(q)=null;q=s;
16736 }
16737
16738 @ @<Put the \(r)\.{\\rightskip} glue after node |q|@>=
16739 r=new_param_glue(right_skip_code);link(r)=link(q);link(q)=r;q=r
16740
16741 @ The following code begins with |q| at the end of the list to be
16742 justified. It ends with |q| at the beginning of that list, and with
16743 |link(temp_head)| pointing to the remainder of the paragraph, if any.
16744
16745 @<Put the \(l)\.{\\leftskip} glue at the left...@>=
16746 r=link(q);link(q)=null;q=link(temp_head);link(temp_head)=r;
16747 if (left_skip!=zero_glue)
16748 {@+r=new_param_glue(left_skip_code);
16749 link(r)=q;q=r;
16750 }
16751
16752 @ @<Append the new box to the current vertical list...@>=
16753 append_to_vlist(just_box);
16754 if (adjust_head!=adjust_tail)
16755 {@+link(tail)=link(adjust_head);tail=adjust_tail;
16756 }
16757 adjust_tail=null
16758
16759 @ Now |q| points to the hlist that represents the current line of the
16760 paragraph. We need to compute the appropriate line width, pack the
16761 line into a box of this size, and shift the box by the appropriate
16762 amount of indentation.
16763
16764 @<Call the packaging subroutine...@>=
16765 if (cur_line > last_special_line)
16766 {@+cur_width=second_width;cur_indent=second_indent;
16767 }
16768 else if (par_shape_ptr==null)
16769 {@+cur_width=first_width;cur_indent=first_indent;
16770 }
16771 else{@+cur_width=mem[par_shape_ptr+2*cur_line].sc;
16772 cur_indent=mem[par_shape_ptr+2*cur_line-1].sc;
16773 }
16774 { pointer before_color_tos=color_tos;
16775 pointer before_link_tos=link_tos;
16776 adjust_tail=adjust_head;just_box=hpack(q, cur_width, 0, 0, exactly, true);
16777 if (before_link_tos!=before_color_tos)
16778 { pointer r;
16779 r=new_color_node(color_ref(before_color_tos));
16780 link(r) = list_ptr(just_box);
16781 list_ptr(just_box)=r;
16782 }
16783 if (before_link_tos!=null) /* an unfinished link was in the previous line */
16784 { pointer r;
16785 int words;
16786 r=get_node(link_node_size);
16787 for (words=0;words<link_node_size; words++)
16788 mem[r+words]= mem[before_link_tos+words];
16789 if (label_has_name(as_label(r)))
16790 add_token_ref(label_ptr(as_label(r)));
16791 link(r) = list_ptr(just_box);
16792 list_ptr(just_box)=r;
16793 }
16794 }
16795 shift_amount(just_box)=cur_indent
16796
16797 @ Penalties between the lines of a paragraph come from club and widow lines,
16798 from the |inter_line_penalty| parameter, and from lines that end at
16799 discretionary breaks. Breaking between lines of a two-line paragraph gets
16800 both club-line and widow-line penalties. The local variable |pen| will
16801 be set to the sum of all relevant penalties for the current line, except
16802 that the final line is never penalized.
16803
16804 @<Append a penalty node, if a nonzero penalty is appropriate@>=
16805 if (cur_line+1!=best_line)
16806 {@+pen=inter_line_penalty;
16807 if (cur_line==prev_graf+1) pen=pen+club_penalty;
16808 if (cur_line+2==best_line) pen=pen+final_widow_penalty;
16809 if (disc_break) pen=pen+broken_penalty;
16810 if (pen!=0)
16811 {@+r=new_penalty(pen);
16812 link(tail)=r;tail=r;
16813 }
16814 }
16815
16816 @* Pre-hyphenation.
16817 When the line-breaking routine is unable to find a feasible sequence of
16818 breakpoints, it makes a second pass over the paragraph, attempting to
16819 hyphenate the hyphenatable words. The goal of hyphenation is to insert
16820 discretionary material into the paragraph so that there are more
16821 potential places to break.
16822
16823 The general rules for hyphenation are somewhat complex and technical,
16824 because we want to be able to hyphenate words that are preceded or
16825 followed by punctuation marks, and because we want the rules to work
16826 for languages other than English. We also must contend with the fact
16827 that hyphens might radically alter the ligature and kerning structure
16828 of a word.
16829
16830 A sequence of characters will be considered for hyphenation only if it
16831 belongs to a ``potentially hyphenatable part'' of the current paragraph.
16832 This is a sequence of nodes $p_0p_1\ldots p_m$ where $p_0$ is a glue node,
16833 $p_1\ldots p_{m-1}$ are either character or ligature or whatsit or
16834 implicit kern nodes, and $p_m$ is a glue or penalty or insertion or adjust
16835 or mark or whatsit or explicit kern node. (Therefore hyphenation is
16836 disabled by boxes, math formulas, and discretionary nodes already inserted
16837 by the user.) The ligature nodes among $p_1\ldots p_{m-1}$ are effectively
16838 expanded into the original non-ligature characters; the kern nodes and
16839 whatsits are ignored. Each character |c| is now classified as either a
16840 nonletter (if |lc_code(c)==0|), a lowercase letter (if
16841 |lc_code(c)==c|), or an uppercase letter (otherwise); an uppercase letter
16842 is treated as if it were |lc_code(c)| for purposes of hyphenation. The
16843 characters generated by $p_1\ldots p_{m-1}$ may begin with nonletters; let
16844 $c_1$ be the first letter that is not in the middle of a ligature. Whatsit
16845 nodes preceding $c_1$ are ignored; a whatsit found after $c_1$ will be the
16846 terminating node $p_m$. All characters that do not have the same font as
16847 $c_1$ will be treated as nonletters. The |hyphen_char| for that font
16848 must be between 0 and 255, otherwise hyphenation will not be attempted.
16849 \TeX\ looks ahead for as many consecutive letters $c_1\ldots c_n$ as
16850 possible; however, |n| must be less than |max_hyph_length|, so a character that would
16851 otherwise be $c_{|max_hyph_length|}$ is effectively not a letter. Furthermore $c_n$ must
16852 not be in the middle of a ligature. In this way we obtain a string of
16853 letters $c_1\ldots c_n$ that are generated by nodes $p_a\ldots p_b$, where
16854 |1 <= a <= b+1 <= m|. If |n >= l_hyf+r_hyf|, this string qualifies for hyphenation;
16855 however, |uc_hyph| must be positive, if $c_1$ is uppercase.
16856
16857 The hyphenation process takes place in three stages. First, the candidate
16858 sequence $c_1\ldots c_n$ is found; then potential positions for hyphens
16859 are determined by referring to hyphenation tables; and finally, the nodes
16860 $p_a\ldots p_b$ are replaced by a new sequence of nodes that includes the
16861 discretionary breaks found.
16862
16863 Fortunately, we do not have to do all this calculation very often, because
16864 of the way it has been taken out of \TeX's inner loop. For example, when
16865 the second edition of the author's 700-page book {\sl Seminumerical
16866 Algorithms} was typeset by \TeX, only about 1.2 hyphenations needed to be
16867 @^Knuth, Donald Ervin@>
16868 tried per paragraph, since the line breaking algorithm needed to use two
16869 passes on only about 5 per cent of the paragraphs.
16870
16871 @d max_hyph_length 256 /*maximum length for a word to be hyphenated*/
16872
16873 @<Initialize for hyphenating...@>=
16874 {
16875 #ifdef @!INIT
16876 if (trie_not_ready) init_trie();
16877 #endif
16878 @;@/
16879 cur_lang=init_cur_lang;l_hyf=init_l_hyf;r_hyf=init_r_hyf;
16880 set_hyph_index;
16881 }
16882
16883 @ The letters $c_1\ldots c_n$ that are candidates for hyphenation are placed
16884 into an array called |hc|; the number |n| is placed into |hn|; pointers to
16885 nodes $p_{a-1}$ and~$p_b$ in the description above are placed into variables
16886 |ha| and |hb|; and the font number is placed into |hf|.
16887
16888 @<Glob...@>=
16889 static int32_t @!hc[max_hyph_length+4]; /*word to be hyphenated*/
16890 static int @!hn; /*the number of positions occupied in |hc|*/
16891 static pointer @!ha, @!hb; /*nodes |ha dotdot hb| should be replaced by the hyphenated result*/
16892 static internal_font_number @!hf; /*font number of the letters in |hc|*/
16893 static int32_t @!hu[max_hyph_length+2]; /*like |hc|, before conversion to lowercase*/
16894 static int @!hyf_char; /*hyphen character of the relevant font*/
16895 static int @!cur_lang, @!init_cur_lang; /*current hyphenation table of interest*/
16896 static int @!l_hyf, @!r_hyf, @!init_l_hyf, @!init_r_hyf; /*limits on fragment sizes*/
16897 static halfword @!hyf_bchar; /*boundary character after $c_n$*/
16898 static int @!max_hyph_char; /*largest character occuring in a pattern*/
16899
16900 @ We set a limit on the maximum character code that might occur in a pattern.
16901 This is necessary, since the table compression uses characters as indices
16902 into arrays and we need to make these arrays large enough.
16903 Following the example of \XeTeX\ we also keep track of the largest character
16904 code that actually occurs in all of the patterns in the valiable |max_hyp_char|.
16905 This variable is initialized using the maximim number of languages, because
16906 the language is used like a character to find the right entry point into
16907 the compressed table.
16908
16909 @d max_language 255 /*the largest hyphenation language*/
16910 @d max_pattern_char 0xFFFF /*the largest character in a pattern*/
16911 @d biggest_char 0x10FFFF /*the largest UTF character*/
16912
16913 @<Set initial values of key variables@>=
16914 max_hyph_char=max_language+1;
16915
16916 @ When the following code is activated, the |line_break| procedure is in its
16917 second pass, and |cur_p| points to a glue node.
16918
16919 @p
16920 static void hyphenate_word(void)@t\2\2@>@/
16921 { pointer @!q, @!s, @!prev_s;@t\1@> /*miscellaneous nodes of temporary interest*/
16922 small_number @!j; /*an index into |hc| or |hu|*/
16923 uint8_t @!c; /*character being considered for hyphenation*/
16924
16925 prev_s=cur_p;s=link(prev_s);
16926 if (s!=null)
16927 {@+@<Skip to node |ha|, or |goto done1| if no hyphenation should be attempted@>;
16928 if (l_hyf+r_hyf > max_hyph_length-1) goto done1;
16929 @<Skip to node |hb|, putting letters into |hu| and |hc|@>;
16930 @<Check that the nodes following |hb| permit hyphenation and that at least
16931 |l_hyf+r_hyf| letters have been found, otherwise |goto done1|@>;
16932 hyphenate();
16933 }
16934 done1: ;}
16935
16936 @ @<Declare subprocedures for |line_break|@>=
16937 @t\4@>@<Declare the function called |reconstitute|@>@;
16938 static void hyphenate(void)
16939 {@+
16940 @<Local variables for hyphenation@>@;
16941 @<Find hyphen locations for the word in |hc|, or |return|@>;
16942 @<If no hyphens were found, |return|@>;
16943 @<Replace nodes |ha..hb| by a sequence of nodes that includes the discretionary
16944 hyphens@>;
16945 }
16946
16947 @ The first thing we need to do is find the node |ha| just before the
16948 first letter.
16949
16950 @<Skip to node |ha|, or |goto done1|...@>=
16951 loop@+{@+if (is_char_node(s))
16952 {@+c=qo(character(s));hf=font(s);
16953 }
16954 else if (type(s)==ligature_node)
16955 if (lig_ptr(s)==null) goto resume;
16956 else{@+q=lig_ptr(s);c=qo(character(q));hf=font(q);
16957 }
16958 else if ((type(s)==kern_node)&&(subtype(s)==normal)) goto resume;
16959 else if (type(s)==whatsit_node)
16960 {@+@<Advance \(p)past a whatsit node in the \(p)pre-hyphenation loop@>;
16961 goto resume;
16962 }
16963 else goto done1;
16964 set_lc_code(c);
16965 if (hc[0]!=0)
16966 if ((hc[0]==c)||(uc_hyph > 0)) goto done2;
16967 else goto done1;
16968 resume: prev_s=s;s=link(prev_s);
16969 }
16970 done2: hyf_char=hyphen_char[hf];
16971 if (hyf_char < 0) goto done1;
16972 if (hyf_char > biggest_char) goto done1;
16973 ha=prev_s
16974
16975 @ The word to be hyphenated is now moved to the |hu| and |hc| arrays.
16976
16977 @<Skip to node |hb|, putting letters...@>=
16978 hn=0;
16979 loop@+{@+if (is_char_node(s))
16980 {@+if (font(s)!=hf) goto done3;
16981 hyf_bchar=character(s);c=qo(hyf_bchar);
16982 set_lc_code(c);
16983 if (hc[0]==0) goto done3;
16984 if (hc[0] > max_hyph_char) goto done3;
16985 if (hn== max_hyph_length-1) goto done3;
16986 hb=s;incr(hn);hu[hn]=c;hc[hn]=hc[0];hyf_bchar=non_char;
16987 }
16988 else if (type(s)==ligature_node)
16989 @<Move the characters of a ligature node to |hu| and |hc|; but |goto done3|
16990 if they are not all letters@>@;
16991 else if ((type(s)==kern_node)&&(subtype(s)==normal))
16992 {@+hb=s;
16993 hyf_bchar=font_bchar[hf];
16994 }
16995 else goto done3;
16996 s=link(s);
16997 }
16998 done3:
16999
17000 @ We let |j| be the index of the character being stored when a ligature node
17001 is being expanded, since we do not want to advance |hn| until we are sure
17002 that the entire ligature consists of letters. Note that it is possible
17003 to get to |done3| with |hn==0| and |hb| not set to any value.
17004
17005 @<Move the characters of a ligature node to |hu| and |hc|...@>=
17006 {@+if (font(lig_char(s))!=hf) goto done3;
17007 j=hn;q=lig_ptr(s);@+if (q > null) hyf_bchar=character(q);
17008 while (q > null)
17009 {@+c=qo(character(q));
17010 set_lc_code(c);
17011 if (hc[0]==0) goto done3;
17012 if (hc[0]>max_hyph_char) goto done3;
17013 if (j==max_hyph_length) goto done3;
17014 incr(j);hu[j]=c;hc[j]=hc[0];@/
17015 q=link(q);
17016 }
17017 hb=s;hn=j;
17018 if (odd(subtype(s))) hyf_bchar=font_bchar[hf];@+else hyf_bchar=non_char;
17019 }
17020
17021 @ @<Check that the nodes following |hb| permit hyphenation...@>=
17022 if (hn < l_hyf+r_hyf) goto done1; /*|l_hyf| and |r_hyf| are | >= 1|*/
17023 loop@+{@+if (!(is_char_node(s)))
17024 switch (type(s)) {
17025 case ligature_node: do_nothing;@+break;
17026 case kern_node: if (subtype(s)!=normal) goto done4;@+break;
17027 case whatsit_node: case glue_node:
17028 case penalty_node: case ins_node: case adjust_node:
17029 case mark_node:
17030 goto done4;
17031 default:goto done1;
17032 }
17033 s=link(s);
17034 }
17035 done4:
17036
17037 @* Post-hyphenation.
17038 If a hyphen may be inserted between |hc[j]| and |hc[j+1]|, the hyphenation
17039 procedure will set |hyf[j]| to some small odd number. But before we look
17040 at \TeX's hyphenation procedure, which is independent of the rest of the
17041 line-breaking algorithm, let us consider what we will do with the hyphens
17042 it finds, since it is better to work on this part of the program before
17043 forgetting what |ha| and |hb|, etc., are all about.
17044
17045 @<Glob...@>=
17046 static int8_t @!hyf[max_hyph_length+2]; /*odd values indicate discretionary hyphens*/
17047 static pointer @!init_list; /*list of punctuation characters preceding the word*/
17048 static bool @!init_lig; /*does |init_list| represent a ligature?*/
17049 static bool @!init_lft; /*if so, did the ligature involve a left boundary?*/
17050
17051 @ @<Local variables for hyphenation@>=
17052 int @!i, @!j, @!l; /*indices into |hc| or |hu|*/
17053 pointer @!q, @!r, @!s; /*temporary registers for list manipulation*/
17054 halfword @!bchar; /*boundary character of hyphenated word, or |non_char|*/
17055
17056 @ \TeX\ will never insert a hyphen that has fewer than
17057 \.{\\lefthyphenmin} letters before it or fewer than
17058 \.{\\righthyphenmin} after it; hence, a short word has
17059 comparatively little chance of being hyphenated. If no hyphens have
17060 been found, we can save time by not having to make any changes to the
17061 paragraph.
17062
17063 @<If no hyphens were found, |return|@>=
17064 for (j=l_hyf; j<=hn-r_hyf; j++) if (odd(hyf[j])) goto found1;
17065 return;
17066 found1:
17067
17068 @ If hyphens are in fact going to be inserted, \TeX\ first deletes the
17069 subsequence of nodes between |ha| and~|hb|. An attempt is made to
17070 preserve the effect that implicit boundary characters and punctuation marks
17071 had on ligatures inside the hyphenated word, by storing a left boundary or
17072 preceding character in |hu[0]| and by storing a possible right boundary
17073 in |bchar|. We set |j=0| if |hu[0]| is to be part of the reconstruction;
17074 otherwise |j=1|.
17075 The variable |s| will point to the tail of the current hlist, and
17076 |q| will point to the node following |hb|, so that
17077 things can be hooked up after we reconstitute the hyphenated word.
17078
17079 @<Replace nodes |ha..hb| by a sequence of nodes...@>=
17080 q=link(hb);link(hb)=null;r=link(ha);link(ha)=null;bchar=hyf_bchar;
17081 if (is_char_node(ha))
17082 if (font(ha)!=hf) goto found2;
17083 else{@+init_list=ha;init_lig=false;hu[0]=qo(character(ha));
17084 }
17085 else if (type(ha)==ligature_node)
17086 if (font(lig_char(ha))!=hf) goto found2;
17087 else{@+init_list=lig_ptr(ha);init_lig=true;init_lft=(subtype(ha) > 1);
17088 hu[0]=qo(character(lig_char(ha)));
17089 if (init_list==null) if (init_lft)
17090 {@+hu[0]=max_hyph_char;init_lig=false;
17091 } /*in this case a ligature will be reconstructed from scratch*/
17092 free_node(ha, small_node_size);
17093 }
17094 else{@+ /*no punctuation found; look for left boundary*/
17095 if (!is_char_node(r)) if (type(r)==ligature_node)
17096 if (subtype(r) > 1) goto found2;
17097 j=1;s=ha;init_list=null;goto common_ending;
17098 }
17099 s=cur_p; /*we have |cur_p!=ha| because |type(cur_p)==glue_node|*/
17100 while (link(s)!=ha) s=link(s);
17101 j=0;goto common_ending;
17102 found2: s=ha;j=0;hu[0]=max_hyph_char;init_lig=false;init_list=null;
17103 common_ending: flush_node_list(r);
17104 @<Reconstitute nodes for the hyphenated word, inserting discretionary hyphens@>;
17105 flush_list(init_list)
17106
17107 @ We must now face the fact that the battle is not over, even though the
17108 {\def\!{\kern-1pt}%
17109 hyphens have been found: The process of reconstituting a word can be nontrivial
17110 because ligatures might change when a hyphen is present. {\sl The \TeX book\/}
17111 discusses the difficulties of the word ``difficult'', and
17112 the discretionary material surrounding a
17113 hyphen can be considerably more complex than that. Suppose
17114 \.{abcdef} is a word in a font for which the only ligatures are \.{b\!c},
17115 \.{c\!d}, \.{d\!e}, and \.{e\!f}. If this word permits hyphenation
17116 between \.b and \.c, the two patterns with and without hyphenation are
17117 $\.a\,\.b\,\.-\,\.{c\!d}\,\.{e\!f}$ and $\.a\,\.{b\!c}\,\.{d\!e}\,\.f$.
17118 Thus the insertion of a hyphen might cause effects to ripple arbitrarily
17119 far into the rest of the word. A further complication arises if additional
17120 hyphens appear together with such rippling, e.g., if the word in the
17121 example just given could also be hyphenated between \.c and \.d; \TeX\
17122 avoids this by simply ignoring the additional hyphens in such weird cases.}
17123
17124 Still further complications arise in the presence of ligatures that do not
17125 delete the original characters. When punctuation precedes the word being
17126 hyphenated, \TeX's method is not perfect under all possible scenarios,
17127 because punctuation marks and letters can propagate information back and forth.
17128 For example, suppose the original pre-hyphenation pair
17129 \.{*a} changes to \.{*y} via a \.{\@@=:} ligature, which changes to \.{xy}
17130 via a \.{=:\@@} ligature; if $p_{a-1}=\.x$ and $p_a=\.y$, the reconstitution
17131 procedure isn't smart enough to obtain \.{xy} again. In such cases the
17132 font designer should include a ligature that goes from \.{xa} to \.{xy}.
17133
17134 @ The processing is facilitated by a subroutine called |reconstitute|. Given
17135 a string of characters $x_j\ldots x_n$, there is a smallest index $m\ge j$
17136 such that the ``translation'' of $x_j\ldots x_n$ by ligatures and kerning
17137 has the form $y_1\ldots y_t$ followed by the translation of $x_{m+1}\ldots x_n$,
17138 where $y_1\ldots y_t$ is some nonempty sequence of character, ligature, and
17139 kern nodes. We call $x_j\ldots x_m$ a ``cut prefix'' of $x_j\ldots x_n$.
17140 For example, if $x_1x_2x_3=\.{fly}$, and if the font contains `fl' as a
17141 ligature and a kern between `fl' and `y', then $m=2$, $t=2$, and $y_1$ will
17142 be a ligature node for `fl' followed by an appropriate kern node~$y_2$.
17143 In the most common case, $x_j$~forms no ligature with $x_{j+1}$ and we
17144 simply have $m=j$, $y_1=x_j$. If $m<n$ we can repeat the procedure on
17145 $x_{m+1}\ldots x_n$ until the entire translation has been found.
17146
17147 The |reconstitute| function returns the integer $m$ and puts the nodes
17148 $y_1\ldots y_t$ into a linked list starting at |link(hold_head)|,
17149 getting the input $x_j\ldots x_n$ from the |hu| array. If $x_j=256$,
17150 we consider $x_j$ to be an implicit left boundary character; in this
17151 case |j| must be strictly less than~|n|. There is a
17152 parameter |bchar|, which is either 256 or an implicit right boundary character
17153 assumed to be present just following~$x_n$. (The value |hu[n+1]| is never
17154 explicitly examined, but the algorithm imagines that |bchar| is there.)
17155
17156 If there exists an index |k| in the range $j\le k\le m$ such that |hyf[k]|
17157 is odd and such that the result of |reconstitute| would have been different
17158 if $x_{k+1}$ had been |hchar|, then |reconstitute| sets |hyphen_passed|
17159 to the smallest such~|k|. Otherwise it sets |hyphen_passed| to zero.
17160
17161 A special convention is used in the case |j==0|: Then we assume that the
17162 translation of |hu[0]| appears in a special list of charnodes starting at
17163 |init_list|; moreover, if |init_lig| is |true|, then |hu[0]| will be
17164 a ligature character, involving a left boundary if |init_lft| is |true|.
17165 This facility is provided for cases when a hyphenated
17166 word is preceded by punctuation (like single or double quotes) that might
17167 affect the translation of the beginning of the word.
17168
17169 @<Glob...@>=
17170 static small_number @!hyphen_passed; /*first hyphen in a ligature, if any*/
17171
17172 @ @<Declare the function called |reconstitute|@>=
17173 static
17174 small_number reconstitute(small_number @!j, small_number @!n, halfword @!bchar, halfword @!hchar)
17175 {@+
17176 pointer @!p; /*temporary register for list manipulation*/
17177 pointer @!t; /*a node being appended to*/
17178 four_quarters @!q; /*character information or a lig/kern instruction*/
17179 halfword @!cur_rh; /*hyphen character for ligature testing*/
17180 halfword @!test_char; /*hyphen or other character for ligature testing*/
17181 scaled @!w; /*amount of kerning*/
17182 font_index @!k; /*position of current lig/kern instruction*/
17183 hyphen_passed=0;t=hold_head;w=0;link(hold_head)=null;
17184 /*at this point |ligature_present==lft_hit==rt_hit==false|*/
17185 @<Set up data structures with the cursor following position |j|@>;
17186 resume: @<If there's a ligature or kern at the cursor position, update the
17187 data structures, possibly advancing~|j|; continue until the cursor moves@>;
17188 @<Append a ligature and/or kern to the translation; |goto resume| if the
17189 stack of inserted ligatures is nonempty@>;
17190 return j;
17191 }
17192
17193 @ The reconstitution procedure shares many of the global data structures
17194 by which \TeX\ has processed the words before they were hyphenated.
17195 There is an implied ``cursor'' between characters |cur_l| and |cur_r|;
17196 these characters will be tested for possible ligature activity. If
17197 |ligature_present| then |cur_l| is a ligature character formed from the
17198 original characters following |cur_q| in the current translation list.
17199 There is a ``ligature stack'' between the cursor and character |j+1|,
17200 consisting of pseudo-ligature nodes linked together by their |link| fields.
17201 This stack is normally empty unless a ligature command has created a new
17202 character that will need to be processed later. A pseudo-ligature is
17203 a special node having a |character| field that represents a potential
17204 ligature and a |lig_ptr| field that points to a |char_node| or is |null|.
17205 We have
17206 $$|cur_r|=\cases{|character(lig_stack)|,&if |lig_stack > null|;\cr
17207 \hbox{|qi(hu[j+1])|},&if |lig_stack==null| and |j < n|;\cr
17208 bchar,&if |lig_stack==null| and |j==n|.\cr}$$
17209
17210 @<Glob...@>=
17211 static halfword @!cur_l, @!cur_r; /*characters before and after the cursor*/
17212 static pointer @!cur_q; /*where a ligature should be detached*/
17213 static pointer @!lig_stack; /*unfinished business to the right of the cursor*/
17214 static bool @!ligature_present; /*should a ligature node be made for |cur_l|?*/
17215 static bool @!lft_hit, @!rt_hit; /*did we hit a ligature with a boundary character?*/
17216
17217 @ @d append_charnode_to_t(A) {@+link(t)=get_avail();t=link(t);
17218 font(t)=hf;character(t)=A;
17219 }
17220 @d set_cur_r {@+if (j < n) cur_r=qi(hu[j+1]);@+else cur_r=bchar;
17221 if (odd(hyf[j])) cur_rh=hchar;@+else cur_rh=non_char;
17222 }
17223
17224 @<Set up data structures with the cursor following position |j|@>=
17225 cur_l=qi(hu[j]);cur_q=t;
17226 if (j==0)
17227 {@+ligature_present=init_lig;p=init_list;
17228 if (ligature_present) lft_hit=init_lft;
17229 while (p > null)
17230 {@+append_charnode_to_t(character(p));p=link(p);
17231 }
17232 }
17233 else if (cur_l < non_char) append_charnode_to_t(cur_l);
17234 lig_stack=null;set_cur_r
17235
17236 @ We may want to look at the lig/kern program twice, once for a hyphen
17237 and once for a normal letter. (The hyphen might appear after the letter
17238 in the program, so we'd better not try to look for both at once.)
17239
17240 @<If there's a ligature or kern at the cursor position, update...@>=
17241 if (cur_l==non_char)
17242 {@+k=bchar_label[hf];
17243 if (k==non_address) goto done;@+else q=font_info[k].qqqq;
17244 }
17245 else{@+q=char_info(hf, cur_l);
17246 if (char_tag(hf,q)!=lig_tag) goto done;
17247 k=lig_kern_start(hf, q);q=font_info[k].qqqq;
17248 if (skip_byte(q) > stop_flag)
17249 {@+k=lig_kern_restart(hf, q);q=font_info[k].qqqq;
17250 }
17251 } /*now |k| is the starting address of the lig/kern program*/
17252 if (cur_rh < non_char) test_char=cur_rh;@+else test_char=cur_r;
17253 loop@+{@+if (next_char(q)==test_char) if (skip_byte(q) <= stop_flag)
17254 if (cur_rh < non_char)
17255 {@+hyphen_passed=j;hchar=non_char;cur_rh=non_char;
17256 goto resume;
17257 }
17258 else{@+if (hchar < non_char) if (odd(hyf[j]))
17259 {@+hyphen_passed=j;hchar=non_char;
17260 }
17261 if (op_byte(q) < kern_flag)
17262 @<Carry out a ligature replacement, updating the cursor structure and
17263 possibly advancing~|j|; |goto resume| if the cursor doesn't advance, otherwise
17264 |goto done|@>;
17265 w=char_kern(hf, q);goto done; /*this kern will be inserted below*/
17266 }
17267 if (skip_byte(q) >= stop_flag)
17268 if (cur_rh==non_char) goto done;
17269 else{@+cur_rh=non_char;goto resume;
17270 }
17271 k=k+qo(skip_byte(q))+1;q=font_info[k].qqqq;
17272 }
17273 done:
17274
17275 @ @d wrap_lig(A) if (ligature_present)
17276 {@+p=new_ligature(hf, cur_l, link(cur_q));
17277 if (lft_hit)
17278 {@+subtype(p)=2;lft_hit=false;
17279 }
17280 if (A) if (lig_stack==null)
17281 {@+incr(subtype(p));rt_hit=false;
17282 }
17283 link(cur_q)=p;t=p;ligature_present=false;
17284 }
17285 @d pop_lig_stack {@+if (lig_ptr(lig_stack) > null)
17286 {@+link(t)=lig_ptr(lig_stack); /*this is a charnode for |hu[j+1]|*/
17287 t=link(t);incr(j);
17288 }
17289 p=lig_stack;lig_stack=link(p);free_node(p, small_node_size);
17290 if (lig_stack==null) set_cur_r@;@+else cur_r=character(lig_stack);
17291 } /*if |lig_stack| isn't |null| we have |cur_rh==non_char|*/
17292
17293 @<Append a ligature and/or kern to the translation...@>=
17294 wrap_lig(rt_hit);
17295 if (w!=0)
17296 {@+link(t)=new_kern(w);t=link(t);w=0;
17297 }
17298 if (lig_stack > null)
17299 {@+cur_q=t;cur_l=character(lig_stack);ligature_present=true;
17300 pop_lig_stack;goto resume;
17301 }
17302
17303 @ @<Carry out a ligature replacement, updating the cursor structure...@>=
17304 {@+if (cur_l==non_char) lft_hit=true;
17305 if (j==n) if (lig_stack==null) rt_hit=true;
17306 check_interrupt; /*allow a way out in case there's an infinite ligature loop*/
17307 switch (op_byte(q)) {
17308 case qi(1): case qi(5): {@+cur_l=rem_byte(q); /*\.{=:\@@}, \.{=:\@@>}*/
17309 ligature_present=true;
17310 } @+break;
17311 case qi(2): case qi(6): {@+cur_r=rem_byte(q); /*\.{\@@=:}, \.{\@@=:>}*/
17312 if (lig_stack > null) character(lig_stack)=cur_r;
17313 else{@+lig_stack=new_lig_item(cur_r);
17314 if (j==n) bchar=non_char;
17315 else{@+p=get_avail();lig_ptr(lig_stack)=p;
17316 character(p)=qi(hu[j+1]);font(p)=hf;
17317 }
17318 }
17319 } @+break;
17320 case qi(3): {@+cur_r=rem_byte(q); /*\.{\@@=:\@@}*/
17321 p=lig_stack;lig_stack=new_lig_item(cur_r);link(lig_stack)=p;
17322 } @+break;
17323 case qi(7): case qi(11): {@+wrap_lig(false); /*\.{\@@=:\@@>}, \.{\@@=:\@@>>}*/
17324 cur_q=t;cur_l=rem_byte(q);ligature_present=true;
17325 } @+break;
17326 default:{@+cur_l=rem_byte(q);ligature_present=true; /*\.{=:}*/
17327 if (lig_stack > null) pop_lig_stack@;
17328 else if (j==n) goto done;
17329 else{@+append_charnode_to_t(cur_r);incr(j);set_cur_r;
17330 }
17331 }
17332 }
17333 if (op_byte(q) > qi(4)) if (op_byte(q)!=qi(7)) goto done;
17334 goto resume;
17335 }
17336
17337 @ Okay, we're ready to insert the potential hyphenations that were found.
17338 When the following program is executed, we want to append the word
17339 |hu[1 dotdot hn]| after node |ha|, and node |q| should be appended to the result.
17340 During this process, the variable |i| will be a temporary
17341 index into |hu|; the variable |j| will be an index to our current position
17342 in |hu|; the variable |l| will be the counterpart of |j|, in a discretionary
17343 branch; the variable |r| will point to new nodes being created; and
17344 we need a few new local variables:
17345
17346 @<Local variables for hyph...@>=
17347 pointer @!major_tail, @!minor_tail; /*the end of lists in the main and
17348 discretionary branches being reconstructed*/
17349 uint32_t @!c; /*character temporarily replaced by a hyphen*/
17350 int @!c_loc; /*where that character came from*/
17351 int @!r_count; /*replacement count for discretionary*/
17352 pointer @!hyf_node; /*the hyphen, if it exists*/
17353
17354 @ When the following code is performed, |hyf[0]| and |hyf[hn]| will be zero.
17355
17356 @<Reconstitute nodes for the hyphenated word...@>=
17357 @/do@+{l=j;j=reconstitute(j, hn, bchar, qi(hyf_char))+1;
17358 if (hyphen_passed==0)
17359 {@+link(s)=link(hold_head);
17360 while (link(s) > null) s=link(s);
17361 if (odd(hyf[j-1]))
17362 {@+l=j;hyphen_passed=j-1;link(hold_head)=null;
17363 }
17364 }
17365 if (hyphen_passed > 0)
17366 @<Create and append a discretionary node as an alternative to the unhyphenated
17367 word, and continue to develop both branches until they become equivalent@>;
17368 }@+ while (!(j > hn));
17369 link(s)=q
17370
17371 @ In this repeat loop we will insert another discretionary if |hyf[j-1]| is
17372 odd, when both branches of the previous discretionary end at position |j-1|.
17373 Strictly speaking, we aren't justified in doing this, because we don't know
17374 that a hyphen after |j-1| is truly independent of those branches. But in almost
17375 all applications we would rather not lose a potentially valuable hyphenation
17376 point. (Consider the word `difficult', where the letter `c' is in position |j|.)
17377
17378 @d advance_major_tail {@+major_tail=link(major_tail);incr(r_count);
17379 }
17380
17381 @<Create and append a discretionary node as an alternative...@>=
17382 @/do@+{r=get_node(small_node_size);
17383 link(r)=link(hold_head);type(r)=disc_node;
17384 major_tail=r;r_count=0;
17385 while (link(major_tail) > null) advance_major_tail;
17386 i=hyphen_passed;hyf[i]=0;
17387 @<Put the \(c)characters |hu[l..i]| and a hyphen into |pre_break(r)|@>;
17388 @<Put the \(c)characters |hu[i+1..]| into |post_break(r)|, appending to this
17389 list and to |major_tail| until synchronization has been achieved@>;
17390 @<Move pointer |s| to the end of the current list, and set |replace_count(r)|
17391 appropriately@>;
17392 hyphen_passed=j-1;link(hold_head)=null;
17393 }@+ while (!(!odd(hyf[j-1])))
17394
17395 @ The new hyphen might combine with the previous character via ligature
17396 or kern. At this point we have |l-1 <= i < j| and |i < hn|.
17397
17398 @<Put the \(c)characters |hu[l..i]| and a hyphen into |pre_break(r)|@>=
17399 minor_tail=null;pre_break(r)=null;hyf_node=new_character(hf, hyf_char);
17400 if (hyf_node!=null)
17401 {@+incr(i);c=hu[i];hu[i]=hyf_char;free_avail(hyf_node);
17402 }
17403 while (l <= i)
17404 {@+l=reconstitute(l, i, font_bchar[hf], non_char)+1;
17405 if (link(hold_head) > null)
17406 {@+if (minor_tail==null) pre_break(r)=link(hold_head);
17407 else link(minor_tail)=link(hold_head);
17408 minor_tail=link(hold_head);
17409 while (link(minor_tail) > null) minor_tail=link(minor_tail);
17410 }
17411 }
17412 if (hyf_node!=null)
17413 {@+hu[i]=c; /*restore the character in the hyphen position*/
17414 l=i;decr(i);
17415 }
17416
17417 @ The synchronization algorithm begins with |l==i+1 <= j|.
17418
17419 @<Put the \(c)characters |hu[i+1..]| into |post_break(r)|...@>=
17420 minor_tail=null;post_break(r)=null;c_loc=0;
17421 if (bchar_label[hf]!=non_address) /*put left boundary at beginning of new line*/
17422 {@+decr(l);c=hu[l];c_loc=l;hu[l]=max_hyph_char;
17423 }
17424 while (l < j)
17425 {@+@/do@+{l=reconstitute(l, hn, bchar, non_char)+1;
17426 if (c_loc > 0)
17427 {@+hu[c_loc]=c;c_loc=0;
17428 }
17429 if (link(hold_head) > null)
17430 {@+if (minor_tail==null) post_break(r)=link(hold_head);
17431 else link(minor_tail)=link(hold_head);
17432 minor_tail=link(hold_head);
17433 while (link(minor_tail) > null) minor_tail=link(minor_tail);
17434 }
17435 }@+ while (!(l >= j));
17436 while (l > j)
17437 @<Append characters of |hu[j..]| to |major_tail|, advancing~|j|@>;
17438 }
17439
17440 @ @<Append characters of |hu[j..]|...@>=
17441 {@+j=reconstitute(j, hn, bchar, non_char)+1;
17442 link(major_tail)=link(hold_head);
17443 while (link(major_tail) > null) advance_major_tail;
17444 }
17445
17446 @ Ligature insertion can cause a word to grow exponentially in size. Therefore
17447 we must test the size of |r_count| here, even though the hyphenated text
17448 was at most |max_hyph_length| characters long.
17449
17450 @<Move pointer |s| to the end of the current list...@>=
17451 if (r_count > 127) /*we have to forget the discretionary hyphen*/
17452 {@+link(s)=link(r);link(r)=null;flush_node_list(r);
17453 }
17454 else{@+link(s)=r;set_replace_count(r,r_count);set_auto_disc(r);
17455 }
17456 s=major_tail
17457
17458 @* Hyphenation.
17459 When a word |hc[1 dotdot hn]| has been set up to contain a candidate for hyphenation,
17460 \TeX\ first looks to see if it is in the user's exception dictionary. If not,
17461 hyphens are inserted based on patterns that appear within the given word,
17462 using an algorithm due to Frank~M. Liang.
17463 @^Liang, Franklin Mark@>
17464
17465 Let's consider Liang's method first, since it is much more interesting than the
17466 exception-lookup routine. The algorithm begins by setting |hyf[j]| to zero
17467 for all |j|, and invalid characters are inserted into |hc[0]|
17468 and |hc[hn+1]| to serve as delimiters. Then a reasonably fast method is
17469 used to see which of a given set of patterns occurs in the word
17470 |hc[0 dotdot(hn+1)]|. Each pattern $p_1\ldots p_k$ of length |k| has an associated
17471 sequence of |k+1| numbers $n_0\ldots n_k$; and if the pattern occurs in
17472 |hc[(j+1)dotdot(j+k)]|, \TeX\ will set |hyf[j+i]=@tmax@>(hyf[j+i],@t$n\_i$@>)| for
17473 |0 <= i <= k|. After this has been done for each pattern that occurs, a
17474 discretionary hyphen will be inserted between |hc[j]| and |hc[j+1]| when
17475 |hyf[j]| is odd, as we have already seen.
17476
17477 The set of patterns $p_1\ldots p_k$ and associated numbers $n_0\ldots n_k$
17478 depends, of course, on the language whose words are being hyphenated, and
17479 on the degree of hyphenation that is desired. A method for finding
17480 appropriate |p|'s and |n|'s, from a given dictionary of words and acceptable
17481 hyphenations, is discussed in Liang's Ph.D. thesis (Stanford University,
17482 1983); \TeX\ simply starts with the patterns and works from there.
17483
17484 @ The patterns are stored in a compact table that is also efficient for
17485 retrieval, using a variant of ``trie memory'' [cf.\ {\sl The Art of
17486 Computer Programming \bf3} (1973), 481--505]. We can find each pattern
17487 $p_1\ldots p_k$ by letting $z_0$ be one greater than the relevant language
17488 index and then, for |1 <= i <= k|,
17489 setting |@t$z\_i$@>=trie_link@t$(z\_{i-1})+p\_i$@>|; the pattern will be
17490 identified by the number $z_k$. Since all the pattern information is
17491 packed together into a single |trie_link| array, it is necessary to
17492 prevent confusion between the data from inequivalent patterns, so another
17493 table is provided such that |trie_char@t$(z\_i)=p\_i$@>| for all |i|. There
17494 is also a table |trie_op|$(z_k)$ to identify the numbers $n_0\ldots n_k$
17495 associated with $p_1\ldots p_k$.
17496
17497 Comparatively few different number sequences $n_0\ldots n_k$ actually occur,
17498 since most of the |n|'s are generally zero. Therefore the number sequences
17499 are encoded in such a way that |trie_op|$(z_k)$ is only one byte long.
17500 If |trie_op(@t$z\_k$@>)!=min_quarterword|, when $p_1\ldots p_k$ has matched
17501 the letters in |hc[(l-k+1)dotdot l@,]| of language |t|,
17502 we perform all of the required operations
17503 for this pattern by carrying out the following little program: Set
17504 |v=trie_op(@t$z\_k$@>)|. Then set |v=v+op_start[t]|,
17505 |hyf[l-hyf_distance[v]]=@tmax@>(hyf[l-hyf_distance[v]], hyf_num[v])|,
17506 and |v=hyf_next[v]|; repeat, if necessary, until |v==min_quarterword|.
17507
17508 @<Types...@>=
17509 typedef int32_t trie_pointer; /*an index into |trie|*/
17510
17511 @ @d trie_link(A) trie[A].rh /*``downward'' link in a trie*/
17512 @d trie_char(A) trie[A].b24 /*character matched at this trie location*/
17513 @d trie_op(A) trie[A].b8 /*program for hyphenation at this trie location*/
17514
17515 @<Glob...@>=
17516 static two_halves @!trie[trie_size+1]; /*|trie_link|, |trie_char|, |trie_op|*/
17517 static small_number @!hyf_distance0[trie_op_size],
17518 *const @!hyf_distance = @!hyf_distance0-1; /*position |k-j| of $n_j$*/
17519 static small_number @!hyf_num0[trie_op_size],
17520 *const @!hyf_num = @!hyf_num0-1; /*value of $n_j$*/
17521 static quarterword @!hyf_next0[trie_op_size],
17522 *const @!hyf_next = @!hyf_next0-1; /*continuation code*/
17523 static uint16_t @!op_start[max_language+1]; /*offset for current language*/
17524
17525 @ @<Local variables for hyph...@>=
17526 trie_pointer @!z; /*an index into |trie|*/
17527 int @!v; /*an index into |hyf_distance|, etc.*/
17528
17529 @ Assuming that these auxiliary tables have been set up properly, the
17530 hyphenation algorithm is quite short. In the following code we set |hc[hn+2]|
17531 to the impossible value 256, in order to guarantee that |hc[hn+3]| will
17532 never be fetched.
17533
17534 @<Find hyphen locations for the word in |hc|...@>=
17535 for (j=0; j<=hn; j++) hyf[j]=0;
17536 @<Look for the word |hc[1..hn]| in the exception table, and |goto found| (with
17537 |hyf| containing the hyphens) if an entry is found@>;
17538 if (trie_char(cur_lang+1)!=qi(cur_lang)) return; /*no patterns for |cur_lang|*/
17539 hc[0]=0;hc[hn+1]=0;hc[hn+2]=max_hyph_char; /*insert delimiters*/
17540 for (j=0; j<=hn-r_hyf+1; j++)
17541 {@+z=trie_link(cur_lang+1)+hc[j];l=j;
17542 while (hc[l]==qo(trie_char(z)))
17543 {@+if (trie_op(z)!=min_quarterword)
17544 @<Store \(m)maximum values in the |hyf| table@>;
17545 incr(l);z=trie_link(z)+hc[l];
17546 }
17547 }
17548 found: for (j=0; j<=l_hyf-1; j++) hyf[j]=0;
17549 for (j=0; j<=r_hyf-1; j++) hyf[hn-j]=0
17550
17551 @ @<Store \(m)maximum values in the |hyf| table@>=
17552 {@+v=trie_op(z);
17553 @/do@+{v=v+op_start[cur_lang];i=l-hyf_distance[v];
17554 if (hyf_num[v] > hyf[i]) hyf[i]=hyf_num[v];
17555 v=hyf_next[v];
17556 }@+ while (!(v==min_quarterword));
17557 }
17558
17559 @ The exception table that is built by \TeX's \.{\\hyphenation} primitive is
17560 organized as an ordered hash table [cf.\ Amble and Knuth, {\sl The Computer
17561 @^Amble, Ole@> @^Knuth, Donald Ervin@>
17562 Journal\/ \bf17} (1974), 135--142] using linear probing. If $\alpha$ and
17563 $\beta$ are words, we will say that $\alpha<\beta$ if $\vert\alpha\vert<
17564 \vert\beta\vert$ or if $\vert\alpha\vert=\vert\beta\vert$ and
17565 $\alpha$ is lexicographically smaller than $\beta$. (The notation $\vert
17566 \alpha\vert$ stands for the length of $\alpha$.) The idea of ordered hashing
17567 is to arrange the table so that a given word $\alpha$ can be sought by computing
17568 a hash address $h=h(\alpha)$ and then looking in table positions |h|, |h-1|,
17569 \dots, until encountering the first word $\le\alpha$. If this word is
17570 different from $\alpha$, we can conclude that $\alpha$ is not in the table.
17571
17572 The words in the table point to lists in |mem| that specify hyphen positions
17573 in their |info| fields. The list for $c_1\ldots c_n$ contains the number |k| if
17574 the word $c_1\ldots c_n$ has a discretionary hyphen between $c_k$ and
17575 $c_{k+1}$.
17576
17577 @<Types...@>=
17578 typedef int16_t hyph_pointer; /*an index into the ordered hash table*/
17579
17580 @ @<Glob...@>=
17581 static str_number @!hyph_word[hyph_size+1]; /*exception words*/
17582 static pointer @!hyph_list[hyph_size+1]; /*lists of hyphen positions*/
17583 static hyph_pointer @!hyph_count; /*the number of words in the exception dictionary*/
17584
17585 @ @<Local variables for init...@>=
17586 int @!z; /*runs through the exception dictionary*/
17587
17588 @ @<Set init...@>=
17589 for (z=0; z<=hyph_size; z++)
17590 {@+hyph_word[z]=0;hyph_list[z]=null;
17591 }
17592 hyph_count=0;
17593
17594 @ The algorithm for exception lookup is quite simple, as soon as we have
17595 a few more local variables to work with.
17596
17597 @<Local variables for hyph...@>=
17598 hyph_pointer @!h; /*an index into |hyph_word| and |hyph_list|*/
17599 str_number @!k; /*an index into |str_start|*/
17600 pool_pointer @!u; /*an index into |str_pool|*/
17601
17602 @ First we compute the hash code |h|, then we search until we either
17603 find the word or we don't. Words from different languages are kept
17604 separate by appending the language code to the string.
17605
17606 @<Look for the word |hc[1...@>=
17607 h=hc[1];incr(hn);hc[hn]=cur_lang;
17608 for (j=2; j<=hn; j++) h=(h+h+hc[j])%hyph_size;
17609 loop@+{@+@<If the string |hyph_word[h]| is less than \(hc)|hc[1..hn]|, |goto
17610 not_found|; but if the two strings are equal, set |hyf| to the hyphen positions
17611 and |goto found|@>;
17612 if (h > 0) decr(h);@+else h=hyph_size;
17613 }
17614 not_found: decr(hn)
17615
17616 @ @<If the string |hyph_word[h]| is less than \(hc)...@>=
17617 k=hyph_word[h];if (k==0) goto not_found;
17618 if (length(k) < hn) goto not_found;
17619 if (length(k)==hn)
17620 {@+j=1;u=str_start[k];
17621 @/do@+{if (str_pool[u] < hc[j]) goto not_found;
17622 if (str_pool[u] > hc[j]) goto done;
17623 incr(j);incr(u);
17624 }@+ while (!(j > hn));
17625 @<Insert hyphens as specified in |hyph_list[h]|@>;
17626 decr(hn);goto found;
17627 }
17628 done:
17629
17630 @ @<Insert hyphens as specified...@>=
17631 s=hyph_list[h];
17632 while (s!=null)
17633 {@+hyf[info(s)]=1;s=link(s);
17634 }
17635
17636 @ @<Search |hyph_list| for pointers to |p|@>=
17637 for (q=0; q<=hyph_size; q++)
17638 {@+if (hyph_list[q]==p)
17639 {@+print_nl("HYPH(");print_int(q);print_char(')');
17640 }
17641 }
17642
17643 @ We have now completed the hyphenation routine, so the |line_break| procedure
17644 is finished at last. Since the hyphenation exception table is fresh in our
17645 minds, it's a good time to deal with the routine that adds new entries to it.
17646
17647 When \TeX\ has scanned `\.{\\hyphenation}', it calls on a procedure named
17648 |new_hyph_exceptions| to do the right thing.
17649
17650 @d set_cur_lang if (language <= 0) cur_lang=0;
17651 else if (language > max_language) cur_lang=0;
17652 else cur_lang=language
17653
17654 @p static void new_hyph_exceptions(void) /*enters new exceptions*/
17655 {@+
17656 int n; /*length of current word; not always a |small_number|*/
17657 int @!j; /*an index into |hc|*/
17658 hyph_pointer @!h; /*an index into |hyph_word| and |hyph_list|*/
17659 str_number @!k; /*an index into |str_start|*/
17660 pointer @!p; /*head of a list of hyphen positions*/
17661 pointer @!q; /*used when creating a new node for list |p|*/
17662 str_number @!s, @!t; /*strings being compared or stored*/
17663 pool_pointer @!u, @!v; /*indices into |str_pool|*/
17664 scan_left_brace(); /*a left brace must follow \.{\\hyphenation}*/
17665 set_cur_lang;
17666 #ifdef @!INIT
17667 if (trie_not_ready)
17668 {@+hyph_index=0;goto not_found1;
17669 }
17670 #endif
17671 set_hyph_index;
17672 not_found1:
17673 @<Enter as many hyphenation exceptions as are listed, until coming to a right
17674 brace; then |return|@>;
17675 }
17676
17677 @ @<Enter as many...@>=
17678 n=0;p=null;
17679 loop@+{@+get_x_token();
17680 reswitch: switch (cur_cmd) {
17681 case letter: case other_char: case char_given: @<Append a new letter or
17682 hyphen@>@;@+break;
17683 case char_num: {@+scan_char_num();cur_chr=cur_val;cur_cmd=char_given;
17684 goto reswitch;
17685 }
17686 case spacer: case right_brace: {@+if (n > 1) @<Enter a hyphenation exception@>;
17687 if (cur_cmd==right_brace) return;
17688 n=0;p=null;
17689 } @+break;
17690 default:@<Give improper \.{\\hyphenation} error@>@;
17691 }
17692 }
17693
17694 @ @<Give improper \.{\\hyph...@>=
17695 {@+print_err("Improper ");print_esc("hyphenation");
17696 @.Improper \\hyphenation...@>
17697 print(" will be flushed");
17698 help2("Hyphenation exceptions must contain only letters",@/
17699 "and hyphens. But continue; I'll forgive and forget.");
17700 error();
17701 }
17702
17703 @ @<Append a new letter or hyphen@>=
17704 if (cur_chr=='-') @<Append the value |n| to list |p|@>@;
17705 else{@+set_lc_code(cur_chr);
17706 if (hc[0]==0)
17707 {@+print_err("Not a letter");
17708 @.Not a letter@>
17709 help2("Letters in \\hyphenation words must have \\lccode>0.",@/
17710 "Proceed; I'll ignore the character I just read.");
17711 error();
17712 }
17713 else if (n < max_hyph_length)
17714 {@+incr(n);hc[n]=hc[0];
17715 }
17716 }
17717
17718 @ @<Append the value |n| to list |p|@>=
17719 {@+if (n < max_hyph_length)
17720 {@+q=get_avail();link(q)=p;info(q)=n;p=q;
17721 }
17722 }
17723
17724 @ @<Enter a hyphenation exception@>=
17725 {@+incr(n);hc[n]=cur_lang;str_room(n);h=0;
17726 for (j=1; j<=n; j++)
17727 {@+h=(h+h+hc[j])%hyph_size;
17728 append_char(hc[j]);
17729 }
17730 s=make_string();
17731 @<Insert the \(p)pair |(s,p)| into the exception table@>;
17732 }
17733
17734 @ @<Insert the \(p)pair |(s,p)|...@>=
17735 if (hyph_count==hyph_size) overflow("exception dictionary", hyph_size);
17736 @:TeX capacity exceeded exception dictionary}{\quad exception dictionary@>
17737 incr(hyph_count);
17738 while (hyph_word[h]!=0)
17739 {@+@<If the string |hyph_word[h]| is less than \(or)or equal to |s|, interchange
17740 |(hyph_word[h],hyph_list[h])| with |(s,p)|@>;
17741 if (h > 0) decr(h);@+else h=hyph_size;
17742 }
17743 hyph_word[h]=s;hyph_list[h]=p
17744
17745 @ @<If the string |hyph_word[h]| is less than \(or)...@>=
17746 k=hyph_word[h];
17747 if (length(k) < length(s)) goto found;
17748 if (length(k) > length(s)) goto not_found;
17749 u=str_start[k];v=str_start[s];
17750 @/do@+{if (str_pool[u] < str_pool[v]) goto found;
17751 if (str_pool[u] > str_pool[v]) goto not_found;
17752 incr(u);incr(v);
17753 }@+ while (!(u==str_start[k+1]));
17754 found: q=hyph_list[h];hyph_list[h]=p;p=q;@/
17755 t=hyph_word[h];hyph_word[h]=s;s=t;
17756 not_found:
17757
17758 @* Initializing the hyphenation tables.
17759 The trie for \TeX's hyphenation algorithm is built from a sequence of
17760 patterns following a \.{\\patterns} specification. Such a specification
17761 is allowed only in \.{INITEX}, since the extra memory for auxiliary tables
17762 and for the initialization program itself would only clutter up the
17763 production version of \TeX\ with a lot of deadwood.
17764
17765 The first step is to build a trie that is linked, instead of packed
17766 into sequential storage, so that insertions are readily made.
17767 After all patterns have been processed, \.{INITEX}
17768 compresses the linked trie by identifying common subtries. Finally the
17769 trie is packed into the efficient sequential form that the hyphenation
17770 algorithm actually uses.
17771
17772 @<Declare subprocedures for |line_break|@>=
17773 #ifdef @!INIT
17774 @<Declare procedures for preprocessing hyphenation patterns@>@;
17775 #endif
17776
17777 @ Before we discuss trie building in detail, let's consider the simpler
17778 problem of creating the |hyf_distance|, |hyf_num|, and |hyf_next| arrays.
17779
17780 Suppose, for example, that \TeX\ reads the pattern `\.{ab2cde1}'. This is
17781 a pattern of length 5, with $n_0\ldots n_5=0\,0\,2\,0\,0\,1$ in the
17782 notation above. We want the corresponding |trie_op| code |v| to have
17783 |hyf_distance[v]==3|, |hyf_num[v]==2|, and |hyf_next[v]==@t$v^\prime$@>|,
17784 where the auxiliary |trie_op| code $v^\prime$ has
17785 |hyf_distance[@t$v^\prime$@>]==0|, |hyf_num[@t$v^\prime$@>]==1|, and
17786 |hyf_next[@t$v^\prime$@>]==min_quarterword|.
17787
17788 \TeX\ computes an appropriate value |v| with the |new_trie_op| subroutine
17789 below, by setting
17790 $$\hbox{|@t$v^\prime$@>=new_trie_op(0, 1, min_quarterword)|,\qquad
17791 |v=new_trie_op(3, 2,@t$v^\prime$@>)|.}$$
17792 This subroutine looks up its three
17793 parameters in a special hash table, assigning a new value only if these
17794 three have not appeared before for the current language.
17795
17796 The hash table is called |trie_op_hash|, and the number of entries it contains
17797 is |trie_op_ptr|.
17798
17799 @<Glob...@>=
17800 #ifdef @!INIT
17801 static uint16_t @!trie_op_hash0[trie_op_size+trie_op_size+1],
17802 *const @!trie_op_hash = @!trie_op_hash0+trie_op_size;
17803 /*trie op codes for quadruples*/
17804 static quarterword @!trie_used[max_language+1];
17805 /*largest opcode used so far for this language*/
17806 static uint8_t @!trie_op_lang0[trie_op_size],
17807 *const @!trie_op_lang = @!trie_op_lang0-1;
17808 /*language part of a hashed quadruple*/
17809 static quarterword @!trie_op_val0[trie_op_size],
17810 *const @!trie_op_val = @!trie_op_val0-1;
17811 /*opcode corresponding to a hashed quadruple*/
17812 static int @!trie_op_ptr; /*number of stored ops so far*/
17813 #endif
17814
17815 @ It's tempting to remove the |overflow| stops in the following procedure;
17816 |new_trie_op| could return |min_quarterword| (thereby simply ignoring
17817 part of a hyphenation pattern) instead of aborting the job. However, that would
17818 lead to different hyphenation results on different installations of \TeX\
17819 using the same patterns. The |overflow| stops are necessary for portability
17820 of patterns.
17821
17822 @<Declare procedures for preprocessing hyph...@>=
17823 static quarterword new_trie_op(small_number @!d, small_number @!n, quarterword @!v)
17824 {@+
17825 int h; /*trial hash location*/
17826 quarterword @!u; /*trial op code*/
17827 int @!l; /*pointer to stored data*/
17828 h=abs(n+313*d+361*v+1009*cur_lang)%(trie_op_size+trie_op_size)
17829 -trie_op_size;
17830 loop@+{@+l=trie_op_hash[h];
17831 if (l==0) /*empty position found for a new op*/
17832 {@+if (trie_op_ptr==trie_op_size)
17833 overflow("pattern memory ops", trie_op_size);
17834 u=trie_used[cur_lang];
17835 if (u==max_quarterword)
17836 overflow("pattern memory ops per language",
17837 max_quarterword-min_quarterword);
17838 incr(trie_op_ptr);incr(u);trie_used[cur_lang]=u;
17839 hyf_distance[trie_op_ptr]=d;
17840 hyf_num[trie_op_ptr]=n;hyf_next[trie_op_ptr]=v;
17841 trie_op_lang[trie_op_ptr]=cur_lang;trie_op_hash[h]=trie_op_ptr;
17842 trie_op_val[trie_op_ptr]=u;return u;
17843 }
17844 if ((hyf_distance[l]==d)&&(hyf_num[l]==n)&&(hyf_next[l]==v)
17845 &&(trie_op_lang[l]==cur_lang))
17846 {@+return trie_op_val[l];
17847 }
17848 if (h > -trie_op_size) decr(h);@+else h=trie_op_size;
17849 }
17850 }
17851
17852 @ After |new_trie_op| has compressed the necessary opcode information,
17853 plenty of information is available to unscramble the data into the
17854 final form needed by our hyphenation algorithm.
17855
17856 @<Sort \(t)the hyphenation op tables into proper order@>=
17857 op_start[0]=-min_quarterword;
17858 for (j=1; j<=max_language; j++) op_start[j]=op_start[j-1]+qo(trie_used[j-1]);
17859 for (j=1; j<=trie_op_ptr; j++)
17860 trie_op_hash[j]=op_start[trie_op_lang[j]]+trie_op_val[j]; /*destination*/
17861 for (j=1; j<=trie_op_ptr; j++) while (trie_op_hash[j] > j)
17862 {@+k=trie_op_hash[j];@/
17863 t=hyf_distance[k];hyf_distance[k]=hyf_distance[j];hyf_distance[j]=t;@/
17864 t=hyf_num[k];hyf_num[k]=hyf_num[j];hyf_num[j]=t;@/
17865 t=hyf_next[k];hyf_next[k]=hyf_next[j];hyf_next[j]=t;@/
17866 trie_op_hash[j]=trie_op_hash[k];trie_op_hash[k]=k;
17867 }
17868
17869 @ Before we forget how to initialize the data structures that have been
17870 mentioned so far, let's write down the code that gets them started.
17871
17872 @<Initialize table entries...@>=
17873 for (k=-trie_op_size; k<=trie_op_size; k++) trie_op_hash[k]=0;
17874 for (k=0; k<=max_language; k++) trie_used[k]=min_quarterword;
17875 trie_op_ptr=0;
17876
17877 @ The linked trie that is used to preprocess hyphenation patterns appears
17878 in several global arrays. Each node represents an instruction of the form
17879 ``if you see character |c|, then perform operation |o|, move to the
17880 next character, and go to node |l|; otherwise go to node |r|.''
17881 The four quantities |c|, |o|, |l|, and |r| are stored in four arrays
17882 |trie_c|, |trie_o|, |trie_l|, and |trie_r|. The root of the trie
17883 is |trie_l[0]|, and the number of nodes is |trie_ptr|. Null trie
17884 pointers are represented by zero. To initialize the trie, we simply
17885 set |trie_l[0]| and |trie_ptr| to zero. We also set |trie_c[0]| to some
17886 arbitrary value, since the algorithm may access it.
17887
17888 The algorithms maintain the condition
17889 $$\hbox{|trie_c[trie_r[z]] > trie_c[z]|\qquad
17890 whenever |z!=0| and |trie_r[z]!=0|};$$ in other words, sibling nodes are
17891 ordered by their |c| fields.
17892
17893 @d trie_root trie_l[0] /*root of the linked trie*/
17894
17895 @<Glob...@>=
17896 #ifdef @!INIT
17897 static uint32_t @!trie_c[trie_size+1];
17898 /*characters to match*/
17899 @t\hskip10pt@>static quarterword @!trie_o[trie_size+1];
17900 /*operations to perform*/
17901 @t\hskip10pt@>static trie_pointer @!trie_l[trie_size+1];
17902 /*left subtrie links*/
17903 @t\hskip10pt@>static trie_pointer @!trie_r[trie_size+1];
17904 /*right subtrie links*/
17905 @t\hskip10pt@>static trie_pointer @!trie_ptr; /*the number of nodes in the trie*/
17906 @t\hskip10pt@>static trie_pointer @!trie_hash[trie_size+1];
17907 /*used to identify equivalent subtries*/
17908 #endif
17909
17910 @ Let us suppose that a linked trie has already been constructed.
17911 Experience shows that we can often reduce its size by recognizing common
17912 subtries; therefore another hash table is introduced for this purpose,
17913 somewhat similar to |trie_op_hash|. The new hash table will be
17914 initialized to zero.
17915
17916 The function |trie_node(p)| returns |p| if |p| is distinct from other nodes
17917 that it has seen, otherwise it returns the number of the first equivalent
17918 node that it has seen.
17919
17920 Notice that we might make subtries equivalent even if they correspond to
17921 patterns for different languages, in which the trie ops might mean quite
17922 different things. That's perfectly all right.
17923
17924 @<Declare procedures for preprocessing hyph...@>=
17925 static trie_pointer trie_node(trie_pointer @!p) /*converts
17926 to a canonical form*/
17927 {@+
17928 trie_pointer h; /*trial hash location*/
17929 trie_pointer @!q; /*trial trie node*/
17930 h=abs(trie_c[p]+1009*trie_o[p]+@|
17931 2718*trie_l[p]+3142*trie_r[p])%trie_size;
17932 loop@+{@+q=trie_hash[h];
17933 if (q==0)
17934 {@+trie_hash[h]=p;return p;
17935 }
17936 if ((trie_c[q]==trie_c[p])&&(trie_o[q]==trie_o[p])&&@|
17937 (trie_l[q]==trie_l[p])&&(trie_r[q]==trie_r[p]))
17938 {@+return q;
17939 }
17940 if (h > 0) decr(h);@+else h=trie_size;
17941 }
17942 }
17943
17944 @ A neat recursive procedure is now able to compress a trie by
17945 traversing it and applying |trie_node| to its nodes in ``bottom up''
17946 fashion. We will compress the entire trie by clearing |trie_hash| to
17947 zero and then saying `|trie_root=compress_trie(trie_root)|'.
17948 @^recursion@>
17949
17950 @<Declare procedures for preprocessing hyph...@>=
17951 static trie_pointer compress_trie(trie_pointer @!p)
17952 {@+if (p==0) return 0;
17953 else{@+trie_l[p]=compress_trie(trie_l[p]);
17954 trie_r[p]=compress_trie(trie_r[p]);
17955 return trie_node(p);
17956 }
17957 }
17958
17959 @ The compressed trie will be packed into the |trie| array using a
17960 ``top-down first-fit'' procedure. This is a little tricky, so the reader
17961 should pay close attention: The |trie_hash| array is cleared to zero
17962 again and renamed |trie_ref| for this phase of the operation; later on,
17963 |trie_ref[p]| will be nonzero only if the linked trie node |p| is the
17964 smallest character
17965 in a family and if the characters |c| of that family have been allocated to
17966 locations |trie_ref[p]+c| in the |trie| array. Locations of |trie| that
17967 are in use will have |trie_link==0|, while the unused holes in |trie|
17968 will be doubly linked with |trie_link| pointing to the next larger vacant
17969 location and |trie_back| pointing to the next smaller one. This double
17970 linking will have been carried out only as far as |trie_max|, where
17971 |trie_max| is the largest index of |trie| that will be needed.
17972 To save time at the low end of the trie, we maintain array entries
17973 |trie_min[c]| pointing to the smallest hole that is greater than~|c|.
17974 Another array |trie_taken| tells whether or not a given location is
17975 equal to |trie_ref[p]| for some |p|; this array is used to ensure that
17976 distinct nodes in the compressed trie will have distinct |trie_ref|
17977 entries.
17978
17979 @d trie_ref trie_hash /*where linked trie families go into |trie|*/
17980 @d trie_back(A) trie[A].lh /*backward links in |trie| holes*/
17981
17982
17983 @<Glob...@>=
17984 #ifdef @!INIT
17985 static bool @!trie_taken0[trie_size],
17986 *const @!trie_taken = @!trie_taken0-1;
17987 /*does a family start here?*/
17988 @t\hskip10pt@>static trie_pointer @!trie_min[max_pattern_char+1];
17989 /*the first possible slot for each character*/
17990 @t\hskip10pt@>static trie_pointer @!trie_max; /*largest location used in |trie|*/
17991 @t\hskip10pt@>static bool @!trie_not_ready; /*is the trie still in linked form?*/
17992 #endif
17993
17994 @ Each time \.{\\patterns} appears, it contributes further patterns to
17995 the future trie, which will be built only when hyphenation is attempted or
17996 when a format file is dumped. The boolean variable |trie_not_ready|
17997 will change to |false| when the trie is compressed; this will disable
17998 further patterns.
17999
18000 @<Initialize table entries...@>=
18001 trie_not_ready=true;trie_root=0;trie_c[0]=0;trie_ptr=0;
18002
18003 @ Here is how the trie-compression data structures are initialized.
18004 If storage is tight, it would be possible to overlap |trie_op_hash|,
18005 |trie_op_lang|, and |trie_op_val| with |trie|, |trie_hash|, and |trie_taken|,
18006 because we finish with the former just before we need the latter.
18007
18008 @<Get ready to compress the trie@>=
18009 @<Sort \(t)the hyphenation...@>;
18010 for (p=0; p<=trie_size; p++) trie_hash[p]=0;
18011 hyph_root=compress_trie(hyph_root);
18012 trie_root=compress_trie(trie_root); /*identify equivalent subtries*/
18013 for (p=0; p<=trie_ptr; p++) trie_ref[p]=0;
18014 for (p=0; p<=max_pattern_char; p++) trie_min[p]=p+1;
18015 trie_link(0)=1;trie_max=0
18016
18017 @ The |first_fit| procedure finds the smallest hole |z| in |trie| such that
18018 a trie family starting at a given node |p| will fit into vacant positions
18019 starting at |z|. If |c==trie_c[p]|, this means that location |z-c| must
18020 not already be taken by some other family, and that |z-c+@t$c^\prime$@>|
18021 must be vacant for all characters $c^\prime$ in the family. The procedure
18022 sets |trie_ref[p]| to |z-c| when the first fit has been found.
18023
18024 @<Declare procedures for preprocessing hyph...@>=
18025 static void first_fit(trie_pointer @!p) /*packs a family into |trie|*/
18026 {@+
18027 trie_pointer h; /*candidate for |trie_ref[p]|*/
18028 trie_pointer @!z; /*runs through holes*/
18029 trie_pointer @!q; /*runs through the family starting at |p|*/
18030 uint32_t @!c; /*smallest character in the family*/
18031 trie_pointer @!l, @!r; /*left and right neighbors*/
18032 int @!ll; /*upper limit of |trie_min| updating*/
18033 c=trie_c[p];
18034 z=trie_min[c]; /*get the first conceivably good hole*/
18035 loop@+{@+h=z-c;@/
18036 @<Ensure that |trie_max>=h+max_hyph_char|@>;
18037 if (trie_taken[h]) goto not_found;
18038 @<If all characters of the family fit relative to |h|, then |goto found|,\30\
18039 otherwise |goto not_found|@>;
18040 not_found:
18041 z=trie_link(z); /*move to the next hole*/
18042 }
18043 found: @<Pack the family into |trie| relative to |h|@>;
18044 }
18045
18046 @ By making sure that |trie_max| is at least |h+max_hyph_char|, we can be sure that
18047 |trie_max > z|, since |h==z-c|. It follows that location |trie_max| will
18048 never be occupied in |trie|, and we will have |trie_max >= trie_link(z)|.
18049
18050 @<Ensure that |trie_max>=h+max_hyph_char|@>=
18051 if (trie_max < h+max_hyph_char)
18052 {@+if (trie_size <= h+max_hyph_char) overflow("pattern memory", trie_size);
18053 @:TeX capacity exceeded pattern memory}{\quad pattern memory@>
18054 @/do@+{incr(trie_max);trie_taken[trie_max]=false;
18055 trie_link(trie_max)=trie_max+1;trie_back(trie_max)=trie_max-1;
18056 }@+ while (!(trie_max==h+max_hyph_char));
18057 }
18058
18059 @ @<If all characters of the family fit relative to |h|...@>=
18060 q=trie_r[p];
18061 while (q > 0)
18062 {@+if (trie_link(h+trie_c[q])==0) goto not_found;
18063 q=trie_r[q];
18064 }
18065 goto found
18066
18067 @ @<Pack the family into |trie| relative to |h|@>=
18068 trie_taken[h]=true;trie_ref[p]=h;q=p;
18069 @/do@+{
18070 z=h+trie_c[q];l=trie_back(z);r=trie_link(z);
18071 trie_back(r)=l;trie_link(l)=r;trie_link(z)=0;
18072 if (l < max_hyph_char)
18073 {@+if (z < max_hyph_char) ll=z;@+else ll=max_hyph_char;
18074 @/do@+{trie_min[l]=r;incr(l);
18075
18076 }@+ while (!(l==ll));
18077 }
18078 q=trie_r[q];
18079 }@+ while (!(q==0))
18080
18081 @ To pack the entire linked trie, we use the following recursive procedure.
18082 @^recursion@>
18083
18084 @<Declare procedures for preprocessing hyph...@>=
18085 static void trie_pack(trie_pointer @!p) /*pack subtries of a family*/
18086 {@+trie_pointer q; /*a local variable that need not be saved on recursive calls*/
18087 @/do@+{q=trie_l[p];
18088 if ((q > 0)&&(trie_ref[q]==0))
18089 {@+first_fit(q);trie_pack(q);
18090 }
18091 p=trie_r[p];
18092 }@+ while (!(p==0));
18093 }
18094
18095 @ When the whole trie has been allocated into the sequential table, we
18096 must go through it once again so that |trie| contains the correct
18097 information. Null pointers in the linked trie will be represented by the
18098 value~0, which properly implements an ``empty'' family.
18099
18100 @<Move the data into |trie|@>=
18101 h.rh=0;h.b0=min_quarterword;h.b1=min_quarterword; /*|trie_link=0|,
18102 |trie_op=min_quarterword|, |trie_char=qi(0)|*/
18103 if (trie_max==0) /*no patterns were given*/
18104 {@+for (r=0; r<=max_language+1; r++) trie[r]=h;
18105 trie_max=max_language+1;
18106 }
18107 else{@+if (hyph_root > 0) trie_fix(hyph_root);
18108 if (trie_root > 0) trie_fix(trie_root); /*this fixes the non-holes in |trie|*/
18109 r=0; /*now we will zero out all the holes*/
18110 @/do@+{s=trie_link(r);trie[r]=h;r=s;
18111 }@+ while (!(r > trie_max));
18112 }
18113 trie_char(0)=qi('?'); /*make |trie_char(c)!=c| for all |c|*/
18114
18115 @ The fixing-up procedure is, of course, recursive. Since the linked trie
18116 usually has overlapping subtries, the same data may be moved several
18117 times; but that causes no harm, and at most as much work is done as it
18118 took to build the uncompressed trie.
18119 @^recursion@>
18120
18121 @<Declare procedures for preprocessing hyph...@>=
18122 static void trie_fix(trie_pointer @!p) /*moves |p| and its siblings into |trie|*/
18123 {@+trie_pointer q; /*a local variable that need not be saved on recursive calls*/
18124 int @!c; /*another one that need not be saved*/
18125 trie_pointer @!z; /*|trie| reference; this local variable must be saved*/
18126 z=trie_ref[p];
18127 @/do@+{q=trie_l[p];c=trie_c[p];
18128 trie_link(z+c)=trie_ref[q];trie_char(z+c)=qi(c);trie_op(z+c)=trie_o[p];
18129 if (q > 0) trie_fix(q);
18130 p=trie_r[p];
18131 }@+ while (!(p==0));
18132 }
18133
18134 @ Now let's go back to the easier problem, of building the linked
18135 trie. When \.{INITEX} has scanned the `\.{\\patterns}' control
18136 sequence, it calls on |new_patterns| to do the right thing.
18137
18138 @<Declare procedures for preprocessing hyph...@>=
18139 static void new_patterns(void) /*initializes the hyphenation pattern data*/
18140 {@+
18141 int k, @!l; /*indices into |hc| and |hyf|;
18142 not always in |small_number| range*/
18143 bool @!digit_sensed; /*should the next digit be treated as a letter?*/
18144 quarterword @!v; /*trie op code*/
18145 trie_pointer @!p, @!q; /*nodes of trie traversed during insertion*/
18146 bool @!first_child; /*is |p==trie_l[q]|?*/
18147 int @!c; /*character being inserted*/
18148 if (trie_not_ready)
18149 {@+set_cur_lang;scan_left_brace(); /*a left brace must follow \.{\\patterns}*/
18150 @<Enter all of the patterns into a linked trie, until coming to a right
18151 brace@>;
18152 if (saving_hyph_codes > 0)
18153 @<Store hyphenation codes for current language@>;
18154 }
18155 else{@+print_err("Too late for ");print_esc("patterns");
18156 help1("All patterns must be given before typesetting begins.");
18157 error();link(garbage)=scan_toks(false, false);flush_list(def_ref);
18158 }
18159 }
18160
18161 @ Novices are not supposed to be using \.{\\patterns}, so the error
18162 messages are terse. (Note that all error messages appear in \TeX's string
18163 pool, even if they are used only by \.{INITEX}.)
18164
18165 @<Enter all of the patterns into a linked trie...@>=
18166 k=0;hyf[0]=0;digit_sensed=false;
18167 pattern_warning_given=false;
18168 loop@+{@+get_x_token();
18169 switch (cur_cmd) {
18170 case letter: case other_char: @<Append a new letter or a hyphen level@>@;@+break;
18171 case spacer: case right_brace: {@+if (k > 0)
18172 @<Insert a new pattern into the linked trie@>;
18173 skip_pattern=false;
18174 if (cur_cmd==right_brace) goto done;
18175 k=0;hyf[0]=0;digit_sensed=false;
18176 } @+break;
18177 default:{@+print_err("Bad ");print_esc("patterns");
18178 @.Bad \\patterns@>
18179 help1("(See Appendix H.)");error();
18180 }
18181 }
18182 }
18183 done:
18184
18185 @ Moving from 8-bit characters to UTF codepoints enlarges the range of |cur_chr|.
18186 The new upper bound of |0x10FFFF| would imply a huge waste of memory in
18187 the compacted tree representation. Therefor |max_pattern_char| is a
18188 smaller upper bound. Patterns using codepoints above this bound will
18189 be ignored. For each call of the \.{\\patterns} primitive only a
18190 single warning is given.
18191
18192 @<Global...@>=
18193 static bool pattern_warning_given=false;
18194 static bool skip_pattern=false;
18195
18196 @ @<Append a new letter or a hyphen level@>=
18197 if (skip_pattern) break;
18198 if (digit_sensed||(cur_chr < '0')||(cur_chr > '9'))
18199 {@+if (cur_chr=='.') cur_chr=0; /*edge-of-word delimiter*/
18200 else{@+cur_chr=lc_code(cur_chr);
18201 if (cur_chr==0)
18202 {@+print_err("Nonletter");
18203 @.Nonletter@>
18204 help1("(See Appendix H.)");error();
18205 }
18206 }
18207 if (cur_chr > max_pattern_char-1)
18208 { if (!pattern_warning_given)
18209 { print_err("Character code "); print_int(cur_chr);
18210 print(" exceeds "); print_int(max_pattern_char-1);
18211 pattern_warning_given=true;
18212 }
18213 skip_pattern=true;
18214 k=0;
18215 break;
18216 }
18217 if (cur_chr > max_hyph_char) max_hyph_char=cur_chr;
18218 if (k < max_hyph_length)
18219 {@+incr(k);hc[k]=cur_chr;hyf[k]=0;digit_sensed=false;
18220 }
18221 }
18222 else if (k < max_hyph_length)
18223 {@+hyf[k]=cur_chr-'0';digit_sensed=true;
18224 }
18225
18226 @ When the following code comes into play, the pattern $p_1\ldots p_k$
18227 appears in |hc[1 dotdot k]|, and the corresponding sequence of numbers $n_0\ldots
18228 n_k$ appears in |hyf[0 dotdot k]|.
18229
18230 @<Insert a new pattern into the linked trie@>=
18231 {@+@<Compute the trie op code, |v|, and set |l:=0|@>;
18232 q=0;hc[0]=cur_lang;
18233 while (l <= k)
18234 {@+c=hc[l];incr(l);p=trie_l[q];first_child=true;
18235 while ((p > 0)&&(c > trie_c[p]))
18236 {@+q=p;p=trie_r[q];first_child=false;
18237 }
18238 if ((p==0)||(c < trie_c[p]))
18239 @<Insert a new trie node between |q| and |p|, and make |p| point to it@>;
18240 q=p; /*now node |q| represents $p_1\ldots p_{l-1}$*/
18241 }
18242 if (trie_o[q]!=min_quarterword)
18243 {@+print_err("Duplicate pattern");
18244 @.Duplicate pattern@>
18245 help1("(See Appendix H.)");error();
18246 }
18247 trie_o[q]=v;
18248 }
18249
18250 @ @<Insert a new trie node between |q| and |p|...@>=
18251 {@+if (trie_ptr==trie_size) overflow("pattern memory", trie_size);
18252 @:TeX capacity exceeded pattern memory}{\quad pattern memory@>
18253 incr(trie_ptr);trie_r[trie_ptr]=p;p=trie_ptr;trie_l[p]=0;
18254 if (first_child) trie_l[q]=p;@+else trie_r[q]=p;
18255 trie_c[p]=c;trie_o[p]=min_quarterword;
18256 }
18257
18258 @ @<Compute the trie op code, |v|...@>=
18259 if (hc[1]==0) hyf[0]=0;
18260 if (hc[k]==0) hyf[k]=0;
18261 l=k;v=min_quarterword;
18262 loop@+{@+if (hyf[l]!=0) v=new_trie_op(k-l, hyf[l], v);
18263 if (l > 0) decr(l);@+else goto done1;
18264 }
18265 done1:
18266
18267 @ Finally we put everything together: Here is how the trie gets to its
18268 final, efficient form.
18269 The following packing routine is rigged so that the root of the linked
18270 tree gets mapped into location 1 of |trie|, as required by the hyphenation
18271 algorithm. This happens because the first call of |first_fit| will
18272 ``take'' location~1.
18273
18274 @<Declare procedures for preprocessing hyphenation patterns@>=
18275 static void init_trie(void)
18276 {@+int @!p; /*pointer for initialization*/
18277 int @!j, @!k, @!t; /*all-purpose registers for initialization*/
18278 int @!r, @!s; /*used to clean up the packed |trie|*/
18279 two_halves @!h; /*template used to zero out |trie|'s holes*/
18280
18281 incr(max_hyph_char);
18282 @<Get ready to compress the trie@>;
18283 if (trie_root!=0)
18284 {@+first_fit(trie_root);trie_pack(trie_root);
18285 }
18286 if (hyph_root!=0) @<Pack all stored |hyph_codes|@>;
18287 @<Move the data into |trie|@>;
18288 trie_not_ready=false;
18289 }
18290
18291 @* Breaking vertical lists into pages.
18292 The |vsplit| procedure, which implements \TeX's \.{\\vsplit} operation,
18293 is considerably simpler than |line_break| because it doesn't have to
18294 worry about hyphenation, and because its mission is to discover a single
18295 break instead of an optimum sequence of breakpoints. But before we get
18296 into the details of |vsplit|, we need to consider a few more basic things.
18297
18298 @ A subroutine called |prune_page_top| takes a pointer to a vlist and
18299 returns a pointer to a modified vlist in which all glue, kern, and penalty nodes
18300 have been deleted before the first box or rule node. However, the first
18301 box or rule is actually preceded by a newly created glue node designed so that
18302 the topmost baseline will be at distance |split_top_skip| from the top,
18303 whenever this is possible without backspacing.
18304
18305 When the second argument |s| is |false| the deleted nodes are destroyed,
18306 otherwise they are collected in a list starting at |split_disc|.
18307
18308 In this routine and those that follow, we make use of the fact that a
18309 vertical list contains no character nodes, hence the |type| field exists
18310 for each node in the list.
18311 @^data structure assumptions@>
18312
18313 @p static pointer prune_page_top(pointer @!p, bool @!s)
18314 /*adjust top after page break*/
18315 {@+pointer prev_p; /*lags one step behind |p|*/
18316 pointer @!q, @!r; /*temporary variables for list manipulation*/
18317 prev_p=temp_head;link(temp_head)=p;
18318 while (p!=null)
18319 switch (type(p)) {
18320 case hlist_node: case vlist_node: case rule_node: @<Insert glue for |split_top_skip|
18321 and set~|p:=null|@>@;@+break;
18322 case whatsit_node: case mark_node: case ins_node: {@+prev_p=p;p=link(prev_p);
18323 } @+break;
18324 case glue_node: case kern_node: case penalty_node: {@+q=p;p=link(q);link(q)=null;
18325 link(prev_p)=p;
18326 if (s)
18327 {@+if (split_disc==null) split_disc=q;@+else link(r)=q;
18328 r=q;
18329 }
18330 else flush_node_list(q);
18331 } @+break;
18332 default:confusion("pruning");
18333 @:this can't happen pruning}{\quad pruning@>
18334 }
18335 return link(temp_head);
18336 }
18337
18338 @ @<Insert glue for |split_top_skip|...@>=
18339 {@+q=new_skip_param(split_top_skip_code);link(prev_p)=q;link(q)=p;
18340 /*now |temp_ptr==glue_ptr(q)|*/
18341 if (width(temp_ptr) > height(p)) width(temp_ptr)=width(temp_ptr)-height(p);
18342 else width(temp_ptr)=0;
18343 p=null;
18344 }
18345
18346 @ The next subroutine finds the best place to break a given vertical list
18347 so as to obtain a box of height~|h|, with maximum depth~|d|.
18348 A pointer to the beginning of the vertical list is given,
18349 and a pointer to the optimum breakpoint is returned. The list is effectively
18350 followed by a forced break, i.e., a penalty node with the |eject_penalty|;
18351 if the best break occurs at this artificial node, the value |null| is returned.
18352
18353 An array of six |scaled| distances is used to keep track of the height
18354 from the beginning of the list to the current place, just as in |line_break|.
18355 In fact, we use one of the same arrays, only changing its name to reflect
18356 its new significance.
18357
18358 @d active_height active_width /*new name for the six distance variables*/
18359 @d cur_height active_height[1] /*the natural height*/
18360 @d set_height_zero(A) active_height[A]=0 /*initialize the height to zero*/
18361 @#
18362 @p static pointer vert_break(pointer @!p, scaled @!h, scaled @!d)
18363 /*finds optimum page break*/
18364 {@+
18365 pointer prev_p; /*if |p| is a glue node, |type(prev_p)| determines
18366 whether |p| is a legal breakpoint*/
18367 pointer @!q, @!r; /*glue specifications*/
18368 int @!pi; /*penalty value*/
18369 int @!b; /*badness at a trial breakpoint*/
18370 int @!least_cost; /*the smallest badness plus penalties found so far*/
18371 pointer @!best_place; /*the most recent break that leads to |least_cost|*/
18372 scaled @!prev_dp; /*depth of previous box in the list*/
18373 small_number @!t; /*|type| of the node following a kern*/
18374 prev_p=p; /*an initial glue node is not a legal breakpoint*/
18375 least_cost=awful_bad;do_all_six(set_height_zero);prev_dp=0;
18376 loop@+{@+@<If node |p| is a legal breakpoint, check if this break is the best
18377 known, and |goto done| if |p| is null or if the page-so-far is already too
18378 full to accept more stuff@>;
18379 prev_p=p;p=link(prev_p);
18380 }
18381 done: return best_place;
18382 }
18383
18384 @ A global variable |best_height_plus_depth| will be set to the natural size
18385 of the box that corresponds to the optimum breakpoint found by |vert_break|.
18386 (This value is used by the insertion-splitting algorithm of the page builder.)
18387
18388 @<Glob...@>=
18389 static scaled @!best_height_plus_depth; /*height of the best box, without stretching or
18390 shrinking*/
18391
18392 @ A subtle point to be noted here is that the maximum depth~|d| might be
18393 negative, so |cur_height| and |prev_dp| might need to be corrected even
18394 after a glue or kern node.
18395
18396 @<If node |p| is a legal breakpoint, check...@>=
18397 if (p==null) pi=eject_penalty;
18398 else@<Use node |p| to update the current height and depth measurements; if
18399 this node is not a legal breakpoint, |goto not_found| or |update_heights|,
18400 otherwise set |pi| to the associated penalty at the break@>;
18401 @<Check if node |p| is a new champion breakpoint; then \(go)|goto done| if
18402 |p| is a forced break or if the page-so-far is already too full@>;
18403 if ((type(p) < glue_node)||(type(p) > kern_node)) goto not_found;
18404 update_heights: @<Update the current height and depth measurements with respect
18405 to a glue or kern node~|p|@>;
18406 not_found: if (prev_dp > d)
18407 {@+cur_height=cur_height+prev_dp-d;
18408 prev_dp=d;
18409 }
18410
18411 @ @<Use node |p| to update the current height and depth measurements...@>=
18412 switch (type(p)) {
18413 case hlist_node: case vlist_node: case rule_node: {@+@t@>@;@/
18414 cur_height=cur_height+prev_dp+height(p);prev_dp=depth(p);
18415 goto not_found;
18416 }
18417 case whatsit_node: @<Process whatsit |p| in |vert_break| loop, |goto not_found|@>;
18418 case glue_node: if (precedes_break(prev_p)) pi=0;
18419 else goto update_heights;@+break;
18420 case kern_node: {@+if (link(p)==null) t=penalty_node;
18421 else t=type(link(p));
18422 if (t==glue_node) pi=0;@+else goto update_heights;
18423 } @+break;
18424 case penalty_node: pi=penalty(p);@+break;
18425 case mark_node: case ins_node: goto not_found;
18426 default:confusion("vertbreak");
18427 @:this can't happen vertbreak}{\quad vertbreak@>
18428 }
18429
18430 @ @d deplorable 100000 /*more than |inf_bad|, but less than |awful_bad|*/
18431
18432 @<Check if node |p| is a new champion breakpoint; then \(go)...@>=
18433 if (pi < inf_penalty)
18434 {@+@<Compute the badness, |b|, using |awful_bad| if the box is too full@>;
18435 if (b < awful_bad)
18436 if (pi <= eject_penalty) b=pi;
18437 else if (b < inf_bad) b=b+pi;
18438 else b=deplorable;
18439 if (b <= least_cost)
18440 {@+best_place=p;least_cost=b;
18441 best_height_plus_depth=cur_height+prev_dp;
18442 }
18443 if ((b==awful_bad)||(pi <= eject_penalty)) goto done;
18444 }
18445
18446 @ @<Compute the badness, |b|, using |awful_bad| if the box is too full@>=
18447 if (cur_height < h)
18448 if ((active_height[3]!=0)||(active_height[4]!=0)||
18449 (active_height[5]!=0)) b=0;
18450 else b=badness(h-cur_height, active_height[2]);
18451 else if (cur_height-h > active_height[6]) b=awful_bad;
18452 else b=badness(cur_height-h, active_height[6])
18453
18454 @ Vertical lists that are subject to the |vert_break| procedure should not
18455 contain infinite shrinkability, since that would permit any amount of
18456 information to ``fit'' on one page.
18457
18458 @<Update the current height and depth measurements with...@>=
18459 if (type(p)==kern_node) q=p;
18460 else{@+q=glue_ptr(p);
18461 active_height[2+stretch_order(q)]=@|
18462 active_height[2+stretch_order(q)]+stretch(q);@/
18463 active_height[6]=active_height[6]+shrink(q);
18464 if ((shrink_order(q)!=normal)&&(shrink(q)!=0))
18465 {@+@t@>@;@/
18466 if (ignore_primitive_error & ignore_infinite_glue_shrinkage_bit)
18467 print_ignored_err("Infinite glue shrinkage found in box being split");@/
18468 else{@+
18469 print_err("Infinite glue shrinkage found in box being split");@/
18470 @.Infinite glue shrinkage...@>
18471 help4("The box you are \\vsplitting contains some infinitely",@/
18472 "shrinkable glue, e.g., `\\vss' or `\\vskip 0pt minus 1fil'.",@/
18473 "Such glue doesn't belong there; but you can safely proceed,",@/
18474 "since the offensive shrinkability has been made finite.");
18475 error();
18476 }
18477 r=new_spec(q);shrink_order(r)=normal;delete_glue_ref(q);
18478 glue_ptr(p)=r;q=r;
18479 }
18480 }
18481 cur_height=cur_height+prev_dp+width(q);prev_dp=0
18482
18483 @ Now we are ready to consider |vsplit| itself. Most of
18484 its work is accomplished by the two subroutines that we have just considered.
18485
18486 Given the number of a vlist box |n|, and given a desired page height |h|,
18487 the |vsplit| function finds the best initial segment of the vlist and
18488 returns a box for a page of height~|h|. The remainder of the vlist, if
18489 any, replaces the original box, after removing glue and penalties and
18490 adjusting for |split_top_skip|. Mark nodes in the split-off box are used to
18491 set the values of |split_first_mark| and |split_bot_mark|; we use the
18492 fact that |split_first_mark==null| if and only if |split_bot_mark==null|.
18493
18494 The original box becomes ``void'' if and only if it has been entirely
18495 extracted. The extracted box is ``void'' if and only if the original
18496 box was void (or if it was, erroneously, an hlist box).
18497
18498 @p @t\4@>@<Declare the function called |do_marks|@>@;
18499 static pointer vsplit(halfword @!n, scaled @!h)
18500 /*extracts a page of height |h| from box |n|*/
18501 {@+
18502 pointer v; /*the box to be split*/
18503 pointer p; /*runs through the vlist*/
18504 pointer q; /*points to where the break occurs*/
18505 cur_val=n;fetch_box(v);
18506 flush_node_list(split_disc);split_disc=null;
18507 if (sa_mark!=null)
18508 if (do_marks(vsplit_init, 0, sa_mark)) sa_mark=null;
18509 if (split_first_mark!=null)
18510 {@+delete_token_ref(split_first_mark);split_first_mark=null;
18511 delete_token_ref(split_bot_mark);split_bot_mark=null;
18512 }
18513 @<Dispense with trivial cases of void or bad boxes@>;
18514 q=vert_break(list_ptr(v), h, split_max_depth);
18515 @<Look at all the marks in nodes before the break, and set the final link
18516 to |null| at the break@>;
18517 q=prune_page_top(q, saving_vdiscards > 0);
18518 p=list_ptr(v);list_ptr(v)=null;flush_node_list(v);
18519 p=vpackage(p, h, 0, 0, exactly, false, split_max_depth);
18520 if (q!=null)
18521 { if (color_tos!=null)
18522 { pointer r = new_color_node(color_ref(color_tos));
18523 color_tos=color_link(color_tos);
18524 link(r)=q; q=r;
18525 }
18526 q=vpack(q, natural);
18527 }
18528 change_box(q); /*the |eq_level| of the box stays the same*/
18529 return p;
18530 }
18531
18532 @ @<Dispense with trivial cases of void or bad boxes@>=
18533 if (v==null)
18534 {@+return null;
18535 }
18536 if (type(v)!=vlist_node)
18537 {@+print_err("");print_esc("vsplit");print(" needs a ");
18538 print_esc("vbox");
18539 @:vsplit\_}{\.{\\vsplit needs a \\vbox}@>
18540 help2("The box you are trying to split is an \\hbox.",@/
18541 "I can't split such a box, so I'll leave it alone.");
18542 error();return null;
18543 }
18544
18545 @ It's possible that the box begins with a penalty node that is the
18546 ``best'' break, so we must be careful to handle this special case correctly.
18547
18548 @<Look at all the marks...@>=
18549 p=list_ptr(v);
18550 if (p==q) list_ptr(v)=null;
18551 else loop@+{@+if (type(p)==mark_node)
18552 if (mark_class(p)!=0) @<Update the current marks for |vsplit|@>@;
18553 else if (split_first_mark==null)
18554 {@+split_first_mark=mark_ptr(p);
18555 split_bot_mark=split_first_mark;
18556 token_ref_count(split_first_mark)=@|
18557 token_ref_count(split_first_mark)+2;
18558 }
18559 else{@+delete_token_ref(split_bot_mark);
18560 split_bot_mark=mark_ptr(p);
18561 add_token_ref(split_bot_mark);
18562 }
18563 if (link(p)==q)
18564 {@+link(p)=null;goto done;
18565 }
18566 p=link(p);
18567 }
18568 done:
18569
18570 @* The page builder.
18571 When \TeX\ appends new material to its main vlist in vertical mode, it uses
18572 a method something like |vsplit| to decide where a page ends, except that
18573 the calculations are done ``on line'' as new items come in.
18574 The main complication in this process is that insertions must be put
18575 into their boxes and removed from the vlist, in a more-or-less optimum manner.
18576
18577 We shall use the term ``current page'' for that part of the main vlist that
18578 is being considered as a candidate for being broken off and sent to the
18579 user's output routine. The current page starts at |link(page_head)|, and
18580 it ends at |page_tail|. We have |page_head==page_tail| if this list is empty.
18581 @^current page@>
18582
18583 Utter chaos would reign if the user kept changing page specifications
18584 while a page is being constructed, so the page builder keeps the pertinent
18585 specifications frozen as soon as the page receives its first box or
18586 insertion. The global variable |page_contents| is |empty| when the
18587 current page contains only mark nodes and content-less whatsit nodes; it
18588 is |inserts_only| if the page contains only insertion nodes in addition to
18589 marks and whatsits. Glue nodes, kern nodes, and penalty nodes are
18590 discarded until a box or rule node appears, at which time |page_contents|
18591 changes to |box_there|. As soon as |page_contents| becomes non-|empty|,
18592 the current |vsize| and |max_depth| are squirreled away into |page_goal|
18593 and |page_max_depth|; the latter values will be used until the page has
18594 been forwarded to the user's output routine. The \.{\\topskip} adjustment
18595 is made when |page_contents| changes to |box_there|.
18596
18597 Although |page_goal| starts out equal to |vsize|, it is decreased by the
18598 scaled natural height-plus-depth of the insertions considered so far, and by
18599 the \.{\\skip} corrections for those insertions. Therefore it represents
18600 the size into which the non-inserted material should fit, assuming that
18601 all insertions in the current page have been made.
18602
18603 The global variables |best_page_break| and |least_page_cost| correspond
18604 respectively to the local variables |best_place| and |least_cost| in the
18605 |vert_break| routine that we have already studied; i.e., they record the
18606 location and value of the best place currently known for breaking the
18607 current page. The value of |page_goal| at the time of the best break is
18608 stored in |best_size|.
18609
18610 @d inserts_only 1
18611 /*|page_contents| when an insert node has been contributed, but no boxes*/
18612 @d box_there 2 /*|page_contents| when a box or rule has been contributed*/
18613
18614 @<Glob...@>=
18615 static pointer @!page_tail; /*the final node on the current page*/
18616 static int @!page_contents; /*what is on the current page so far?*/
18617 static scaled @!page_max_depth; /*maximum box depth on page being built*/
18618 static int @!least_page_cost; /*the score for this currently best page*/
18619
18620 @ The page builder has another data structure to keep track of insertions.
18621 This is a list of four-word nodes, starting and ending at |page_ins_head|.
18622 That is, the first element of the list is node |r@t$\_1$@>==link(page_ins_head)|;
18623 node $r_j$ is followed by |r@t$\_{j+1}$@>==link(r@t$\_j$@>)|; and if there are
18624 |n| items we have |r@t$\_{n+1}$@>==page_ins_head|. The |subtype| field of
18625 each node in this list refers to an insertion number; for example, `\.{\\insert
18626 250}' would correspond to a node whose |subtype| is |qi(250)|
18627 (the same as the |subtype| field of the relevant |ins_node|). These |subtype|
18628 fields are in increasing order, and |subtype(page_ins_head)==
18629 qi(255)|, so |page_ins_head| serves as a convenient sentinel
18630 at the end of the list. A record is present for each insertion number that
18631 appears in the current page.
18632
18633 The |type| field in these nodes distinguishes two possibilities that
18634 might occur as we look ahead before deciding on the optimum page break.
18635 If |type(r)==inserting|, then |height(r)| contains the total of the
18636 height-plus-depth dimensions of the box and all its inserts seen so far.
18637 If |type(r)==split_up|, then no more insertions will be made into this box,
18638 because at least one previous insertion was too big to fit on the current
18639 page; |broken_ptr(r)| points to the node where that insertion will be
18640 split, if \TeX\ decides to split it, |broken_ins(r)| points to the
18641 insertion node that was tentatively split, and |height(r)| includes also the
18642 natural height plus depth of the part that would be split off.
18643
18644 In both cases, |last_ins_ptr(r)| points to the last |ins_node|
18645 encountered for box |qo(subtype(r))| that would be at least partially
18646 inserted on the next page; and |best_ins_ptr(r)| points to the last
18647 such |ins_node| that should actually be inserted, to get the page with
18648 minimum badness among all page breaks considered so far. We have
18649 |best_ins_ptr(r)==null| if and only if no insertion for this box should
18650 be made to produce this optimum page.
18651
18652 The data structure definitions here use the fact that the |@!height| field
18653 appears in the fourth word of a box node.
18654 @^data structure assumptions@>
18655
18656 @d page_ins_node_size 4 /*number of words for a page insertion node*/
18657 @d inserting 0 /*an insertion class that has not yet overflowed*/
18658 @d split_up 1 /*an overflowed insertion class*/
18659 @d broken_ptr(A) link(A+1)
18660 /*an insertion for this class will break here if anywhere*/
18661 @d broken_ins(A) info(A+1) /*this insertion might break at |broken_ptr|*/
18662 @d last_ins_ptr(A) link(A+2) /*the most recent insertion for this |subtype|*/
18663 @d best_ins_ptr(A) info(A+2) /*the optimum most recent insertion*/
18664
18665 @<Initialize the special list heads...@>=
18666 subtype(page_ins_head)=qi(255);
18667 type(page_ins_head)=split_up;link(page_ins_head)=page_ins_head;
18668
18669 @ An array |page_so_far| records the heights and depths of everything
18670 on the current page. This array contains six |scaled| numbers, like the
18671 similar arrays already considered in |line_break| and |vert_break|; and it
18672 also contains |page_goal| and |page_depth|, since these values are
18673 all accessible to the user via |set_page_dimen| commands. The
18674 value of |page_so_far[1]| is also called |page_total|. The stretch
18675 and shrink components of the \.{\\skip} corrections for each insertion are
18676 included in |page_so_far|, but the natural space components of these
18677 corrections are not, since they have been subtracted from |page_goal|.
18678
18679 The variable |page_depth| records the depth of the current page; it has been
18680 adjusted so that it is at most |page_max_depth|. The variable
18681 |last_glue| points to the glue specification of the most recent node
18682 contributed from the contribution list, if this was a glue node; otherwise
18683 |last_glue==max_halfword|. (If the contribution list is nonempty,
18684 however, the value of |last_glue| is not necessarily accurate.)
18685 The variables |last_penalty|, |last_kern|, and |last_node_type|
18686 are similar. And
18687 finally, |insert_penalties| holds the sum of the penalties associated with
18688 all split and floating insertions.
18689
18690 @d page_goal page_so_far[0] /*desired height of information on page being built*/
18691 @d page_total page_so_far[1] /*height of the current page*/
18692 @d page_shrink page_so_far[6] /*shrinkability of the current page*/
18693 @d page_depth page_so_far[7] /*depth of the current page*/
18694
18695 @<Glob...@>=
18696 static scaled @!page_so_far[8]; /*height and glue of the current page*/
18697 static pointer @!last_glue; /*used to implement \.{\\lastskip}*/
18698 static int @!last_penalty; /*used to implement \.{\\lastpenalty}*/
18699 static scaled @!last_kern; /*used to implement \.{\\lastkern}*/
18700 static int @!last_node_type; /*used to implement \.{\\lastnodetype}*/
18701 static int @!insert_penalties; /*sum of the penalties for insertions
18702 that were held over*/
18703
18704 @ @<Put each...@>=
18705 primitive("pagegoal", set_page_dimen, 0);
18706 @!@:page\_goal\_}{\.{\\pagegoal} primitive@>
18707 primitive("pagetotal", set_page_dimen, 1);
18708 @!@:page\_total\_}{\.{\\pagetotal} primitive@>
18709 primitive("pagestretch", set_page_dimen, 2);
18710 @!@:page\_stretch\_}{\.{\\pagestretch} primitive@>
18711 primitive("pagefilstretch", set_page_dimen, 3);
18712 @!@:page\_fil\_stretch\_}{\.{\\pagefilstretch} primitive@>
18713 primitive("pagefillstretch", set_page_dimen, 4);
18714 @!@:page\_fill\_stretch\_}{\.{\\pagefillstretch} primitive@>
18715 primitive("pagefilllstretch", set_page_dimen, 5);
18716 @!@:page\_filll\_stretch\_}{\.{\\pagefilllstretch} primitive@>
18717 primitive("pageshrink", set_page_dimen, 6);
18718 @!@:page\_shrink\_}{\.{\\pageshrink} primitive@>
18719 primitive("pagedepth", set_page_dimen, 7);
18720 @!@:page\_depth\_}{\.{\\pagedepth} primitive@>
18721
18722 @ @<Cases of |print_cmd_chr|...@>=
18723 case set_page_dimen: switch (chr_code) {
18724 case 0: print_esc("pagegoal");@+break;
18725 case 1: print_esc("pagetotal");@+break;
18726 case 2: print_esc("pagestretch");@+break;
18727 case 3: print_esc("pagefilstretch");@+break;
18728 case 4: print_esc("pagefillstretch");@+break;
18729 case 5: print_esc("pagefilllstretch");@+break;
18730 case 6: print_esc("pageshrink");@+break;
18731 default:print_esc("pagedepth");
18732 } @+break;
18733
18734 @ @d print_plus(A, B) if (page_so_far[A]!=0)
18735 {@+print(" plus ");print_scaled(page_so_far[A]);print(B);@+}
18736
18737 @p static void print_totals(void)
18738 {@+print_scaled(page_total);
18739 print_plus(2,"");
18740 print_plus(3,"fil");
18741 print_plus(4,"fill");
18742 print_plus(5,"filll");
18743 if (page_shrink!=0)
18744 {@+print(" minus ");print_scaled(page_shrink);
18745 }
18746 }
18747
18748 @ @<Show the status of the current page@>=
18749 if (page_head!=page_tail)
18750 {@+print_nl("### current page:");
18751 if (output_active) print(" (held over for next output)");
18752 @.held over for next output@>
18753 show_box(link(page_head));
18754 if (page_contents > empty)
18755 {@+print_nl("total height ");print_totals();
18756 @:total\_height}{\.{total height}@>
18757 print_nl(" goal height ");print_scaled(page_goal);
18758 @.goal height@>
18759 r=link(page_ins_head);
18760 while (r!=page_ins_head)
18761 {@+print_ln();print_esc("insert");t=qo(subtype(r));
18762 print_int(t);print(" adds ");
18763 if (count(t)==1000) t=height(r);
18764 else t=x_over_n(height(r), 1000)*count(t);
18765 print_scaled(t);
18766 if (type(r)==split_up)
18767 {@+q=page_head;t=0;
18768 @/do@+{q=link(q);
18769 if ((type(q)==ins_node)&&(subtype(q)==subtype(r))) incr(t);
18770 }@+ while (!(q==broken_ins(r)));
18771 print(", #");print_int(t);print(" might split");
18772 }
18773 r=link(r);
18774 }
18775 }
18776 }
18777
18778 @ Here is a procedure that is called when the |page_contents| is changing
18779 from |empty| to |inserts_only| or |box_there|.
18780
18781 @d set_page_so_far_zero(A) page_so_far[A]=0
18782
18783 @p static void freeze_page_specs(small_number @!s)
18784 {@+page_contents=s;
18785 page_goal=vsize;page_max_depth=max_depth;
18786 page_depth=0;do_all_six(set_page_so_far_zero);
18787 least_page_cost=awful_bad;
18788 #ifdef @!STAT
18789 if (tracing_pages > 0)
18790 {@+begin_diagnostic();
18791 print_nl("%% goal height=");print_scaled(page_goal);
18792 @.goal height@>
18793 print(", max depth=");print_scaled(page_max_depth);
18794 end_diagnostic(false);
18795 } @;
18796 #endif
18797 @;@/
18798 }
18799
18800 @ Pages are built by appending nodes to the current list in \TeX's
18801 vertical mode, which is at the outermost level of the semantic nest. This
18802 vlist is split into two parts; the ``current page'' that we have been
18803 talking so much about already, and the ``contribution list'' that receives
18804 new nodes as they are created. The current page contains everything that
18805 the page builder has accounted for in its data structures, as described
18806 above, while the contribution list contains other things that have been
18807 generated by other parts of \TeX\ but have not yet been
18808 seen by the page builder.
18809 The contribution list starts at |link(contrib_head)|, and it ends at the
18810 current node in \TeX's vertical mode.
18811
18812 When \TeX\ has appended new material in vertical mode, it calls the procedure
18813 |build_page|, which tries to catch up by moving nodes from the contribution
18814 list to the current page. This procedure will succeed in its goal of
18815 emptying the contribution list, unless a page break is discovered, i.e.,
18816 unless the current page has grown to the point where the optimum next
18817 page break has been determined. In the latter case, the nodes after the
18818 optimum break will go back onto the contribution list, and control will
18819 effectively pass to the user's output routine.
18820
18821 We make |type(page_head)==glue_node|, so that an initial glue node on
18822 the current page will not be considered a valid breakpoint.
18823
18824 @<Initialize the special list...@>=
18825 type(page_head)=glue_node;subtype(page_head)=normal;
18826
18827 @ The global variable |output_active| is true during the time the
18828 user's output routine is driving \TeX.
18829
18830 @<Glob...@>=
18831 static bool @!output_active; /*are we in the midst of an output routine?*/
18832
18833 @ @<Set init...@>=
18834 output_active=false;insert_penalties=0;
18835
18836 @ The page builder is ready to start a fresh page if we initialize
18837 the following state variables. (However, the page insertion list is initialized
18838 elsewhere.)
18839
18840 @<Start a new current page@>=
18841 page_contents=empty;page_tail=page_head;link(page_head)=null;@/
18842 last_glue=max_halfword;last_penalty=0;last_kern=0;
18843 last_node_type=-1;
18844 page_depth=0;page_max_depth=0
18845
18846 @ At certain times box 255 is supposed to be void (i.e., |null|),
18847 or an insertion box is supposed to be ready to accept a vertical list.
18848 If not, an error message is printed, and the following subroutine
18849 flushes the unwanted contents, reporting them to the user.
18850
18851 @p static void box_error(eight_bits @!n)
18852 {@+error();begin_diagnostic();
18853 print_nl("The following box has been deleted:");
18854 @.The following...deleted@>
18855 show_box(box(n));end_diagnostic(true);
18856 flush_node_list(box(n));box(n)=null;
18857 }
18858
18859 @ \TeX\ is not always in vertical mode at the time |build_page|
18860 is called; the current mode reflects what \TeX\ should return to, after
18861 the contribution list has been emptied. A call on |build_page| should
18862 be immediately followed by `|goto big_switch|', which is \TeX's central
18863 control point.
18864
18865 @p
18866 static void update_last_values(pointer p)
18867 {@<Update the values of |last_glue|, |last_penalty|, and |last_kern|@>;
18868 }
18869
18870 @ @d contrib_tail nest[0].tail_field /*tail of the contribution list*/
18871
18872 @<Make the contribution list empty...@>=
18873 if (nest_ptr==0) tail=contrib_head; /*vertical mode*/
18874 else contrib_tail=contrib_head /*other modes*/
18875
18876 @ @<Update the values of |last_glue|...@>=
18877 if (last_glue!=max_halfword) delete_glue_ref(last_glue);
18878 last_penalty=0;last_kern=0;
18879 last_node_type=type(p)+1;
18880 if (type(p)==glue_node)
18881 {@+last_glue=glue_ptr(p);add_glue_ref(last_glue);
18882 }
18883 else{@+last_glue=max_halfword;
18884 if (type(p)==penalty_node) last_penalty=penalty(p);
18885 else if (type(p)==kern_node) last_kern=width(p);
18886 }
18887
18888
18889 @ When the user's output routine finishes, it has constructed a vlist
18890 in internal vertical mode, and \TeX\ will do the following:
18891
18892 @<Resume the page builder after an output routine has come to an end@>=
18893 {@+if ((loc!=null)||
18894 ((token_type!=output_text)&&(token_type!=backed_up)))
18895 @<Recover from an unbalanced output routine@>;
18896 end_token_list(); /*conserve stack space in case more outputs are triggered*/
18897 end_graf();unsave();output_active=false;insert_penalties=0;@/
18898 @<Ensure that box 255 is empty after output@>;
18899 if (tail!=head) /*current list goes after heldover insertions*/
18900 {@+link(page_tail)=link(head);
18901 page_tail=tail;
18902 }
18903 if (link(page_head)!=null) /*and both go before heldover contributions*/
18904 {@+if (link(contrib_head)==null) contrib_tail=page_tail;
18905 link(page_tail)=link(contrib_head);
18906 link(contrib_head)=link(page_head);
18907 link(page_head)=null;page_tail=page_head;
18908 }
18909 flush_node_list(page_disc);page_disc=null;
18910 pop_nest();build_page();
18911 }
18912
18913 @ @<Recover from an unbalanced output routine@>=
18914 {@+print_err("Unbalanced output routine");
18915 @.Unbalanced output routine@>
18916 help2("Your sneaky output routine has problematic {'s and/or }'s.",@/
18917 "I can't handle that very well; good luck.");error();
18918 @/do@+{get_token();
18919 }@+ while (!(loc==null));
18920 } /*loops forever if reading from a file, since |null==min_halfword <= 0|*/
18921
18922 @ @<Ensure that box 255 is empty after output@>=
18923 if (box(255)!=null)
18924 {@+print_err("Output routine didn't use all of ");
18925 print_esc("box");print_int(255);
18926 @.Output routine didn't use...@>
18927 help3("Your \\output commands should empty \\box255,",@/
18928 "e.g., by saying `\\shipout\\box255'.",@/
18929 "Proceed; I'll discard its present contents.");
18930 box_error(255);
18931 }
18932
18933 @* The chief executive.
18934 We come now to the |main_control| routine, which contains the master
18935 switch that causes all the various pieces of \TeX\ to do their things,
18936 in the right order.
18937
18938 In a sense, this is the grand climax of the program: It applies all the
18939 tools that we have worked so hard to construct. In another sense, this is
18940 the messiest part of the program: It necessarily refers to other pieces
18941 of code all over the place, so that a person can't fully understand what is
18942 going on without paging back and forth to be reminded of conventions that
18943 are defined elsewhere. We are now at the hub of the web, the central nervous
18944 system that touches most of the other parts and ties them together.
18945 @^brain@>
18946
18947 The structure of |main_control| itself is quite simple. There's a label
18948 called |big_switch|, at which point the next token of input is fetched
18949 using |get_x_token|. Then the program branches at high speed into one of
18950 about 100 possible directions, based on the value of the current
18951 mode and the newly fetched command code; the sum |abs(mode)+cur_cmd|
18952 indicates what to do next. For example, the case `|vmode+letter|' arises
18953 when a letter occurs in vertical mode (or internal vertical mode); this
18954 case leads to instructions that initialize a new paragraph and enter
18955 horizontal mode.
18956
18957 The big |case| statement that contains this multiway switch has been labeled
18958 |reswitch|, so that the program can |goto reswitch| when the next token
18959 has already been fetched. Most of the cases are quite short; they call
18960 an ``action procedure'' that does the work for that case, and then they
18961 either |goto reswitch| or they ``fall through'' to the end of the |case|
18962 statement, which returns control back to |big_switch|. Thus, |main_control|
18963 is not an extremely large procedure, in spite of the multiplicity of things
18964 it must do; it is small enough to be handled by \PASCAL\ compilers that put
18965 severe restrictions on procedure size.
18966 @!@^action procedure@>
18967
18968 One case is singled out for special treatment, because it accounts for most
18969 of \TeX's activities in typical applications. The process of reading simple
18970 text and converting it into |char_node| records, while looking for ligatures
18971 and kerns, is part of \TeX's ``inner loop''; the whole program runs
18972 efficiently when its inner loop is fast, so this part has been written
18973 with particular care.
18974
18975 @ We shall concentrate first on the inner loop of |main_control|, deferring
18976 consideration of the other cases until later.
18977 @^inner loop@>
18978
18979 @p @t\4@>@<Declare action procedures for use by |main_control|@>@;
18980 @t\4@>@<Declare the procedure called |handle_right_brace|@>@;
18981 static void main_control(void) /*governs \TeX's activities*/
18982 {@+
18983
18984
18985
18986
18987 int @!t; /*general-purpose temporary variable*/
18988 if (every_job!=null) begin_token_list(every_job, every_job_text);
18989 big_switch: get_x_token();@/
18990 reswitch: @<Give diagnostic information, if requested@>;
18991 switch (abs(mode)+cur_cmd) {
18992 case hmode+letter: case hmode+other_char:
18993 case hmode+char_given: goto main_loop;
18994 case hmode+char_num: {@+scan_char_num();cur_chr=cur_val;goto main_loop;@+}
18995 case hmode+no_boundary: {@+get_x_token();
18996 if ((cur_cmd==letter)||(cur_cmd==other_char)||(cur_cmd==char_given)||
18997 (cur_cmd==char_num)) cancel_boundary=true;
18998 goto reswitch;
18999 }
19000 case hmode+spacer: if (space_factor==1000) goto append_normal_space;
19001 else app_space();@+break;
19002 case hmode+ex_space: case mmode+ex_space: goto append_normal_space;
19003 @t\4@>@<Cases of |main_control| that are not part of the inner loop@>@;
19004 } /*End of the big |case| statement*/
19005 goto big_switch;
19006 main_loop: @<Append character |cur_chr| and the following characters (if~any)
19007 to the current hlist in the current font; |goto reswitch| when a non-character
19008 has been fetched@>;
19009 append_normal_space: @<Append a normal inter-word space to the current list,
19010 then |goto big_switch|@>;
19011 }
19012
19013 @ When a new token has just been fetched at |big_switch|, we have an
19014 ideal place to monitor \TeX's activity.
19015 @^debugging@>
19016
19017 @<Give diagnostic information, if requested@>=
19018 if (interrupt!=0) if (OK_to_interrupt)
19019 {@+back_input();check_interrupt;goto big_switch;
19020 }
19021 #ifdef @!DEBUG
19022 if (panicking) check_mem(false);@;
19023 #endif
19024 if (tracing_commands > 0) show_cur_cmd_chr()
19025
19026 @ The following part of the program was first written in a structured
19027 manner, according to the philosophy that ``premature optimization is
19028 the root of all evil.'' Then it was rearranged into pieces of
19029 spaghetti so that the most common actions could proceed with little or
19030 no redundancy.
19031
19032 The original unoptimized form of this algorithm resembles the
19033 |reconstitute| procedure, which was described earlier in connection with
19034 hyphenation. Again we have an implied ``cursor'' between characters
19035 |cur_l| and |cur_r|. The main difference is that the |lig_stack| can now
19036 contain a charnode as well as pseudo-ligatures; that stack is now
19037 usually nonempty, because the next character of input (if any) has been
19038 appended to it. In |main_control| we have
19039 $$|cur_r|=\cases{|character(lig_stack)|,&if |lig_stack > null|;\cr
19040 |font_bchar[cur_font]|,&otherwise;\cr}$$
19041 except when |character(lig_stack)==font_false_bchar[cur_font]|.
19042 Several additional global variables are needed.
19043
19044 @<Glob...@>=
19045 static internal_font_number @!main_f; /*the current font*/
19046 static four_quarters @!main_i; /*character information bytes for |cur_l|*/
19047 static four_quarters @!main_j; /*ligature/kern command*/
19048 static font_index @!main_k; /*index into |font_info|*/
19049 static pointer @!main_p; /*temporary register for list manipulation*/
19050 static int @!main_s; /*space factor value*/
19051 static halfword @!bchar; /*boundary character of current font, or |non_char|*/
19052 static halfword @!false_bchar; /*nonexistent character matching |bchar|, or |non_char|*/
19053 static bool @!cancel_boundary; /*should the left boundary be ignored?*/
19054 static bool @!ins_disc; /*should we insert a discretionary node?*/
19055
19056 @ The boolean variables of the main loop are normally false, and always reset
19057 to false before the loop is left. That saves us the extra work of initializing
19058 each time.
19059
19060 @<Set init...@>=
19061 ligature_present=false;cancel_boundary=false;lft_hit=false;rt_hit=false;
19062 ins_disc=false;
19063
19064 @ We leave the |space_factor| unchanged if |sf_code(cur_chr)==0|; otherwise we
19065 set it equal to |sf_code(cur_chr)|, except that it should never change
19066 from a value less than 1000 to a value exceeding 1000. The most common
19067 case is |sf_code(cur_chr)==1000|, so we want that case to be fast.
19068
19069 The overall structure of the main loop is presented here. Some program labels
19070 are inside the individual sections.
19071 @^inner loop@>
19072
19073 @d adjust_space_factor @t@>@;@/
19074 main_s=sf_code(cur_chr);
19075 if (main_s==1000) space_factor=1000;
19076 else if (main_s < 1000)
19077 {@+if (main_s > 0) space_factor=main_s;
19078 }
19079 else if (space_factor < 1000) space_factor=1000;
19080 else space_factor=main_s
19081
19082 @<Append character |cur_chr|...@>=
19083 adjust_space_factor;@/
19084 main_f=cur_font;
19085 if (mode > 0) if (language!=clang) fix_language();
19086 if (IS_X_FONT(main_f))
19087 @<Append characters from an extended font; |goto reswitch| when done@>@;
19088 bchar=font_bchar[main_f];false_bchar=font_false_bchar[main_f];
19089 fast_get_avail(lig_stack);font(lig_stack)=main_f;cur_l=qi(cur_chr);
19090 character(lig_stack)=cur_l;@/
19091 cur_q=tail;
19092 if (cancel_boundary)
19093 {@+cancel_boundary=false;main_k=non_address;
19094 }
19095 else main_k=bchar_label[main_f];
19096 if (main_k==non_address) goto main_loop_move2; /*no left boundary processing*/
19097 cur_r=cur_l;cur_l=non_char;
19098 goto main_lig_loop1; /*begin with cursor after left boundary*/
19099 @#
19100 main_loop_wrapup: @<Make a ligature node, if |ligature_present|; insert a
19101 null discretionary, if appropriate@>;
19102 main_loop_move: @<If the cursor is immediately followed by the right boundary,
19103 |goto reswitch|; if it's followed by an invalid character, |goto big_switch|;
19104 otherwise move the cursor one step to the right and |goto main_lig_loop|@>;
19105 main_loop_lookahead: @<Look ahead for another character, or leave |lig_stack|
19106 empty if there's none there@>;
19107 main_lig_loop: @<If there's a ligature/kern command relevant to |cur_l| and
19108 |cur_r|, adjust the text appropriately; exit to |main_loop_wrapup|@>;
19109 main_loop_move_lig: @<Move the cursor past a pseudo-ligature, then |goto main_loop_lookahead|
19110 or |main_lig_loop|@>@;
19111
19112 @ If |link(cur_q)| is nonnull when |wrapup| is invoked, |cur_q| points to
19113 the list of characters that were consumed while building the ligature
19114 character~|cur_l|.
19115
19116 A discretionary break is not inserted for an explicit hyphen when we are in
19117 restricted horizontal mode. In particular, this avoids putting discretionary
19118 nodes inside of other discretionaries.
19119 @^inner loop@>
19120
19121 @d pack_lig(X) /*the parameter is either |rt_hit| or |false|*/
19122 {@+main_p=new_ligature(main_f, cur_l, link(cur_q));
19123 if (lft_hit)
19124 {@+subtype(main_p)=2;lft_hit=false;
19125 }
19126 if (X) if (lig_stack==null)
19127 {@+incr(subtype(main_p));rt_hit=false;
19128 }
19129 link(cur_q)=main_p;tail=main_p;ligature_present=false;
19130 }
19131
19132 @d wrapup(A) if (cur_l < non_char)
19133 {@+if (link(cur_q) > null)
19134 if (character(tail)==qi(hyphen_char[main_f])) ins_disc=true;
19135 if (ligature_present) pack_lig(A);
19136 if (ins_disc)
19137 {@+ins_disc=false;
19138 if (mode > 0) tail_append(new_disc());
19139 }
19140 }
19141
19142 @<Make a ligature node, if |ligature_present|;...@>=
19143 wrapup(rt_hit)
19144
19145 @ @<If the cursor is immediately followed by the right boundary...@>=
19146 @^inner loop@>
19147 if (lig_stack==null) goto reswitch;
19148 cur_q=tail;cur_l=character(lig_stack);
19149 main_loop_move1: if (!is_char_node(lig_stack)) goto main_loop_move_lig;
19150 main_loop_move2: if ((cur_chr < font_bc[main_f])||(cur_chr > font_ec[main_f]))
19151 {@+char_warning(main_f, cur_chr);free_avail(lig_stack);goto big_switch;
19152 }
19153 main_i=char_info(main_f, cur_l);
19154 if (!char_exists(main_f,cur_l))
19155 {@+char_warning(main_f, cur_chr);free_avail(lig_stack);goto big_switch;
19156 }
19157 link(tail)=lig_stack;tail=lig_stack /*|main_loop_lookahead| is next*/
19158
19159 @ Here we are at |main_loop_move_lig|.
19160 When we begin this code we have |cur_q==tail| and |cur_l==character(lig_stack)|.
19161
19162 @<Move the cursor past a pseudo-ligature...@>=
19163 main_p=lig_ptr(lig_stack);
19164 if (main_p > null) tail_append(main_p); /*append a single character*/
19165 temp_ptr=lig_stack;lig_stack=link(temp_ptr);
19166 free_node(temp_ptr, small_node_size);
19167 main_i=char_info(main_f, cur_l);ligature_present=true;
19168 if (lig_stack==null)
19169 if (main_p > null) goto main_loop_lookahead;
19170 else cur_r=bchar;
19171 else cur_r=character(lig_stack);
19172 goto main_lig_loop
19173
19174 @ The result of \.{\\char} can participate in a ligature or kern, so we must
19175 look ahead for it.
19176
19177 @<Look ahead for another character...@>=
19178 get_next(); /*set only |cur_cmd| and |cur_chr|, for speed*/
19179 if (cur_cmd==letter) goto main_loop_lookahead1;
19180 if (cur_cmd==other_char) goto main_loop_lookahead1;
19181 if (cur_cmd==char_given) goto main_loop_lookahead1;
19182 x_token(); /*now expand and set |cur_cmd|, |cur_chr|, |cur_tok|*/
19183 if (cur_cmd==letter) goto main_loop_lookahead1;
19184 if (cur_cmd==other_char) goto main_loop_lookahead1;
19185 if (cur_cmd==char_given) goto main_loop_lookahead1;
19186 if (cur_cmd==char_num)
19187 {@+scan_char_num();cur_chr=cur_val;goto main_loop_lookahead1;
19188 }
19189 if (cur_cmd==no_boundary) bchar=non_char;
19190 cur_r=bchar;lig_stack=null;goto main_lig_loop;
19191 main_loop_lookahead1: adjust_space_factor;
19192 fast_get_avail(lig_stack);font(lig_stack)=main_f;
19193 cur_r=qi(cur_chr);character(lig_stack)=cur_r;
19194 if (cur_r==false_bchar) cur_r=non_char /*this prevents spurious ligatures*/
19195
19196 @ Even though comparatively few characters have a lig/kern program, several
19197 of the instructions here count as part of \TeX's inner loop, since a
19198 @^inner loop@>
19199 potentially long sequential search must be performed. For example, tests with
19200 Computer Modern Roman showed that about 40 per cent of all characters
19201 actually encountered in practice had a lig/kern program, and that about four
19202 lig/kern commands were investigated for every such character.
19203
19204 At the beginning of this code we have |main_i==char_info(main_f, cur_l)|.
19205
19206 @<If there's a ligature/kern command...@>=
19207 if (char_tag(main_f, main_i)!=lig_tag) goto main_loop_wrapup;
19208 if (cur_r==non_char) goto main_loop_wrapup;
19209 main_k=lig_kern_start(main_f, main_i);main_j=font_info[main_k].qqqq;
19210 if (skip_byte(main_j) <= stop_flag) goto main_lig_loop2;
19211 main_k=lig_kern_restart(main_f, main_j);
19212 main_lig_loop1: main_j=font_info[main_k].qqqq;
19213 main_lig_loop2: if (next_char(main_j)==cur_r)
19214 if (skip_byte(main_j) <= stop_flag)
19215 @<Do ligature or kern command, returning to |main_lig_loop| or |main_loop_wrapup|
19216 or |main_loop_move|@>;
19217 if (skip_byte(main_j)==qi(0)) incr(main_k);
19218 else{@+if (skip_byte(main_j) >= stop_flag) goto main_loop_wrapup;
19219 main_k=main_k+qo(skip_byte(main_j))+1;
19220 }
19221 goto main_lig_loop1
19222
19223 @ When a ligature or kern instruction matches a character, we know from
19224 |read_font_info| that the character exists in the font, even though we
19225 haven't verified its existence in the normal way.
19226
19227 This section could be made into a subroutine, if the code inside
19228 |main_control| needs to be shortened.
19229
19230 \chardef\@@='174 % vertical line to indicate character retention
19231
19232 @<Do ligature or kern command...@>=
19233 {@+if (op_byte(main_j) >= kern_flag)
19234 {@+wrapup(rt_hit);
19235 tail_append(new_kern(char_kern(main_f, main_j)));goto main_loop_move;
19236 }
19237 if (cur_l==non_char) lft_hit=true;
19238 else if (lig_stack==null) rt_hit=true;
19239 check_interrupt; /*allow a way out in case there's an infinite ligature loop*/
19240 switch (op_byte(main_j)) {
19241 case qi(1): case qi(5): {@+cur_l=rem_byte(main_j); /*\.{=:\@@}, \.{=:\@@>}*/
19242 main_i=char_info(main_f, cur_l);ligature_present=true;
19243 } @+break;
19244 case qi(2): case qi(6): {@+cur_r=rem_byte(main_j); /*\.{\@@=:}, \.{\@@=:>}*/
19245 if (lig_stack==null) /*right boundary character is being consumed*/
19246 {@+lig_stack=new_lig_item(cur_r);bchar=non_char;
19247 }
19248 else if (is_char_node(lig_stack)) /*|link(lig_stack)==null|*/
19249 {@+main_p=lig_stack;lig_stack=new_lig_item(cur_r);
19250 lig_ptr(lig_stack)=main_p;
19251 }
19252 else character(lig_stack)=cur_r;
19253 } @+break;
19254 case qi(3): {@+cur_r=rem_byte(main_j); /*\.{\@@=:\@@}*/
19255 main_p=lig_stack;lig_stack=new_lig_item(cur_r);
19256 link(lig_stack)=main_p;
19257 } @+break;
19258 case qi(7): case qi(11): {@+wrapup(false); /*\.{\@@=:\@@>}, \.{\@@=:\@@>>}*/
19259 cur_q=tail;cur_l=rem_byte(main_j);
19260 main_i=char_info(main_f, cur_l);ligature_present=true;
19261 } @+break;
19262 default:{@+cur_l=rem_byte(main_j);ligature_present=true; /*\.{=:}*/
19263 if (lig_stack==null) goto main_loop_wrapup;
19264 else goto main_loop_move1;
19265 }
19266 }
19267 if (op_byte(main_j) > qi(4))
19268 if (op_byte(main_j)!=qi(7)) goto main_loop_wrapup;
19269 if (cur_l < non_char) goto main_lig_loop;
19270 main_k=bchar_label[main_f];goto main_lig_loop1;
19271 }
19272
19273 @ The occurrence of blank spaces is almost part of \TeX's inner loop,
19274 @^inner loop@>
19275 since we usually encounter about one space for every five non-blank characters.
19276 Therefore |main_control| gives second-highest priority to ordinary spaces.
19277
19278 When a glue parameter like \.{\\spaceskip} is set to `\.{0pt}', we will
19279 see to it later that the corresponding glue specification is precisely
19280 |zero_glue|, not merely a pointer to some specification that happens
19281 to be full of zeroes. Therefore it is simple to test whether a glue parameter
19282 is zero or~not.
19283
19284 @<Append a normal inter-word space...@>=
19285 if (space_skip==zero_glue)
19286 {@+@<Find the glue specification, |main_p|, for text spaces in the current
19287 font@>;
19288 temp_ptr=new_glue(main_p);
19289 }
19290 else temp_ptr=new_param_glue(space_skip_code);
19291 link(tail)=temp_ptr;tail=temp_ptr;
19292 goto big_switch
19293
19294 @ Having |font_glue| allocated for each text font saves both time and memory.
19295 If any of the three spacing parameters are subsequently changed by the
19296 use of \.{\\fontdimen}, the |find_font_dimen| procedure deallocates the
19297 |font_glue| specification allocated here.
19298
19299 @<Find the glue specification...@>=
19300 {@+main_p=font_glue[cur_font];
19301 if (main_p==null)
19302 {@+main_p=new_spec(zero_glue);main_k=param_base[cur_font]+space_code;
19303 width(main_p)=font_info[main_k].sc; /*that's |space(cur_font)|*/
19304 stretch(main_p)=font_info[main_k+1].sc; /*and |space_stretch(cur_font)|*/
19305 shrink(main_p)=font_info[main_k+2].sc; /*and |space_shrink(cur_font)|*/
19306 font_glue[cur_font]=main_p;
19307 }
19308 }
19309
19310 @ @<Declare act...@>=
19311 static void app_space(void) /*handle spaces when |space_factor!=1000|*/
19312 {@+pointer @!q; /*glue node*/
19313 if ((space_factor >= 2000)&&(xspace_skip!=zero_glue))
19314 q=new_param_glue(xspace_skip_code);
19315 else{@+if (space_skip!=zero_glue) main_p=space_skip;
19316 else@<Find the glue specification...@>;
19317 main_p=new_spec(main_p);
19318 @<Modify the glue specification in |main_p| according to the space factor@>;
19319 q=new_glue(main_p);glue_ref_count(main_p)=null;
19320 }
19321 link(tail)=q;tail=q;
19322 }
19323
19324 @ @<Modify the glue specification in |main_p| according to the space factor@>=
19325 if (space_factor >= 2000) width(main_p)=width(main_p)+extra_space(cur_font);
19326 stretch(main_p)=xn_over_d(stretch(main_p), space_factor, 1000);
19327 shrink(main_p)=xn_over_d(shrink(main_p), 1000, space_factor)
19328
19329 @ Whew---that covers the main loop. We can now proceed at a leisurely
19330 pace through the other combinations of possibilities.
19331
19332 @d any_mode(A) case vmode+A: case hmode+A:
19333 case mmode+A /*for mode-independent commands*/
19334
19335 @<Cases of |main_control| that are not part of the inner loop@>=
19336 any_mode(relax): case vmode+spacer: case mmode+spacer:
19337 case mmode+no_boundary: do_nothing;@+break;
19338 any_mode(ignore_spaces): {@+@<Get the next non-blank non-call...@>;
19339 goto reswitch;
19340 }
19341 case vmode+stop: if (its_all_over()) return;@+break; /*this is the only way out*/
19342 @t\4@>@<Forbidden cases detected in |main_control|@>@+@, any_mode(mac_param):
19343 report_illegal_case();@+break;
19344 @<Math-only cases in non-math modes, or vice versa@>: insert_dollar_sign();@+break;
19345 @t\4@>@<Cases of |main_control| that build boxes and lists@>@;
19346 @t\4@>@<Cases of |main_control| that don't depend on |mode|@>@;
19347 @t\4@>@<Cases of |main_control| that are for extensions to \TeX@>@;
19348
19349 @ Here is a list of cases where the user has probably gotten into or out of math
19350 mode by mistake. \TeX\ will insert a dollar sign and rescan the current token.
19351
19352 @d non_math(A) case vmode+A: case hmode+A
19353
19354 @<Math-only cases in non-math modes...@>=
19355 non_math(sup_mark): non_math(sub_mark): non_math(math_char_num):
19356 non_math(math_given): non_math(math_comp): non_math(delim_num):
19357 non_math(left_right): non_math(above): non_math(radical):
19358 non_math(math_style): non_math(math_choice): non_math(vcenter):
19359 non_math(non_script): non_math(mkern): non_math(limit_switch):
19360 non_math(mskip): non_math(math_accent):
19361 case mmode+endv: case mmode+par_end: case mmode+stop:
19362 case mmode+vskip: case mmode+un_vbox:
19363 case mmode+valign: case mmode+hrule
19364
19365 @ @<Declare action...@>=
19366 static void insert_dollar_sign(void)
19367 {@+back_input();cur_tok=math_shift_token+'$';
19368 print_err("Missing $ inserted");
19369 @.Missing \$ inserted@>
19370 help2("I've inserted a begin-math/end-math symbol since I think",@/
19371 "you left one out. Proceed, with fingers crossed.");ins_error();
19372 }
19373
19374 @ When erroneous situations arise, \TeX\ usually issues an error message
19375 specific to the particular error. For example, `\.{\\noalign}' should
19376 not appear in any mode, since it is recognized by the |align_peek| routine
19377 in all of its legitimate appearances; a special error message is given
19378 when `\.{\\noalign}' occurs elsewhere. But sometimes the most appropriate
19379 error message is simply that the user is not allowed to do what he or she
19380 has attempted. For example, `\.{\\moveleft}' is allowed only in vertical mode,
19381 and `\.{\\lower}' only in non-vertical modes. Such cases are enumerated
19382 here and in the other sections referred to under `See also \dots.'
19383
19384 @<Forbidden cases...@>=
19385 case vmode+vmove: case hmode+hmove: case mmode+hmove: any_mode(last_item):
19386
19387 @ The `|you_cant|' procedure prints a line saying that the current command
19388 is illegal in the current mode; it identifies these things symbolically.
19389
19390 @<Declare action...@>=
19391 static void you_cant(void)
19392 {@+print_err("You can't use `");
19393 @.You can't use x in y mode@>
19394 print_cmd_chr(cur_cmd, cur_chr);
19395 print("' in ");print_mode(mode);
19396 }
19397
19398 @ @<Declare act...@>=
19399 static void report_illegal_case(void)
19400 {@+you_cant();
19401 help4("Sorry, but I'm not programmed to handle this case;",@/
19402 "I'll just pretend that you didn't ask for it.",@/
19403 "If you're in the wrong mode, you might be able to",@/
19404 "return to the right one by typing `I}' or `I$' or `I\\par'.");@/
19405 error();
19406 }
19407
19408 @ Some operations are allowed only in privileged modes, i.e., in cases
19409 that |mode > 0|. The |privileged| function is used to detect violations
19410 of this rule; it issues an error message and returns |false| if the
19411 current |mode| is negative.
19412
19413 @<Declare act...@>=
19414 static bool privileged(void)
19415 {@+if (mode > 0) return true;
19416 else{@+report_illegal_case();return false;
19417 }
19418 }
19419
19420 @ Either \.{\\dump} or \.{\\end} will cause |main_control| to enter the
19421 endgame, since both of them have `|stop|' as their command code.
19422
19423 @<Put each...@>=
19424 primitive("end", stop, 0);@/
19425 @!@:end\_}{\.{\\end} primitive@>
19426 primitive("dump", stop, 1);@/
19427 @!@:dump\_}{\.{\\dump} primitive@>
19428
19429 @ @<Cases of |print_cmd_chr|...@>=
19430 case stop: if (chr_code==1) print_esc("dump");@+else print_esc("end");@+break;
19431
19432 @ We don't want to leave |main_control| immediately when a |stop| command
19433 is sensed, because it may be necessary to invoke an \.{\\output} routine
19434 several times before things really grind to a halt. (The output routine
19435 might even say `\.{\\gdef\\end\{...\}}', to prolong the life of the job.)
19436 Therefore |its_all_over| is |true| only when the current page
19437 and contribution list are empty, and when the last output was not a
19438 ``dead cycle.''
19439
19440 @<Declare act...@>=
19441 static bool its_all_over(void) /*do this when \.{\\end} or \.{\\dump} occurs*/
19442 {@+
19443 if (privileged())
19444 {@+if ((page_head==page_tail)&&(dead_cycles==0))
19445 {
19446 if (head==tail) return true;
19447 else if (option_no_empty_page)
19448 { pointer p=link(head);
19449 while (p!=null)
19450 { if (is_visible(p)) break;
19451 else p=link(p);
19452 }
19453 if (p==null) return true;
19454 }
19455 }
19456 back_input(); /*we will try to end again after ejecting residual material*/
19457 tail_append(new_set_node());
19458 set_extent(tail)=new_xdimen(dimen_par(hsize_code),
19459 dimen_par_hfactor(hsize_code),dimen_par_vfactor(hsize_code));
19460 tail_append(new_glue(fill_glue));
19461 tail_append(new_penalty(2*(eject_penalty)));@/
19462 build_page(); /*append \.{\\hbox to \\hsize\{\}\\vfill\\penalty-'10000000000}*/
19463 }
19464 return false;
19465 }
19466
19467 @* Building boxes and lists.
19468 The most important parts of |main_control| are concerned with \TeX's
19469 chief mission of box-making. We need to control the activities that put
19470 entries on vlists and hlists, as well as the activities that convert
19471 those lists into boxes. All of the necessary machinery has already been
19472 developed; it remains for us to ``push the buttons'' at the right times.
19473
19474 @ As an introduction to these routines, let's consider one of the simplest
19475 cases: What happens when `\.{\\hrule}' occurs in vertical mode, or
19476 `\.{\\vrule}' in horizontal mode or math mode? The code in |main_control|
19477 is short, since the |scan_rule_spec| routine already does most of what is
19478 required; thus, there is no need for a special action procedure.
19479
19480 Note that baselineskip calculations are disabled after a rule in vertical
19481 mode, by setting |prev_depth=ignore_depth|.
19482
19483 @<Cases of |main_control| that build...@>=
19484 case vmode+hrule: case hmode+vrule: case mmode+vrule: {@+tail_append(scan_rule_spec());
19485 if (abs(mode)==vmode) prev_depth=ignore_depth;
19486 else if (abs(mode)==hmode) space_factor=1000;
19487 } @+break;
19488
19489 @ The processing of things like \.{\\hskip} and \.{\\vskip} is slightly
19490 more complicated. But the code in |main_control| is very short, since
19491 it simply calls on the action routine |append_glue|. Similarly, \.{\\kern}
19492 activates |append_kern|.
19493
19494 @<Cases of |main_control| that build...@>=
19495 case vmode+vskip: case hmode+hskip: case mmode+hskip:
19496 case mmode+mskip: append_glue();@+break;
19497 any_mode(kern): case mmode+mkern: append_kern();@+break;
19498
19499 @ The |hskip| and |vskip| command codes are used for control sequences
19500 like \.{\\hss} and \.{\\vfil} as well as for \.{\\hskip} and \.{\\vskip}.
19501 The difference is in the value of |cur_chr|.
19502
19503 @d fil_code 0 /*identifies \.{\\hfil} and \.{\\vfil}*/
19504 @d fill_code 1 /*identifies \.{\\hfill} and \.{\\vfill}*/
19505 @d ss_code 2 /*identifies \.{\\hss} and \.{\\vss}*/
19506 @d fil_neg_code 3 /*identifies \.{\\hfilneg} and \.{\\vfilneg}*/
19507 @d skip_code 4 /*identifies \.{\\hskip} and \.{\\vskip}*/
19508 @d mskip_code 5 /*identifies \.{\\mskip}*/
19509
19510 @<Put each...@>=
19511 primitive("hskip", hskip, skip_code);@/
19512 @!@:hskip\_}{\.{\\hskip} primitive@>
19513 primitive("hfil", hskip, fil_code);
19514 @!@:hfil\_}{\.{\\hfil} primitive@>
19515 primitive("hfill", hskip, fill_code);@/
19516 @!@:hfill\_}{\.{\\hfill} primitive@>
19517 primitive("hss", hskip, ss_code);
19518 @!@:hss\_}{\.{\\hss} primitive@>
19519 primitive("hfilneg", hskip, fil_neg_code);@/
19520 @!@:hfil\_neg\_}{\.{\\hfilneg} primitive@>
19521 primitive("vskip", vskip, skip_code);@/
19522 @!@:vskip\_}{\.{\\vskip} primitive@>
19523 primitive("vfil", vskip, fil_code);
19524 @!@:vfil\_}{\.{\\vfil} primitive@>
19525 primitive("vfill", vskip, fill_code);@/
19526 @!@:vfill\_}{\.{\\vfill} primitive@>
19527 primitive("vss", vskip, ss_code);
19528 @!@:vss\_}{\.{\\vss} primitive@>
19529 primitive("vfilneg", vskip, fil_neg_code);@/
19530 @!@:vfil\_neg\_}{\.{\\vfilneg} primitive@>
19531 primitive("mskip", mskip, mskip_code);@/
19532 @!@:mskip\_}{\.{\\mskip} primitive@>
19533 primitive("kern", kern, explicit);
19534 @!@:kern\_}{\.{\\kern} primitive@>
19535 primitive("mkern", mkern, mu_glue);@/
19536 @!@:mkern\_}{\.{\\mkern} primitive@>
19537
19538 @ @<Cases of |print_cmd_chr|...@>=
19539 case hskip: switch (chr_code) {
19540 case skip_code: print_esc("hskip");@+break;
19541 case fil_code: print_esc("hfil");@+break;
19542 case fill_code: print_esc("hfill");@+break;
19543 case ss_code: print_esc("hss");@+break;
19544 default:print_esc("hfilneg");
19545 } @+break;
19546 case vskip: switch (chr_code) {
19547 case skip_code: print_esc("vskip");@+break;
19548 case fil_code: print_esc("vfil");@+break;
19549 case fill_code: print_esc("vfill");@+break;
19550 case ss_code: print_esc("vss");@+break;
19551 default:print_esc("vfilneg");
19552 } @+break;
19553 case mskip: print_esc("mskip");@+break;
19554 case kern: print_esc("kern");@+break;
19555 case mkern: print_esc("mkern");@+break;
19556
19557 @ All the work relating to glue creation has been relegated to the
19558 following subroutine. It does not call |build_page|, because it is
19559 used in at least one place where that would be a mistake.
19560
19561 @<Declare action...@>=
19562 static void append_glue(void)
19563 {@+small_number s; /*modifier of skip command*/
19564 s=cur_chr;
19565 switch (s) {
19566 case fil_code: cur_val=fil_glue;@+break;
19567 case fill_code: cur_val=fill_glue;@+break;
19568 case ss_code: cur_val=ss_glue;@+break;
19569 case fil_neg_code: cur_val=fil_neg_glue;@+break;
19570 case skip_code: scan_glue(glue_val);@+break;
19571 case mskip_code: scan_glue(mu_val);
19572 } /*now |cur_val| points to the glue specification*/
19573 tail_append(new_glue(cur_val));
19574 if (s >= skip_code)
19575 {@+decr(glue_ref_count(cur_val));
19576 if (s > skip_code) subtype(tail)=mu_glue;
19577 }
19578 }
19579
19580 @ @<Declare act...@>=
19581 static void append_kern(void)
19582 {@+quarterword s; /*|subtype| of the kern node*/
19583 s=cur_chr;scan_dimen(s==mu_glue, false, false);
19584 tail_append(new_kern(cur_val));subtype(tail)=s;
19585 }
19586
19587 @ Many of the actions related to box-making are triggered by the appearance
19588 of braces in the input. For example, when the user says `\.{\\hbox}
19589 \.{to} \.{100pt\{$\langle\,\hbox{\rm hlist}\,\rangle$\}}' in vertical mode,
19590 the information about the box size (100pt, |exactly|) is put onto |save_stack|
19591 with a level boundary word just above it, and |cur_group=adjusted_hbox_group|;
19592 \TeX\ enters restricted horizontal mode to process the hlist. The right
19593 brace eventually causes |save_stack| to be restored to its former state,
19594 at which time the information about the box size (100pt, |exactly|) is
19595 available once again; a box is packaged and we leave restricted horizontal
19596 mode, appending the new box to the current list of the enclosing mode
19597 (in this case to the current list of vertical mode), followed by any
19598 vertical adjustments that were removed from the box by |hpack|.
19599
19600 The next few sections of the program are therefore concerned with the
19601 treatment of left and right curly braces.
19602
19603 @ If a left brace occurs in the middle of a page or paragraph, it simply
19604 introduces a new level of grouping, and the matching right brace will not have
19605 such a drastic effect. Such grouping affects neither the mode nor the
19606 current list.
19607
19608 @<Cases of |main_control| that build...@>=
19609 non_math(left_brace): new_save_level(simple_group);@+break;
19610 any_mode(begin_group): new_save_level(semi_simple_group);@+break;
19611 any_mode(end_group): if (cur_group==semi_simple_group) unsave();
19612 else off_save();@+break;
19613
19614 @ We have to deal with errors in which braces and such things are not
19615 properly nested. Sometimes the user makes an error of commission by
19616 inserting an extra symbol, but sometimes the user makes an error of omission.
19617 \TeX\ can't always tell one from the other, so it makes a guess and tries
19618 to avoid getting into a loop.
19619
19620 The |off_save| routine is called when the current group code is wrong. It tries
19621 to insert something into the user's input that will help clean off
19622 the top level.
19623
19624 @<Declare act...@>=
19625 static void off_save(void)
19626 {@+pointer p; /*inserted token*/
19627 if (cur_group==bottom_level)
19628 @<Drop current token and complain that it was unmatched@>@;
19629 else{@+back_input();p=get_avail();link(temp_head)=p;
19630 print_err("Missing ");
19631 @<Prepare to insert a token that matches |cur_group|, and print what it
19632 is@>;
19633 print(" inserted");ins_list(link(temp_head));
19634 help5("I've inserted something that you may have forgotten.",@/
19635 "(See the <inserted text> above.)",@/
19636 "With luck, this will get me unwedged. But if you",@/
19637 "really didn't forget anything, try typing `2' now; then",@/
19638 "my insertion and my current dilemma will both disappear.");
19639 error();
19640 }
19641 }
19642
19643 @ At this point, |link(temp_head)==p|, a pointer to an empty one-word node.
19644
19645 @<Prepare to insert a token that matches |cur_group|...@>=
19646 switch (cur_group) {
19647 case semi_simple_group: {@+info(p)=cs_token_flag+frozen_end_group;
19648 print_esc("endgroup");
19649 @.Missing \\endgroup inserted@>
19650 } @+break;
19651 case math_shift_group: {@+info(p)=math_shift_token+'$';print_char('$');
19652 @.Missing \$ inserted@>
19653 } @+break;
19654 case math_left_group: {@+info(p)=cs_token_flag+frozen_right;link(p)=get_avail();
19655 p=link(p);info(p)=other_token+'.';print_esc("right.");
19656 @.Missing \\right\hbox{.} inserted@>
19657 @^null delimiter@>
19658 } @+break;
19659 default:{@+info(p)=right_brace_token+'}';print_char('}');
19660 @.Missing \} inserted@>
19661 }
19662 }
19663
19664 @ @<Drop current token and complain that it was unmatched@>=
19665 {@+print_err("Extra ");print_cmd_chr(cur_cmd, cur_chr);
19666 @.Extra x@>
19667 help1("Things are pretty mixed up, but I think the worst is over.");@/
19668 error();
19669 }
19670
19671 @ The routine for a |right_brace| character branches into many subcases,
19672 since a variety of things may happen, depending on |cur_group|. Some
19673 types of groups are not supposed to be ended by a right brace; error
19674 messages are given in hopes of pinpointing the problem. Most branches
19675 of this routine will be filled in later, when we are ready to understand
19676 them; meanwhile, we must prepare ourselves to deal with such errors.
19677
19678 @<Cases of |main_control| that build...@>=
19679 any_mode(right_brace): handle_right_brace();@+break;
19680
19681 @ @<Declare the procedure called |handle_right_brace|@>=
19682 static void handle_right_brace(void)
19683 {@+pointer p, @!q; /*for short-term use*/
19684 scaled @!d; /*holds |split_max_depth| in |insert_group|*/
19685 int @!f; /*holds |floating_penalty| in |insert_group|*/
19686 switch (cur_group) {
19687 case simple_group: unsave();@+break;
19688 case bottom_level: {@+print_err("Too many }'s");
19689 @.Too many \}'s@>
19690 help2("You've closed more groups than you opened.",@/
19691 "Such booboos are generally harmless, so keep going.");error();
19692 } @+break;
19693 case semi_simple_group: case math_shift_group:
19694 case math_left_group: extra_right_brace();@+break;
19695 @t\4@>@<Cases of |handle_right_brace| where a |right_brace| triggers a delayed
19696 action@>@;
19697 default:confusion("rightbrace");
19698 @:this can't happen rightbrace}{\quad rightbrace@>
19699 }
19700 }
19701
19702 @ @<Declare act...@>=
19703 static void extra_right_brace(void)
19704 {@+print_err("Extra }, or forgotten ");
19705 @.Extra \}, or forgotten x@>
19706 switch (cur_group) {
19707 case semi_simple_group: print_esc("endgroup");@+break;
19708 case math_shift_group: print_char('$');@+break;
19709 case math_left_group: print_esc("right");
19710 } @/
19711 help5("I've deleted a group-closing symbol because it seems to be",@/
19712 "spurious, as in `$x}$'. But perhaps the } is legitimate and",@/
19713 "you forgot something else, as in `\\hbox{$x}'. In such cases",@/
19714 "the way to recover is to insert both the forgotten and the",@/
19715 "deleted material, e.g., by typing `I$}'.");error();
19716 incr(align_state);
19717 }
19718
19719 @ Here is where we clear the parameters that are supposed to revert to their
19720 default values after every paragraph and when internal vertical mode is entered.
19721
19722 @<Declare act...@>=
19723 static void normal_paragraph(void)
19724 {@+if (looseness!=0) eq_word_define(int_base+looseness_code, 0);
19725 if (hang_indent!=0) eq_word_define(dimen_base+hang_indent_code, 0);
19726 if (hang_after!=1) eq_word_define(int_base+hang_after_code, 1);
19727 if (par_shape_ptr!=null) eq_define(par_shape_loc, shape_ref, null);
19728 if (inter_line_penalties_ptr!=null)
19729 eq_define(inter_line_penalties_loc, shape_ref, null);
19730 }
19731
19732 @ Now let's turn to the question of how \.{\\hbox} is treated. We actually
19733 need to consider also a slightly larger context, since constructions like
19734 `\.{\\setbox3=}\penalty0\.{\\hbox...}' and
19735 `\.{\\leaders}\penalty0\.{\\hbox...}' and
19736 `\.{\\lower3.8pt\\hbox...}'
19737 are supposed to invoke quite
19738 different actions after the box has been packaged. Conversely,
19739 constructions like `\.{\\setbox3=}' can be followed by a variety of
19740 different kinds of boxes, and we would like to encode such things in an
19741 efficient way.
19742
19743 In other words, there are two problems: to represent the context of a box,
19744 and to represent its type.
19745
19746 The first problem is solved by putting a ``context code'' on the |save_stack|,
19747 just below the two entries that give the dimensions produced by |scan_spec|.
19748 The context code is either a (signed) shift amount, or it is a large
19749 integer | >= box_flag|, where |box_flag==@t$2^{30}$@>|. Codes |box_flag| through
19750 |global_box_flag-1| represent `\.{\\setbox0}' through `\.{\\setbox32767}';
19751 codes |global_box_flag| through |ship_out_flag-1| represent
19752 `\.{\\global\\setbox0}' through `\.{\\global\\setbox32767}';
19753 code |ship_out_flag| represents `\.{\\shipout}'; and codes |leader_flag|
19754 through |leader_flag+2| represent `\.{\\leaders}', `\.{\\cleaders}',
19755 and `\.{\\xleaders}'.
19756
19757 The second problem is solved by giving the command code |make_box| to all
19758 control sequences that produce a box, and by using the following |chr_code|
19759 values to distinguish between them: |box_code|, |copy_code|, |last_box_code|,
19760 |vsplit_code|, |vtop_code|, |vtop_code+vmode|, and |vtop_code+hmode|, where
19761 the latter two are used to denote \.{\\vbox} and \.{\\hbox}, respectively.
19762
19763 @d box_flag 010000000000 /*context code for `\.{\\setbox0}'*/
19764 @d global_box_flag 010000100000 /*context code for `\.{\\global\\setbox0}'*/
19765 @d ship_out_flag 010000200000 /*context code for `\.{\\shipout}'*/
19766 @d leader_flag 010000200001 /*context code for `\.{\\leaders}'*/
19767 @d box_code 0 /*|chr_code| for `\.{\\box}'*/
19768 @d copy_code 1 /*|chr_code| for `\.{\\copy}'*/
19769 @d last_box_code 2 /*|chr_code| for `\.{\\lastbox}'*/
19770 @d vsplit_code 3 /*|chr_code| for `\.{\\vsplit}'*/
19771 @d vtop_code 4 /*|chr_code| for `\.{\\vtop}'*/
19772
19773 @<Put each...@>=
19774 primitive("moveleft", hmove, 1);
19775 @!@:move\_left\_}{\.{\\moveleft} primitive@>
19776 primitive("moveright", hmove, 0);@/
19777 @!@:move\_right\_}{\.{\\moveright} primitive@>
19778 primitive("raise", vmove, 1);
19779 @!@:raise\_}{\.{\\raise} primitive@>
19780 primitive("lower", vmove, 0);
19781 @!@:lower\_}{\.{\\lower} primitive@>
19782 @#
19783 primitive("box", make_box, box_code);
19784 @!@:box\_}{\.{\\box} primitive@>
19785 primitive("copy", make_box, copy_code);
19786 @!@:copy\_}{\.{\\copy} primitive@>
19787 primitive("lastbox", make_box, last_box_code);
19788 @!@:last\_box\_}{\.{\\lastbox} primitive@>
19789 primitive("vsplit", make_box, vsplit_code);
19790 @!@:vsplit\_}{\.{\\vsplit} primitive@>
19791 primitive("vtop", make_box, vtop_code);@/
19792 @!@:vtop\_}{\.{\\vtop} primitive@>
19793 primitive("vbox", make_box, vtop_code+vmode);
19794 @!@:vbox\_}{\.{\\vbox} primitive@>
19795 primitive("hbox", make_box, vtop_code+hmode);@/
19796 @!@:hbox\_}{\.{\\hbox} primitive@>
19797 primitive("shipout", leader_ship, a_leaders-1); /*|ship_out_flag==leader_flag-1|*/
19798 @!@:ship\_out\_}{\.{\\shipout} primitive@>
19799 primitive("leaders", leader_ship, a_leaders);
19800 @!@:leaders\_}{\.{\\leaders} primitive@>
19801 primitive("cleaders", leader_ship, c_leaders);
19802 @!@:c\_leaders\_}{\.{\\cleaders} primitive@>
19803 primitive("xleaders", leader_ship, x_leaders);
19804 @!@:x\_leaders\_}{\.{\\xleaders} primitive@>
19805
19806 @ @<Cases of |print_cmd_chr|...@>=
19807 case hmove: if (chr_code==1) print_esc("moveleft");@+else print_esc("moveright");@+break;
19808 case vmove: if (chr_code==1) print_esc("raise");@+else print_esc("lower");@+break;
19809 case make_box: switch (chr_code) {
19810 case box_code: print_esc("box");@+break;
19811 case copy_code: print_esc("copy");@+break;
19812 case last_box_code: print_esc("lastbox");@+break;
19813 case vsplit_code: print_esc("vsplit");@+break;
19814 case vtop_code: print_esc("vtop");@+break;
19815 case vtop_code+vmode: print_esc("vbox");@+break;
19816 default:print_esc("hbox");
19817 } @+break;
19818 case leader_ship: if (chr_code==a_leaders) print_esc("leaders");
19819 else if (chr_code==c_leaders) print_esc("cleaders");
19820 else if (chr_code==x_leaders) print_esc("xleaders");
19821 else print_esc("shipout");@+break;
19822
19823 @ Constructions that require a box are started by calling |scan_box| with
19824 a specified context code. The |scan_box| routine verifies
19825 that a |make_box| command comes next and then it calls |begin_box|.
19826
19827 @<Cases of |main_control| that build...@>=
19828 case vmode+hmove: case hmode+vmove: case mmode+vmove: {@+t=cur_chr;
19829 scan_normal_dimen;
19830 if (t==0) scan_box(cur_val);@+else scan_box(-cur_val);
19831 } @+break;
19832 any_mode(leader_ship): scan_box(leader_flag-a_leaders+cur_chr);@+break;
19833 any_mode(make_box): begin_box(0);@+break;
19834
19835 @ The global variable |cur_box| will point to a newly made box. If the box
19836 is void, we will have |cur_box==null|. Otherwise we will have
19837 |type(cur_box)==hlist_node| or |vlist_node| or |rule_node|; the |rule_node|
19838 case can occur only with leaders.
19839
19840 @<Glob...@>=
19841 static pointer @!cur_box; /*box to be placed into its context*/
19842
19843 @ The |box_end| procedure does the right thing with |cur_box|, if
19844 |box_context| represents the context as explained above.
19845
19846 @<Declare act...@>=
19847 static void box_end(int @!box_context)
19848 {@+pointer p; /*|ord_noad| for new box in math mode*/
19849 small_number @!a; /*global prefix*/
19850 if (box_context < box_flag) @<Append box |cur_box| to the current list, shifted
19851 by |box_context|@>@;
19852 else if (box_context < ship_out_flag) @<Store \(c)|cur_box| in a box register@>@;
19853 else if (cur_box!=null)
19854 if (box_context > ship_out_flag) @<Append a new leader node that uses |cur_box|@>@;
19855 else ship_out(cur_box);
19856 }
19857
19858 @ The global variable |adjust_tail| will be non-null if and only if the
19859 current box might include adjustments that should be appended to the
19860 current vertical list.
19861
19862 @<Append box |cur_box| to the current...@>=
19863 {@+if (cur_box!=null)
19864 {@+shift_amount(cur_box)=box_context;
19865 if (abs(mode)==vmode)
19866 {@+append_to_vlist(cur_box);
19867 if (adjust_tail!=null)
19868 {@+if (adjust_head!=adjust_tail)
19869 {@+link(tail)=link(adjust_head);tail=adjust_tail;
19870 }
19871 adjust_tail=null;
19872 }
19873 if (mode > 0) build_page();
19874 }
19875 else{@+if (abs(mode)==hmode) space_factor=1000;
19876 else{@+p=new_noad();
19877 math_type(nucleus(p))=sub_box;
19878 info(nucleus(p))=cur_box;cur_box=p;
19879 }
19880 link(tail)=cur_box;tail=cur_box;
19881 }
19882 }
19883 }
19884
19885 @ @<Store \(c)|cur_box| in a box register@>=
19886 {@+if (box_context < global_box_flag)
19887 {@+cur_val=box_context-box_flag;a=0;
19888 }
19889 else{@+cur_val=box_context-global_box_flag;a=4;
19890 }
19891 if (cur_val < 256) define(box_base+cur_val, box_ref, cur_box);
19892 else sa_def_box;
19893 }
19894
19895 @ @<Append a new leader node...@>=
19896 {@+@<Get the next non-blank non-relax...@>;
19897 if (((cur_cmd==hskip)&&(abs(mode)!=vmode))||@|
19898 ((cur_cmd==vskip)&&(abs(mode)==vmode)))
19899 {@+append_glue();subtype(tail)=box_context-(leader_flag-a_leaders);
19900 leader_ptr(tail)=cur_box;
19901 }
19902 else{@+print_err("Leaders not followed by proper glue");
19903 @.Leaders not followed by...@>
19904 help3("You should say `\\leaders <box or rule><hskip or vskip>'.",@/
19905 "I found the <box or rule>, but there's no suitable",@/
19906 "<hskip or vskip>, so I'm ignoring these leaders.");back_error();
19907 flush_node_list(cur_box);
19908 }
19909 }
19910
19911 @ Now that we can see what eventually happens to boxes, we can consider
19912 the first steps in their creation. The |begin_box| routine is called when
19913 |box_context| is a context specification, |cur_chr| specifies the type of
19914 box desired, and |cur_cmd==make_box|.
19915
19916 @<Declare act...@>=
19917 static void begin_box(int @!box_context)
19918 {@+
19919 pointer @!p, @!q; /*run through the current list*/
19920 int @!m; /*the length of a replacement list*/
19921 halfword @!k; /*0 or |vmode| or |hmode|*/
19922 halfword @!n; /*a box number*/
19923 switch (cur_chr) {
19924 case box_code: {@+scan_register_num();fetch_box(cur_box);
19925 change_box(null); /*the box becomes void, at the same level*/
19926 } @+break;
19927 case copy_code: {@+scan_register_num();fetch_box(q);cur_box=copy_node_list(q);
19928 } @+break;
19929 case last_box_code: @<If the current list ends with a box node, delete it
19930 from the list and make |cur_box| point to it; otherwise set |cur_box:=null|@>@;@+break;
19931 case vsplit_code: @<Split off part of a vertical box, make |cur_box| point
19932 to it@>@;@+break;
19933 default:@<Initiate the construction of an hbox or vbox, then |return|@>@;
19934 } @/
19935 box_end(box_context); /*in simple cases, we use the box immediately*/
19936 }
19937
19938 @ Note that the condition |!is_char_node(tail)| implies that |head!=tail|,
19939 since |head| is a one-word node.
19940
19941 @<If the current list ends with a box node, delete it...@>=
19942 {@+cur_box=null;
19943 if (abs(mode)==mmode)
19944 {@+you_cant();help1("Sorry; this \\lastbox will be void.");error();
19945 }
19946 else if ((mode==vmode)&&(head==tail))
19947 {@+you_cant();
19948 help2("Sorry...I usually can't take things from the current page.",@/
19949 "This \\lastbox will therefore be void.");error();
19950 }
19951 else{@+if (!is_char_node(tail))
19952 if ((type(tail)==hlist_node)||(type(tail)==vlist_node))
19953 @<Remove the last box, unless it's part of a discretionary@>;
19954 }
19955 }
19956
19957 @ @<Remove the last box...@>=
19958 {@+q=head;
19959 @/do@+{p=q;
19960 if (!is_char_node(q)) if (type(q)==disc_node)
19961 {@+for (m=1; m<=replace_count(q); m++) p=link(p);
19962 if (p==tail) goto done;
19963 }
19964 q=link(p);
19965 }@+ while (!(q==tail));
19966 cur_box=tail;shift_amount(cur_box)=0;
19967 tail=p;link(p)=null;
19968 done: ;}
19969
19970 @ Here we deal with things like `\.{\\vsplit 13 to 100pt}'.
19971
19972 @<Split off part of a vertical box, make |cur_box| point to it@>=
19973 {@+scan_register_num();n=cur_val;
19974 if (!scan_keyword("to"))
19975 @.to@>
19976 {@+print_err("Missing `to' inserted");
19977 @.Missing `to' inserted@>
19978 help2("I'm working on `\\vsplit<box number> to <dimen>';",@/
19979 "will look for the <dimen> next.");error();
19980 }
19981 scan_normal_dimen;
19982 cur_box=vsplit(n, cur_val);
19983 }
19984
19985 @ Here is where we enter restricted horizontal mode or internal vertical
19986 mode, in order to make a box.
19987
19988 @<Initiate the construction of an hbox or vbox, then |return|@>=
19989 {@+k=cur_chr-vtop_code;saved(0)=box_context;
19990 if (k==hmode)
19991 if ((box_context < box_flag)&&(abs(mode)==vmode))
19992 scan_spec(adjusted_hbox_group, true);
19993 else scan_spec(hbox_group, true);
19994 else{@+if (k==vmode) scan_spec(vbox_group, true);
19995 else{@+scan_spec(vtop_group, true);k=vmode;
19996 }
19997 normal_paragraph();
19998 }
19999 push_nest();mode=-k;
20000 if (k==vmode)
20001 {@+prev_depth=ignore_depth;
20002 if (every_vbox!=null) begin_token_list(every_vbox, every_vbox_text);
20003 }
20004 else{@+space_factor=1000;
20005 if (every_hbox!=null) begin_token_list(every_hbox, every_hbox_text);
20006 }
20007 return;
20008 }
20009
20010 @ @<Declare act...@>=
20011 static void scan_box(int @!box_context)
20012 /*the next input should specify a box or perhaps a rule*/
20013 {@+@<Get the next non-blank non-relax...@>;
20014 if (cur_cmd==make_box) begin_box(box_context);
20015 else if ((box_context >= leader_flag)&&((cur_cmd==hrule)||(cur_cmd==vrule)))
20016 {@+cur_box=scan_rule_spec();box_end(box_context);
20017 }
20018 else{@+@t@>@;@/
20019 print_err("A <box> was supposed to be here");@/
20020 @.A <box> was supposed to...@>
20021 help3("I was expecting to see \\hbox or \\vbox or \\copy or \\box or",@/
20022 "something like that. So you might find something missing in",@/
20023 "your output. But keep trying; you can fix this later.");back_error();
20024 }
20025 }
20026
20027 @ When the right brace occurs at the end of an \.{\\hbox} or \.{\\vbox} or
20028 \.{\\vtop} construction, the |package| routine comes into action. We might
20029 also have to finish a paragraph that hasn't ended.
20030
20031 @<Cases of |handle...@>=
20032 case hbox_group: package(0);@+break;
20033 case adjusted_hbox_group: {@+adjust_tail=adjust_head;package(0);
20034 } @+break;
20035 case vbox_group: {@+end_graf();package(0);
20036 } @+break;
20037 case vtop_group: {@+end_graf();package(vtop_code);
20038 } @+break;
20039
20040 @ @<Declare action...@>=
20041 static void package(small_number @!c)
20042 {@+scaled h; /*height of box*/
20043 pointer @!p; /*first node in a box*/
20044 scaled @!d; /*max depth*/
20045 d=box_max_depth;unsave();save_ptr=save_ptr-3;
20046 if (mode==-hmode) cur_box=hpack(link(head), saved(2), saved_hfactor(2), saved_vfactor(2), saved(1), false);
20047 else{@+cur_box=vpackage(link(head), saved(2), saved_hfactor(2), saved_vfactor(2), saved(1), false, d);
20048 if (c==vtop_code) @<Readjust the height and depth of |cur_box|, for \.{\\vtop}@>;
20049 }
20050 pop_nest();box_end(saved(0));
20051 }
20052
20053 @ The height of a `\.{\\vtop}' box is inherited from the first item on its list,
20054 if that item is an |hlist_node|, |vlist_node|, or |rule_node|; otherwise
20055 the \.{\\vtop} height is zero.
20056
20057
20058 @<Readjust the height...@>=
20059 {@+if (type(cur_box)==vlist_node)
20060 {@+h=0;p=list_ptr(cur_box);
20061 if (p!=null && type(p) <= rule_node) h=height(p);
20062 depth(cur_box)=depth(cur_box)-h+height(cur_box);height(cur_box)=h;
20063 }
20064 else if (type(cur_box) == whatsit_node)
20065 { if (subtype(cur_box)==vpack_node)
20066 pack_limit(cur_box)^=MAX_DIMEN+1;
20067 else if(subtype(cur_box)==vset_node)
20068 { height(cur_box)=height(cur_box)+depth(cur_box);
20069 depth(cur_box)^=MAX_DIMEN+1;
20070 }
20071 }
20072 }
20073
20074 @ A paragraph begins when horizontal-mode material occurs in vertical mode,
20075 or when the paragraph is explicitly started by `\.{\\indent}' or
20076 `\.{\\noindent}'.
20077
20078 @<Put each...@>=
20079 primitive("indent", start_par, 1);
20080 @!@:indent\_}{\.{\\indent} primitive@>
20081 primitive("noindent", start_par, 0);
20082 @!@:no\_indent\_}{\.{\\noindent} primitive@>
20083
20084 @ @<Cases of |print_cmd_chr|...@>=
20085 case start_par: if (chr_code==0) print_esc("noindent");@+else print_esc("indent");@+break;
20086
20087 @ @<Cases of |main_control| that build...@>=
20088 case vmode+start_par: new_graf(cur_chr > 0);@+break;
20089 case vmode+letter: case vmode+other_char:
20090 case vmode+char_num: case vmode+char_given:
20091 case vmode+math_shift: case vmode+un_hbox:
20092 case vmode+vrule:
20093 case vmode+accent: case vmode+discretionary:
20094 case vmode+hskip: case vmode+valign:
20095 case vmode+ex_space: case vmode+no_boundary: @t@>@;@/
20096 {@+back_input();new_graf(true);
20097 } @+break;
20098
20099 @ @<Declare act...@>=
20100 static small_number norm_min(int @!h)
20101 {@+if (h <= 0) return 1;@+else if (h >= 63) return 63;@+
20102 else return h;
20103 }
20104 @#
20105 static void new_graf(bool @!indented)
20106 {@+prev_graf=0;
20107 if ((mode==vmode)||(head!=tail))
20108 tail_append(new_param_glue(par_skip_code));
20109 push_nest();mode=hmode;space_factor=1000;set_cur_lang;clang=cur_lang;
20110 prev_graf=(norm_min(left_hyphen_min)*0100+norm_min(right_hyphen_min))
20111 *0200000+cur_lang;
20112 if (indented)
20113 {@+tail=new_null_box();link(head)=tail;width(tail)=par_indent;@+
20114 }
20115 if (every_par!=null) begin_token_list(every_par, every_par_text);
20116 if (nest_ptr==1) build_page(); /*put |par_skip| glue on current page*/
20117 }
20118
20119 @ @<Cases of |main_control| that build...@>=
20120 case hmode+start_par: case mmode+start_par: indent_in_hmode();@+break;
20121
20122 @ @<Declare act...@>=
20123 static void indent_in_hmode(void)
20124 {@+pointer p, @!q;
20125 if (cur_chr > 0) /*\.{\\indent}*/
20126 {@+p=new_null_box();width(p)=par_indent;
20127 if (abs(mode)==hmode) space_factor=1000;
20128 else{@+q=new_noad();math_type(nucleus(q))=sub_box;
20129 info(nucleus(q))=p;p=q;
20130 }
20131 tail_append(p);
20132 }
20133 }
20134
20135 @ A paragraph ends when a |par_end| command is sensed, or when we are in
20136 horizontal mode when reaching the right brace of vertical-mode routines
20137 like \.{\\vbox}, \.{\\insert}, or \.{\\output}.
20138
20139 @<Cases of |main_control| that build...@>=
20140 case vmode+par_end: {@+normal_paragraph();
20141 if (mode > 0) build_page();
20142 } @+break;
20143 case hmode+par_end: {@+if (align_state < 0) off_save(); /*this tries to
20144 recover from an alignment that didn't end properly*/
20145 end_graf(); /*this takes us to the enclosing mode, if |mode > 0|*/
20146 if (mode==vmode) build_page();
20147 } @+break;
20148 case hmode+stop: case hmode+vskip: case hmode+hrule:
20149 case hmode+un_vbox: case hmode+halign: head_for_vmode();@+break;
20150
20151 @ @<Declare act...@>=
20152 static void head_for_vmode(void)
20153 {@+if (mode < 0)
20154 if (cur_cmd!=hrule) off_save();
20155 else{@+print_err("You can't use `");
20156 print_esc("hrule");print("' here except with leaders");
20157 @.You can't use \\hrule...@>
20158 help2("To put a horizontal rule in an hbox or an alignment,",@/
20159 "you should use \\leaders or \\hrulefill (see The TeXbook).");
20160 error();
20161 }
20162 else{@+back_input();cur_tok=par_token;back_input();token_type=inserted;
20163 }
20164 }
20165
20166 @ @<Declare act...@>=
20167 static void end_graf(void)
20168 {@+if (mode==hmode)
20169 {@+if (head==tail) pop_nest(); /*null paragraphs are ignored*/
20170 else hline_break(widow_penalty);
20171 normal_paragraph();
20172 error_count=0;
20173 }
20174 }
20175
20176 @ Insertion and adjustment and mark nodes are constructed by the following
20177 pieces of the program.
20178
20179 @<Cases of |main_control| that build...@>=
20180 any_mode(insert): case hmode+vadjust:
20181 case mmode+vadjust: begin_insert_or_adjust();@+break;
20182 any_mode(mark): make_mark();@+break;
20183
20184 @ @<Forbidden...@>=
20185 case vmode+vadjust:
20186
20187 @ @<Declare act...@>=
20188 static void begin_insert_or_adjust(void)
20189 {@+if (cur_cmd==vadjust) cur_val=255;
20190 else{@+scan_eight_bit_int();
20191 if (cur_val==255)
20192 {@+print_err("You can't ");print_esc("insert");print_int(255);
20193 @.You can't \\insert255@>
20194 help1("I'm changing to \\insert0; box 255 is special.");
20195 error();cur_val=0;
20196 }
20197 }
20198 saved(0)=cur_val;incr(save_ptr);
20199 new_save_level(insert_group);scan_left_brace();normal_paragraph();
20200 push_nest();mode=-vmode;prev_depth=ignore_depth;
20201 }
20202
20203 @ @<Cases of |handle...@>=
20204 case insert_group: {@+end_graf();q=split_top_skip;add_glue_ref(q);
20205 d=split_max_depth;f=floating_penalty;unsave();decr(save_ptr);
20206 /*now |saved(0)| is the insertion number, or 255 for |vadjust|*/
20207 p=link(head);pop_nest();
20208 if (saved(0) < 255)
20209 {@+tail_append(get_node(ins_node_size));
20210 type(tail)=ins_node;subtype(tail)=qi(saved(0));
20211 height(tail)=0; ins_ptr(tail)=p; hget_stream_no(subtype(tail));
20212 split_top_ptr(tail)=q;depth(tail)=d;float_cost(tail)=f;
20213 }
20214 else{@+tail_append(get_node(small_node_size));
20215 type(tail)=adjust_node;@/
20216 subtype(tail)=0; /*the |subtype| is not used*/
20217 adjust_ptr(tail)=p;delete_glue_ref(q);
20218 }
20219 if (nest_ptr==0) build_page();
20220 } @+break;
20221 case output_group: @<Resume the page builder...@>@;@+break;
20222 case page_group: hfinish_page_group();@+break;
20223 case stream_group: hfinish_stream_group();@+break;
20224 case stream_before_group: hfinish_stream_before_group();@+break;
20225 case stream_after_group: hfinish_stream_after_group();@+break;
20226 case outline_group: hfinish_outline_group();@+break;
20227
20228 @ @<Declare act...@>=
20229 static void make_mark(void)
20230 {@+pointer p; /*new node*/
20231 halfword @!c; /*the mark class*/
20232 if (cur_chr==0) c=0;
20233 else{@+scan_register_num();c=cur_val;
20234 }
20235 p=scan_toks(false, true);p=get_node(small_node_size);
20236 mark_class(p)=c;
20237 type(p)=mark_node;subtype(p)=0; /*the |subtype| is not used*/
20238 mark_ptr(p)=def_ref;link(tail)=p;tail=p;
20239 }
20240
20241 @ Penalty nodes get into a list via the |break_penalty| command.
20242 @^penalties@>
20243
20244 @<Cases of |main_control| that build...@>=
20245 any_mode(break_penalty): append_penalty();@+break;
20246
20247 @ @<Declare action...@>=
20248 static void append_penalty(void)
20249 {@+scan_int();tail_append(new_penalty(cur_val));
20250 if (mode==vmode) build_page();
20251 }
20252
20253 @ The |remove_item| command removes a penalty, kern, or glue node if it
20254 appears at the tail of the current list, using a brute-force linear scan.
20255 Like \.{\\lastbox}, this command is not allowed in vertical mode (except
20256 internal vertical mode), since the current list in vertical mode is sent
20257 to the page builder. But if we happen to be able to implement it in
20258 vertical mode, we do.
20259
20260 @<Cases of |main_control| that build...@>=
20261 any_mode(remove_item): delete_last();@+break;
20262
20263 @ When |delete_last| is called, |cur_chr| is the |type| of node that
20264 will be deleted, if present.
20265
20266 @<Declare action...@>=
20267 static void delete_last(void)
20268 {@+
20269 pointer @!p, @!q; /*run through the current list*/
20270 int @!m; /*the length of a replacement list*/
20271 if ((mode==vmode)&&(tail==head))
20272 @<Apologize for inability to do the operation now, unless \.{\\unskip} follows
20273 non-glue@>@;
20274 else{@+if (!is_char_node(tail)) if (type(tail)==cur_chr)
20275 {@+q=head;
20276 @/do@+{p=q;
20277 if (!is_char_node(q)) if (type(q)==disc_node)
20278 {@+for (m=1; m<=replace_count(q); m++) p=link(p);
20279 if (p==tail) return;
20280 }
20281 q=link(p);
20282 }@+ while (!(q==tail));
20283 link(p)=null;flush_node_list(tail);tail=p;
20284 }
20285 }
20286 }
20287
20288 @ @<Apologize for inability to do the operation...@>=
20289 {@+if ((cur_chr!=glue_node)||(last_glue!=max_halfword))
20290 {@+you_cant();
20291 help2("Sorry...I usually can't take things from the current page.",@/
20292 "Try `I\\vskip-\\lastskip' instead.");
20293 if (cur_chr==kern_node) help_line[0]=
20294 ("Try `I\\kern-\\lastkern' instead.");
20295 else if (cur_chr!=glue_node) help_line[0]=@|
20296 ("Perhaps you can make the output routine do it.");
20297 error();
20298 }
20299 }
20300
20301 @ @<Put each...@>=
20302 primitive("unpenalty", remove_item, penalty_node);@/
20303 @!@:un\_penalty\_}{\.{\\unpenalty} primitive@>
20304 primitive("unkern", remove_item, kern_node);@/
20305 @!@:un\_kern\_}{\.{\\unkern} primitive@>
20306 primitive("unskip", remove_item, glue_node);@/
20307 @!@:un\_skip\_}{\.{\\unskip} primitive@>
20308 primitive("unhbox", un_hbox, box_code);@/
20309 @!@:un\_hbox\_}{\.{\\unhbox} primitive@>
20310 primitive("unhcopy", un_hbox, copy_code);@/
20311 @!@:un\_hcopy\_}{\.{\\unhcopy} primitive@>
20312 primitive("unvbox", un_vbox, box_code);@/
20313 @!@:un\_vbox\_}{\.{\\unvbox} primitive@>
20314 primitive("unvcopy", un_vbox, copy_code);@/
20315 @!@:un\_vcopy\_}{\.{\\unvcopy} primitive@>
20316
20317 @ @<Cases of |print_cmd_chr|...@>=
20318 case remove_item: if (chr_code==glue_node) print_esc("unskip");
20319 else if (chr_code==kern_node) print_esc("unkern");
20320 else print_esc("unpenalty");@+break;
20321 case un_hbox: if (chr_code==copy_code) print_esc("unhcopy");
20322 else print_esc("unhbox");@+break;
20323 case un_vbox: if (chr_code==copy_code) print_esc("unvcopy")
20324 @<Cases of |un_vbox| for |print_cmd_chr|@>;@/
20325 else print_esc("unvbox");@+break;
20326
20327 @ The |un_hbox| and |un_vbox| commands unwrap one of the 256 current boxes.
20328
20329 @<Cases of |main_control| that build...@>=
20330 case vmode+un_vbox: case hmode+un_hbox:
20331 case mmode+un_hbox: unpackage();@+break;
20332
20333 @ @<Declare act...@>=
20334 static void unpackage(void)
20335 {@+
20336 pointer p; /*the box*/
20337 int @!c; /*should we copy?*/
20338 if (cur_chr > copy_code) @<Handle saved items and |goto done|@>;
20339 c=cur_chr;scan_register_num();fetch_box(p);
20340 if (p==null) return;
20341 if ((abs(mode)==mmode)||@|
20342 ((abs(mode)==vmode)&& (type(p)!=vlist_node)
20343 && (type(p)!=whatsit_node || (subtype(p)!=vset_node
20344 && subtype(p)!=vpack_node))) ||@|
20345 ((abs(mode)==hmode)&& (type(p)!=hlist_node)
20346 && (type(p)!=whatsit_node || ( subtype(p)!=hset_node
20347 && subtype(p)!=hpack_node))))
20348 {@+print_err("Incompatible list can't be unboxed");
20349 @.Incompatible list...@>
20350 help3("Sorry, Pandora. (You sneaky devil.)",@/
20351 "I refuse to unbox an \\hbox in vertical mode or vice versa.",@/
20352 "And I can't open any boxes in math mode.");@/
20353 error();return;
20354 }
20355 if (c==copy_code) link(tail)=copy_node_list(list_ptr(p));
20356 else{@+link(tail)=list_ptr(p);change_box(null);
20357 list_ptr(p)=null;flush_node_list(p);
20358 }
20359 done:
20360 while (link(tail)!=null) tail=link(tail);
20361 }
20362
20363 @ @<Forbidden...@>=case vmode+ital_corr:
20364
20365 @ Italic corrections are converted to kern nodes when the |ital_corr| command
20366 follows a character. In math mode the same effect is achieved by appending
20367 a kern of zero here, since italic corrections are supplied later.
20368
20369 @<Cases of |main_control| that build...@>=
20370 case hmode+ital_corr: append_italic_correction();@+break;
20371 case mmode+ital_corr: tail_append(new_kern(0))@;@+break;
20372
20373 @ @<Declare act...@>=
20374 static void append_italic_correction(void)
20375 {@+
20376 pointer p; /*|char_node| at the tail of the current list*/
20377 internal_font_number @!f; /*the font in the |char_node|*/
20378 if (tail!=head)
20379 {@+if (is_char_node(tail)) p=tail;
20380 else if (type(tail)==ligature_node) p=lig_char(tail);
20381 else return;
20382 f=font(p);
20383 tail_append(new_kern(char_italic(f, character(p))));
20384 subtype(tail)=explicit;
20385 }
20386 }
20387
20388 @ Discretionary nodes are easy in the common case `\.{\\-}', but in the
20389 general case we must process three braces full of items.
20390
20391 @<Put each...@>=
20392 primitive("-", discretionary, 1);
20393 @!@:Single-character primitives -}{\quad\.{\\-}@>
20394 primitive("discretionary", discretionary, 0);
20395 @!@:discretionary\_}{\.{\\discretionary} primitive@>
20396
20397 @ @<Cases of |print_cmd_chr|...@>=
20398 case discretionary: if (chr_code==1)
20399 print_esc("-");@+else print_esc("discretionary");@+break;
20400
20401 @ @<Cases of |main_control| that build...@>=
20402 case hmode+discretionary: case mmode+discretionary: append_discretionary();@+break;
20403
20404 @ The space factor does not change when we append a discretionary node,
20405 but it starts out as 1000 in the subsidiary lists.
20406
20407 @<Declare act...@>=
20408 static void append_discretionary(void)
20409 {@+int c; /*hyphen character*/
20410 tail_append(new_disc());
20411 if (cur_chr==1)
20412 {@+c=hyphen_char[cur_font];
20413 if (c >= 0) if (c < 256) pre_break(tail)=new_character(cur_font, c);
20414 }
20415 else{@+incr(save_ptr);saved(-1)=0;new_save_level(disc_group);
20416 scan_left_brace();push_nest();mode=-hmode;space_factor=1000;
20417 }
20418 }
20419
20420 @ The three discretionary lists are constructed somewhat as if they were
20421 hboxes. A~subroutine called |build_discretionary| handles the transitions.
20422 (This is sort of fun.)
20423
20424 @<Cases of |handle...@>=
20425 case disc_group: build_discretionary();@+break;
20426
20427 @ @<Declare act...@>=
20428 static void build_discretionary(void)
20429 {@+
20430 pointer p, @!q; /*for link manipulation*/
20431 int @!n; /*length of discretionary list*/
20432 unsave();
20433 @<Prune the current list, if necessary, until it contains only |char_node|,
20434 |kern_node|, |hlist_node|, |vlist_node|, |rule_node|, and |ligature_node|
20435 items; set |n| to the length of the list, and set |q| to the list's tail@>;
20436 p=link(head);pop_nest();
20437 switch (saved(-1)) {
20438 case 0: pre_break(tail)=p;@+break;
20439 case 1: post_break(tail)=p;@+break;
20440 case 2: @<Attach list |p| to the current list, and record its length; then
20441 finish up and |return|@>;
20442 } /*there are no other cases*/
20443 incr(saved(-1));new_save_level(disc_group);scan_left_brace();
20444 push_nest();mode=-hmode;space_factor=1000;
20445 }
20446
20447 @ @<Attach list |p| to the current...@>=
20448 {@+if ((n > 0)&&(abs(mode)==mmode))
20449 {@+print_err("Illegal math ");print_esc("discretionary");
20450 @.Illegal math \\disc...@>
20451 help2("Sorry: The third part of a discretionary break must be",@/
20452 "empty, in math formulas. I had to delete your third part.");
20453 flush_node_list(p);n=0;error();
20454 }
20455 else link(tail)=p;
20456 if (n <= 0x7F) set_replace_count(tail,n);
20457 else{@+print_err("Discretionary list is too long");
20458 @.Discretionary list is too long@>
20459 help2("Wow---I never thought anybody would tweak me here.",@/
20460 "You can't seriously need such a huge discretionary list?");
20461 error();
20462 }
20463 if (n > 0) tail=q;
20464 decr(save_ptr);return;
20465 }
20466
20467 @ During this loop, |p==link(q)| and there are |n| items preceding |p|.
20468
20469 @<Prune the current list, if necessary...@>=
20470 q=head;p=link(q);n=0;
20471 while (p!=null)
20472 {@+if (!is_char_node(p)) if (type(p) > rule_node)
20473 if (type(p)!=kern_node) if (type(p)!=ligature_node)
20474 {@+print_err("Improper discretionary list");
20475 @.Improper discretionary list@>
20476 help1("Discretionary lists must contain only boxes and kerns.");@/
20477 error();
20478 begin_diagnostic();
20479 print_nl("The following discretionary sublist has been deleted:");
20480 @.The following...deleted@>
20481 show_box(p);
20482 end_diagnostic(true);
20483 flush_node_list(p);link(q)=null;goto done;
20484 }
20485 q=p;p=link(q);incr(n);
20486 }
20487 done:
20488
20489 @ We need only one more thing to complete the horizontal mode routines, namely
20490 the \.{\\accent} primitive.
20491
20492 @<Cases of |main_control| that build...@>=
20493 case hmode+accent: make_accent();@+break;
20494
20495 @ The positioning of accents is straightforward but tedious. Given an accent
20496 of width |a|, designed for characters of height |x| and slant |s|;
20497 and given a character of width |w|, height |h|, and slant |t|: We will shift
20498 the accent down by |x-h|, and we will insert kern nodes that have the effect of
20499 centering the accent over the character and shifting the accent to the
20500 right by $\delta={1\over2}(w-a)+h\cdot t-x\cdot s$. If either character is
20501 absent from the font, we will simply use the other, without shifting.
20502
20503 @<Declare act...@>=
20504 static void make_accent(void)
20505 {@+double s, @!t; /*amount of slant*/
20506 pointer @!p, @!q, @!r; /*character, box, and kern nodes*/
20507 internal_font_number @!f; /*relevant font*/
20508 scaled @!a, @!h, @!x, @!w, @!delta; /*heights and widths, as explained above*/
20509 scan_char_num();f=cur_font;p=new_character(f, cur_val);
20510 if (p!=null)
20511 {@+x=x_height(f);s=slant(f)/float_constant(65536);
20512 @^real division@>
20513 a=char_width(f, character(p));@/
20514 do_assignments();@/
20515 @<Create a character node |q| for the next character, but set |q:=null|
20516 if problems arise@>;
20517 if (q!=null) @<Append the accent with appropriate kerns, then set |p:=q|@>;
20518 link(tail)=p;tail=p;space_factor=1000;
20519 }
20520 }
20521
20522 @ @<Create a character node |q| for the next...@>=
20523 q=null;f=cur_font;
20524 if ((cur_cmd==letter)||(cur_cmd==other_char)||(cur_cmd==char_given))
20525 q=new_character(f, cur_chr);
20526 else if (cur_cmd==char_num)
20527 {@+scan_char_num();q=new_character(f, cur_val);
20528 }
20529 else back_input()
20530
20531 @ The kern nodes appended here must be distinguished from other kerns, lest
20532 they be wiped away by the hyphenation algorithm or by a previous line break.
20533
20534 The two kerns are computed with (machine-dependent) |double| arithmetic, but
20535 their sum is machine-independent; the net effect is machine-independent,
20536 because the user cannot remove these nodes nor access them via \.{\\lastkern}.
20537
20538 @<Append the accent with appropriate kerns...@>=
20539 {@+t=slant(f)/float_constant(65536);
20540 @^real division@>
20541 if (IS_X_FONT(f))
20542 { hb_codepoint_t glyph;
20543 if (x_glyph(f,character(q),&glyph))
20544 { scaled dummy;
20545 w=x_glyph_width(f,glyph);
20546 x_glyph_height_depth(f,glyph,&h,&dummy);
20547 }
20548 else
20549 w=h=0;
20550 }
20551 else
20552 { w=char_width(f, character(q));h=char_height(f, character(q));}
20553 if (h!=x) /*the accent must be shifted up or down*/
20554 {@+p=hpack(p, natural);shift_amount(p)=x-h;
20555 }
20556 delta=round((w-a)/float_constant(2)+h*t-x*s);
20557 @^real multiplication@>
20558 @^real addition@>
20559 r=new_kern(delta);subtype(r)=acc_kern;link(tail)=r;link(r)=p;
20560 tail=new_kern(-a-delta);subtype(tail)=acc_kern;link(p)=tail;p=q;
20561 }
20562
20563 @ When `\.{\\cr}' or `\.{\\span}' or a tab mark comes through the scanner
20564 into |main_control|, it might be that the user has foolishly inserted
20565 one of them into something that has nothing to do with alignment. But it is
20566 far more likely that a left brace or right brace has been omitted, since
20567 |get_next| takes actions appropriate to alignment only when `\.{\\cr}'
20568 or `\.{\\span}' or tab marks occur with |align_state==0|. The following
20569 program attempts to make an appropriate recovery.
20570
20571 @<Cases of |main_control| that build...@>=
20572 any_mode(car_ret): any_mode(tab_mark): align_error();@+break;
20573 any_mode(no_align): no_align_error();@+break;
20574 any_mode(omit): omit_error();@+break;
20575
20576 @ @<Declare act...@>=
20577 static void align_error(void)
20578 {@+if (abs(align_state) > 2)
20579 @<Express consternation over the fact that no alignment is in progress@>@;
20580 else{@+back_input();
20581 if (align_state < 0)
20582 {@+print_err("Missing { inserted");
20583 @.Missing \{ inserted@>
20584 incr(align_state);cur_tok=left_brace_token+'{';
20585 }
20586 else{@+print_err("Missing } inserted");
20587 @.Missing \} inserted@>
20588 decr(align_state);cur_tok=right_brace_token+'}';
20589 }
20590 help3("I've put in what seems to be necessary to fix",@/
20591 "the current column of the current alignment.",@/
20592 "Try to go on, since this might almost work.");ins_error();
20593 }
20594 }
20595
20596 @ @<Express consternation...@>=
20597 {@+print_err("Misplaced ");print_cmd_chr(cur_cmd, cur_chr);
20598 @.Misplaced \&@>
20599 @.Misplaced \\span@>
20600 @.Misplaced \\cr@>
20601 if (cur_tok==tab_token+'&')
20602 {@+help6("I can't figure out why you would want to use a tab mark",@/
20603 "here. If you just want an ampersand, the remedy is",@/
20604 "simple: Just type `I\\&' now. But if some right brace",@/
20605 "up above has ended a previous alignment prematurely,",@/
20606 "you're probably due for more error messages, and you",@/
20607 "might try typing `S' now just to see what is salvageable.");
20608 }
20609 else{@+help5("I can't figure out why you would want to use a tab mark",@/
20610 "or \\cr or \\span just now. If something like a right brace",@/
20611 "up above has ended a previous alignment prematurely,",@/
20612 "you're probably due for more error messages, and you",@/
20613 "might try typing `S' now just to see what is salvageable.");
20614 }
20615 error();
20616 }
20617
20618 @ The help messages here contain a little white lie, since \.{\\noalign}
20619 and \.{\\omit} are allowed also after `\.{\\noalign\{...\}}'.
20620
20621 @<Declare act...@>=
20622 static void no_align_error(void)
20623 {@+print_err("Misplaced ");print_esc("noalign");
20624 @.Misplaced \\noalign@>
20625 help2("I expect to see \\noalign only after the \\cr of",@/
20626 "an alignment. Proceed, and I'll ignore this case.");error();
20627 }
20628 static void omit_error(void)
20629 {@+print_err("Misplaced ");print_esc("omit");
20630 @.Misplaced \\omit@>
20631 help2("I expect to see \\omit only after tab marks or the \\cr of",@/
20632 "an alignment. Proceed, and I'll ignore this case.");error();
20633 }
20634
20635 @ We've now covered most of the abuses of \.{\\halign} and \.{\\valign}.
20636 Let's take a look at what happens when they are used correctly.
20637
20638 @<Cases of |main_control| that build...@>=
20639 case vmode+halign: case hmode+valign: init_align();@+break;
20640 case mmode+halign: if (privileged())
20641 if (cur_group==math_shift_group) init_align();
20642 else off_save();@+break;
20643 case vmode+endv: case hmode+endv: do_endv();@+break;
20644
20645 @ An |align_group| code is supposed to remain on the |save_stack|
20646 during an entire alignment, until |fin_align| removes it.
20647
20648 A devious user might force an |endv| command to occur just about anywhere;
20649 we must defeat such hacks.
20650
20651 @<Declare act...@>=
20652 static void do_endv(void)
20653 {@+base_ptr=input_ptr;input_stack[base_ptr]=cur_input;
20654 while ((input_stack[base_ptr].index_field!=v_template)&&
20655 (input_stack[base_ptr].loc_field==null)&&
20656 (input_stack[base_ptr].state_field==token_list)) decr(base_ptr);
20657 if ((input_stack[base_ptr].index_field!=v_template)||
20658 (input_stack[base_ptr].loc_field!=null)||
20659 (input_stack[base_ptr].state_field!=token_list))
20660 fatal_error("(interwoven alignment preambles are not allowed)");
20661 @.interwoven alignment preambles...@>
20662 if (cur_group==align_group)
20663 {@+end_graf();
20664 if (fin_col()) fin_row();
20665 }
20666 else off_save();
20667 }
20668
20669 @ @<Cases of |handle_right_brace|...@>=
20670 case align_group: {@+back_input();cur_tok=cs_token_flag+frozen_cr;
20671 print_err("Missing ");print_esc("cr");print(" inserted");
20672 @.Missing \\cr inserted@>
20673 help1("I'm guessing that you meant to end an alignment here.");
20674 ins_error();
20675 } @+break;
20676
20677 @ @<Cases of |handle_right_brace|...@>=
20678 case no_align_group: {@+end_graf();unsave();align_peek();
20679 } @+break;
20680
20681 @ Finally, \.{\\endcsname} is not supposed to get through to |main_control|.
20682
20683 @<Cases of |main_control| that build...@>=
20684 any_mode(end_cs_name): cs_error();@+break;
20685
20686 @ @<Declare act...@>=
20687 static void cs_error(void)
20688 {@+print_err("Extra ");print_esc("endcsname");
20689 @.Extra \\endcsname@>
20690 help1("I'm ignoring this, since I wasn't doing a \\csname.");
20691 error();
20692 }
20693
20694 @* Building math lists.
20695 The routines that \TeX\ uses to create mlists are similar to those we have
20696 just seen for the generation of hlists and vlists. But it is necessary to
20697 make ``noads'' as well as nodes, so the reader should review the
20698 discussion of math mode data structures before trying to make sense out of
20699 the following program.
20700
20701 Here is a little routine that needs to be done whenever a subformula
20702 is about to be processed. The parameter is a code like |math_group|.
20703
20704 @<Declare act...@>=
20705 static void push_math(group_code @!c)
20706 {@+push_nest();mode=-mmode;incompleat_noad=null;new_save_level(c);
20707 }
20708
20709 @ We get into math mode from horizontal mode when a `\.\$' (i.e., a
20710 |math_shift| character) is scanned. We must check to see whether this
20711 `\.\$' is immediately followed by another, in case display math mode is
20712 called for.
20713
20714 @<Cases of |main_control| that build...@>=
20715 case hmode+math_shift: init_math();@+break;
20716
20717 @ @<Declare act...@>=
20718 static void init_math(void)
20719 {@+
20720 scaled w=0; /*new or partial |pre_display_size|*/
20721 scaled @!l; /*new |display_width|*/
20722 scaled @!s; /*new |display_indent|*/
20723 pointer @!p; /*current node when calculating |pre_display_size|*/
20724 int @!n; /*scope of paragraph shape specification*/
20725 get_token(); /*|get_x_token| would fail on \.{\\ifmmode}\thinspace!*/
20726 if ((cur_cmd==math_shift)&&(mode > 0)) @<Go into display math mode@>@;
20727 else{@+back_input();@<Go into ordinary math mode@>;
20728 }
20729 }
20730
20731 @ @<Go into ordinary math mode@>=
20732 {@+push_math(math_shift_group);eq_word_define(int_base+cur_fam_code,-1);
20733 if (every_math!=null) begin_token_list(every_math, every_math_text);
20734 }
20735
20736 @ We get into ordinary math mode from display math mode when `\.{\\eqno}' or
20737 `\.{\\leqno}' appears. In such cases |cur_chr| will be 0 or~1, respectively;
20738 the value of |cur_chr| is placed onto |save_stack| for safe keeping.
20739
20740 @<Cases of |main_control| that build...@>=
20741 case mmode+eq_no: if (privileged())
20742 if (cur_group==math_shift_group) start_eq_no();
20743 else off_save();@+break;
20744
20745 @ @<Put each...@>=
20746 primitive("eqno", eq_no, 0);
20747 @!@:eq\_no\_}{\.{\\eqno} primitive@>
20748 primitive("leqno", eq_no, 1);
20749 @!@:leq\_no\_}{\.{\\leqno} primitive@>
20750
20751 @ When \TeX\ is in display math mode, |cur_group==math_shift_group|,
20752 so it is not necessary for the |start_eq_no| procedure to test for
20753 this condition.
20754
20755 @<Declare act...@>=
20756 static void start_eq_no(void)
20757 {@+saved(0)=cur_chr;incr(save_ptr);
20758 @<Go into ordinary math mode@>;
20759 }
20760
20761 @ @<Cases of |print_cmd_chr|...@>=
20762 case eq_no: if (chr_code==1) print_esc("leqno");@+else print_esc("eqno");@+break;
20763
20764 @ @<Forbidden...@>=non_math(eq_no):
20765
20766 @ When we enter display math mode, we need to call |line_break| to
20767 process the partial paragraph that has just been interrupted by the
20768 display. Then we can set the proper values of |display_width| and
20769 |display_indent| and |pre_display_size|.
20770
20771 @<Go into display math mode@>=
20772 { if (head!=tail && !(type(tail)==whatsit_node && subtype(tail)==disp_node))
20773 { if (is_char_node(tail)) tail_append(new_penalty(inf_penalty))@;
20774 else if (type(tail)!=glue_node) tail_append(new_penalty(inf_penalty))@;
20775 else
20776 {@+type(tail)=penalty_node;delete_glue_ref(glue_ptr(tail));
20777 flush_node_list(leader_ptr(tail));penalty(tail)=inf_penalty;
20778 }
20779 tail_append(new_param_glue(par_fill_skip_code));
20780 }
20781 @<Calculate the length, |l|, and the shift amount, |s|, of the display lines@>;
20782 push_math(math_shift_group);mode=mmode;
20783 eq_word_define(int_base+cur_fam_code,-1);@/
20784 eq_word_define(dimen_base+display_width_code, l); cur_hfactor=0;
20785 eq_word_define(dimen_base+pre_display_size_code, w);
20786 eq_word_define(dimen_base+display_indent_code, s);
20787 if (every_display!=null) begin_token_list(every_display, every_display_text);
20788 }
20789
20790 @ A displayed equation is considered to be three lines long, so we
20791 calculate the length and offset of line number |prev_graf+2|.
20792
20793 @<Calculate the length, |l|,...@>=
20794 if (par_shape_ptr==null)
20795 if ((hang_indent!=0)&&@|
20796 (((hang_after >= 0)&&(prev_graf+2 > hang_after))||@|
20797 (prev_graf+1 < -hang_after)))
20798 {@+l=-abs(hang_indent); cur_hfactor=unity;
20799 if (hang_indent > 0) s=hang_indent;@+else s=0;
20800 }
20801 else{@+l=0;s=0; cur_hfactor=unity;
20802 }
20803 else{@+n=info(par_shape_ptr);
20804 if (prev_graf+2 >= n) p=par_shape_ptr+2*n;
20805 else p=par_shape_ptr+2*(prev_graf+2);
20806 s=mem[p-1].sc;l=mem[p].sc;cur_hfactor=0;
20807 }
20808
20809 @ Subformulas of math formulas cause a new level of math mode to be entered,
20810 on the semantic nest as well as the save stack. These subformulas arise in
20811 several ways: (1)~A left brace by itself indicates the beginning of a
20812 subformula that will be put into a box, thereby freezing its glue and
20813 preventing line breaks. (2)~A subscript or superscript is treated as a
20814 subformula if it is not a single character; the same applies to
20815 the nucleus of things like \.{\\underline}. (3)~The \.{\\left} primitive
20816 initiates a subformula that will be terminated by a matching \.{\\right}.
20817 The group codes placed on |save_stack| in these three cases are
20818 |math_group|, |math_group|, and |math_left_group|, respectively.
20819
20820 Here is the code that handles case (1); the other cases are not quite as
20821 trivial, so we shall consider them later.
20822
20823 @<Cases of |main_control| that build...@>=
20824 case mmode+left_brace: {@+tail_append(new_noad());
20825 back_input();scan_math(nucleus(tail));
20826 } @+break;
20827
20828 @ Recall that the |nucleus|, |subscr|, and |supscr| fields in a noad are
20829 broken down into subfields called |math_type| and either |info| or
20830 |(fam, character)|. The job of |scan_math| is to figure out what to place
20831 in one of these principal fields; it looks at the subformula that
20832 comes next in the input, and places an encoding of that subformula
20833 into a given word of |mem|.
20834
20835 @d fam_in_range ((cur_fam >= 0)&&(cur_fam < 16))
20836
20837 @<Declare act...@>=
20838 static void scan_math(pointer @!p)
20839 {@+
20840 int c; /*math character code*/
20841 restart: @<Get the next non-blank non-relax...@>;
20842 reswitch: switch (cur_cmd) {
20843 case letter: case other_char: case char_given: {@+c=ho(math_code(cur_chr));
20844 if (c==active_math_character_code)
20845 {@+@<Treat |cur_chr| as an active character@>;
20846 goto restart;
20847 }
20848 } @+break;
20849 case char_num: {@+scan_char_num();cur_chr=cur_val;cur_cmd=char_given;
20850 goto reswitch;
20851 }
20852 case math_char_num: {@+scan_fifteen_bit_int(); math_to_Umath(cur_val); c=cur_val;
20853 } @+break;
20854 case math_given: c=cur_chr;@+break;
20855 case delim_num: {@+scan_twenty_seven_bit_int();c=cur_val/010000; math_to_Umath(c);
20856 } @+break;
20857 default:@<Scan a subformula enclosed in braces and |return|@>@;
20858 } @/
20859 math_type(p)=math_char;character(p)=math_code_char(c);
20860 if ((math_code_class(c) >= 7)&&fam_in_range) fam(p)=cur_fam;
20861 else fam(p)=math_code_fam(c);
20862 }
20863
20864 @ An active character that is an |outer_call| is allowed here.
20865
20866 @<Treat |cur_chr|...@>=
20867 {@+ if (cur_chr<utf8_single_size)
20868 cur_cs=cur_chr+active_base;
20869 else
20870 cur_cs=active_lookup(cur_chr);
20871 cur_cmd=eq_type(cur_cs);cur_chr=equiv(cur_cs);
20872 x_token();back_input();
20873 }
20874
20875 @ The pointer |p| is placed on |save_stack| while a complex subformula
20876 is being scanned.
20877
20878 @<Scan a subformula...@>=
20879 {@+back_input();scan_left_brace();@/
20880 saved(0)=p;incr(save_ptr);push_math(math_group);return;
20881 }
20882
20883 @ The simplest math formula is, of course, `\.{\${ }\$}', when no noads are
20884 generated. The next simplest cases involve a single character, e.g.,
20885 `\.{\$x\$}'. Even though such cases may not seem to be very interesting,
20886 the reader can perhaps understand how happy the author was when `\.{\$x\$}'
20887 was first properly typeset by \TeX. The code in this section was used.
20888 @^Knuth, Donald Ervin@>
20889
20890 @<Cases of |main_control| that build...@>=
20891 case mmode+letter: case mmode+other_char:
20892 case mmode+char_given:
20893 set_math_char(ho(math_code(cur_chr)));@+break;
20894 case mmode+char_num: {@+scan_char_num();cur_chr=cur_val;
20895 set_math_char(ho(math_code(cur_chr)));
20896 } @+break;
20897 case mmode+math_char_num: {@+scan_fifteen_bit_int(); math_to_Umath(cur_val); set_math_char(cur_val);
20898 } @+break;
20899 case mmode+math_given: set_math_char(cur_chr);@+break;
20900 case mmode+delim_num: {@+scan_twenty_seven_bit_int(); cur_val=cur_val/010000; math_to_Umath(cur_val);
20901 set_math_char(cur_val);
20902 } @+break;
20903
20904 @ The |set_math_char| procedure creates a new noad appropriate to a given
20905 math code, and appends it to the current mlist. However, if the math code
20906 is sufficiently large, the |cur_chr| is treated as an active character and
20907 nothing is appended.
20908
20909 @<Declare act...@>=
20910 static void set_math_char(int @!c)
20911 {@+pointer p; /*the new noad*/
20912 if (c == active_math_character_code)
20913 @<Treat |cur_chr|...@>@;
20914 else{@+p=new_noad();math_type(nucleus(p))=math_char;
20915 character(nucleus(p))=math_code_char(c);
20916 fam(nucleus(p))=math_code_fam(c);
20917 if (math_code_class(c) >= 7)
20918 {@+if (fam_in_range) fam(nucleus(p))=cur_fam;
20919 type(p)=ord_noad;
20920 }
20921 else type(p)=ord_noad+math_code_class(c);
20922 link(tail)=p;tail=p;
20923 }
20924 }
20925
20926 @ Primitive math operators like \.{\\mathop} and \.{\\underline} are given
20927 the command code |math_comp|, supplemented by the noad type that they
20928 generate.
20929
20930 @<Put each...@>=
20931 primitive("mathord", math_comp, ord_noad);
20932 @!@:math\_ord\_}{\.{\\mathord} primitive@>
20933 primitive("mathop", math_comp, op_noad);
20934 @!@:math\_op\_}{\.{\\mathop} primitive@>
20935 primitive("mathbin", math_comp, bin_noad);
20936 @!@:math\_bin\_}{\.{\\mathbin} primitive@>
20937 primitive("mathrel", math_comp, rel_noad);
20938 @!@:math\_rel\_}{\.{\\mathrel} primitive@>
20939 primitive("mathopen", math_comp, open_noad);
20940 @!@:math\_open\_}{\.{\\mathopen} primitive@>
20941 primitive("mathclose", math_comp, close_noad);
20942 @!@:math\_close\_}{\.{\\mathclose} primitive@>
20943 primitive("mathpunct", math_comp, punct_noad);
20944 @!@:math\_punct\_}{\.{\\mathpunct} primitive@>
20945 primitive("mathinner", math_comp, inner_noad);
20946 @!@:math\_inner\_}{\.{\\mathinner} primitive@>
20947 primitive("underline", math_comp, under_noad);
20948 @!@:underline\_}{\.{\\underline} primitive@>
20949 primitive("overline", math_comp, over_noad);@/
20950 @!@:overline\_}{\.{\\overline} primitive@>
20951 primitive("displaylimits", limit_switch, normal);
20952 @!@:display\_limits\_}{\.{\\displaylimits} primitive@>
20953 primitive("limits", limit_switch, limits);
20954 @!@:limits\_}{\.{\\limits} primitive@>
20955 primitive("nolimits", limit_switch, no_limits);
20956 @!@:no\_limits\_}{\.{\\nolimits} primitive@>
20957
20958 @ @<Cases of |print_cmd_chr|...@>=
20959 case math_comp: switch (chr_code) {
20960 case ord_noad: print_esc("mathord");@+break;
20961 case op_noad: print_esc("mathop");@+break;
20962 case bin_noad: print_esc("mathbin");@+break;
20963 case rel_noad: print_esc("mathrel");@+break;
20964 case open_noad: print_esc("mathopen");@+break;
20965 case close_noad: print_esc("mathclose");@+break;
20966 case punct_noad: print_esc("mathpunct");@+break;
20967 case inner_noad: print_esc("mathinner");@+break;
20968 case under_noad: print_esc("underline");@+break;
20969 default:print_esc("overline");
20970 } @+break;
20971 case limit_switch: if (chr_code==limits) print_esc("limits");
20972 else if (chr_code==no_limits) print_esc("nolimits");
20973 else print_esc("displaylimits");@+break;
20974
20975 @ @<Cases of |main_control| that build...@>=
20976 case mmode+math_comp: {@+tail_append(new_noad());
20977 type(tail)=cur_chr;scan_math(nucleus(tail));
20978 } @+break;
20979 case mmode+limit_switch: math_limit_switch();@+break;
20980
20981 @ @<Declare act...@>=
20982 static void math_limit_switch(void)
20983 {@+
20984 if (head!=tail) if (type(tail)==op_noad)
20985 {@+subtype(tail)=cur_chr;return;
20986 }
20987 print_err("Limit controls must follow a math operator");
20988 @.Limit controls must follow...@>
20989 help1("I'm ignoring this misplaced \\limits or \\nolimits command.");error();
20990 }
20991
20992 @ Delimiter fields of noads are filled in by the |scan_delimiter| routine.
20993 The first parameter of this procedure is the |mem| address where the
20994 delimiter is to be placed; the second tells if this delimiter follows
20995 \.{\\radical} or not.
20996
20997 @<Declare act...@>=
20998 static void scan_delimiter(pointer @!p, bool @!r)
20999 {@+if (r) scan_twenty_seven_bit_int();
21000 else{@+@<Get the next non-blank non-relax...@>;
21001 switch (cur_cmd) {
21002 case letter: case other_char: cur_val=del_code(cur_chr);@+break;
21003 case delim_num: scan_twenty_seven_bit_int();@+break;
21004 default:cur_val=-1;
21005 }
21006 }
21007 if (cur_val < 0) @<Report that an invalid delimiter code is being changed
21008 to null; set~|cur_val:=0|@>;
21009 small_fam(p)=(cur_val/04000000)%16;
21010 small_char(p)=qi((cur_val/010000)%256);
21011 large_fam(p)=(cur_val/256)%16;
21012 large_char(p)=qi(cur_val%256);
21013 }
21014
21015 @ @<Report that an invalid delimiter...@>=
21016 {@+print_err("Missing delimiter (. inserted)");
21017 @.Missing delimiter...@>
21018 help6("I was expecting to see something like `(' or `\\{' or",@/
21019 "`\\}' here. If you typed, e.g., `{' instead of `\\{', you",@/
21020 "should probably delete the `{' by typing `1' now, so that",@/
21021 "braces don't get unbalanced. Otherwise just proceed.",@/
21022 "Acceptable delimiters are characters whose \\delcode is",@/
21023 "nonnegative, or you can use `\\delimiter <delimiter code>'.");
21024 back_error();cur_val=0;
21025 }
21026
21027 @ @<Cases of |main_control| that build...@>=
21028 case mmode+radical: math_radical();@+break;
21029
21030 @ @<Declare act...@>=
21031 static void math_radical(void)
21032 {@+tail_append(get_node(radical_noad_size));
21033 type(tail)=radical_noad;subtype(tail)=normal;
21034 mem[nucleus(tail)].hh=empty_field;
21035 mem[subscr(tail)].hh=empty_field;
21036 mem[supscr(tail)].hh=empty_field;
21037 scan_delimiter(left_delimiter(tail), true);scan_math(nucleus(tail));
21038 }
21039
21040 @ @<Cases of |main_control| that build...@>=
21041 case mmode+accent: case mmode+math_accent: math_ac();@+break;
21042
21043 @ @<Declare act...@>=
21044 static void math_ac(void)
21045 {@+if (cur_cmd==accent)
21046 @<Complain that the user should have said \.{\\mathaccent}@>;
21047 tail_append(get_node(accent_noad_size));
21048 type(tail)=accent_noad;subtype(tail)=normal;
21049 mem[nucleus(tail)].hh=empty_field;
21050 mem[subscr(tail)].hh=empty_field;
21051 mem[supscr(tail)].hh=empty_field;
21052 math_type(accent_chr(tail))=math_char;
21053 scan_fifteen_bit_int();
21054 character(accent_chr(tail))=cur_val&0xFF;
21055 if ((cur_val >= 0x7000)&&fam_in_range) fam(accent_chr(tail))=cur_fam;
21056 else fam(accent_chr(tail))=(cur_val>>8)&0xF;
21057 scan_math(nucleus(tail));
21058 }
21059
21060 @ @<Complain that the user should have said \.{\\mathaccent}@>=
21061 {@+print_err("Please use ");print_esc("mathaccent");
21062 print(" for accents in math mode");
21063 @.Please use \\mathaccent...@>
21064 help2("I'm changing \\accent to \\mathaccent here; wish me luck.",@/
21065 "(Accents are not the same in formulas as they are in text.)");
21066 error();
21067 }
21068
21069 @ @<Cases of |main_control| that build...@>=
21070 case mmode+vcenter: {@+scan_spec(vcenter_group, false);normal_paragraph();
21071 push_nest();mode=-vmode;prev_depth=ignore_depth;
21072 if (every_vbox!=null) begin_token_list(every_vbox, every_vbox_text);
21073 } @+break;
21074
21075 @ @<Cases of |handle...@>=
21076 case vcenter_group: {@+end_graf();unsave();save_ptr=save_ptr-2;
21077 p=vpack(link(head), saved(1), saved_hfactor(1), saved_vfactor(1), saved(0), false);pop_nest();
21078 tail_append(new_noad());type(tail)=vcenter_noad;
21079 math_type(nucleus(tail))=sub_box;info(nucleus(tail))=p;
21080 } @+break;
21081
21082 @ The routine that inserts a |style_node| holds no surprises.
21083
21084 @<Put each...@>=
21085 primitive("displaystyle", math_style, display_style);
21086 @!@:display\_style\_}{\.{\\displaystyle} primitive@>
21087 primitive("textstyle", math_style, text_style);
21088 @!@:text\_style\_}{\.{\\textstyle} primitive@>
21089 primitive("scriptstyle", math_style, script_style);
21090 @!@:script\_style\_}{\.{\\scriptstyle} primitive@>
21091 primitive("scriptscriptstyle", math_style, script_script_style);
21092 @!@:script\_script\_style\_}{\.{\\scriptscriptstyle} primitive@>
21093
21094 @ @<Cases of |print_cmd_chr|...@>=
21095 case math_style: print_style(chr_code);@+break;
21096
21097 @ @<Cases of |main_control| that build...@>=
21098 case mmode+math_style: tail_append(new_style(cur_chr))@;@+break;
21099 case mmode+non_script: {@+tail_append(new_glue(zero_glue));
21100 subtype(tail)=cond_math_glue;
21101 } @+break;
21102 case mmode+math_choice: append_choices();@+break;
21103
21104 @ The routine that scans the four mlists of a \.{\\mathchoice} is very
21105 much like the routine that builds discretionary nodes.
21106
21107 @<Declare act...@>=
21108 static void append_choices(void)
21109 {@+tail_append(new_choice());incr(save_ptr);saved(-1)=0;
21110 push_math(math_choice_group);scan_left_brace();
21111 }
21112
21113 @ @<Cases of |handle_right_brace|...@>=
21114 case math_choice_group: build_choices();@+break;
21115
21116 @ @<Declare act...@>=
21117 @t\4@>@<Declare the function called |fin_mlist|@>@t@>@;@/
21118 static void build_choices(void)
21119 {@+
21120 pointer p; /*the current mlist*/
21121 unsave();p=fin_mlist(null);
21122 switch (saved(-1)) {
21123 case 0: display_mlist(tail)=p;@+break;
21124 case 1: text_mlist(tail)=p;@+break;
21125 case 2: script_mlist(tail)=p;@+break;
21126 case 3: {@+script_script_mlist(tail)=p;decr(save_ptr);return;
21127 }
21128 } /*there are no other cases*/
21129 incr(saved(-1));push_math(math_choice_group);scan_left_brace();
21130 }
21131
21132 @ Subscripts and superscripts are attached to the previous nucleus by the
21133 @^superscripts@>@^subscripts@>
21134 action procedure called |sub_sup|. We use the facts that |sub_mark==sup_mark+1|
21135 and |subscr(p)==supscr(p)+1|.
21136
21137 @<Cases of |main_control| that build...@>=
21138 case mmode+sub_mark: case mmode+sup_mark: sub_sup();@+break;
21139
21140 @ @<Declare act...@>=
21141 static void sub_sup(void)
21142 {@+small_number t; /*type of previous sub/superscript*/
21143 pointer @!p; /*field to be filled by |scan_math|*/
21144 t=empty;p=null;
21145 if (tail!=head) if (scripts_allowed(tail))
21146 {@+p=supscr(tail)+cur_cmd-sup_mark; /*|supscr| or |subscr|*/
21147 t=math_type(p);
21148 }
21149 if ((p==null)||(t!=empty)) @<Insert a dummy noad to be sub/superscripted@>;
21150 scan_math(p);
21151 }
21152
21153 @ @<Insert a dummy...@>=
21154 {@+tail_append(new_noad());
21155 p=supscr(tail)+cur_cmd-sup_mark; /*|supscr| or |subscr|*/
21156 if (t!=empty)
21157 {@+if (cur_cmd==sup_mark)
21158 {@+print_err("Double superscript");
21159 @.Double superscript@>
21160 help1("I treat `x^1^2' essentially like `x^1{}^2'.");
21161 }
21162 else{@+print_err("Double subscript");
21163 @.Double subscript@>
21164 help1("I treat `x_1_2' essentially like `x_1{}_2'.");
21165 }
21166 error();
21167 }
21168 }
21169
21170 @ An operation like `\.{\\over}' causes the current mlist to go into a
21171 state of suspended animation: |incompleat_noad| points to a |fraction_noad|
21172 that contains the mlist-so-far as its numerator, while the denominator
21173 is yet to come. Finally when the mlist is finished, the denominator will
21174 go into the incompleat fraction noad, and that noad will become the
21175 whole formula, unless it is surrounded by `\.{\\left}' and `\.{\\right}'
21176 delimiters.
21177
21178 @d above_code 0 /* `\.{\\above}' */
21179 @d over_code 1 /* `\.{\\over}' */
21180 @d atop_code 2 /* `\.{\\atop}' */
21181 @d delimited_code 3 /* `\.{\\abovewithdelims}', etc.*/
21182
21183 @<Put each...@>=
21184 primitive("above", above, above_code);@/
21185 @!@:above\_}{\.{\\above} primitive@>
21186 primitive("over", above, over_code);@/
21187 @!@:over\_}{\.{\\over} primitive@>
21188 primitive("atop", above, atop_code);@/
21189 @!@:atop\_}{\.{\\atop} primitive@>
21190 primitive("abovewithdelims", above, delimited_code+above_code);@/
21191 @!@:above\_with\_delims\_}{\.{\\abovewithdelims} primitive@>
21192 primitive("overwithdelims", above, delimited_code+over_code);@/
21193 @!@:over\_with\_delims\_}{\.{\\overwithdelims} primitive@>
21194 primitive("atopwithdelims", above, delimited_code+atop_code);
21195 @!@:atop\_with\_delims\_}{\.{\\atopwithdelims} primitive@>
21196
21197 @ @<Cases of |print_cmd_chr|...@>=
21198 case above: switch (chr_code) {
21199 case over_code: print_esc("over");@+break;
21200 case atop_code: print_esc("atop");@+break;
21201 case delimited_code+above_code: print_esc("abovewithdelims");@+break;
21202 case delimited_code+over_code: print_esc("overwithdelims");@+break;
21203 case delimited_code+atop_code: print_esc("atopwithdelims");@+break;
21204 default:print_esc("above");
21205 } @+break;
21206
21207 @ @<Cases of |main_control| that build...@>=
21208 case mmode+above: math_fraction();@+break;
21209
21210 @ @<Declare act...@>=
21211 static void math_fraction(void)
21212 {@+small_number c; /*the type of generalized fraction we are scanning*/
21213 c=cur_chr;
21214 if (incompleat_noad!=null)
21215 @<Ignore the fraction operation and complain about this ambiguous case@>@;
21216 else{@+incompleat_noad=get_node(fraction_noad_size);
21217 type(incompleat_noad)=fraction_noad;
21218 subtype(incompleat_noad)=normal;
21219 math_type(numerator(incompleat_noad))=sub_mlist;
21220 info(numerator(incompleat_noad))=link(head);
21221 mem[denominator(incompleat_noad)].hh=empty_field;
21222 mem[left_delimiter(incompleat_noad)].qqqq=null_delimiter;
21223 mem[right_delimiter(incompleat_noad)].qqqq=null_delimiter;@/
21224 link(head)=null;tail=head;
21225 @<Use code |c| to distinguish between generalized fractions@>;
21226 }
21227 }
21228
21229 @ @<Use code |c|...@>=
21230 if (c >= delimited_code)
21231 {@+scan_delimiter(left_delimiter(incompleat_noad), false);
21232 scan_delimiter(right_delimiter(incompleat_noad), false);
21233 }
21234 switch (c%delimited_code) {
21235 case above_code: {@+scan_normal_dimen;
21236 thickness(incompleat_noad)=cur_val;
21237 } @+break;
21238 case over_code: thickness(incompleat_noad)=default_code;@+break;
21239 case atop_code: thickness(incompleat_noad)=0;
21240 } /*there are no other cases*/
21241
21242 @ @<Ignore the fraction...@>=
21243 {@+if (c >= delimited_code)
21244 {@+scan_delimiter(garbage, false);scan_delimiter(garbage, false);
21245 }
21246 if (c%delimited_code==above_code) scan_normal_dimen;
21247 print_err("Ambiguous; you need another { and }");
21248 @.Ambiguous...@>
21249 help3("I'm ignoring this fraction specification, since I don't",@/
21250 "know whether a construction like `x \\over y \\over z'",@/
21251 "means `{x \\over y} \\over z' or `x \\over {y \\over z}'.");
21252 error();
21253 }
21254
21255 @ At the end of a math formula or subformula, the |fin_mlist| routine is
21256 called upon to return a pointer to the newly completed mlist, and to
21257 pop the nest back to the enclosing semantic level. The parameter to
21258 |fin_mlist|, if not null, points to a |right_noad| that ends the
21259 current mlist; this |right_noad| has not yet been appended.
21260
21261 @<Declare the function called |fin_mlist|@>=
21262 static pointer fin_mlist(pointer @!p)
21263 {@+pointer q; /*the mlist to return*/
21264 if (incompleat_noad!=null) @<Compleat the incompleat noad@>@;
21265 else{@+link(tail)=p;q=link(head);
21266 }
21267 pop_nest();return q;
21268 }
21269
21270 @ @<Compleat...@>=
21271 {@+math_type(denominator(incompleat_noad))=sub_mlist;
21272 info(denominator(incompleat_noad))=link(head);
21273 if (p==null) q=incompleat_noad;
21274 else{@+q=info(numerator(incompleat_noad));
21275 if ((type(q)!=left_noad)||(delim_ptr==null)) confusion("right");
21276 @:this can't happen right}{\quad right@>
21277 info(numerator(incompleat_noad))=link(delim_ptr);
21278 link(delim_ptr)=incompleat_noad;link(incompleat_noad)=p;
21279 }
21280 }
21281
21282 @ Now at last we're ready to see what happens when a right brace occurs
21283 in a math formula. Two special cases are simplified here: Braces are effectively
21284 removed when they surround a single Ord without sub/superscripts, or when they
21285 surround an accent that is the nucleus of an Ord atom.
21286
21287 @<Cases of |handle...@>=
21288 case math_group: {@+unsave();decr(save_ptr);@/
21289 math_type(saved(0))=sub_mlist;p=fin_mlist(null);info(saved(0))=p;
21290 if (p!=null) if (link(p)==null)
21291 if (type(p)==ord_noad)
21292 {@+if (math_type(subscr(p))==empty)
21293 if (math_type(supscr(p))==empty)
21294 {@+mem[saved(0)].hh=mem[nucleus(p)].hh;
21295 free_node(p, noad_size);
21296 }
21297 }
21298 else if (type(p)==accent_noad) if (saved(0)==nucleus(tail))
21299 if (type(tail)==ord_noad) @<Replace the tail of the list by |p|@>;
21300 } @+break;
21301
21302 @ @<Replace the tail...@>=
21303 {@+q=head;while (link(q)!=tail) q=link(q);
21304 link(q)=p;free_node(tail, noad_size);tail=p;
21305 }
21306
21307 @ We have dealt with all constructions of math mode except `\.{\\left}' and
21308 `\.{\\right}', so the picture is completed by the following sections of
21309 the program.
21310
21311 @<Put each...@>=
21312 primitive("left", left_right, left_noad);
21313 @!@:left\_}{\.{\\left} primitive@>
21314 primitive("right", left_right, right_noad);
21315 @!@:right\_}{\.{\\right} primitive@>
21316 text(frozen_right)=text(cur_val);eqtb[frozen_right]=eqtb[cur_val];
21317
21318 @ @<Cases of |print_cmd_chr|...@>=
21319 case left_right: if (chr_code==left_noad) print_esc("left")
21320 @/@<Cases of |left_right| for |print_cmd_chr|@>;@/
21321 else print_esc("right");@+break;
21322
21323 @ @<Cases of |main_control| that build...@>=
21324 case mmode+left_right: math_left_right();@+break;
21325
21326 @ @<Declare act...@>=
21327 static void math_left_right(void)
21328 {@+small_number t; /*|left_noad| or |right_noad|*/
21329 pointer @!p; /*new noad*/
21330 pointer @!q; /*resulting mlist*/
21331 t=cur_chr;
21332 if ((t!=left_noad)&&(cur_group!=math_left_group))
21333 @<Try to recover from mismatched \.{\\right}@>@;
21334 else{@+p=new_noad();type(p)=t;
21335 scan_delimiter(delimiter(p), false);
21336 if (t==middle_noad)
21337 {@+type(p)=right_noad;subtype(p)=middle_noad;
21338 }
21339 if (t==left_noad) q=p;
21340 else{@+q=fin_mlist(p);unsave(); /*end of |math_left_group|*/
21341 }
21342 if (t!=right_noad)
21343 {@+push_math(math_left_group);link(head)=q;tail=p;
21344 delim_ptr=p;
21345 }
21346 else{@+
21347 tail_append(new_noad());type(tail)=inner_noad;
21348 math_type(nucleus(tail))=sub_mlist;
21349 info(nucleus(tail))=q;
21350 }
21351 }
21352 }
21353
21354 @ @<Try to recover from mismatch...@>=
21355 {@+if (cur_group==math_shift_group)
21356 {@+scan_delimiter(garbage, false);
21357 print_err("Extra ");
21358 if (t==middle_noad)
21359 {@+print_esc("middle");
21360 @.Extra \\middle.@>
21361 help1("I'm ignoring a \\middle that had no matching \\left.");
21362 }
21363 else{@+print_esc("right");
21364 @.Extra \\right.@>
21365 help1("I'm ignoring a \\right that had no matching \\left.");
21366 }
21367 error();
21368 }
21369 else off_save();
21370 }
21371
21372 @ Here is the only way out of math mode.
21373
21374 @<Cases of |main_control| that build...@>=
21375 case mmode+math_shift: if (cur_group==math_shift_group) after_math();
21376 else off_save();@+break;
21377
21378 @ @<Declare act...@>=
21379 static void after_math(void)
21380 {@+bool l; /*`\.{\\leqno}' instead of `\.{\\eqno}'*/
21381 bool @!danger; /*not enough symbol fonts are present*/
21382 int @!m; /*|mmode| or |-mmode|*/
21383 pointer @!p; /*the formula*/
21384 pointer @!a; /*box containing equation number*/
21385 danger=false;
21386 @<Check that the necessary fonts for math symbols are present; if not, flush
21387 the current math lists and set |danger:=true|@>;
21388 m=mode;l=false;p=fin_mlist(null); /*this pops the nest*/
21389 if (mode==-m) /*end of equation number*/
21390 {@+@<Check that another \.\$ follows@>;
21391 cur_mlist=p;cur_style=text_style;mlist_penalties=false;
21392 mlist_to_hlist();a=hpack(link(temp_head), natural);
21393 unsave();decr(save_ptr); /*now |cur_group==math_shift_group|*/
21394 if (saved(0)==1) l=true;
21395 danger=false;
21396 @<Check that the necessary fonts for math symbols are present; if not, flush
21397 the current math lists and set |danger:=true|@>;
21398 m=mode;p=fin_mlist(null);
21399 }
21400 else a=null;
21401 if (m < 0) @<Finish math in text@>@;
21402 else{@+if (a==null) @<Check that another \.\$ follows@>;
21403 @<Finish displayed math@>;
21404 }
21405 }
21406
21407 @ @<Check that the necessary fonts...@>=
21408 if ((font_params[fam_fnt(2+text_size)] < total_mathsy_params)||@|
21409 (font_params[fam_fnt(2+script_size)] < total_mathsy_params)||@|
21410 (font_params[fam_fnt(2+script_script_size)] < total_mathsy_params))
21411 {@+print_err("Math formula deleted: Insufficient symbol fonts");@/
21412 @.Math formula deleted...@>
21413 help3("Sorry, but I can't typeset math unless \\textfont 2",@/
21414 "and \\scriptfont 2 and \\scriptscriptfont 2 have all",@/
21415 "the \\fontdimen values needed in math symbol fonts.");
21416 error();flush_math();danger=true;
21417 }
21418 else if ((font_params[fam_fnt(3+text_size)] < total_mathex_params)||@|
21419 (font_params[fam_fnt(3+script_size)] < total_mathex_params)||@|
21420 (font_params[fam_fnt(3+script_script_size)] < total_mathex_params))
21421 {@+print_err("Math formula deleted: Insufficient extension fonts");@/
21422 help3("Sorry, but I can't typeset math unless \\textfont 3",@/
21423 "and \\scriptfont 3 and \\scriptscriptfont 3 have all",@/
21424 "the \\fontdimen values needed in math extension fonts.");
21425 error();flush_math();danger=true;
21426 }
21427 else
21428 @<Load predefined fonts if needed in mathmode@>@;
21429
21430 @
21431
21432 @<Load predefined fonts if needed in mathmode@>=
21433 { int f;
21434 for(f=0; f<7;f++)
21435 { if (needs_loading(fam_fnt(f+text_size)))
21436 read_predefined_font(fam_fnt(f+text_size));
21437 if (needs_loading(fam_fnt(f+script_size)))
21438 read_predefined_font(fam_fnt(f+script_size));
21439 if (needs_loading(fam_fnt(f+script_script_size)))
21440 read_predefined_font(fam_fnt(f+script_script_size));
21441 }
21442 if (fam_in_range)
21443 { f=cur_fam;
21444 if (needs_loading(fam_fnt(f+text_size)))
21445 read_predefined_font(fam_fnt(f+text_size));
21446 if (needs_loading(fam_fnt(f+script_size)))
21447 read_predefined_font(fam_fnt(f+script_size));
21448 if (needs_loading(fam_fnt(f+script_script_size)))
21449 read_predefined_font(fam_fnt(f+script_script_size));
21450 }
21451 }
21452
21453
21454 @ The |unsave| is done after everything else here; hence an appearance of
21455 `\.{\\mathsurround}' inside of `\.{\$...\$}' affects the spacing at these
21456 particular \.\$'s. This is consistent with the conventions of
21457 `\.{\$\$...\$\$}', since `\.{\\abovedisplayskip}' inside a display affects the
21458 space above that display.
21459
21460 @<Finish math in text@>=
21461 {@+tail_append(new_math(math_surround, before));
21462 cur_mlist=p;cur_style=text_style;mlist_penalties=(mode > 0);mlist_to_hlist();
21463 link(tail)=link(temp_head);
21464 while (link(tail)!=null) tail=link(tail);
21465 tail_append(new_math(math_surround, after));
21466 space_factor=1000;unsave();
21467 }
21468
21469 @ \TeX\ gets to the following part of the program when the first `\.\$' ending
21470 a display has been scanned.
21471
21472 @<Check that another \.\$ follows@>=
21473 {@+get_x_token();
21474 if (cur_cmd!=math_shift)
21475 {@+print_err("Display math should end with $$");
21476 @.Display math...with \$\$@>
21477 help2("The `$' that I just saw supposedly matches a previous `$$'.",@/
21478 "So I shall assume that you typed `$$' both times.");
21479 back_error();
21480 }
21481 }
21482
21483
21484 @ At this time |p| points to the mlist for the formula; |a| is either
21485 |null| or it points to a box containing the equation number; and we are in
21486 vertical mode (or internal vertical mode).
21487
21488 @<Finish displayed math@>=
21489 cur_mlist=p;cur_style=display_style;mlist_penalties=false;
21490 mlist_to_hlist();p=link(temp_head); link(temp_head)=null;@/
21491 {@+ pointer q;
21492 q=new_disp_node();
21493 if (!danger) { display_formula(q)=p; display_eqno(q)=a; display_left(q)=l; }
21494 /* adding parameter nodes */
21495 /* these are paragraph parameters
21496 needed for the baseline skip before the above display skip
21497 */
21498 if (hang_indent!=0)
21499 { new_param_node(dimen_type,hang_indent_code,hang_indent);
21500 if (hang_after!=1)
21501 new_param_node(int_type,hang_after_code,hang_after);
21502 }
21503 new_param_node(dimen_type,line_skip_limit_code,line_skip_limit);
21504 new_param_node(glue_type,line_skip_code,line_skip);
21505 new_param_node(glue_type,baseline_skip_code,baseline_skip);
21506
21507 #if 0 /* unsure */
21508 new_param_node(dimen_type,math_quad_no ...)
21509 #endif
21510
21511 new_param_node(int_type,pre_display_penalty_code,pre_display_penalty);
21512 new_param_node(int_type,post_display_penalty_code,post_display_penalty);
21513 new_param_node(glue_type,above_display_skip_code,above_display_skip);
21514 new_param_node(glue_type,below_display_skip_code,below_display_skip);
21515 new_param_node(glue_type,above_display_short_skip_code,above_display_short_skip);
21516 new_param_node(glue_type,below_display_short_skip_code,below_display_short_skip);
21517
21518 display_params(q)=link(temp_head); link(temp_head)=null;
21519 display_no_bs(q)= prev_depth <= ignore_depth;
21520 tail_append(q);
21521 }
21522 resume_after_display()
21523
21524 @ @<Declare act...@>=
21525 static void resume_after_display(void)
21526 {@+if (cur_group!=math_shift_group) confusion("display");
21527 @:this can't happen display}{\quad display@>
21528 unsave();
21529 mode=hmode;space_factor=1000;set_cur_lang;clang=cur_lang;
21530 prev_graf=(norm_min(left_hyphen_min)*0100+norm_min(right_hyphen_min))
21531 *0200000+cur_lang;
21532 @<Scan an optional space@>;
21533 }
21534
21535 @ When \.{\\halign} appears in a display, the alignment routines operate
21536 essentially as they do in vertical mode. Then the following program is
21537 activated, with |p| and |q| pointing to the beginning and end of the
21538 resulting list, and with |aux_save| holding the |prev_depth| value.
21539
21540 @<Finish an alignment in a display@>=
21541 {@+do_assignments();
21542 if (cur_cmd!=math_shift) @<Pontificate about improper alignment in display@>@;
21543 else@<Check that another \.\$ follows@>;
21544 pop_nest();
21545 prev_depth=aux_save.sc;
21546 tail_append(new_disp_node());
21547 display_formula(tail)=vpack(p, natural);
21548 /* adding parameter nodes */
21549 link(temp_head)=null;
21550 if (hang_indent!=0)
21551 { new_param_node(dimen_type,hang_indent_code,hang_indent);
21552 if (hang_after!=1)
21553 new_param_node(int_type,hang_after_code,hang_after);
21554 }
21555 new_param_node(dimen_type,line_skip_limit_code,line_skip_limit);
21556 new_param_node(glue_type,line_skip_code,line_skip);
21557 new_param_node(glue_type,baseline_skip_code,baseline_skip);
21558 display_params(tail)=link(temp_head); link(temp_head)=null;
21559 display_no_bs(tail)= prev_depth <= ignore_depth;
21560 resume_after_display();
21561 }
21562
21563 @ @<Pontificate...@>=
21564 {@+print_err("Missing $$ inserted");
21565 @.Missing {\$\$} inserted@>
21566 help2("Displays can use special alignments (like \\eqalignno)",@/
21567 "only if nothing but the alignment itself is between $$'s.");
21568 back_error();
21569 }
21570
21571 @* Mode-independent processing.
21572 The long |main_control| procedure has now been fully specified, except for
21573 certain activities that are independent of the current mode. These activities
21574 do not change the current vlist or hlist or mlist; if they change anything,
21575 it is the value of a parameter or the meaning of a control sequence.
21576
21577 Assignments to values in |eqtb| can be global or local. Furthermore, a
21578 control sequence can be defined to be `\.{\\long}', `\.{\\protected}',
21579 or `\.{\\outer}', and it might or might not be expanded. The prefixes
21580 `\.{\\global}', `\.{\\long}', `\.{\\protected}',
21581 and `\.{\\outer}' can occur in any order. Therefore we assign binary numeric
21582 codes, making it possible to accumulate the union of all specified prefixes
21583 by adding the corresponding codes. (\PASCAL's |set| operations could also
21584 have been used.)
21585
21586 @<Put each...@>=
21587 primitive("long", prefix, 1);
21588 @!@:long\_}{\.{\\long} primitive@>
21589 primitive("outer", prefix, 2);
21590 @!@:outer\_}{\.{\\outer} primitive@>
21591 primitive("global", prefix, 4);
21592 @!@:global\_}{\.{\\global} primitive@>
21593 primitive("def", def, 0);
21594 @!@:def\_}{\.{\\def} primitive@>
21595 primitive("gdef", def, 1);
21596 @!@:gdef\_}{\.{\\gdef} primitive@>
21597 primitive("edef", def, 2);
21598 @!@:edef\_}{\.{\\edef} primitive@>
21599 primitive("xdef", def, 3);
21600 @!@:xdef\_}{\.{\\xdef} primitive@>
21601
21602 @ @<Cases of |print_cmd_chr|...@>=
21603 case prefix: if (chr_code==1) print_esc("long");
21604 else if (chr_code==2) print_esc("outer")
21605 @/@<Cases of |prefix| for |print_cmd_chr|@>;@/
21606 else print_esc("global");@+break;
21607 case def: if (chr_code==0) print_esc("def");
21608 else if (chr_code==1) print_esc("gdef");
21609 else if (chr_code==2) print_esc("edef");
21610 else print_esc("xdef");@+break;
21611
21612 @ Every prefix, and every command code that might or might not be prefixed,
21613 calls the action procedure |prefixed_command|. This routine accumulates
21614 a sequence of prefixes until coming to a non-prefix, then it carries out
21615 the command.
21616
21617 @<Cases of |main_control| that don't...@>=
21618 any_mode(toks_register):
21619 any_mode(assign_toks):
21620 any_mode(assign_int):
21621 any_mode(assign_dimen):
21622 any_mode(assign_glue):
21623 any_mode(assign_mu_glue):
21624 any_mode(assign_font_dimen):
21625 any_mode(assign_font_int):
21626 any_mode(set_aux):
21627 any_mode(set_prev_graf):
21628 any_mode(set_page_dimen):
21629 any_mode(set_page_int):
21630 any_mode(set_box_dimen):
21631 any_mode(set_shape):
21632 any_mode(def_code):
21633 any_mode(def_family):
21634 any_mode(set_font):
21635 any_mode(def_font):
21636 any_mode(internal_register):
21637 any_mode(advance):
21638 any_mode(multiply):
21639 any_mode(divide):
21640 any_mode(prefix):
21641 any_mode(let):
21642 any_mode(shorthand_def):
21643 any_mode(read_to_cs):
21644 any_mode(def):
21645 any_mode(set_box):
21646 any_mode(hyph_data):
21647 any_mode(set_interaction): prefixed_command();@+break;
21648
21649 @ If the user says, e.g., `\.{\\global\\global}', the redundancy is
21650 silently accepted.
21651
21652 @<Declare act...@>=
21653 @t\4@>@<Declare subprocedures for |prefixed_command|@>@t@>@;@/
21654 static void prefixed_command(void)
21655 {@+
21656 small_number a; /*accumulated prefix codes so far*/
21657 internal_font_number @!f; /*identifies a font*/
21658 int @!j; /*index into a \.{\\parshape} specification*/
21659 font_index @!k; /*index into |font_info|*/
21660 pointer @!p, @!q; /*for temporary short-term use*/
21661 int @!n; /*ditto*/
21662 bool @!e; /*should a definition be expanded? or was \.{\\let} not done?*/
21663 a=0;
21664 while (cur_cmd==prefix)
21665 {@+if (!odd(a/cur_chr)) a=a+cur_chr;
21666 @<Get the next non-blank non-relax...@>;
21667 if (cur_cmd <= max_non_prefixed_command)
21668 @<Discard erroneous prefixes and |return|@>;
21669 if (tracing_commands > 2) if (eTeX_ex) show_cur_cmd_chr();
21670 }
21671 @<Discard the prefixes \.{\\long} and \.{\\outer} if they are irrelevant@>;
21672 @<Adjust \(f)for the setting of \.{\\globaldefs}@>;
21673 switch (cur_cmd) {
21674 @t\4@>@<Assignments@>@;
21675 default:confusion("prefix");
21676 @:this can't happen prefix}{\quad prefix@>
21677 }
21678 done: @<Insert a token saved by \.{\\afterassignment}, if any@>;
21679 }
21680
21681 @ @<Discard erroneous...@>=
21682 {@+print_err("You can't use a prefix with `");
21683 @.You can't use a prefix with x@>
21684 print_cmd_chr(cur_cmd, cur_chr);print_char('\'');
21685 help1("I'll pretend you didn't say \\long or \\outer or \\global.");
21686 if (eTeX_ex) help_line[0]=@|
21687 "I'll pretend you didn't say \\long or \\outer or \\global or \\protected.";
21688 back_error();return;
21689 }
21690
21691 @ @<Discard the prefixes...@>=
21692 if (a >= 8)
21693 {@+j=protected_token;a=a-8;
21694 }
21695 else j=0;
21696 if ((cur_cmd!=def)&&((a%4!=0)||(j!=0)))
21697 {@+print_err("You can't use `");print_esc("long");print("' or `");
21698 print_esc("outer");
21699 help1("I'll pretend you didn't say \\long or \\outer here.");
21700 if (eTeX_ex)
21701 {@+help_line[0]=@|
21702 "I'll pretend you didn't say \\long or \\outer or \\protected here.";
21703 print("' or `");print_esc("protected");
21704 }
21705 print("' with `");
21706 @.You can't use \\long...@>
21707 print_cmd_chr(cur_cmd, cur_chr);print_char('\'');
21708 error();
21709 }
21710
21711 @ The previous routine does not have to adjust |a| so that |a%4==0|,
21712 since the following routines test for the \.{\\global} prefix as follows.
21713
21714 @d global (a >= 4)
21715 @d define(A, B, C) if (global) geq_define(A, B, C);@+else eq_define(A, B, C)
21716 @d word_define(A, B) if (global) geq_word_define(A, B);@+else eq_word_define(A, B)
21717
21718 @<Adjust \(f)for the setting of \.{\\globaldefs}@>=
21719 if (global_defs!=0)
21720 if (global_defs < 0)
21721 {@+if (global) a=a-4;
21722 }
21723 else{@+if (!global) a=a+4;
21724 }
21725
21726 @ When a control sequence is to be defined, by \.{\\def} or \.{\\let} or
21727 something similar, the |get_r_token| routine will substitute a special
21728 control sequence for a token that is not redefinable.
21729
21730 @<Declare subprocedures for |prefixed_command|@>=
21731 static void get_r_token(void)
21732 {@+
21733 restart: @/do@+{get_token();
21734 }@+ while (!(cur_tok!=space_token));
21735 if ((cur_cs==0)||(cur_cs > frozen_control_sequence))
21736 {@+print_err("Missing control sequence inserted");
21737 @.Missing control...@>
21738 help5("Please don't say `\\def cs{...}', say `\\def\\cs{...}'.",@/
21739 "I've inserted an inaccessible control sequence so that your",@/
21740 "definition will be completed without mixing me up too badly.",@/
21741 "You can recover graciously from this error, if you're",@/
21742 "careful; see exercise 27.2 in The TeXbook.");
21743 @:TeXbook}{\sl The \TeX book@>
21744 if (cur_cs==0) back_input();
21745 cur_tok=cs_token_flag+frozen_protection;ins_error();goto restart;
21746 }
21747 }
21748
21749 @ @<Initialize table entries...@>=
21750 text(frozen_protection)=s_no("inaccessible");
21751 @.inaccessible@>
21752
21753 @ Here's an example of the way many of the following routines operate.
21754 After some preprocessing---here we check for extended fonts that were
21755 defined in a format file, but are not yet loaded intp memory---the |define|
21756 macro will set the a value/type pair at the given location in the table
21757 of equivalents.
21758
21759 @<Assignments@>=
21760 case set_font:
21761 if (needs_loading(cur_chr))
21762 read_predefined_font(cur_chr);
21763 define(cur_font_loc, data, cur_chr);@+break;
21764
21765 @ When a |def| command has been scanned,
21766 |cur_chr| is odd if the definition is supposed to be global, and
21767 |cur_chr >= 2| if the definition is supposed to be expanded.
21768
21769 @<Assignments@>=
21770 case def: {@+if (odd(cur_chr)&&!global&&(global_defs >= 0)) a=a+4;
21771 e=(cur_chr >= 2);get_r_token();p=cur_cs;
21772 q=scan_toks(true, e);
21773 if (j!=0)
21774 {@+q=get_avail();info(q)=j;link(q)=link(def_ref);
21775 link(def_ref)=q;
21776 }
21777 define(p, call+(a%4), def_ref);
21778 } @+break;
21779
21780 @ Both \.{\\let} and \.{\\futurelet} share the command code |let|.
21781
21782 @<Put each...@>=
21783 primitive("let", let, normal);@/
21784 @!@:let\_}{\.{\\let} primitive@>
21785 primitive("futurelet", let, normal+1);@/
21786 @!@:future\_let\_}{\.{\\futurelet} primitive@>
21787
21788 @ @<Cases of |print_cmd_chr|...@>=
21789 case let: if (chr_code!=normal) print_esc("futurelet");@+else print_esc("let");@+break;
21790
21791 @ @<Assignments@>=
21792 case let: {@+n=cur_chr;
21793 get_r_token();p=cur_cs;
21794 if (n==normal)
21795 {@+@/do@+{get_token();
21796 }@+ while (!(cur_cmd!=spacer));
21797 if (cur_tok==other_token+'=')
21798 {@+get_token();
21799 if (cur_cmd==spacer) get_token();
21800 }
21801 }
21802 else{@+get_token();q=cur_tok;get_token();back_input();
21803 cur_tok=q;back_input(); /*look ahead, then back up*/
21804 } /*note that |back_input| doesn't affect |cur_cmd|, |cur_chr|*/
21805 if (cur_cmd >= call) add_token_ref(cur_chr);
21806 else if ((cur_cmd==internal_register)||(cur_cmd==toks_register))
21807 if ((cur_chr < mem_bot)||(cur_chr > lo_mem_stat_max))
21808 add_sa_ref(cur_chr);
21809 define(p, cur_cmd, cur_chr);
21810 } @+break;
21811
21812 @ A \.{\\chardef} creates a control sequence whose |cmd| is |char_given|;
21813 a \.{\\mathchardef} creates a control sequence whose |cmd| is |math_given|;
21814 and the corresponding |chr| is the character code or math code. A \.{\\countdef}
21815 or \.{\\dimendef} or \.{\\skipdef} or \.{\\muskipdef} creates a control
21816 sequence whose |cmd| is |assign_int| or \dots\ or |assign_mu_glue|, and the
21817 corresponding |chr| is the |eqtb| location of the internal register in question.
21818
21819 @d char_def_code 0 /*|shorthand_def| for \.{\\chardef}*/
21820 @d math_char_def_code 1 /*|shorthand_def| for \.{\\mathchardef}*/
21821 @d count_def_code 2 /*|shorthand_def| for \.{\\countdef}*/
21822 @d dimen_def_code 3 /*|shorthand_def| for \.{\\dimendef}*/
21823 @d skip_def_code 4 /*|shorthand_def| for \.{\\skipdef}*/
21824 @d mu_skip_def_code 5 /*|shorthand_def| for \.{\\muskipdef}*/
21825 @d toks_def_code 6 /*|shorthand_def| for \.{\\toksdef}*/
21826
21827 @<Put each...@>=
21828 primitive("chardef", shorthand_def, char_def_code);@/
21829 @!@:char\_def\_}{\.{\\chardef} primitive@>
21830 primitive("mathchardef", shorthand_def, math_char_def_code);@/
21831 @!@:math\_char\_def\_}{\.{\\mathchardef} primitive@>
21832 primitive("countdef", shorthand_def, count_def_code);@/
21833 @!@:count\_def\_}{\.{\\countdef} primitive@>
21834 primitive("dimendef", shorthand_def, dimen_def_code);@/
21835 @!@:dimen\_def\_}{\.{\\dimendef} primitive@>
21836 primitive("skipdef", shorthand_def, skip_def_code);@/
21837 @!@:skip\_def\_}{\.{\\skipdef} primitive@>
21838 primitive("muskipdef", shorthand_def, mu_skip_def_code);@/
21839 @!@:mu\_skip\_def\_}{\.{\\muskipdef} primitive@>
21840 primitive("toksdef", shorthand_def, toks_def_code);@/
21841 @!@:toks\_def\_}{\.{\\toksdef} primitive@>
21842
21843 @ @<Cases of |print_cmd_chr|...@>=
21844 case shorthand_def: switch (chr_code) {
21845 case char_def_code: print_esc("chardef");@+break;
21846 case math_char_def_code: print_esc("mathchardef");@+break;
21847 case count_def_code: print_esc("countdef");@+break;
21848 case dimen_def_code: print_esc("dimendef");@+break;
21849 case skip_def_code: print_esc("skipdef");@+break;
21850 case mu_skip_def_code: print_esc("muskipdef");@+break;
21851 default:print_esc("toksdef");
21852 } @+break;
21853 case char_given: {@+print_esc("char");print_hex(chr_code);
21854 } @+break;
21855 case math_given: {@+print_esc("mathchar"); Umath_to_math(chr_code); print_hex(chr_code);
21856 } @+break;
21857
21858 @ We temporarily define |p| to be |relax|, so that an occurrence of |p|
21859 while scanning the definition will simply stop the scanning instead of
21860 producing an ``undefined control sequence'' error or expanding the
21861 previous meaning. This allows, for instance, `\.{\\chardef\\foo=123\\foo}'.
21862
21863 @<Assignments@>=
21864 case shorthand_def: {@+n=cur_chr;get_r_token();p=cur_cs;define(p, relax, 256);
21865 scan_optional_equals();
21866 switch (n) {
21867 case char_def_code: {@+scan_char_num();define(p, char_given, cur_val);
21868 } @+break;
21869 case math_char_def_code: {@+scan_fifteen_bit_int(); math_to_Umath(cur_val); define(p, math_given, cur_val);
21870 } @+break;
21871 default:{@+scan_register_num();
21872 if (cur_val > 255)
21873 {@+j=n-count_def_code; /*|int_val dotdot box_val|*/
21874 if (j > mu_val) j=tok_val; /*|int_val dotdot mu_val| or |tok_val|*/
21875 find_sa_element(j, cur_val, true);add_sa_ref(cur_ptr);
21876 if (j==tok_val) j=toks_register;@+else j=internal_register;
21877 define(p, j, cur_ptr);
21878 }
21879 else
21880 switch (n) {
21881 case count_def_code: define(p, assign_int, count_base+cur_val);@+break;
21882 case dimen_def_code: define(p, assign_dimen, scaled_base+cur_val);@+break;
21883 case skip_def_code: define(p, assign_glue, skip_base+cur_val);@+break;
21884 case mu_skip_def_code: define(p, assign_mu_glue, mu_skip_base+cur_val);@+break;
21885 case toks_def_code: define(p, assign_toks, toks_base+cur_val);
21886 } /*there are no other cases*/
21887 }
21888 }
21889 } @+break;
21890
21891 @ @<Assignments@>=
21892 case read_to_cs: {@+j=cur_chr;scan_int();n=cur_val;
21893 if (!scan_keyword("to"))
21894 @.to@>
21895 {@+print_err("Missing `to' inserted");
21896 @.Missing `to'...@>
21897 help2("You should have said `\\read<number> to \\cs'.",@/
21898 "I'm going to look for the \\cs now.");error();
21899 }
21900 get_r_token();
21901 p=cur_cs;read_toks(n, p, j);define(p, call, cur_val);
21902 } @+break;
21903
21904 @ The token-list parameters, \.{\\output} and \.{\\everypar}, etc., receive
21905 their values in the following way. (For safety's sake, we place an
21906 enclosing pair of braces around an \.{\\output} list.)
21907
21908 @<Assignments@>=
21909 case toks_register: case assign_toks: {@+q=cur_cs;
21910 e=false; /*just in case, will be set |true| for sparse array elements*/
21911 if (cur_cmd==toks_register)
21912 if (cur_chr==mem_bot)
21913 {@+scan_register_num();
21914 if (cur_val > 255)
21915 {@+find_sa_element(tok_val, cur_val, true);
21916 cur_chr=cur_ptr;e=true;
21917 }
21918 else cur_chr=toks_base+cur_val;
21919 }
21920 else e=true;
21921 p=cur_chr; /*|p==every_par_loc| or |output_routine_loc| or \dots*/
21922 scan_optional_equals();
21923 @<Get the next non-blank non-relax non-call token@>;
21924 if (cur_cmd!=left_brace) @<If the right-hand side is a token parameter or
21925 token register, finish the assignment and |goto done|@>;
21926 back_input();cur_cs=q;q=scan_toks(false, false);
21927 if (link(def_ref)==null) /*empty list: revert to the default*/
21928 {@+sa_define(p, null, p, undefined_cs, null);free_avail(def_ref);
21929 }
21930 else{@+if ((p==output_routine_loc)&&!e) /*enclose in curlies*/
21931 {@+link(q)=get_avail();q=link(q);
21932 info(q)=right_brace_token+'}';
21933 q=get_avail();info(q)=left_brace_token+'{';
21934 link(q)=link(def_ref);link(def_ref)=q;
21935 }
21936 sa_define(p, def_ref, p, call, def_ref);
21937 }
21938 } @+break;
21939
21940 @ @<If the right-hand side is a token parameter...@>=
21941 if ((cur_cmd==toks_register)||(cur_cmd==assign_toks))
21942 {@+if (cur_cmd==toks_register)
21943 if (cur_chr==mem_bot)
21944 {@+scan_register_num();
21945 if (cur_val < 256) q=equiv(toks_base+cur_val);
21946 else{@+find_sa_element(tok_val, cur_val, false);
21947 if (cur_ptr==null) q=null;
21948 else q=sa_ptr(cur_ptr);
21949 }
21950 }
21951 else q=sa_ptr(cur_chr);
21952 else q=equiv(cur_chr);
21953 if (q==null) sa_define(p, null, p, undefined_cs, null);
21954 else{@+add_token_ref(q);sa_define(p, q, p, call, q);
21955 }
21956 goto done;
21957 }
21958
21959 @ Similar routines are used to assign values to the numeric parameters.
21960
21961 @<Assignments@>=
21962 case assign_int: {@+p=cur_chr;scan_optional_equals();scan_int();
21963 word_define(p, cur_val);
21964 } @+break;
21965 case assign_dimen: {@+p=cur_chr;scan_optional_equals();
21966 scan_normal_dimen;word_define(p, cur_val);
21967 } @+break;
21968 case assign_glue: case assign_mu_glue: {@+p=cur_chr;n=cur_cmd;scan_optional_equals();
21969 if (n==assign_mu_glue) scan_glue(mu_val);@+else scan_glue(glue_val);
21970 trap_zero_glue();
21971 define(p, glue_ref, cur_val);
21972 } @+break;
21973
21974 @ When a glue register or parameter becomes zero, it will always point to
21975 |zero_glue| because of the following procedure. (Exception: The tabskip
21976 glue isn't trapped while preambles are being scanned.)
21977
21978 @<Declare subprocedures for |prefixed_command|@>=
21979 static void trap_zero_glue(void)
21980 {@+if ((width(cur_val)==0)&&(stretch(cur_val)==0)&&(shrink(cur_val)==0))
21981 {@+add_glue_ref(zero_glue);
21982 delete_glue_ref(cur_val);cur_val=zero_glue;
21983 }
21984 }
21985
21986 @ The various character code tables are changed by the |def_code| commands,
21987 and the font families are declared by |def_family|.
21988
21989 @<Put each...@>=
21990 primitive("catcode", def_code, utf_cat_code_base);
21991 @!@:cat\_code\_}{\.{\\catcode} primitive@>
21992 primitive("mathcode", def_code, math_code_base);
21993 @!@:math\_code\_}{\.{\\mathcode} primitive@>
21994 primitive("Umathcode", def_code, utf_math_code_base);
21995 @!@:Umath\_code\_}{\.{\\Umathcode} primitive@>
21996 primitive("Umathcodenum", def_code, utf_math_codenum_base);
21997 @!@:Umath\_code\_num}{\.{\\Umathcodenum} primitive@>
21998 primitive("lccode", def_code, utf_lc_code_base);
21999 @!@:lc\_code\_}{\.{\\lccode} primitive@>
22000 primitive("uccode", def_code, utf_uc_code_base);
22001 @!@:uc\_code\_}{\.{\\uccode} primitive@>
22002 primitive("sfcode", def_code, utf_sf_code_base);
22003 @!@:sf\_code\_}{\.{\\sfcode} primitive@>
22004 primitive("delcode", def_code, utf_del_code_base);
22005 @!@:del\_code\_}{\.{\\delcode} primitive@>
22006 primitive("textfont", def_family, math_font_base);
22007 @!@:text\_font\_}{\.{\\textfont} primitive@>
22008 primitive("scriptfont", def_family, math_font_base+script_size);
22009 @!@:script\_font\_}{\.{\\scriptfont} primitive@>
22010 primitive("scriptscriptfont", def_family, math_font_base+script_script_size);
22011 @!@:script\_script\_font\_}{\.{\\scriptscriptfont} primitive@>
22012
22013 @ @<Cases of |print_cmd_chr|...@>=
22014 case def_code: if (chr_code==utf_cat_code_base) print_esc("catcode");
22015 else if (chr_code==utf_math_code_base) print_esc("Umathcode");
22016 else if (chr_code==utf_math_codenum_base) print_esc("Umathcodenum");
22017 else if (chr_code==utf_lc_code_base) print_esc("lccode");
22018 else if (chr_code==utf_uc_code_base) print_esc("uccode");
22019 else if (chr_code==utf_sf_code_base) print_esc("sfcode");
22020 else if (chr_code==math_code_base) print_esc("mathcode");
22021 else if (chr_code==sf_code_base) print_esc("sfcode");
22022 else print_esc("delcode");@+break;
22023 case def_family: print_size(chr_code-math_font_base);@+break;
22024
22025 @ The different types of code values have different legal ranges; the
22026 following program is careful to check each case properly.
22027
22028 @<Assignments@>=
22029 case def_code: {@+int cp;
22030 @<Let |n| be the largest legal code value, based on |cur_chr|@>;
22031 p=cur_chr;scan_char_num();cp=cur_val;scan_optional_equals();
22032 if (p==utf_math_code_base)
22033 { @<Read the arguments of \.{\\Umathcode}@>@;
22034 p=utf_math_codenum_base;
22035 }
22036 else
22037 scan_int();
22038 if (p==math_code_base)
22039 { math_to_Umath(cur_val); p=utf_math_codenum_base;
22040 }
22041 if (p>=utf_first_base && cp<0x100) p=utf_adjust_base(p);
22042 if (((cur_val < 0)&&(p < del_code_base))||(cur_val > n))
22043 {@+print_err("Invalid code (");print_int(cur_val);
22044 @.Invalid code@>
22045 if (p < del_code_base) print("), should be in the range 0..");
22046 else print("), should be at most ");
22047 print_int(n);
22048 help1("I'm going to use 0 instead of that illegal code value.");@/
22049 error();cur_val=0;
22050 }
22051 if (p>=utf_first_base) utf_define(p,cp,cur_val,global);
22052 else if (p < math_code_base) define(p+cp, data, cur_val);
22053 else if (p < del_code_base) define(p+cp, data, hi(cur_val));
22054 else word_define(p+cp, cur_val);
22055 } @+break;
22056
22057 @ @<Let |n| be the largest...@>=
22058 if (cur_chr==math_code_base) n=0x7FFFFFFF;
22059 else if (cur_chr==utf_cat_code_base) n=max_char_code;
22060 else if (cur_chr==utf_math_code_base) n=0x7FFFFFFF;
22061 else if (cur_chr==utf_math_codenum_base) n=0x7FFFFFFF;
22062 else if (cur_chr==utf_sf_code_base) n=077777;
22063 else if (cur_chr==utf_lc_code_base) n=0x10FFFF;
22064 else if (cur_chr==utf_uc_code_base) n=0x10FFFF;
22065 else if (cur_chr==utf_del_code_base) n=077777777;
22066 else n=255
22067
22068 @ @<Assignments@>=
22069 case def_family: {@+p=cur_chr;scan_four_bit_int();p=p+cur_val;
22070 scan_optional_equals();scan_font_ident();define(p, data, cur_val);
22071 if (needs_loading(cur_val))
22072 read_predefined_font(cur_val);
22073 } @+break;
22074
22075 @ Next we consider changes to \TeX's numeric registers.
22076
22077 @<Assignments@>=
22078 case internal_register: case advance:
22079 case multiply: case divide: do_register_command(a);@+break;
22080
22081 @ We use the fact that |internal_register < advance < multiply < divide|.
22082
22083 @<Declare subprocedures for |prefixed_command|@>=
22084 static void do_register_command(small_number @!a)
22085 {@+
22086 pointer l, @!q, @!r, @!s; /*for list manipulation*/
22087 int @!p; /*type of register involved*/
22088 bool @!e; /*does |l| refer to a sparse array element?*/
22089 int @!w; /*integer or dimen value of |l|*/
22090 q=cur_cmd;
22091 e=false; /*just in case, will be set |true| for sparse array elements*/
22092 @<Compute the register location |l| and its type |p|; but |return| if invalid@>;
22093 if (q==internal_register) scan_optional_equals();
22094 else if (scan_keyword("by")) do_nothing; /*optional `\.{by}'*/
22095 @.by@>
22096 arith_error=false;
22097 if (q < multiply) @<Compute result of |register| or |advance|, put it in |cur_val|@>@;
22098 else@<Compute result of |multiply| or |divide|, put it in |cur_val|@>;
22099 if (arith_error)
22100 {@+print_err("Arithmetic overflow");
22101 @.Arithmetic overflow@>
22102 help2("I can't carry out that multiplication or division,",@/
22103 "since the result is out of range.");
22104 if (p >= glue_val) delete_glue_ref(cur_val);
22105 error();return;
22106 }
22107 if (p < glue_val) sa_word_define(l, cur_val);
22108 else{@+trap_zero_glue();sa_define(l, cur_val, l, glue_ref, cur_val);
22109 }
22110 }
22111
22112 @ Here we use the fact that the consecutive codes |int_val dotdot mu_val| and
22113 |assign_int dotdot assign_mu_glue| correspond to each other nicely.
22114
22115 @<Compute the register location |l| and its type |p|...@>=
22116 {@+if (q!=internal_register)
22117 {@+get_x_token();
22118 if ((cur_cmd >= assign_int)&&(cur_cmd <= assign_mu_glue))
22119 {@+l=cur_chr;p=cur_cmd-assign_int;goto found;
22120 }
22121 if (cur_cmd!=internal_register)
22122 {@+print_err("You can't use `");print_cmd_chr(cur_cmd, cur_chr);
22123 @.You can't use x after ...@>
22124 print("' after ");print_cmd_chr(q, 0);
22125 help1("I'm forgetting what you said and not changing anything.");
22126 error();return;
22127 }
22128 }
22129 if ((cur_chr < mem_bot)||(cur_chr > lo_mem_stat_max))
22130 {@+l=cur_chr;p=sa_type(l);e=true;
22131 }
22132 else{@+p=cur_chr-mem_bot;scan_register_num();
22133 if (cur_val > 255)
22134 {@+find_sa_element(p, cur_val, true);l=cur_ptr;e=true;
22135 }
22136 else
22137 switch (p) {
22138 case int_val: l=cur_val+count_base;@+break;
22139 case dimen_val: l=cur_val+scaled_base;@+break;
22140 case glue_val: l=cur_val+skip_base;@+break;
22141 case mu_val: l=cur_val+mu_skip_base;
22142 } /*there are no other cases*/
22143 }
22144 }
22145 found: if (p < glue_val) @+if (e) w=sa_int(l);@+else w=eqtb[l].i;
22146 else if (e) s=sa_ptr(l);@+else s=equiv(l)
22147
22148 @ @<Compute result of |register| or |advance|...@>=
22149 if (p < glue_val)
22150 {@+if (p==int_val) scan_int();@+else scan_normal_dimen;
22151 if (q==advance)
22152 { cur_val=cur_val+w;
22153 if (!e && l>=dimen_base)
22154 { cur_hfactor+=hfactor_eqtb[l].sc;
22155 cur_vfactor+=vfactor_eqtb[l].sc;
22156 }
22157 }
22158 }
22159 else{@+scan_glue(p);
22160 if (q==advance) @<Compute the sum of two glue specs@>;
22161 }
22162
22163 @ @<Compute the sum of two glue specs@>=
22164 {@+q=new_spec(cur_val);r=s;
22165 delete_glue_ref(cur_val);
22166 width(q)=width(q)+width(r);
22167 if (stretch(q)==0) stretch_order(q)=normal;
22168 if (stretch_order(q)==stretch_order(r)) stretch(q)=stretch(q)+stretch(r);
22169 else if ((stretch_order(q) < stretch_order(r))&&(stretch(r)!=0))
22170 {@+stretch(q)=stretch(r);stretch_order(q)=stretch_order(r);
22171 }
22172 if (shrink(q)==0) shrink_order(q)=normal;
22173 if (shrink_order(q)==shrink_order(r)) shrink(q)=shrink(q)+shrink(r);
22174 else if ((shrink_order(q) < shrink_order(r))&&(shrink(r)!=0))
22175 {@+shrink(q)=shrink(r);shrink_order(q)=shrink_order(r);
22176 }
22177 cur_val=q;
22178 }
22179
22180 @ @<Compute result of |multiply| or |divide|...@>=
22181 {@+scan_int();
22182 if (p < glue_val)
22183 if (q==multiply)
22184 if (p==int_val) cur_val=mult_integers(w, cur_val);
22185 else cur_val=nx_plus_y(w, cur_val, 0);
22186 else cur_val=x_over_n(w, cur_val);
22187 else{@+r=new_spec(s);
22188 if (q==multiply)
22189 {@+width(r)=nx_plus_y(width(s), cur_val, 0);
22190 stretch(r)=nx_plus_y(stretch(s), cur_val, 0);
22191 shrink(r)=nx_plus_y(shrink(s), cur_val, 0);
22192 }
22193 else{@+width(r)=x_over_n(width(s), cur_val);
22194 stretch(r)=x_over_n(stretch(s), cur_val);
22195 shrink(r)=x_over_n(shrink(s), cur_val);
22196 }
22197 cur_val=r;
22198 }
22199 }
22200
22201 @ The processing of boxes is somewhat different, because we may need
22202 to scan and create an entire box before we actually change the value of the old
22203 one.
22204
22205 @<Assignments@>=
22206 case set_box: {@+scan_register_num();
22207 if (global) n=global_box_flag+cur_val;@+else n=box_flag+cur_val;
22208 scan_optional_equals();
22209 if (set_box_allowed) scan_box(n);
22210 else{@+print_err("Improper ");print_esc("setbox");
22211 @.Improper \\setbox@>
22212 help2("Sorry, \\setbox is not allowed after \\halign in a display,",@/
22213 "or between \\accent and an accented character.");error();
22214 }
22215 } @+break;
22216
22217 @ The |space_factor| or |prev_depth| settings are changed when a |set_aux|
22218 command is sensed. Similarly, |prev_graf| is changed in the presence of
22219 |set_prev_graf|, and |dead_cycles| or |insert_penalties| in the presence of
22220 |set_page_int|. These definitions are always global.
22221
22222 When some dimension of a box register is changed, the change isn't exactly
22223 global; but \TeX\ does not look at the \.{\\global} switch.
22224
22225 @<Assignments@>=
22226 case set_aux: alter_aux();@+break;
22227 case set_prev_graf: alter_prev_graf();@+break;
22228 case set_page_dimen: alter_page_so_far();@+break;
22229 case set_page_int: alter_integer();@+break;
22230 case set_box_dimen: alter_box_dimen();@+break;
22231
22232 @ @<Declare subprocedures for |prefixed_command|@>=
22233 static void alter_aux(void)
22234 {@+halfword c; /*|hmode| or |vmode|*/
22235 if (cur_chr!=abs(mode)) report_illegal_case();
22236 else{@+c=cur_chr;scan_optional_equals();
22237 if (c==vmode)
22238 {@+scan_normal_dimen;prev_depth=cur_val;
22239 }
22240 else{@+scan_int();
22241 if ((cur_val <= 0)||(cur_val > 32767))
22242 {@+print_err("Bad space factor");
22243 @.Bad space factor@>
22244 help1("I allow only values in the range 1..32767 here.");
22245 int_error(cur_val);
22246 }
22247 else space_factor=cur_val;
22248 }
22249 }
22250 }
22251
22252 @ @<Declare subprocedures for |prefixed_command|@>=
22253 static void alter_prev_graf(void)
22254 {@+int p; /*index into |nest|*/
22255 nest[nest_ptr]=cur_list;p=nest_ptr;
22256 while (abs(nest[p].mode_field)!=vmode) decr(p);
22257 scan_optional_equals();scan_int();
22258 if (cur_val < 0)
22259 {@+print_err("Bad ");print_esc("prevgraf");
22260 @.Bad \\prevgraf@>
22261 help1("I allow only nonnegative values here.");
22262 int_error(cur_val);
22263 }
22264 else{@+nest[p].pg_field=cur_val;cur_list=nest[nest_ptr];
22265 }
22266 }
22267
22268 @ @<Declare subprocedures for |prefixed_command|@>=
22269 static void alter_page_so_far(void)
22270 {@+int c; /*index into |page_so_far|*/
22271 c=cur_chr;scan_optional_equals();scan_normal_dimen;
22272 page_so_far[c]=cur_val;
22273 }
22274
22275 @ @<Declare subprocedures for |prefixed_command|@>=
22276 static void alter_integer(void)
22277 {@+small_number c;
22278 /*0 for \.{\\deadcycles}, 1 for \.{\\insertpenalties}, etc.*/
22279 c=cur_chr;scan_optional_equals();scan_int();
22280 if (c==0) dead_cycles=cur_val
22281 @/@<Cases for |alter_integer|@>@;@/
22282 else insert_penalties=cur_val;
22283 }
22284
22285 @ @<Declare subprocedures for |prefixed_command|@>=
22286 static void alter_box_dimen(void)
22287 {@+small_number c; /*|width_offset| or |height_offset| or |depth_offset|*/
22288 pointer @!b; /*box register*/
22289 c=cur_chr;scan_register_num();fetch_box(b);scan_optional_equals();
22290 scan_normal_dimen;
22291 if (b!=null) mem[b+c].sc=cur_val;
22292 }
22293
22294 @ Paragraph shapes are set up in the obvious way.
22295
22296 @<Assignments@>=
22297 case set_shape: {@+q=cur_chr;scan_optional_equals();scan_int();n=cur_val;
22298 if (n <= 0) p=null;
22299 else if (q > par_shape_loc)
22300 {@+n=(cur_val/2)+1;p=get_node(2*n+1);info(p)=n;
22301 n=cur_val;mem[p+1].i=n; /*number of penalties*/
22302 for (j=p+2; j<=p+n+1; j++)
22303 {@+scan_int();mem[j].i=cur_val; /*penalty values*/
22304 }
22305 if (!odd(n)) mem[p+n+2].i=0; /*unused*/
22306 }
22307 else{@+
22308 scaled fh=0, fv=0;
22309 p=get_node(2*n+1);info(p)=n;
22310 for (j=1; j<=n; j++)
22311 {@+scan_normal_dimen;
22312 mem[p+2*j-1].sc=cur_val; /*indentation*/
22313 scan_normal_dimen;
22314 if (j==1) {fh=cur_hfactor; fv=cur_vfactor;}
22315 mem[p+2*j].sc=cur_val; /*width*/
22316 }
22317 cur_hfactor=fh; cur_vfactor=fv;
22318 }
22319 define(q, shape_ref, p);
22320 } @+break;
22321
22322 @ Here's something that isn't quite so obvious. It guarantees that
22323 |info(par_shape_ptr)| can hold any positive~|n| for which |get_node(2*n+1)|
22324 doesn't overflow the memory capacity.
22325
22326 @<Check the ``constant''...@>=
22327 if (2*max_halfword < mem_top-mem_min) bad=41;
22328
22329 @ New hyphenation data is loaded by the |hyph_data| command.
22330
22331 @<Put each...@>=
22332 primitive("hyphenation", hyph_data, 0);
22333 @!@:hyphenation\_}{\.{\\hyphenation} primitive@>
22334 primitive("patterns", hyph_data, 1);
22335 @!@:patterns\_}{\.{\\patterns} primitive@>
22336
22337 @ @<Cases of |print_cmd_chr|...@>=
22338 case hyph_data: if (chr_code==1) print_esc("patterns");
22339 else print_esc("hyphenation");@+break;
22340
22341 @ @<Assignments@>=
22342 case hyph_data: if (cur_chr==1)
22343 {
22344 #ifdef @!INIT
22345 new_patterns();goto done;@;
22346 #endif
22347 print_err("Patterns can be loaded only by INITEX");
22348 @.Patterns can be...@>
22349 help0;error();
22350 @/do@+{get_token();}@+ while (!(cur_cmd==right_brace)); /*flush the patterns*/
22351 return;
22352 }
22353 else{@+new_hyph_exceptions();goto done;
22354 } @+break;
22355
22356 @ All of \TeX's parameters are kept in |eqtb| except the font information,
22357 the interaction mode, and the hyphenation tables; these are strictly global.
22358
22359 @<Assignments@>=
22360 case assign_font_dimen: {@+find_font_dimen(true);k=cur_val;
22361 scan_optional_equals();scan_normal_dimen;font_info[k].sc=cur_val;
22362 } @+break;
22363 case assign_font_int: {@+n=cur_chr;scan_font_ident();f=cur_val;
22364 scan_optional_equals();scan_int();
22365 if (n==0) hyphen_char[f]=cur_val;@+else skew_char[f]=cur_val;
22366 } @+break;
22367
22368 @ @<Put each...@>=
22369 primitive("hyphenchar", assign_font_int, 0);
22370 @!@:hyphen\_char\_}{\.{\\hyphenchar} primitive@>
22371 primitive("skewchar", assign_font_int, 1);
22372 @!@:skew\_char\_}{\.{\\skewchar} primitive@>
22373
22374 @ @<Cases of |print_cmd_chr|...@>=
22375 case assign_font_int: if (chr_code==0) print_esc("hyphenchar");
22376 else print_esc("skewchar");@+break;
22377
22378 @ Here is where the information for a new font gets loaded.
22379
22380 @<Assignments@>=
22381 case def_font: new_font(a);@+break;
22382
22383 @ @<Declare subprocedures for |prefixed_command|@>=
22384 static void new_font(small_number @!a)
22385 {@+
22386 pointer u; /*user's font identifier*/
22387 scaled @!s; /*stated ``at'' size, or negative of scaled magnification*/
22388 int @!f=null_font; /*runs through existing fonts*/
22389 str_number @!t; /*name for the frozen font identifier*/
22390 str_number @!nom, @!aire;
22391 int @!old_setting; /*holds |selector| setting*/
22392 str_number @!flushable_string; /*string not yet referenced*/
22393 bool @!file_opened; /*was the file successfully opened?*/
22394 char* path = NULL; /*the path of the new font file*/
22395 if (job_name==0) open_log_file();
22396 /*avoid confusing \.{texput} with the font name*/
22397 @.texput@>
22398 get_r_token();u=cur_cs;
22399 if (u >= hash_base) t=text(u);
22400 else if (u >= single_base)
22401 if (u==null_cs) t=s_no("FONT");@+else t=u-single_base;
22402 else{@+old_setting=selector;selector=new_string;
22403 print("FONT");
22404 if (u-active_base<utf8_single_size)
22405 printn(u-active_base);
22406 else
22407 print_utf8(active_hash[u]);
22408 selector=old_setting;
22409 @.FONTx@>
22410 str_room(1);t=make_string();
22411 }
22412 define(u, set_font, null_font);scan_optional_equals();scan_font_name();
22413 nom=cur_name; aire=cur_area;
22414 @<Scan the font size specification@>;
22415 @<Trace the font specification@>@;
22416 @<If this font has already been loaded, set |f| to the internal font number
22417 and |goto common_ending|@>;
22418 @<Open |tfm_file| for input@>;
22419 if (file_opened)
22420 f=read_font_info(u, cur_name, cur_area, cur_ext, s);
22421 else
22422 { @<Open an extended font file for input@>@;
22423 if (path!=NULL)
22424 { if (font_ptr==font_max|| fmem_ptr+8 > font_mem_size)
22425 @<Apologize for not loading the font, |goto done|@>;
22426 font_ptr++;
22427 f=font_ptr;
22428 font_name[f]=nom;
22429 read_extended_font(f,t, cur_name, cur_area, s, path);
22430 @<Initialize the font tables for the extended font |f|@>@;
22431 }
22432 else
22433 { done:
22434 f=null_font;
22435 }
22436 }
22437 common_ending:
22438 define(u, set_font, f);eqtb[font_id_base+f]=eqtb[u];font_id_text(f)=t;
22439 }
22440
22441 @ @<Scan the font size specification@>=
22442 name_in_progress=true; /*this keeps |cur_name| from being changed*/
22443 if (scan_keyword("at")) @<Put the \(p)(positive) `at' size into |s|@>@;
22444 @.at@>
22445 else if (scan_keyword("scaled"))
22446 @.scaled@>
22447 {@+scan_int();s=-cur_val;
22448 if ((cur_val <= 0)||(cur_val > 32768))
22449 {@+print_err("Illegal magnification has been changed to 1000");@/
22450 @.Illegal magnification...@>
22451 help1("The magnification ratio must be between 1 and 32768.");
22452 int_error(cur_val);s=-1000;
22453 }
22454 }
22455 else s=-1000;
22456 name_in_progress=false
22457
22458 @ @<Put the \(p)(positive) `at' size into |s|@>=
22459 {@+scan_normal_dimen;s=cur_val;
22460 if ((s <= 0)||(s >= 01000000000))
22461 {@+print_err("Improper `at' size (");
22462 print_scaled(s);print("pt), replaced by 10pt");
22463 @.Improper `at' size...@>
22464 help2("I can only handle fonts at positive sizes that are",@/
22465 "less than 2048pt, so I've changed what you said to 10pt.");
22466 error();s=10*unity;
22467 }
22468 }
22469
22470 @ When the user gives a new identifier to a font that was previously loaded,
22471 the new name becomes the font identifier of record. Font names `\.{xyz}' and
22472 `\.{XYZ}' are considered to be different. The following test will not cover
22473 the extended fonts. These are tested later.
22474
22475 @<If this font has already been loaded...@>=
22476 flushable_string=str_ptr-1;
22477 for (f=font_base+1; f<=font_ptr; f++)
22478 if (!IS_X_FONT(f) && str_eq_str(font_name[f], cur_name)&&str_eq_str(font_area[f], cur_area))
22479 {@+if (cur_name==flushable_string)
22480 {@+flush_string;cur_name=font_name[f];
22481 }
22482 if (s > 0)
22483 {@+if (s==font_size[f]) goto common_ending;
22484 }
22485 else if (font_size[f]==xn_over_d(font_dsize[f],-s, 1000))
22486 goto common_ending;
22487 }
22488
22489 @ @<Cases of |print_cmd_chr|...@>=
22490 case set_font: {@+print("select font ");slow_print(font_name[chr_code]);
22491 if (font_size[chr_code]!=font_dsize[chr_code])
22492 {@+print(" at ");print_scaled(font_size[chr_code]);
22493 print("pt");
22494 }
22495 } @+break;
22496
22497 @ @<Put each...@>=
22498 primitive("batchmode", set_interaction, batch_mode);
22499 @!@:batch\_mode\_}{\.{\\batchmode} primitive@>
22500 primitive("nonstopmode", set_interaction, nonstop_mode);
22501 @!@:nonstop\_mode\_}{\.{\\nonstopmode} primitive@>
22502 primitive("scrollmode", set_interaction, scroll_mode);
22503 @!@:scroll\_mode\_}{\.{\\scrollmode} primitive@>
22504 primitive("errorstopmode", set_interaction, error_stop_mode);
22505 @!@:error\_stop\_mode\_}{\.{\\errorstopmode} primitive@>
22506
22507 @ @<Cases of |print_cmd_chr|...@>=
22508 case set_interaction: switch (chr_code) {
22509 case batch_mode: print_esc("batchmode");@+break;
22510 case nonstop_mode: print_esc("nonstopmode");@+break;
22511 case scroll_mode: print_esc("scrollmode");@+break;
22512 default:print_esc("errorstopmode");
22513 } @+break;
22514
22515 @ @<Assignments@>=
22516 case set_interaction: new_interaction();@+break;
22517
22518 @ @<Declare subprocedures for |prefixed_command|@>=
22519 static void new_interaction(void)
22520 {@+print_ln();
22521 interaction=cur_chr;
22522 @<Initialize the print |selector| based on |interaction|@>;
22523 if (log_opened) selector=selector+2;
22524 }
22525
22526 @ The \.{\\afterassignment} command puts a token into the global
22527 variable |after_token|. This global variable is examined just after
22528 every assignment has been performed.
22529
22530 @<Glob...@>=
22531 static halfword @!after_token; /*zero, or a saved token*/
22532
22533 @ @<Set init...@>=
22534 after_token=0;
22535
22536 @ @<Cases of |main_control| that don't...@>=
22537 any_mode(after_assignment): {@+get_token();after_token=cur_tok;
22538 } @+break;
22539
22540 @ @<Insert a token saved by \.{\\afterassignment}, if any@>=
22541 if (after_token!=0)
22542 {@+cur_tok=after_token;back_input();after_token=0;
22543 }
22544
22545 @ Here is a procedure that might be called `Get the next non-blank non-relax
22546 non-call non-assignment token'.
22547
22548 @<Declare act...@>=
22549 static void do_assignments(void)
22550 {@+
22551 loop{@+@<Get the next non-blank non-relax...@>;
22552 if (cur_cmd <= max_non_prefixed_command) return;
22553 set_box_allowed=false;prefixed_command();set_box_allowed=true;
22554 }
22555 }
22556
22557 @ @<Cases of |main_control| that don't...@>=
22558 any_mode(after_group): {@+get_token();save_for_after(cur_tok);
22559 } @+break;
22560
22561 @ Files for \.{\\read} are opened and closed by the |in_stream| command.
22562
22563 @<Put each...@>=
22564 primitive("openin", in_stream, 1);
22565 @!@:open\_in\_}{\.{\\openin} primitive@>
22566 primitive("closein", in_stream, 0);
22567 @!@:close\_in\_}{\.{\\closein} primitive@>
22568
22569 @ @<Cases of |print_cmd_chr|...@>=
22570 case in_stream: if (chr_code==0) print_esc("closein");
22571 else print_esc("openin");@+break;
22572
22573 @ @<Cases of |main_control| that don't...@>=
22574 any_mode(in_stream): open_or_close_in();@+break;
22575
22576 @ @<Declare act...@>=
22577 static void open_or_close_in(void)
22578 {@+int c; /*1 for \.{\\openin}, 0 for \.{\\closein}*/
22579 int @!n; /*stream number*/
22580 c=cur_chr;scan_four_bit_int();n=cur_val;
22581 if (read_open[n]!=closed)
22582 {@+a_close(&read_file[n]);read_open[n]=closed;
22583 }
22584 if (c!=0)
22585 {@+scan_optional_equals();scan_file_name();
22586 pack_cur_name(".tex");
22587 if (a_open_in(&read_file[n])) read_open[n]=just_open;
22588 }
22589 }
22590
22591 @ The user can issue messages to the terminal, regardless of the
22592 current mode.
22593
22594 @<Cases of |main_control| that don't...@>=
22595 any_mode(message): issue_message();@+break;
22596
22597 @ @<Put each...@>=
22598 primitive("message", message, 0);
22599 @!@:message\_}{\.{\\message} primitive@>
22600 primitive("errmessage", message, 1);
22601 @!@:err\_message\_}{\.{\\errmessage} primitive@>
22602
22603 @ @<Cases of |print_cmd_chr|...@>=
22604 case message: if (chr_code==0) print_esc("message");
22605 else print_esc("errmessage");@+break;
22606
22607 @ @<Declare act...@>=
22608 static void issue_message(void)
22609 {@+int old_setting; /*holds |selector| setting*/
22610 int @!c; /*identifies \.{\\message} and \.{\\errmessage}*/
22611 str_number @!s; /*the message*/
22612 c=cur_chr;link(garbage)=scan_toks(false, true);
22613 old_setting=selector;selector=new_string;
22614 token_show(def_ref);selector=old_setting;
22615 flush_list(def_ref);
22616 str_room(1);s=make_string();
22617 if (c==0) @<Print string |s| on the terminal@>@;
22618 else@<Print string |s| as an error message@>;
22619 flush_string;
22620 }
22621
22622 @ @<Print string |s| on the terminal@>=
22623 {@+if (term_offset+length(s) > max_print_line-2) print_ln();
22624 else if ((term_offset > 0)||(file_offset > 0)) print_char(' ');
22625 slow_print(s);update_terminal;
22626 }
22627
22628 @ If \.{\\errmessage} occurs often in |scroll_mode|, without user-defined
22629 \.{\\errhelp}, we don't want to give a long help message each time. So we
22630 give a verbose explanation only once.
22631
22632 @<Glob...@>=
22633 static bool @!long_help_seen; /*has the long \.{\\errmessage} help been used?*/
22634
22635 @ @<Set init...@>=long_help_seen=false;
22636
22637 @ @<Print string |s| as an error message@>=
22638 {@+print_err("");slow_print(s);
22639 if (err_help!=null) use_err_help=true;
22640 else if (long_help_seen) help1("(That was another \\errmessage.)")@;
22641 else{@+if (interaction < error_stop_mode) long_help_seen=true;
22642 help4("This error message was generated by an \\errmessage",@/
22643 "command, so I can't give any explicit help.",@/
22644 "Pretend that you're Hercule Poirot: Examine all clues,",@/
22645 @^Poirot, Hercule@>
22646 "and deduce the truth by order and method.");
22647 }
22648 error();use_err_help=false;
22649 }
22650
22651 @ The |error| routine calls on |give_err_help| if help is requested from
22652 the |err_help| parameter.
22653
22654 @p static void give_err_help(void)
22655 {@+token_show(err_help);
22656 }
22657
22658 @ The \.{\\uppercase} and \.{\\lowercase} commands are implemented by
22659 building a token list and then changing the cases of the letters in it.
22660
22661 @<Cases of |main_control| that don't...@>=
22662 any_mode(case_shift): shift_case();@+break;
22663
22664 @ @<Put each...@>=
22665 primitive("lowercase", case_shift, utf_lc_code_base);
22666 @!@:lowercase\_}{\.{\\lowercase} primitive@>
22667 primitive("uppercase", case_shift, utf_uc_code_base);
22668 @!@:uppercase\_}{\.{\\uppercase} primitive@>
22669
22670 @ @<Cases of |print_cmd_chr|...@>=
22671 case case_shift: if (chr_code==utf_lc_code_base) print_esc("lowercase");
22672 else print_esc("uppercase");@+break;
22673
22674 @ @<Declare act...@>=
22675 static void shift_case(void)
22676 {@+pointer b; /*|lc_code_base| or |uc_code_base|*/
22677 pointer @!p; /*runs through the token list*/
22678 halfword @!t; /*token*/
22679 int @!c; /*character code*/
22680 b=cur_chr;p=scan_toks(false, false);p=link(def_ref);
22681 while (p!=null)
22682 {@+@<Change the case of the token in |p|, if a change is appropriate@>;
22683 p=link(p);
22684 }
22685 back_list(link(def_ref));free_avail(def_ref); /*omit reference count*/
22686 }
22687
22688 @ When the case of a |chr_code| changes, we don't change the |cmd|.
22689 We also change active characters, using the fact that
22690 |cs_token_flag+active_base| is a multiple of~256.
22691 @^data structure assumptions@>
22692
22693 @<Change the case of the token in |p|, if a change is appropriate@>=
22694 t=info(p);
22695 if (t < cs_token_flag+single_base)
22696 {@+c=t%cmd_factor;
22697 if (c>=utf8_single_size)
22698 c=active_hash[c];
22699 if (b==utf_lc_code_base)
22700 { int d = utf_lccode(c);
22701 if (d!=0) info(p)=t-c+d;
22702 }
22703 else if (b==utf_uc_code_base)
22704 { int d = utf_uccode(c);
22705 if (d!=0) info(p)=t-c+d;
22706 }
22707 }
22708
22709 @ We come finally to the last pieces missing from |main_control|, namely the
22710 `\.{\\show}' commands that are useful when debugging.
22711
22712 @<Cases of |main_control| that don't...@>=
22713 any_mode(xray): show_whatever();@+break;
22714
22715 @ @d show_code 0 /* \.{\\show} */
22716 @d show_box_code 1 /* \.{\\showbox} */
22717 @d show_the_code 2 /* \.{\\showthe} */
22718 @d show_lists_code 3 /* \.{\\showlists} */
22719
22720 @<Put each...@>=
22721 primitive("show", xray, show_code);
22722 @!@:show\_}{\.{\\show} primitive@>
22723 primitive("showbox", xray, show_box_code);
22724 @!@:show\_box\_}{\.{\\showbox} primitive@>
22725 primitive("showthe", xray, show_the_code);
22726 @!@:show\_the\_}{\.{\\showthe} primitive@>
22727 primitive("showlists", xray, show_lists_code);
22728 @!@:show\_lists\_code\_}{\.{\\showlists} primitive@>
22729
22730 @ @<Cases of |print_cmd_chr|...@>=
22731 case xray: switch (chr_code) {
22732 case show_box_code: print_esc("showbox");@+break;
22733 case show_the_code: print_esc("showthe");@+break;
22734 case show_lists_code: print_esc("showlists");@+break;
22735 @<Cases of |xray| for |print_cmd_chr|@>@;@/
22736 default:print_esc("show");
22737 } @+break;
22738
22739 @ @<Declare act...@>=
22740 static void show_whatever(void)
22741 {@+
22742 pointer p; /*tail of a token list to show*/
22743 small_number @!t; /*type of conditional being shown*/
22744 int @!m; /*upper bound on |fi_or_else| codes*/
22745 int @!l; /*line where that conditional began*/
22746 int @!n; /*level of \.{\\if...\\fi} nesting*/
22747 switch (cur_chr) {
22748 case show_lists_code: {@+begin_diagnostic();show_activities();
22749 } @+break;
22750 case show_box_code: @<Show the current contents of a box@>@;@+break;
22751 case show_code: @<Show the current meaning of a token, then |goto common_ending|@>@;
22752 @<Cases for |show_whatever|@>@;@/
22753 default:@<Show the current value of some parameter or register, then |goto
22754 common_ending|@>@;
22755 } @/
22756 @<Complete a potentially long \.{\\show} command@>;
22757 common_ending: if (interaction < error_stop_mode)
22758 {@+help0;decr(error_count);
22759 }
22760 else if (tracing_online > 0)
22761 {@+@t@>@;@/
22762 help3("This isn't an error message; I'm just \\showing something.",@/
22763 "Type `I\\show...' to show more (e.g., \\show\\cs,",@/
22764 "\\showthe\\count10, \\showbox255, \\showlists).");
22765 }
22766 else{@+@t@>@;@/
22767 help5("This isn't an error message; I'm just \\showing something.",@/
22768 "Type `I\\show...' to show more (e.g., \\show\\cs,",@/
22769 "\\showthe\\count10, \\showbox255, \\showlists).",@/
22770 "And type `I\\tracingonline=1\\show...' to show boxes and",@/
22771 "lists on your terminal as well as in the transcript file.");
22772 }
22773 error();
22774 }
22775
22776 @ @<Show the current meaning of a token...@>=
22777 {@+get_token();
22778 if (interaction==error_stop_mode) wake_up_terminal;
22779 print_nl("> ");
22780 if (cur_cs!=0)
22781 {@+sprint_cs(cur_cs);print_char('=');
22782 }
22783 print_meaning();goto common_ending;
22784 }
22785
22786 @ @<Cases of |print_cmd_chr|...@>=
22787 case undefined_cs: print("undefined");@+break;
22788 case call: case long_call: case outer_call:
22789 case long_outer_call: {@+n=cmd-call;
22790 if (info(link(chr_code))==protected_token) n=n+4;
22791 if (odd(n/4)) print_esc("protected");
22792 if (odd(n)) print_esc("long");
22793 if (odd(n/2)) print_esc("outer");
22794 if (n > 0) print_char(' ');
22795 print("macro");
22796 } @+break;
22797 case end_template: print_esc("outer endtemplate");@+break;
22798
22799 @ @<Show the current contents of a box@>=
22800 {@+scan_register_num();fetch_box(p);begin_diagnostic();
22801 print_nl("> \\box");print_int(cur_val);print_char('=');
22802 if (p==null) print("void");@+else show_box(p);
22803 }
22804
22805 @ @<Show the current value of some parameter...@>=
22806 {@+the_toks();
22807 if (interaction==error_stop_mode) wake_up_terminal;
22808 print_nl("> ");token_show(temp_head);
22809 flush_list(link(temp_head));goto common_ending;
22810 }
22811
22812 @ @<Complete a potentially long \.{\\show} command@>=
22813 end_diagnostic(true);print_err("OK");
22814 @.OK@>
22815 if (selector==term_and_log) if (tracing_online <= 0)
22816 {@+selector=term_only;print(" (see the transcript file)");
22817 selector=term_and_log;
22818 }
22819
22820 @* Dumping and undumping the tables.
22821 After \.{INITEX} has seen a collection of fonts and macros, it
22822 can write all the necessary information on an auxiliary file so
22823 that production versions of \TeX\ are able to initialize their
22824 memory at high speed. The present section of the program takes
22825 care of such output and input. We shall consider simultaneously
22826 the processes of storing and restoring,
22827 so that the inverse relation between them is clear.
22828 @.INITEX@>
22829
22830 The global variable |format_ident| is a string that is printed right
22831 after the |banner| line when \TeX\ is ready to start. For \.{INITEX} this
22832 string says simply `\.{ (INITEX)}'; for other versions of \TeX\ it says,
22833 for example, `\.{ (preloaded format=plain 1982.11.19)}', showing the year,
22834 month, and day that the format file was created. We have |format_ident==0|
22835 before \TeX's tables are loaded.
22836
22837 @<Glob...@>=
22838 static str_number @!format_ident, frozen_format_ident;
22839
22840 @ @<Set init...@>=
22841 format_ident=frozen_format_ident=0;
22842
22843 @ We keep a copy of the initial value, be able to test for it later.
22844
22845 @<Initialize table entries...@>=
22846 format_ident=frozen_format_ident=s_no(" (INITEX)");
22847
22848 @ @<Declare act...@>=
22849 #ifdef @!INIT
22850 static void store_fmt_file(void)
22851 {@+
22852 int j, @!k, @!l; /*all-purpose indices*/
22853 int @!p, @!q; /*all-purpose pointers*/
22854 int @!x; /*something to dump*/
22855 four_quarters @!w; /*four ASCII codes*/
22856 @<If dumping is not allowed, abort@>;
22857 @<Create the |format_ident|, open the format file, and inform the user that
22858 dumping has begun@>;
22859 eqtb[dimen_base+hsize_code].i=hhsize;
22860 eqtb[dimen_base+vsize_code].i=hvsize;
22861 @<Dump constants for consistency check@>;
22862 @<Dump the string pool@>;
22863 @<Dump the dynamic memory@>;
22864 @<Dump the table of equivalents@>;
22865 @<Dump the font information@>;
22866 @<Dump the hyphenation tables@>;
22867 @<Dump a couple more things and the closing check word@>;
22868 @<Close the format file@>;
22869 eqtb[dimen_base+hsize_code].i=0;
22870 eqtb[dimen_base+vsize_code].i=0;
22871 }
22872 #endif
22873
22874 @ Corresponding to the procedure that dumps a format file, we have a function
22875 that reads one in. The function returns |false| if the dumped format is
22876 incompatible with the present \TeX\ table sizes, etc.
22877
22878 @d too_small(X) {@+wake_up_terminal;
22879 wterm_ln("---! Must increase the %s", X);
22880 @.Must increase the x@>
22881 goto bad_fmt;
22882 }
22883
22884 @p @t\4@>@<Declare the function called |open_fmt_file|@>@;
22885 static bool load_fmt_file(void)
22886 {@+
22887 int j, @!k; /*all-purpose indices*/
22888 int @!p, @!q; /*all-purpose pointers*/
22889 int @!x; /*something undumped*/
22890 four_quarters @!w; /*four ASCII codes*/
22891 @<Undump constants for consistency check@>;
22892 @<Undump the string pool@>;
22893 @<Undump the dynamic memory@>;
22894 @<Undump the table of equivalents@>;
22895 @<Undump the font information@>;
22896 @<Undump the hyphenation tables@>;
22897 @<Undump a couple more things and the closing check word@>;
22898 return true; /*it worked!*/
22899 bad_fmt: wake_up_terminal;
22900 wterm_ln("(Fatal format file error; I'm stymied)");
22901 @.Fatal format file error@>
22902 return false;
22903 }
22904
22905 @ The user is not allowed to dump a format file unless |save_ptr==0|.
22906 This condition implies that |cur_level==level_one|, hence
22907 the |xeq_level| array is constant and it need not be dumped.
22908
22909 @<If dumping is not allowed, abort@>=
22910 if (save_ptr!=0)
22911 {@+print_err("You can't dump inside a group");
22912 @.You can't dump...@>
22913 help1("`{...\\dump}' is a no-no.");succumb;
22914 }
22915
22916 @ Format files consist of |memory_word| items, and we use the following
22917 macros to dump words of different types:
22918
22919 @d dump_wd(A) {@+fmt_file.d=A;put(fmt_file);@+}
22920 @d dump_int(A) {@+fmt_file.d.i=A;put(fmt_file);@+}
22921 @d dump_hh(A) {@+fmt_file.d.hh=A;put(fmt_file);@+}
22922 @d dump_qqqq(A) {@+fmt_file.d.qqqq=A;put(fmt_file);@+}
22923
22924 @<Glob...@>=
22925 static word_file @!fmt_file; /*for input or output of format information*/
22926
22927 @ The inverse macros are slightly more complicated, since we need to check
22928 the range of the values we are reading in. We say `|undump(a)(b)(x)|' to
22929 read an integer value |x| that is supposed to be in the range |a <= x <= b|.
22930 System error messages should be suppressed when undumping.
22931 @^system dependencies@>
22932
22933 @d undump_wd(A) {@+get(fmt_file);A=fmt_file.d;@+}
22934 @d undump_int(A) {@+get(fmt_file);A=fmt_file.d.i;@+}
22935 @d undump_hh(A) {@+get(fmt_file);A=fmt_file.d.hh;@+}
22936 @d undump_qqqq(A) {@+get(fmt_file);A=fmt_file.d.qqqq;@+}
22937 @d undump(A, B, C) {@+undump_int(x);if ((x < A)||(x > B)) goto bad_fmt;@+else C=x;@+}
22938 @d undump_size(A, B, C, D) {@+undump_int(x);
22939 if (x < A) goto bad_fmt;if (x > B) too_small(C)@;@+else D=x;@+}
22940
22941 @ The next few sections of the program should make it clear how we use the
22942 dump/undump macros.
22943
22944 @<Dump constants for consistency check@>=
22945 dump_int(0);@/
22946 @<Dump the \eTeX\ state@>@/
22947 @<Dump the \Prote\ state@>@/
22948 @<Dump the |ROM| array@>@/
22949 dump_int(mem_bot);@/
22950 dump_int(mem_top);@/
22951 dump_int(eqtb_size);@/
22952 dump_int(hash_prime);@/
22953 dump_int(hyph_size)
22954
22955 @ Sections of a \.{WEB} program that are ``commented out'' still contribute
22956 strings to the string pool; therefore \.{INITEX} and \TeX\ will have
22957 the same strings. (And it is, of course, a good thing that they do.)
22958 @.WEB@>
22959 @^string pool@>
22960
22961 @<Undump constants for consistency check@>=
22962 x=fmt_file.d.i;
22963 if (x!=0) goto bad_fmt; /*check that strings are the same*/
22964 @/@<Undump the \eTeX\ state@>@/
22965 @/@<Undump the \Prote\ state@>@/
22966 @/@<Undump the |ROM| array@>@/
22967 undump_int(x);
22968 if (x!=mem_bot) goto bad_fmt;
22969 undump_int(x);
22970 if (x!=mem_top) goto bad_fmt;
22971 undump_int(x);
22972 if (x!=eqtb_size) goto bad_fmt;
22973 undump_int(x);
22974 if (x!=hash_prime) goto bad_fmt;
22975 undump_int(x);
22976 if (x!=hyph_size) goto bad_fmt
22977
22978 @ @d dump_four_ASCII
22979 w.b0=qi(str_pool[k]);w.b1=qi(str_pool[k+1]);
22980 w.b2=qi(str_pool[k+2]);w.b3=qi(str_pool[k+3]);
22981 dump_qqqq(w)
22982
22983 @<Dump the string pool@>=
22984 dump_int(pool_ptr);
22985 dump_int(str_ptr);
22986 for (k=0; k<=str_ptr; k++) dump_int(str_start[k]);
22987 k=0;
22988 while (k+4 < pool_ptr)
22989 {@+dump_four_ASCII;k=k+4;
22990 }
22991 k=pool_ptr-4;dump_four_ASCII;
22992 print_ln();print_int(str_ptr);print(" strings of total length ");
22993 print_int(pool_ptr)
22994
22995 @ @d undump_four_ASCII
22996 undump_qqqq(w);
22997 str_pool[k]=qo(w.b0);str_pool[k+1]=qo(w.b1);
22998 str_pool[k+2]=qo(w.b2);str_pool[k+3]=qo(w.b3)
22999
23000 @<Undump the string pool@>=
23001 undump_size(0, pool_size,"string pool size", pool_ptr);
23002 undump_size(0, max_strings,"max strings", str_ptr);
23003 for (k=0; k<=str_ptr; k++) undump(0, pool_ptr, str_start[k]);
23004 k=0;
23005 while (k+4 < pool_ptr)
23006 {@+undump_four_ASCII;k=k+4;
23007 }
23008 k=pool_ptr-4;undump_four_ASCII;
23009 init_str_ptr=str_ptr;init_pool_ptr=pool_ptr
23010
23011 @ By sorting the list of available spaces in the variable-size portion of
23012 |mem|, we are usually able to get by without having to dump very much
23013 of the dynamic memory.
23014
23015 We recompute |var_used| and |dyn_used|, so that \.{INITEX} dumps valid
23016 information even when it has not been gathering statistics.
23017
23018 @<Dump the dynamic memory@>=
23019 sort_avail();var_used=0;
23020 dump_int(lo_mem_max);dump_int(rover);
23021 if (eTeX_ex) for (k=int_val; k<=tok_val; k++) dump_int(sa_root[k]);
23022 p=mem_bot;q=rover;x=0;
23023 @/do@+{for (k=p; k<=q+1; k++) dump_wd(mem[k]);
23024 x=x+q+2-p;var_used=var_used+q-p;
23025 p=q+node_size(q);q=rlink(q);
23026 }@+ while (!(q==rover));
23027 var_used=var_used+lo_mem_max-p;dyn_used=mem_end+1-hi_mem_min;@/
23028 for (k=p; k<=lo_mem_max; k++) dump_wd(mem[k]);
23029 x=x+lo_mem_max+1-p;
23030 dump_int(hi_mem_min);dump_int(avail);
23031 for (k=hi_mem_min; k<=mem_end; k++) dump_wd(mem[k]);
23032 x=x+mem_end+1-hi_mem_min;
23033 p=avail;
23034 while (p!=null)
23035 {@+decr(dyn_used);p=link(p);
23036 }
23037 dump_int(var_used);dump_int(dyn_used);
23038 print_ln();print_int(x);
23039 print(" memory locations dumped; current usage is ");
23040 print_int(var_used);print_char('&');print_int(dyn_used)
23041
23042 @ @<Undump the dynamic memory@>=
23043 undump(lo_mem_stat_max+1000, hi_mem_stat_min-1, lo_mem_max);
23044 undump(lo_mem_stat_max+1, lo_mem_max, rover);
23045 if (eTeX_ex) for (k=int_val; k<=tok_val; k++)
23046 undump(null, lo_mem_max, sa_root[k]);
23047 p=mem_bot;q=rover;
23048 @/do@+{for (k=p; k<=q+1; k++) undump_wd(mem[k]);
23049 p=q+node_size(q);
23050 if ((p > lo_mem_max)||((q >= rlink(q))&&(rlink(q)!=rover))) goto bad_fmt;
23051 q=rlink(q);
23052 }@+ while (!(q==rover));
23053 for (k=p; k<=lo_mem_max; k++) undump_wd(mem[k]);
23054 if (mem_min < mem_bot-2) /*make more low memory available*/
23055 {@+p=llink(rover);q=mem_min+1;
23056 link(mem_min)=null;info(mem_min)=null; /*we don't use the bottom word*/
23057 rlink(p)=q;llink(rover)=q;@/
23058 rlink(q)=rover;llink(q)=p;link(q)=empty_flag;
23059 node_size(q)=mem_bot-q;
23060 }
23061 undump(lo_mem_max+1, hi_mem_stat_min, hi_mem_min);
23062 undump(null, mem_top, avail);mem_end=mem_top;
23063 for (k=hi_mem_min; k<=mem_end; k++) undump_wd(mem[k]);
23064 undump_int(var_used);undump_int(dyn_used)
23065
23066 @ @<Dump the table of equivalents@>=
23067 @<Dump regions 1 to 4 of |eqtb|@>;
23068 @<Dump regions 5 and 6 of |eqtb|@>;
23069 @<Dump the |active_hash| table@>@;
23070 dump_int(par_loc);dump_int(write_loc);@/
23071 dump_int(input_loc);@/
23072 @<Dump the hash table@>@;
23073
23074 @ @<Undump the table of equivalents@>=
23075 @<Undump regions 1 to 6 of |eqtb|@>;
23076 @<Undump the |active_hash| table@>@;
23077 undump(hash_base, frozen_control_sequence, par_loc);
23078 par_token=cs_token_flag+par_loc;@/
23079 undump(hash_base, frozen_control_sequence, write_loc);@/
23080 undump(hash_base, frozen_control_sequence, input_loc);
23081 input_token=cs_token_flag+input_loc;@/
23082 @<Undump the hash table@>@;
23083
23084 @ The table of equivalents usually contains repeated information, so we dump it
23085 in compressed form: The sequence of $n+2$ values $(n,x_1,\ldots,x_n,m)$ in the
23086 format file represents $n+m$ consecutive entries of |eqtb|, with |m| extra
23087 copies of $x_n$, namely $(x_1,\ldots,x_n,x_n,\ldots,x_n)$.
23088
23089 @<Dump regions 1 to 4 of |eqtb|@>=
23090 k=active_base;
23091 @/do@+{j=k;
23092 while (j < int_base-1)
23093 {@+if ((equiv(j)==equiv(j+1))&&(eq_type(j)==eq_type(j+1))&&@|
23094 (eq_level(j)==eq_level(j+1))) goto found1;
23095 incr(j);
23096 }
23097 l=int_base;goto done1; /*|j==int_base-1|*/
23098 found1: incr(j);l=j;
23099 while (j < int_base-1)
23100 {@+if ((equiv(j)!=equiv(j+1))||(eq_type(j)!=eq_type(j+1))||@|
23101 (eq_level(j)!=eq_level(j+1))) goto done1;
23102 incr(j);
23103 }
23104 done1: dump_int(l-k);
23105 while (k < l)
23106 {@+dump_wd(eqtb[k]);incr(k);
23107 }
23108 k=j+1;dump_int(k-l);
23109 }@+ while (!(k==int_base))
23110
23111 @ @<Dump regions 5 and 6 of |eqtb|@>=
23112 @/do@+{j=k;
23113 while (j < eqtb_size)
23114 {@+if (eqtb[j].i==eqtb[j+1].i) goto found2;
23115 incr(j);
23116 }
23117 l=eqtb_size+1;goto done2; /*|j==eqtb_size|*/
23118 found2: incr(j);l=j;
23119 while (j < eqtb_size)
23120 {@+if (eqtb[j].i!=eqtb[j+1].i) goto done2;
23121 incr(j);
23122 }
23123 done2: dump_int(l-k);
23124 while (k < l)
23125 {@+dump_wd(eqtb[k]);incr(k);
23126 }
23127 k=j+1;dump_int(k-l);
23128 }@+ while (!(k > eqtb_size))
23129
23130 @ @<Undump regions 1 to 6 of |eqtb|@>=
23131 k=active_base;
23132 @/do@+{undump_int(x);
23133 if ((x < 1)||(k+x > eqtb_size+1)) goto bad_fmt;
23134 for (j=k; j<=k+x-1; j++) undump_wd(eqtb[j]);
23135 k=k+x;
23136 undump_int(x);
23137 if ((x < 0)||(k+x > eqtb_size+1)) goto bad_fmt;
23138 for (j=k; j<=k+x-1; j++) eqtb[j]=eqtb[k-1];
23139 k=k+x;
23140 }@+ while (!(k > eqtb_size))
23141
23142 @ A different scheme is used to compress the hash table, since its lower
23143 region is usually sparse. When |text(p)!=0| for |p <= hash_used|, we output
23144 two words, |p| and |hash[p]|. The hash table is, of course, densely packed
23145 for |p >= hash_used|, so the remaining entries are output in a~block.
23146
23147 @<Dump the hash table@>=
23148 dump_int(hash_used);cs_count=frozen_control_sequence-1-hash_used;
23149 for (p=hash_base; p<=hash_used; p++) if (text(p)!=0)
23150 {@+dump_int(p);dump_hh(hash[p]);incr(cs_count);
23151 }
23152 for (p=hash_used+1; p<=undefined_control_sequence-1; p++) dump_hh(hash[p]);
23153 dump_int(cs_count);@/
23154 print_ln();print_int(cs_count);print(" multiletter control sequences")
23155
23156 @ @<Undump the hash table@>=
23157 undump(hash_base, frozen_control_sequence, hash_used);p=hash_base-1;
23158 @/do@+{undump(p+1, hash_used, p);undump_hh(hash[p]);
23159 }@+ while (!(p==hash_used));
23160 for (p=hash_used+1; p<=undefined_control_sequence-1; p++) undump_hh(hash[p]);
23161 undump_int(cs_count)
23162
23163 @ @<Dump the font information@>=
23164 dump_int(fmem_ptr);
23165 for (k=0; k<=fmem_ptr-1; k++) dump_wd(font_info[k]);
23166 dump_int(font_ptr);
23167 for (k=null_font; k<=font_ptr; k++)
23168 {
23169 #if 0
23170 if (IS_X_FONT(k)) fatal_error("I can't dump extended fonts. Sorry!");
23171 #endif
23172 @<Dump the array info for internal font number |k|@>;
23173 }
23174 print_ln();print_int(fmem_ptr-7);print(" words of font info for ");
23175 print_int(font_ptr-font_base);print(" preloaded font");
23176 if (font_ptr!=font_base+1) print_char('s')
23177
23178 @ @<Undump the font information@>=
23179 undump_size(7, font_mem_size,"font mem size", fmem_ptr);
23180 for (k=0; k<=fmem_ptr-1; k++) undump_wd(font_info[k]);
23181 undump_size(font_base, font_max,"font max", font_ptr);
23182 for (k=null_font; k<=font_ptr; k++)
23183 @<Undump the array info for internal font number |k|@>@;
23184
23185 @ @<Dump the array info for internal font number |k|@>=
23186 {@+dump_qqqq(font_check[k]);
23187 dump_int(font_size[k]);
23188 dump_int(font_dsize[k]);
23189 dump_int(font_params[k]);@/
23190 dump_int(hyphen_char[k]);
23191 dump_int(skew_char[k]);@/
23192 dump_int(font_name[k]);
23193 dump_int(font_area[k]);@/
23194 dump_int(font_bc[k]);
23195 dump_int(font_ec[k]);@/
23196 dump_int(char_base[k]);
23197 dump_int(width_base[k]);
23198 dump_int(height_base[k]);@/
23199 dump_int(depth_base[k]);
23200 dump_int(italic_base[k]);
23201 dump_int(lig_kern_base[k]);@/
23202 dump_int(kern_base[k]);
23203 dump_int(exten_base[k]);
23204 dump_int(param_base[k]);@/
23205 dump_int(font_glue[k]);@/
23206 dump_int(bchar_label[k]);
23207 dump_int(font_bchar[k]);
23208 dump_int(font_false_bchar[k]);@/
23209 print_nl("\\font");printn_esc(font_id_text(k));print_char('=');
23210 print_file_name(font_name[k], font_area[k],empty_string);
23211 if (font_size[k]!=font_dsize[k])
23212 {@+print(" at ");print_scaled(font_size[k]);print("pt");
23213 }
23214 }
23215
23216 @ @<Undump the array info for internal font number |k|@>=
23217 {@+undump_qqqq(font_check[k]);@/
23218 undump_int(font_size[k]);
23219 undump_int(font_dsize[k]);
23220 undump(min_halfword, max_halfword, font_params[k]);@/
23221 undump_int(hyphen_char[k]);
23222 undump_int(skew_char[k]);@/
23223 undump(0, str_ptr, font_name[k]);
23224 undump(0, str_ptr, font_area[k]);@/
23225 undump(0, biggest_char, font_bc[k]);
23226 undump(0, biggest_char, font_ec[k]);@/
23227 undump_int(char_base[k]);
23228 undump_int(width_base[k]);
23229 undump_int(height_base[k]);@/
23230 undump_int(depth_base[k]);
23231 undump_int(italic_base[k]);
23232 undump_int(lig_kern_base[k]);@/
23233 undump_int(kern_base[k]);
23234 undump_int(exten_base[k]);
23235 undump_int(param_base[k]);@/
23236 undump(min_halfword, lo_mem_max, font_glue[k]);@/
23237 undump(0, fmem_ptr-1, bchar_label[k]);
23238 undump(min_quarterword, non_char, font_bchar[k]);
23239 undump(min_quarterword, non_char, font_false_bchar[k]);
23240 }
23241
23242 @ @<Dump the hyphenation tables@>=
23243 dump_int(hyph_count);
23244 for (k=0; k<=hyph_size; k++) if (hyph_word[k]!=0)
23245 {@+dump_int(k);dump_int(hyph_word[k]);dump_int(hyph_list[k]);
23246 }
23247 print_ln();print_int(hyph_count);print(" hyphenation exception");
23248 if (hyph_count!=1) print_char('s');
23249 if (trie_not_ready) init_trie();
23250 dump_int(trie_max);
23251 dump_int(hyph_start);
23252 for (k=0; k<=trie_max; k++) dump_hh(trie[k]);
23253 dump_int(max_hyph_char);
23254 dump_int(trie_op_ptr);
23255 for (k=1; k<=trie_op_ptr; k++)
23256 {@+dump_int(hyf_distance[k]);
23257 dump_int(hyf_num[k]);
23258 dump_int(hyf_next[k]);
23259 }
23260 print_nl("Hyphenation trie of length ");print_int(trie_max);
23261 @.Hyphenation trie...@>
23262 print(" has ");print_int(trie_op_ptr);print(" op");
23263 if (trie_op_ptr!=1) print_char('s');
23264 print(" out of ");print_int(trie_op_size);
23265 print_nl("Largest codepoint in hyphenation patterns ");print_int(max_hyph_char);
23266 print(" is lower than "); print_int(max_pattern_char);
23267 for (k=max_language; k>=0; k--) if (trie_used[k] > min_quarterword)
23268 {@+print_nl(" ");print_int(qo(trie_used[k]));
23269 print(" for language ");print_int(k);
23270 dump_int(k);dump_int(qo(trie_used[k]));
23271 }
23272
23273 @ Only ``nonempty'' parts of |op_start| need to be restored.
23274
23275 @<Undump the hyphenation tables@>=
23276 undump(0, hyph_size, hyph_count);
23277 for (k=1; k<=hyph_count; k++)
23278 {@+undump(0, hyph_size, j);
23279 undump(0, str_ptr, hyph_word[j]);
23280 undump(min_halfword, max_halfword, hyph_list[j]);
23281 }
23282 undump_size(0, trie_size,"trie size", j);
23283 #ifdef @!INIT
23284 trie_max=j;
23285 #endif
23286 undump(0, j, hyph_start);
23287 for (k=0; k<=j; k++) undump_hh(trie[k]);
23288 undump_int(max_hyph_char);
23289 undump_size(0, trie_op_size,"trie op size", j);
23290 #ifdef @!INIT
23291 trie_op_ptr=j;
23292 #endif
23293 for (k=1; k<=j; k++)
23294 {@+undump(0, 63, hyf_distance[k]); /*a |small_number|*/
23295 undump(0, 63, hyf_num[k]);
23296 undump(min_quarterword, max_quarterword, hyf_next[k]);
23297 }
23298 #ifdef @!INIT
23299 for (k=0; k<=max_language; k++) trie_used[k]=min_quarterword;
23300 #endif
23301 @;@/
23302 k=256;
23303 while (j > 0)
23304 {@+undump(0, k-1, k);undump(1, j, x);
23305 #ifdef @!INIT
23306 trie_used[k]=qi(x);
23307 #endif
23308 @;@/
23309 j=j-x;op_start[k]=qo(j);
23310 }
23311 #ifdef @!INIT
23312 trie_not_ready=false
23313 #endif
23314
23315 @ We have already printed a lot of statistics, so we set |tracing_stats=0|
23316 to prevent them from appearing again.
23317
23318 @<Dump a couple more things and the closing check word@>=
23319 dump_int(interaction);dump_int(format_ident);dump_int(69069);
23320 tracing_stats=0
23321
23322 @ @<Undump a couple more things and the closing check word@>=
23323 undump(batch_mode, error_stop_mode, interaction);
23324 if (interaction_option>=0) interaction=interaction_option; /* \TeX\ Live */
23325 undump(0, str_ptr, format_ident);
23326 undump_int(x);
23327 if ((x!=69069)||eof(fmt_file)) goto bad_fmt
23328
23329 @ @<Create the |format_ident|...@>=
23330 selector=new_string;
23331 print(" (preloaded format=");printn(job_name);print_char(' ');
23332 print_int(year);print_char('.');
23333 print_int(month);print_char('.');print_int(day);print_char(')');
23334 if (interaction==batch_mode) selector=log_only;
23335 else selector=term_and_log;
23336 str_room(1);
23337 format_ident=make_string();
23338 pack_job_name(format_extension);
23339 while (!w_open_out(&fmt_file))
23340 prompt_file_name("format file name", format_extension);
23341 print_nl("Beginning to dump on file ");
23342 @.Beginning to dump...@>
23343 slow_print(w_make_name_string(&fmt_file));flush_string;
23344 print_nl("");slow_print(format_ident)
23345
23346 @ @<Close the format file@>=
23347 w_close(&fmt_file)
23348
23349 @* The main program.
23350 This is it: the part of \TeX\ that executes all those procedures we have
23351 written.
23352
23353 Well---almost. Let's leave space for a few more routines that we may
23354 have forgotten.
23355
23356 @p @<Last-minute procedures@>@;
23357
23358 @ We have noted that there are two versions of \TeX82. One, called \.{INITEX},
23359 @.INITEX@>
23360 has to be run first; it initializes everything from scratch, without
23361 reading a format file, and it has the capability of dumping a format file.
23362 The other one is called `\.{VIRTEX}'; it is a ``virgin'' program that needs
23363 @.VIRTEX@>
23364 to input a format file in order to get started. \.{VIRTEX} typically has
23365 more memory capacity than \.{INITEX}, because it does not need the space
23366 consumed by the auxiliary hyphenation tables and the numerous calls on
23367 |primitive|, etc.
23368
23369 The \.{VIRTEX} program cannot read a format file instantaneously, of course;
23370 the best implementations therefore allow for production versions of \TeX\ that
23371 not only avoid the loading routine for \PASCAL\ object code, they also have
23372 a format file pre-loaded. This is impossible to do if we stick to standard
23373 \PASCAL; but there is a simple way to fool many systems into avoiding the
23374 initialization, as follows:\quad(1)~We declare a global integer variable
23375 called |ready_already|. The probability is negligible that this
23376 variable holds any particular value like 314159 when \.{VIRTEX} is first
23377 loaded.\quad(2)~After we have read in a format file and initialized
23378 everything, we set |ready_already=314159|.\quad(3)~Soon \.{VIRTEX}
23379 will print `\.*', waiting for more input; and at this point we
23380 interrupt the program and save its core image in some form that the
23381 operating system can reload speedily.\quad(4)~When that core image is
23382 activated, the program starts again at the beginning; but now
23383 |ready_already==314159| and all the other global variables have
23384 their initial values too. The former chastity has vanished!
23385
23386 In other words, if we allow ourselves to test the condition
23387 |ready_already==314159|, before |ready_already| has been
23388 assigned a value, we can avoid the lengthy initialization. Dirty tricks
23389 rarely pay off so handsomely.
23390 @^dirty \PASCAL@>
23391 @^system dependencies@>
23392
23393 On systems that allow such preloading, the standard program called \.{TeX}
23394 should be the one that has \.{plain} format preloaded, since that agrees
23395 with {\sl The \TeX book}. Other versions, e.g., \.{AmSTeX}, should also
23396 @:TeXbook}{\sl The \TeX book@>
23397 @.AmSTeX@>
23398 @.plain@>
23399 be provided for commonly used formats.
23400
23401 @<Glob...@>=
23402 static int @!ready_already; /*a sacrifice of purity for economy*/
23403
23404 @ Now this is really it: \TeX\ starts and ends here.
23405
23406 The initial test involving |ready_already| should be deleted if the
23407 \PASCAL\ runtime system is smart enough to detect such a ``mistake.''
23408 @^system dependencies@>
23409
23410 @p
23411 int main(int argc, char *argv[]) {@! /*|start_here|*/
23412 hlog=stderr;
23413 main_init(argc, argv); /* \TeX\ Live */
23414 history=fatal_error_stop; /*in case we quit during initialization*/
23415 t_open_out; /*open the terminal for output*/
23416 if (ready_already==314159) goto start_of_TEX;
23417 @<Check the ``constant'' values...@>@;
23418 if (bad > 0)
23419 {@+wterm_ln("Ouch---my internal constants have been clobbered!"
23420 "---case %d", bad);
23421 @.Ouch...clobbered@>
23422 exit(0);
23423 }
23424 get_strings_started();
23425 initialize(); /*set global variables to their starting values*/
23426 #ifdef @!INIT
23427 if (iniversion) /* \TeX\ Live */
23428 { init_prim(); /*call |primitive| for each primitive*/
23429 init_str_ptr=str_ptr;init_pool_ptr=pool_ptr;fix_date_and_time(); }
23430 #endif
23431 ready_already=314159;
23432 start_of_TEX: @<Initialize the output routines@>;
23433 @<Get the first line of input and prepare to start@>;
23434 history=spotless; /*ready to go!*/
23435 hhsize=hsize; hvsize=vsize; hout_allocate();@/
23436 main_control(); /*come to life*/
23437 final_cleanup(); /*prepare for death*/
23438 close_files_and_terminate();
23439 ready_already=0;
23440 return 0; }
23441
23442 @ Here we do whatever is needed to complete \TeX's job gracefully on the
23443 local operating system. The code here might come into play after a fatal
23444 error; it must therefore consist entirely of ``safe'' operations that
23445 cannot produce error messages. For example, it would be a mistake to call
23446 |str_room| or |make_string| at this time, because a call on |overflow|
23447 might lead to an infinite loop.
23448 @^system dependencies@>
23449 (Actually there's one way to get error messages, via |prepare_mag|;
23450 but that can't cause infinite recursion.)
23451 @^recursion@>
23452
23453 If |final_cleanup| is bypassed, this program doesn't bother to close
23454 the input files that may still be open.
23455
23456 @<Last-minute...@>=
23457 static void close_files_and_terminate(void)
23458 {@+int k; /*all-purpose index*/
23459 @<Finish the extensions@>;new_line_char=-1;
23460 #ifdef @!STAT
23461 if (tracing_stats > 0) @<Output statistics about this job@>;@;
23462 #endif
23463 wake_up_terminal; hint_close();
23464 if (log_opened)
23465 {@+wlog_cr;a_close(&log_file);selector=selector-2;
23466 if (selector==term_only)
23467 {@+print_nl("Transcript written on ");
23468 @.Transcript written...@>
23469 slow_print(log_name);print_char('.');print_nl("");
23470 }
23471 }
23472 }
23473
23474 @ The present section goes directly to the log file instead of using
23475 |print| commands, because there's no need for these strings to take
23476 up |str_pool| memory when a non-{\bf stat} version of \TeX\ is being used.
23477
23478 @<Output statistics...@>=
23479 if (log_opened)
23480 {@+wlog_ln(" ");
23481 wlog_ln("Here is how much of TeX's memory you used:");
23482 @.Here is how much...@>
23483 wlog(" %d string", str_ptr-init_str_ptr);
23484 if (str_ptr!=init_str_ptr+1) wlog( "s" );
23485 wlog_ln( " out of %d", max_strings-init_str_ptr);@/
23486 wlog_ln( " %d string characters out of %d", pool_ptr-init_pool_ptr,
23487 pool_size-init_pool_ptr);@/
23488 wlog_ln(" %d words of memory out of %d", lo_mem_max-mem_min+mem_end-hi_mem_min+2,@|
23489 mem_end+1-mem_min);@/
23490 wlog_ln(" %d multiletter control sequences out of %d", cs_count, hash_size);@/
23491 wlog(" %d words of font info for %d font", fmem_ptr, font_ptr-font_base);
23492 if (font_ptr!=font_base+1) wlog("s");
23493 wlog_ln( ", out of %d for %d", font_mem_size, font_max-font_base);@/
23494 wlog(" %d hyphenation exception", hyph_count);
23495 if (hyph_count!=1) wlog("s");
23496 wlog_ln( " out of %d", hyph_size);@/
23497 wlog_ln(" %di,%dn,%dp,%db,%ds stack positions out of %di,%dn,%dp,%db,%ds",
23498 max_in_stack, max_nest_stack,@|
23499 max_param_stack,@|
23500 max_buf_stack+1,@|
23501 max_save_stack+6,@|
23502 stack_size,
23503 nest_size,
23504 param_size,
23505 buf_size,
23506 save_size );
23507 wlog_ln(" %d/%d utf block/info records out of %d/%d",
23508 utf_b_used, utf_i_used, 0x100, 0x100);
23509 }
23510
23511 @ We get to the |final_cleanup| routine when \.{\\end} or \.{\\dump} has
23512 been scanned and |its_all_over|\kern-2pt.
23513
23514 @<Last-minute...@>=
23515 static void final_cleanup(void)
23516 {@+
23517 int c; /*0 for \.{\\end}, 1 for \.{\\dump}*/
23518 c=cur_chr;if (c!=1) new_line_char=-1;
23519 if (job_name==0) open_log_file();
23520 while (input_ptr > 0)
23521 if (state==token_list) end_token_list();@+else end_file_reading();
23522 while (open_parens > 0)
23523 {@+print(" )");decr(open_parens);
23524 }
23525 if (cur_level > level_one)
23526 {@+print_nl("(");print_esc("end occurred ");
23527 print("inside a group at level ");
23528 @:end\_}{\.{(\\end occurred...)}@>
23529 print_int(cur_level-level_one);print_char(')');
23530 if (eTeX_ex) show_save_groups();
23531 }
23532 while (cond_ptr!=null)
23533 {@+print_nl("(");print_esc("end occurred ");
23534 print("when ");print_cmd_chr(if_test, cur_if);
23535 if (if_line!=0)
23536 {@+print(" on line ");print_int(if_line);
23537 }
23538 print(" was incomplete)");
23539 if_line=if_line_field(cond_ptr);
23540 cur_if=subtype(cond_ptr);temp_ptr=cond_ptr;
23541 cond_ptr=link(cond_ptr);free_node(temp_ptr, if_node_size);
23542 }
23543 if (history!=spotless)
23544 if (((history==warning_issued)||(interaction < error_stop_mode)))
23545 if (selector==term_and_log)
23546 {@+selector=term_only;
23547 print_nl("(see the transcript file for additional information)");
23548 @.see the transcript file...@>
23549 selector=term_and_log;
23550 }
23551 if (c==1)
23552 {
23553 #ifdef @!INIT
23554 for (c=top_mark_code; c<=split_bot_mark_code; c++)
23555 if (cur_mark[c]!=null) delete_token_ref(cur_mark[c]);
23556 if (sa_mark!=null)
23557 if (do_marks(destroy_marks, 0, sa_mark)) sa_mark=null;
23558 for (c=last_box_code; c<=vsplit_code; c++) flush_node_list(disc_ptr[c]);
23559 if (last_glue!=max_halfword) delete_glue_ref(last_glue);
23560 store_fmt_file();return;
23561 #endif
23562 print_nl("(\\dump is performed only by INITEX)");return;
23563 @:dump\_}{\.{\\dump...only by INITEX}@>
23564 }
23565 }
23566
23567 @ @<Last-minute...@>=
23568 #ifdef @!INIT
23569 static void init_prim(void) /*initialize all the primitives*/
23570 {@+no_new_control_sequence=false;
23571 first=0;
23572 @<Put each...@>;
23573 no_new_control_sequence=true;
23574 }
23575 #endif
23576
23577 @ When we begin the following code, \TeX's tables may still contain garbage;
23578 the strings might not even be present. Thus we must proceed cautiously to get
23579 bootstrapped in.
23580
23581 But when we finish this part of the program, \TeX\ is ready to call on the
23582 |main_control| routine to do its work.
23583
23584 @<Get the first line...@>=
23585 {@+@<Initialize the input routines@>;
23586 @<Enable \eTeX\ and furthermore Prote, if requested@>@;@/
23587 if ((format_ident==0)||(buffer[loc]=='&'))
23588 {@+if (format_ident!=0) initialize(); /*erase preloaded format*/
23589 if (!open_fmt_file()) exit(0);
23590 if (!load_fmt_file())
23591 {@+w_close(&fmt_file);exit(0);
23592 }
23593 else if (needs_loading(cur_font))
23594 read_predefined_font(cur_font);
23595 w_close(&fmt_file);
23596 while ((loc < limit)&&(buffer[loc]==' ')) incr(loc);
23597 }
23598 if (eTeX_ex) wterm_ln("entering extended mode");
23599 if (Prote_ex) {@+Prote_initialize();
23600 }
23601 if (end_line_char_inactive) decr(limit);
23602 else buffer[limit]=end_line_char;
23603 fix_date_and_time();@/
23604 @<Initialize the print |selector|...@>;
23605 if ((loc < limit)&&(cat_code(buffer[loc])!=escape)) start_input();
23606 /*\.{\\input} assumed*/
23607 }
23608
23609 @* Debugging.
23610 Once \TeX\ is working, you should be able to diagnose most errors with
23611 the \.{\\show} commands and other diagnostic features. But for the initial
23612 stages of debugging, and for the revelation of really deep mysteries, you
23613 can compile \TeX\ with a few more aids, including the \PASCAL\ runtime
23614 checks and its debugger. An additional routine called |debug_help|
23615 will also come into play when you type `\.D' after an error message;
23616 |debug_help| also occurs just before a fatal error causes \TeX\ to succumb.
23617 @^debugging@>
23618 @^system dependencies@>
23619
23620 The interface to |debug_help| is primitive, but it is good enough when used
23621 with a \PASCAL\ debugger that allows you to set breakpoints and to read
23622 variables and change their values. After getting the prompt `\.{debug \#}', you
23623 type either a negative number (this exits |debug_help|), or zero (this
23624 goes to a location where you can set a breakpoint, thereby entering into
23625 dialog with the \PASCAL\ debugger), or a positive number |m| followed by
23626 an argument |n|. The meaning of |m| and |n| will be clear from the
23627 program below. (If |m==13|, there is an additional argument, |l|.)
23628 @.debug \#@>
23629
23630 @<Last-minute...@>=
23631 #ifdef @!DEBUG
23632 static void debug_help(void) /*routine to display various things*/
23633 {@+
23634 int k, @!l, @!m, @!n;
23635 clear_terminal;
23636 loop{@+wake_up_terminal;
23637 print_nl("debug # (-1 to exit):");update_terminal;
23638 @.debug \#@>
23639 if (fscanf(term_in.f," %d",&m)<1 ||
23640 m < 0) return;
23641 else if (m==0)
23642 {@+goto breakpoint;@/ /*go to every declared label at least once*/
23643 breakpoint: m=0; /*'BREAKPOINT'*/@/
23644 }
23645 else{@+fscanf(term_in.f," %d",&n);
23646 switch (m) {
23647 @t\4@>@<Numbered cases for |debug_help|@>@;
23648 default:print("?");
23649 }
23650 }
23651 }
23652 }
23653 #endif
23654
23655 @ @<Numbered cases...@>=
23656 case 1: print_word(mem[n]);@+break; /*display |mem[n]| in all forms*/
23657 case 2: print_int(info(n));@+break;
23658 case 3: print_int(link(n));@+break;
23659 case 4: print_word(eqtb[n]);@+break;
23660 case 5: print_word(font_info[n]);@+break;
23661 case 6: print_word(save_stack[n]);@+break;
23662 case 7: show_box(n);@+break;
23663 /*show a box, abbreviated by |show_box_depth| and |show_box_breadth|*/
23664 case 8: {@+breadth_max=10000;depth_threshold=pool_size-pool_ptr-10;
23665 show_node_list(n); /*show a box in its entirety*/
23666 } @+break;
23667 case 9: show_token_list(n, null, 1000);@+break;
23668 case 10: slow_print(n);@+break;
23669 case 11: check_mem(n > 0);@+break; /*check wellformedness; print new busy locations if |n > 0|*/
23670 case 12: search_mem(n);@+break; /*look for pointers to |n|*/
23671 case 13: {@+fscanf(term_in.f," %d",&l);print_cmd_chr(n, l);
23672 } @+break;
23673 case 14: for (k=0; k<=n; k++) printn(buffer[k]);@+break;
23674 case 15: {@+font_in_short_display=null_font;short_display(n);
23675 } @+break;
23676 case 16: panicking=!panicking;@+break;
23677
23678 @* Extensions.
23679 The program above includes a bunch of ``hooks'' that allow further
23680 capabilities to be added without upsetting \TeX's basic structure.
23681 Most of these hooks are concerned with ``whatsit'' nodes, which are
23682 intended to be used for special purposes; whenever a new extension to
23683 \TeX\ involves a new kind of whatsit node, a corresponding change needs
23684 to be made to the routines below that deal with such nodes,
23685 but it will usually be unnecessary to make many changes to the
23686 other parts of this program.
23687
23688 In order to demonstrate how extensions can be made, we shall treat
23689 `\.{\\write}', `\.{\\openout}', `\.{\\closeout}', `\.{\\immediate}',
23690 `\.{\\special}', and `\.{\\setlanguage}' as if they were extensions.
23691 These commands are actually primitives of \TeX, and they should
23692 appear in all implementations of the system; but let's try to imagine
23693 that they aren't. Then the program below illustrates how a person
23694 could add them.
23695
23696 Sometimes, of course, an extension will require changes to \TeX\ itself;
23697 no system of hooks could be complete enough for all conceivable extensions.
23698 The features associated with `\.{\\write}' are almost all confined to the
23699 following paragraphs, but there are small parts of the |print_ln| and
23700 |print_char| procedures that were introduced specifically to \.{\\write}
23701 characters. Furthermore one of the token lists recognized by the scanner
23702 is a |write_text|; and there are a few other miscellaneous places where we
23703 have already provided for some aspect of \.{\\write}. The goal of a \TeX\
23704 extender should be to minimize alterations to the standard parts of the
23705 program, and to avoid them completely if possible. He or she should also
23706 be quite sure that there's no easy way to accomplish the desired goals
23707 with the standard features that \TeX\ already has. ``Think thrice before
23708 extending,'' because that may save a lot of work, and it will also keep
23709 incompatible extensions of \TeX\ from proliferating.
23710 @^system dependencies@>
23711 @^extensions to \TeX@>
23712
23713 @ First let's consider the format of whatsit nodes that are used to represent
23714 the data associated with \.{\\write} and its relatives. Recall that a whatsit
23715 has |type==whatsit_node|, and the |subtype| is supposed to distinguish
23716 different kinds of whatsits. Each node occupies two or more words; the
23717 exact number is immaterial, as long as it is readily determined from the
23718 |subtype| or other data.
23719
23720 We shall introduce five |subtype| values here, corresponding to the
23721 control sequences \.{\\openout}, \.{\\write}, \.{\\closeout}, \.{\\special}, and
23722 \.{\\setlanguage}. The second word of I/O whatsits has a |write_stream| field
23723 that identifies the write-stream number (0 to 15, or 16 for out-of-range and
23724 positive, or 17 for out-of-range and negative).
23725 In the case of \.{\\write} and \.{\\special}, there is also a field that
23726 points to the reference count of a token list that should be sent. In the
23727 case of \.{\\openout}, we need three words and three auxiliary subfields
23728 to hold the string numbers for name, area, and extension.
23729
23730 @d write_node_size 2 /*number of words in a write/whatsit node*/
23731 @d open_node_size 3 /*number of words in an open/whatsit node*/
23732 @d open_node 0 /*|subtype| in whatsits that represent files to \.{\\openout}*/
23733 @d write_node 1 /*|subtype| in whatsits that represent things to \.{\\write}*/
23734 @d close_node 2 /*|subtype| in whatsits that represent streams to \.{\\closeout}*/
23735 @d special_node 3 /*|subtype| in whatsits that represent \.{\\special} things*/
23736 @d language_node 4 /*|subtype| in whatsits that change the current language*/
23737 @d what_lang(A) link(A+1) /*language number, in the range |0 dotdot 255|*/
23738 @d what_lhm(A) type(A+1) /*minimum left fragment, in the range |1 dotdot 63|*/
23739 @d what_rhm(A) subtype(A+1) /*minimum right fragment, in the range |1 dotdot 63|*/
23740 @d write_tokens(A) link(A+1) /*reference count of token list to write*/
23741 @d write_stream(A) info(A+1) /*stream number (0 to 17)*/
23742 @d open_name(A) link(A+1) /*string number of file name to open*/
23743 @d open_area(A) info(A+2) /*string number of file area for |open_name|*/
23744 @d open_ext(A) link(A+2) /*string number of file extension for |open_name|*/ @#
23745
23746 @d hitex_ext save_pos_code+1
23747 @d param_node hitex_ext /*|subtype| that records the change of a parameter*/
23748 @d param_node_size 3 /* number of memory words in a |param_node| */
23749 @d param_type(A) type(A+1) /* type of parameter */
23750 @d int_type 0 /* type of an |int_par| node */
23751 @d dimen_type 1 /* type of an |dimen_par| node */
23752 @d glue_type 2 /* type of an |glue_par| node */
23753 @d param_no(A) subtype(A+1) /* the parameter number */
23754 @d param_value(A) mem[A+2] /* the parameter value */@#
23755
23756 @d par_node hitex_ext+1 /*|subtype| that records a paragraph*/
23757 @d par_node_size 5 /* number of memory words in a |par_node| */
23758 @d par_penalty(A) mem[A+1].i /* the final penalty */
23759 @d par_extent(A) link(A+3) /* the extent */@#
23760 @d par_params(A) info(A+4) /* list of parameter nodes */
23761 @d par_list(A) link(A+4) /* list of content nodes */
23762
23763 @d disp_node hitex_ext+2 /*|subtype| that records a math display*/
23764 @d disp_node_size 3 /* number of memory words in a |disp_node| */
23765 @d display_left(A) type(A+1) /* 1=left 0=right */
23766 @d display_no_bs(A) subtype(A+1) /* |prev_depth==ignore_depth| */
23767 @d display_params(A) link(A+1) /* list of parameter nodes */
23768 @d display_formula(A) link(A+2) /* formula list */
23769 @d display_eqno(A) info(A+2) /* box with equation number */@#
23770
23771 @d baseline_node hitex_ext+3 /*|subtype| that records a |baseline_skip| */
23772 @d baseline_node_size small_node_size /* This is 2; we will convert baseline nodes to glue nodes */
23773 @d baseline_node_no(A) mem[A+1].i /* baseline reference */@#
23774
23775 @d image_node hitex_ext+4 /*|subtype| that records an image */
23776 @d image_node_size 6 /* number of memory words in an |image_node| */
23777 @d image_xwidth(A) link(A+1) /*extended width of image */
23778 @d image_xheight(A) info(A+1) /*extended height of image */
23779 @d image_aspect(A) mem[(A)+2].sc /* aspect ratio of image */
23780 @d image_no(A) link(A+3) /* the section number */
23781 @d image_name(A) info(A+3) /*string number of file name */
23782 @d image_area(A) info(A+4) /*string number of file area */
23783 @d image_ext(A) link(A+4) /*string number of file extension */
23784 @d image_alt(A) link(A+5) /* alternative image description text */@#
23785
23786 @d hpack_node hitex_ext+5 /* a hlist that needs to go to hpack */
23787 @d vpack_node hitex_ext+6 /* a vlist that needs to go to vpackage */
23788 @d pack_node_size box_node_size /* a box node up to |list_ptr|*/
23789 @d pack_m(A) type(A+list_offset) /* either additional or exactly */
23790 @d pack_limit(A) mem[(A)+1+list_offset].sc /* depth limit in |vpack| */
23791 @d pack_extent(A) link(A+2+list_offset) /* extent */@#
23792
23793 @d hset_node hitex_ext+7 /* represents a hlist that needs |glue_set| */
23794 @d vset_node hitex_ext+8 /* represents a vlist that needs |glue_set| */
23795 @d set_node_size box_node_size /* up to |list_ptr| like a box node */
23796 @d set_stretch_order glue_sign
23797 @d set_shrink_order glue_order
23798 @d set_stretch(A) mem[(A)+1+list_offset].sc /* replaces |glue_set| */
23799 @d set_extent(A) pack_extent(A) /* extent */
23800 @d set_shrink(A) mem[(A)+3+list_offset].sc @#
23801
23802 @d align_node hitex_ext+9 /* represents an alignment */
23803 @d align_node_size 4
23804 @d align_extent(A) link(A+2) /* the extent of the alignment */
23805 @d align_m(A) type(A+2) /* either additional or exactly */
23806 @d align_v(A) subtype(A+2) /* true if vertical */
23807 @d align_preamble(A) info(A+3) /* the preamble */
23808 @d align_list(A) link(A+3) /* the unset rows/columns */
23809
23810 @d setpage_node hitex_ext+10 /* represents a page template */
23811 @d setpage_node_size 6
23812 @d setpage_name(A) link(A+1)
23813 @d setpage_number(A) type(A+1) /* the \HINT/ number */
23814 @d setpage_id(A) subtype(A+1) /* the \TeX\ number */
23815 @d setpage_priority(A) info(A+2)
23816 @d setpage_topskip(A) link(A+2)
23817 @d setpage_depth(A) mem[A+3].sc /* maximum depth */
23818 @d setpage_height(A) info(A+4) /* extended dimension number */
23819 @d setpage_width(A) link(A+4) /* extended dimension number */
23820 @d setpage_list(A) info(A+5) /* the template itself */
23821 @d setpage_streams(A) link(A+5) /* list of stream definitions */
23822
23823 @d setstream_node hitex_ext+11 /* represents a stream definition */
23824 @d setstream_node_size 6
23825 @d setstream_number(A) type(A+1)
23826 @d setstream_insertion(A) subtype(A+1)
23827 @d setstream_mag(A) link(A+1) /* magnification factor */
23828 @d setstream_preferred(A) type(A+2)
23829 @d setstream_next(A) subtype(A+2)
23830 @d setstream_ratio(A) link(A+2) /* split ratio */
23831 @d setstream_max(A) info(A+3) /* extended dimension number */
23832 @d setstream_width(A) link(A+3) /* extended dimension number */
23833 @d setstream_topskip(A) info(A+4)
23834 @d setstream_height(A) link(A+4)
23835 @d setstream_before(A) info(A+5)
23836 @d setstream_after(A) link(A+5)
23837
23838 @d stream_node hitex_ext+12 /* represents a stream insertion point */
23839 @d stream_node_size 2
23840 @d stream_number(A) type(A+1)
23841 @d stream_insertion(A) subtype(A+1)
23842
23843 @d stream_after_node hitex_ext+13 /* never allocated */
23844 @d stream_before_node hitex_ext+14 /* never allocated */
23845
23846 @d xdimen_node hitex_ext+15
23847 @d xdimen_node_size 4
23848 @d xdimen_ref_count(A) link(A)
23849 @d xdimen_width(A) mem[A+1].sc
23850 @d xdimen_hfactor(A) mem[A+2].sc
23851 @d xdimen_vfactor(A) mem[A+3].sc
23852
23853 @d ignore_node hitex_ext+16 /* ignored used to attach extra information */
23854 @d ignore_node_size small_node_size /* same as |disc_node| */
23855 @d ignore_info(A) type(A+1)
23856 @d ignore_list(A) link(A+1)
23857
23858 @d color_node hitex_ext+17 /* represent a color node */
23859 @d end_color_node hitex_ext+18 /* represent an end color node */
23860 @d default_color_node hitex_ext+19 /* set default colors*/
23861 @d link_color_node hitex_ext+20 /* set link colors */
23862 @d default_link_color_node hitex_ext+21 /* set default link colors */
23863 @d no_color_node hitex_ext+22 /* a deleted end color node */
23864 @d color_node_size small_node_size
23865 @d color_ref(A) type(A+1) /* reference to the color set */
23866 @d color_link(A) link(A+1) /* pointer down the color stack */
23867
23868 @d label_node hitex_ext+23 /* represents a link to a another location */
23869 @d label_node_size 2
23870 @d label_has_name(A) type(A+1) /* 1 for a name , 0 for a number */
23871 @d label_where(A) subtype(A+1) /* 1 for top, 2 for bot, 3 for mid */
23872 @d label_ptr(A) link(A+1) /* hitex: a name (token list) or a number */
23873
23874 @d start_link_node hitex_ext+24 /* represents a link to another location */
23875 @d end_link_node hitex_ext+25 /* represents a link to another location */
23876 @d link_node_size 3 /* second word like a |color_node| */
23877 @d as_label(A) ((A)+1) /* third word like a |label_node| */
23878
23879 @d outline_node hitex_ext+26 /* represents an outline item */
23880 @d outline_node_size 3 /* second word like a |label_node| */
23881 @d outline_ptr(A) link(A+2) /* text to be displayed */
23882 @d outline_depth(A) info(A+2) /* depth of sub items */
23883
23884
23885 @ The sixteen possible \.{\\write} streams are represented by the |write_file|
23886 array. The |j|th file is open if and only if |write_open[j]==true|. The last
23887 two streams are special; |write_open[16]| represents a stream number
23888 greater than 15, while |write_open[17]| represents a negative stream number,
23889 and both of these variables are always |false|.
23890
23891 @<Glob...@>=
23892 static alpha_file @!write_file[16];
23893 static bool @!write_open[18];
23894
23895 @ @<Set init...@>=
23896 for (k=0; k<=17; k++) write_open[k]=false;
23897
23898 @ Extensions might introduce new command codes; but it's best to use
23899 |extension| with a modifier, whenever possible, so that |main_control|
23900 stays the same.
23901
23902 @d immediate_code 4 /*command modifier for \.{\\immediate}*/
23903 @d latex_first_extension_code 5
23904 @d latespecial_node (latex_first_extension_code+0) /*|subtype| in whatsits that represent \.{\\special} things expanded during output*/
23905 @d set_language_code (latex_first_extension_code+1) /*command modifier for \.{\\setlanguage}*/
23906 @d TeX_last_extension_cmd_mod set_language_code
23907
23908 @<Put each...@>=
23909 primitive("openout", extension, open_node);@/
23910 @!@:open\_out\_}{\.{\\openout} primitive@>
23911 primitive("write", extension, write_node);write_loc=cur_val;@/
23912 @!@:write\_}{\.{\\write} primitive@>
23913 primitive("closeout", extension, close_node);@/
23914 @!@:close\_out\_}{\.{\\closeout} primitive@>
23915 primitive("special", extension, special_node);@/
23916 @!@:special\_}{\.{\\special} primitive@>
23917 primitive("immediate", extension, immediate_code);@/
23918 @!@:immediate\_}{\.{\\immediate} primitive@>
23919 primitive("setlanguage", extension, set_language_code);@/
23920 @!@:set\_language\_}{\.{\\setlanguage} primitive@>
23921
23922 @ The variable |write_loc| just introduced is used to provide an
23923 appropriate error message in case of ``runaway'' write texts.
23924
23925 @<Glob...@>=
23926 static pointer @!write_loc; /*|eqtb| address of \.{\\write}*/
23927
23928 @ @<Cases of |print_cmd_chr|...@>=
23929 case extension: switch (chr_code) {
23930 case open_node: print_esc("openout");@+break;
23931 case write_node: print_esc("write");@+break;
23932 case close_node: print_esc("closeout");@+break;
23933 case special_node: print_esc("special");@+break;
23934 case image_node: print_esc("HINTimage");@+break;
23935 case color_node: print_esc("HINTcolor");@+break;
23936 case end_color_node: print_esc("HINTendcolor");@+break;
23937 case no_color_node: print_esc("HINTendcolor ignored");@+break;
23938 case default_color_node: print_esc("HINTdefaultcolor");@+break;
23939 case link_color_node: print_esc("HINTlinkcolor");@+break;
23940 case default_link_color_node: print_esc("HINTdefaultlinkcolor");@+break;
23941 case start_link_node: print_esc("HINTstartlink");@+break;
23942 case end_link_node: print_esc("HINTendlink");@+break;
23943 case label_node: print_esc("HINTdest");@+break;
23944 case outline_node: print_esc("HINToutline");@+break;
23945 case setpage_node: print_esc("HINTsetpage");@+break;
23946 case stream_before_node: print_esc("HINTbefore");@+break;
23947 case stream_after_node: print_esc("HINTafter");@+break;
23948 case setstream_node: print_esc("HINTsetstream");@+break;
23949 case stream_node: print_esc("HINTstream");@+break;
23950 case param_node: print("[HINT internal: parameter list]");@+break;
23951 case par_node: print("[HINT internal: paragraph]");@+break;
23952 case disp_node: print("[HINT internal: display]");@+break;
23953 case baseline_node: print("[HINT internal: baselineskip]");@+break;
23954 case hpack_node: print("[HINT internal: hpack]");@+break;
23955 case vpack_node: print("[HINT internal: vpack");@+break;
23956 case hset_node: print("[HINT internal: hset]");@+break;
23957 case vset_node: print("[HINT internal: vset]");@+break;
23958 case align_node: print("[HINT internal: align]");@+break;
23959 case xdimen_node: print("[HINT internal: xdimen]");@+break;
23960 case ignore_node: print("[HINT internal: ignore]");@+break;
23961 case immediate_code: print_esc("immediate");@+break;
23962 case set_language_code: print_esc("setlanguage");@+break;
23963 @/@<Cases of |extension| for |print_cmd_chr|@>@/
23964 default:print("[unknown extension!]");
23965 } @+break;
23966
23967 @ When an |extension| command occurs in |main_control|, in any mode,
23968 the |do_extension| routine is called.
23969
23970 @<Cases of |main_control| that are for extensions...@>=
23971 any_mode(extension): do_extension();
23972
23973 @ @<Declare act...@>=
23974 @t\4@>@<Declare procedures needed in |do_extension|@>@;
23975 static void do_extension(void)
23976 {@+int @!k; /*all-purpose integer*/
23977 pointer @!p; /*all-purpose pointer*/
23978 switch (cur_chr) {
23979 case open_node: @<Implement \.{\\openout}@>@;@+break;
23980 case write_node: @<Implement \.{\\write}@>@;@+break;
23981 case close_node: @<Implement \.{\\closeout}@>@;@+break;
23982 case special_node: @<Implement \.{\\special}@>@;@+break;
23983 case param_node:
23984 case par_node:
23985 case disp_node:
23986 case baseline_node:
23987 case hpack_node:
23988 case vpack_node:
23989 case hset_node:
23990 case vset_node:
23991 case align_node: @+break;@#
23992 case image_node:@/
23993 {@+ pointer p;
23994 scaled iw=0,ih=0;
23995 double ia=0.0;
23996 scan_optional_equals();
23997 scan_file_name();
23998 p=new_image_node(cur_name,cur_area,cur_ext);
23999 loop {
24000 if (scan_keyword("width"))
24001 {@+scan_normal_dimen; image_xwidth(p)=new_xdimen(cur_val,cur_hfactor,cur_vfactor);
24002 if (cur_hfactor==0 && cur_vfactor==0) iw=cur_val;
24003 }
24004 else if (scan_keyword("height"))
24005 {@+scan_normal_dimen; image_xheight(p)=new_xdimen(cur_val,cur_hfactor,cur_vfactor);
24006 if (cur_hfactor==0 && cur_vfactor==0) ih=cur_val;
24007 }
24008 else
24009 break;
24010 }
24011 {
24012 pointer r,q;
24013 if (ih!=0 && iw!=0 ) ia=(double)iw/ih;
24014 else hextract_image_dimens(image_no(p),&ia,&iw,&ih);
24015 image_aspect(p)=round(ia*ONE);
24016 r=image_xwidth(p);
24017 q=image_xheight(p);
24018 if (r==null && q==null)
24019 { if (iw>0)
24020 { image_xwidth(p)=r=new_xdimen(iw,0,0);
24021 image_xheight(p)=q=new_xdimen(ih,0,0);
24022 }
24023 else if (iw<0)
24024 { MESSAGE("Unable to determine size of image %s; using 72dpi.\n",
24025 dir[image_no(p)].file_name);
24026 image_xwidth(p)=r=new_xdimen(-iw,0,0);
24027 image_xheight(p)=q=new_xdimen(-ih,0,0);
24028 }
24029 else
24030 { MESSAGE("Unable to determine size of image %s; using 100pt x 100pt\n",
24031 dir[image_no(p)].file_name);
24032 image_xwidth(p)=r=new_xdimen(100*ONE,0,0);
24033 image_xheight(p)=q=new_xdimen(100*ONE,0,0);
24034 }
24035 }
24036 else if (r!=null && q==null)
24037 image_xheight(p)=q=new_xdimen(round(xdimen_width(r)/ia),
24038 round(xdimen_hfactor(r)/ia),round(xdimen_vfactor(r)/ia));
24039 else if (r==null && q!=null)
24040 image_xwidth(p)=r=new_xdimen(round(xdimen_width(q)*ia),
24041 round(xdimen_hfactor(q)*ia),round(xdimen_vfactor(q)*ia));
24042 }
24043 if (abs(mode)==vmode)
24044 { prev_depth=ignore_depth; /* this could be deleted if baseline nodes treat
24045 images as boxes in the viewer */
24046 append_to_vlist(p); /* image nodes have height, width, and depth like boxes */
24047 }
24048 else
24049 tail_append(p);
24050 break;
24051 }
24052 case color_node:
24053 { ColorSet c;
24054 new_whatsit(color_node,color_node_size);
24055 scan_color_spec(c,0);
24056 color_ref(tail)=next_colorset(c);
24057 color_link(tail)=null;
24058 default_color_frozen=true;
24059 }
24060 break;
24061 case no_color_node: break;
24062 case end_color_node:
24063 { new_whatsit(end_color_node,color_node_size);
24064 color_ref(tail)=0xFF;
24065 color_link(tail)=null;
24066 }
24067 break;
24068 case default_color_node:
24069 if (default_color_frozen)
24070 { print_err("You can not use \\HINTdefaultcolor after \\HINTcolor");
24071 error();
24072 }
24073 else
24074 { ColorSet c;
24075 scan_color_spec(c,0);
24076 colorset_copy(colors[0],c);
24077 }
24078 break;
24079 case link_color_node:
24080 { ColorSet c;
24081 scan_color_spec(c,1);
24082 cur_link_color=next_colorset(c);
24083 default_link_color_frozen=true;
24084 }
24085 break;
24086 case default_link_color_node:
24087 if (default_link_color_frozen)
24088 {@+print_err("You can not use \\HINTdefaultlinkcolor after \\HINTlinkcolor"); error();
24089 }
24090 else
24091 { ColorSet c;
24092 scan_color_spec(c,1);
24093 colorset_copy(colors[1],c);
24094 }
24095 break;
24096 case start_link_node:
24097 if (abs(mode) == vmode)
24098 fatal_error("HINTstartlink cannot be used in vertical mode");
24099 else
24100 { new_whatsit(start_link_node,link_node_size);
24101 scan_label(as_label(tail));
24102 color_ref(tail)=cur_link_color;
24103 }
24104 break;
24105 case end_link_node:
24106 if (abs(mode) == vmode)
24107 fatal_error("HINTendlink cannot be used in vertical mode");
24108 else
24109 { new_whatsit(end_link_node,link_node_size);
24110 color_ref(tail)=0xFF;
24111 }
24112 break;
24113 case label_node:
24114 new_whatsit(label_node,label_node_size);
24115 scan_destination(tail);
24116 if (scan_keyword("top")) label_where(tail)=1;
24117 else if (scan_keyword("bot")) label_where(tail)=2;
24118 else label_where(tail)=3;
24119 scan_spaces();
24120 break;
24121 case outline_node:
24122 new_whatsit(outline_node,outline_node_size);
24123 scan_label(tail);
24124 if (scan_keyword("depth"))
24125 { scan_int();
24126 outline_depth(tail)= cur_val;
24127 }
24128 else outline_depth(tail)=0;
24129 outline_ptr(tail)=null;
24130 new_save_level(outline_group);scan_left_brace();
24131 push_nest();mode=-hmode;prev_depth=ignore_depth;space_factor=1000;
24132 break;
24133 case setpage_node:
24134 { uint8_t n;@+
24135 pointer t;
24136 scan_eight_bit_int(); n=cur_val;
24137 if (n==0)
24138 { print_err("Illegal redefinition of page template 0"); print_int(n); error(); break;}
24139 scan_optional_equals();
24140 scan_file_name(); /* this should be improved to use |scan_name|*/
24141 t=new_setpage_node(n,cur_name);
24142 loop {
24143 if (scan_keyword("priority"))
24144 {@+scan_eight_bit_int();setpage_priority(t)=cur_val; }
24145 else if (scan_keyword("width"))
24146 {@+scan_normal_dimen; delete_xdimen_ref(setpage_width(t));
24147 setpage_width(t)=new_xdimen(cur_val,cur_hfactor,cur_vfactor); }
24148 else if (scan_keyword("height"))
24149 {@+scan_normal_dimen; delete_xdimen_ref(setpage_height(t));
24150 setpage_height(t)=new_xdimen(cur_val,cur_hfactor,cur_vfactor); }
24151 else
24152 break;
24153 }
24154 new_save_level(page_group);scan_left_brace();normal_paragraph();
24155 push_nest();mode=-vmode;prev_depth=ignore_depth;
24156 break;
24157 }
24158 case stream_node:
24159 { uint8_t n;
24160 scan_eight_bit_int(); n=cur_val;
24161 new_whatsit(stream_node,stream_node_size);
24162 stream_insertion(tail)=n;
24163 stream_number(tail)=hget_stream_no(n);
24164 break;
24165 }
24166 case setstream_node:
24167 { uint8_t n;
24168 pointer t, s;
24169 scan_eight_bit_int(); n=cur_val;
24170 scan_optional_equals();
24171 t=link(setpage_head);
24172 if (t==null) { print_err("\\setstream without \\setpage"); error(); break;}
24173 s=new_setstream_node(n);
24174 link(s)=setpage_streams(t); setpage_streams(t)=s;
24175 loop {
24176 if (scan_keyword("preferred"))
24177 {@+scan_eight_bit_int();
24178 if (cur_val!=255)
24179 setstream_preferred(s)=hget_stream_no(cur_val); }
24180 else if (scan_keyword("next"))
24181 {@+scan_eight_bit_int();
24182 if (cur_val!=255)
24183 setstream_next(s)=hget_stream_no(cur_val); }
24184 else if (scan_keyword("ratio"))
24185 {@+scan_int();setstream_ratio(s)=cur_val; }
24186 else
24187 break;
24188 }
24189 new_save_level(stream_group);scan_left_brace();normal_paragraph();
24190 push_nest();mode=-vmode;prev_depth=ignore_depth;
24191 break;
24192 }
24193 case stream_before_node:
24194 scan_optional_equals();
24195 new_save_level(stream_before_group);scan_left_brace();normal_paragraph();
24196 push_nest();mode=-vmode;prev_depth=ignore_depth;
24197 break;
24198 case stream_after_node:
24199 scan_optional_equals();
24200 new_save_level(stream_after_group);scan_left_brace();normal_paragraph();
24201 push_nest();mode=-vmode;prev_depth=ignore_depth;
24202 break;
24203 case xdimen_node:
24204 case ignore_node: @+break;
24205 case immediate_code: @<Implement \.{\\immediate}@>@;@+break;
24206 case set_language_code: @<Implement \.{\\setlanguage}@>@;@+break;
24207 @/@<Cases for |do_extension|@>@/
24208 default:confusion("ext1");
24209 @:this can't happen ext1}{\quad ext1@>
24210 }
24211 }
24212
24213 @ @<Declare procedures needed in |do_extension|@>=
24214 static void scan_spaces(void)
24215 { @<Get the next non-blank non-call token@>;
24216 back_input();
24217 }
24218 static void scan_destination(pointer p)
24219 {@+if (scan_keyword("name"))
24220 { label_has_name(p)=1;
24221 scan_toks(false,true); label_ptr(p)=def_ref;
24222 }
24223 else if (scan_keyword("num"))
24224 { label_has_name(p)=0; scan_int(); label_ptr(p)=cur_val;
24225 }
24226 else
24227 { print_err("`name {...}' or `num 000' expected. Inserted `num 0'.");
24228 label_has_name(p)=0; label_ptr(p)=0;
24229 error();
24230 return;
24231 }
24232 scan_spaces();
24233 }
24234 static void scan_label(pointer p)
24235 { if (!scan_keyword("goto"))
24236 print_err("keyword `goto' inserted");
24237 scan_destination(p);
24238 }
24239
24240 @ Here is a subroutine that creates a whatsit node having a given |subtype|
24241 and a given number of words. It initializes only the first word of the whatsit,
24242 and appends it to the current list.
24243
24244 @<Declare procedures needed in |do_extension|@>=
24245 static void new_whatsit(small_number @!s, small_number @!w)
24246 {@+pointer p; /*the new node*/
24247 p=get_node(w);type(p)=whatsit_node;subtype(p)=s;
24248 link(tail)=p;tail=p;
24249 }
24250
24251 @ The next subroutine uses |cur_chr| to decide what sort of whatsit is
24252 involved, and also inserts a |write_stream| number.
24253
24254 @<Declare procedures needed in |do_ext...@>=
24255 static void new_write_whatsit(small_number @!w)
24256 {@+new_whatsit(cur_chr, w);
24257 if (w!=write_node_size) scan_four_bit_int();
24258 else{@+scan_int();
24259 if (cur_val < 0) cur_val=17;
24260 else if (cur_val > 15) cur_val=16;
24261 }
24262 write_stream(tail)=cur_val;
24263 }
24264
24265 @ @<Implement \.{\\openout}@>=
24266 {@+new_write_whatsit(open_node_size);
24267 scan_optional_equals();scan_file_name();@/
24268 open_name(tail)=cur_name;open_area(tail)=cur_area;open_ext(tail)=cur_ext;
24269 }
24270
24271 @ When `\.{\\write 12\{...\}}' appears, we scan the token list `\.{\{...\}}'
24272 without expanding its macros; the macros will be expanded later when this
24273 token list is rescanned.
24274
24275 @<Implement \.{\\write}@>=
24276 {@+k=cur_cs;new_write_whatsit(write_node_size);@/
24277 cur_cs=k;p=scan_toks(false, false);write_tokens(tail)=def_ref;
24278 }
24279
24280 @ @<Implement \.{\\closeout}@>=
24281 {@+new_write_whatsit(write_node_size);write_tokens(tail)=null;
24282 }
24283
24284 @ When `\.{\\special\{...\}}' appears, we expand the macros in the token
24285 list as in \.{\\xdef} and \.{\\mark}. When marked with \.{shipout}, we keep
24286 tokens unexpanded for now.
24287
24288 @<Implement \.{\\special}@>=
24289 {@+if (scan_keyword("shipout"))
24290 {@+new_whatsit(latespecial_node, write_node_size);write_stream(tail)=null;
24291 p=scan_toks(false, false);write_tokens(tail)=def_ref;
24292 } else
24293 {@+new_whatsit(special_node, write_node_size);write_stream(tail)=null;
24294 p=scan_toks(false, true);write_tokens(tail)=def_ref;
24295 } }
24296
24297 @ Each new type of node that appears in our data structure must be capable
24298 of being displayed, copied, destroyed, and so on. The routines that we
24299 need for write-oriented whatsits are somewhat like those for mark nodes;
24300 other extensions might, of course, involve more subtlety here.
24301
24302 @<Basic printing...@>=
24303 static void print_mark(int @!p);
24304 static void print_label(pointer @!p)
24305 { print("goto ");
24306 if (label_has_name(p)) { print("name "); print_mark(label_ptr(p));}
24307 else { print("num "); print_int(label_ptr(p));}
24308 }
24309
24310 static void print_write_whatsit(char *@!s, pointer @!p)
24311 {@+print_esc(s);
24312 if (write_stream(p) < 16) print_int(write_stream(p));
24313 else if (write_stream(p)==16) print_char('*');
24314 @.*\relax@>
24315 else print_char('-');
24316 }
24317
24318 @ @<Display the whatsit...@>=
24319 switch (subtype(p)) {
24320 case open_node: {@+print_write_whatsit("openout", p);
24321 print_char('=');print_file_name(open_name(p), open_area(p), open_ext(p));
24322 } @+break;
24323 case write_node: {@+print_write_whatsit("write", p);
24324 print_mark(write_tokens(p));
24325 } @+break;
24326 case close_node: print_write_whatsit("closeout", p);@+break;
24327 case latespecial_node: {@+print_esc("special");print(" shipout");
24328 print_mark(write_tokens(p));
24329 } @+break;
24330 case special_node: {@+print_esc("special");
24331 print_mark(write_tokens(p));
24332 } @+break;
24333 case language_node: {@+print_esc("setlanguage");
24334 print_int(what_lang(p));print(" (hyphenmin ");
24335 print_int(what_lhm(p));print_char(',');
24336 print_int(what_rhm(p));print_char(')');
24337 } @+break;
24338 @/@<Cases for displaying the |whatsit| node@>@/
24339 case param_node: print_esc("parameter ");
24340 print_int(param_type(p));print_char(',');print_int(param_no(p));
24341 print_char(':');print_int(param_value(p).i);
24342 break;
24343 case par_node: print_esc("paragraph(");
24344 print_xdimen(par_extent(p));
24345 print(", ");
24346 print_int(par_penalty(p));
24347 print_char(')');
24348 node_list_display(par_params(p));
24349 node_list_display(par_list(p));
24350 break;
24351 case disp_node: print_esc("display ");
24352 node_list_display(display_eqno(p));
24353 if (display_left(p)) print("left "); else print("right ");
24354 node_list_display(display_formula(p));
24355 node_list_display(display_params(p));
24356 break;
24357 case baseline_node: print_esc("baselineskip ");
24358 print_baseline_skip(baseline_node_no(p));
24359 break;
24360 case hset_node: case vset_node:
24361 print_char('\\');
24362 print_char(subtype(p)==hset_node?'h':'v');
24363 print("set(");
24364 print_scaled(height(p)); print_char('+');
24365 print_scaled(depth(p)); print(")x"); print_scaled(width(p));
24366 if (shift_amount(p)!=0)
24367 {@+print(", shifted ");print_scaled(shift_amount(p));
24368 }
24369 if (set_stretch(p)!=0)
24370 {@+print(", stretch ");print_glue(set_stretch(p),set_stretch_order(p),"pt");
24371 }
24372 if (set_shrink(p)!=0)
24373 {@+print(", shrink ");print_glue(set_shrink(p),set_shrink_order(p),"pt");
24374 }
24375 print(", extent "); print_xdimen(set_extent(p));
24376 node_list_display(list_ptr(p)); /*recursive call*/
24377 break;
24378 case hpack_node: case vpack_node:
24379 print_char('\\');
24380 print_char(subtype(p)==hpack_node?'h':'v');
24381 print("pack(");
24382 print(pack_m(p)==exactly?"exactly ":"additional ");
24383 print_xdimen(pack_extent(p));
24384 if (subtype(p)==vpack_node && pack_limit(p)!=max_dimen) { print(", limit "); print_scaled(pack_limit(p)); }
24385 print_char(')');
24386 node_list_display(list_ptr(p));
24387 break;
24388 case image_node:
24389 print_esc("HINTimage(");
24390 print("width ");print_xdimen(image_xheight(p));
24391 print(" height "); print_xdimen(image_xwidth(p));
24392 print(" aspect "); print_scaled(image_aspect(p));
24393 print("), section ");print_int(image_no(p));
24394 if (image_name(p)!=0) {print(", "); printn(image_name(p));}
24395 break;
24396 case color_node:
24397 print_esc("HINTcolor ");print_int(color_ref(p));
24398 break;
24399 case no_color_node:
24400 print_esc("HINTendcolor ignored");
24401 break;
24402 case end_color_node:
24403 print_esc("HINTendcolor ");
24404 break;
24405 case align_node:
24406 print_esc("align(");
24407 print(align_m(p)==exactly?"exactly ":"additional ");
24408 print_xdimen(align_extent(p));print_char(')');
24409 node_list_display(align_preamble(p));
24410 print_char(':');
24411 node_list_display(align_list(p));
24412 break;
24413 case setpage_node:
24414 print_esc("HINTsetpage");print_int(setpage_number(p));print_char(' '); printn(setpage_name(p));
24415 print(" priority ");print_int(setpage_priority(p));
24416 print(" width ");print_xdimen(setpage_width(p));
24417 print(" height ");print_xdimen(setpage_height(p));
24418 print_ln();print_current_string();print(".\\topskip=");print_spec(setpage_topskip(p),0);
24419 print_ln();print_current_string();print(".\\maxdepth=");print_scaled(setpage_depth(p));
24420 node_list_display(setpage_list(p));
24421 node_list_display(setpage_streams(p));
24422 break;
24423 case setstream_node:
24424 print_esc("HINTsetstream");print_int(setstream_insertion(p));
24425 print_char('(');print_int(setstream_number(p));print_char(')');
24426 if (setstream_preferred(p)!=255) { print(" preferred ");print_int(setstream_preferred(p)); }
24427 if (setstream_ratio(p)>0) { print(" ratio ");print_int(setstream_ratio(p)); }
24428 if (setstream_next(p)!=255) { print(" next ");print_int(setstream_next(p)); }
24429 append_char('.');
24430 print_ln();print_current_string();print_esc("count");print_int(setstream_insertion(p));print_char('=');
24431 print_int(setstream_mag(p));
24432 print_ln();print_current_string();print_esc("dimen");print_int(setstream_insertion(p));print_char('=');
24433 print_xdimen(setstream_max(p));
24434 print_ln();print_current_string();print_esc("skip");print_int(setstream_insertion(p));print_char('=');
24435 print_spec(setstream_height(p),0);
24436 print_ln();print_current_string();print_esc("hsize=");print_xdimen(setstream_width(p));
24437 print_ln();print_current_string();print_esc("topskip=");print_spec(setstream_topskip(p),0);
24438 if (setstream_before(p)!=null) { print_ln();print_current_string();print_esc("HINTbefore");node_list_display(setstream_before(p));}
24439 if (setstream_after(p)!=null) { print_ln();print_current_string();print_esc("HINTafter");node_list_display(setstream_after(p));}
24440 flush_char;
24441 break;
24442 case ignore_node:
24443 print_esc("ignore ");print_int(ignore_info(p));print_char(':');
24444 node_list_display(ignore_list(p));
24445 break;
24446 case start_link_node:
24447 print_esc("HINTstartlink ");
24448 print_label(as_label(p));
24449 if (color_ref(p)!=1) { print("color "); print_int(color_ref(p)); }
24450 break;
24451 case end_link_node:
24452 print_esc("HINTendlink ");
24453 if (color_ref(p)!=0xFF) { print("color "); print_int(color_ref(p)); }
24454 break;
24455 case label_node:
24456 print_esc("HINTdest ");
24457 print_label(p);
24458 if (label_where(p)==1) print("top");
24459 else if (label_where(p)==2) print("bot");
24460 else if (label_where(p)==3) print("mid");
24461 else print("undefined");
24462 break;
24463 case outline_node:
24464 print_esc("HINToutline");
24465 print_label(p);
24466 print(" depth "); print_int(outline_depth(p));
24467 if (outline_ptr(p)==null) print("{}"); else
24468 { print_ln();print_current_string();node_list_display(outline_ptr(p));}
24469 break;
24470 case stream_node:
24471 print_esc("HINTstream");print_int(stream_insertion(p));
24472 print_char('(');print_int(stream_number(p));print_char(')');
24473 break;
24474 case xdimen_node:
24475 print_esc("xdimen ");print_xdimen(p);
24476 break;
24477 default: print("whatsit?");
24478 }
24479
24480 @ @<Make a partial copy of the whatsit...@>=
24481 switch (subtype(p)) {
24482 case open_node: {@+r=get_node(open_node_size);words=open_node_size;
24483 } @+break;
24484 case write_node: case special_node: case latespecial_node: {@+r=get_node(write_node_size);
24485 add_token_ref(write_tokens(p));words=write_node_size;
24486 } @+break;
24487 case close_node: case language_node: {@+r=get_node(small_node_size);
24488 words=small_node_size;
24489 } @+break;
24490 @/@<Cases for making a partial copy of the whatsit node@>@/
24491 case param_node:
24492 {@+r=get_node(param_node_size);
24493 if (param_type(p)==glue_type) add_glue_ref(param_value(p).i);
24494 words=param_node_size;
24495 } @+break;
24496 case par_node:
24497 {@+r=get_node(par_node_size);
24498 add_xdimen_ref(par_extent(p));
24499 par_params(r)=copy_node_list(par_params(p));
24500 par_list(r)=copy_node_list(par_list(p));
24501 words=par_node_size-1;
24502 } @+break;
24503 case disp_node:
24504 {@+r=get_node(disp_node_size);
24505 display_left(r)=display_left(p);
24506 display_no_bs(r)=display_no_bs(p);
24507 display_eqno(r)=copy_node_list(display_eqno(p));
24508 display_formula(r)=copy_node_list(display_formula(p));
24509 display_params(r)=copy_node_list(display_params(p));
24510 words=disp_node_size-2;
24511 } @+break;
24512 case baseline_node:
24513 {@+r=get_node(baseline_node_size);
24514 words=baseline_node_size;
24515 } @+break;
24516 case hpack_node: case vpack_node:
24517 {@+r=get_node(pack_node_size);
24518 mem[r+7]=mem[p+7];mem[r+6]=mem[p+6];mem[r+5]=mem[p+5]; /*copy the last three words*/
24519 list_ptr(r)=copy_node_list(list_ptr(p));/*this affects |mem[r+5]|*/
24520 add_xdimen_ref(pack_extent(p));/*this affects |mem[r+7]|*/
24521 words=5;
24522 } @+break;
24523 case hset_node: case vset_node:
24524 {@+r=get_node(set_node_size);
24525 mem[r+8]=mem[p+8];mem[r+7]=mem[p+7];mem[r+6]=mem[p+6];mem[r+5]=mem[p+5]; /*copy the last four words*/
24526 list_ptr(r)=copy_node_list(list_ptr(p)); /*this affects |mem[r+5]|*/
24527 add_xdimen_ref(set_extent(p));/*this affects |mem[r+7]|*/
24528 words=5;
24529 } @+break;
24530 case image_node:
24531 r=get_node(image_node_size);
24532 add_xdimen_ref(image_xheight(p));add_xdimen_ref(image_xwidth(p));
24533 image_alt(r)=copy_node_list(image_alt(p));
24534 words=image_node_size-1;
24535 break;
24536 case color_node:
24537 case no_color_node:
24538 case end_color_node:
24539 r=get_node(color_node_size);
24540 words=color_node_size;
24541 break;
24542 case align_node:
24543 {@+r=get_node(align_node_size);
24544 align_preamble(r)=copy_node_list(align_preamble(p));
24545 align_list(r)=copy_node_list(align_list(p));
24546 add_xdimen_ref(align_extent(p));
24547 words=align_node_size-1;
24548 } @+break;
24549 case setpage_node:
24550 {@+r=get_node(setpage_node_size);
24551 add_glue_ref(setpage_topskip(p));
24552 add_xdimen_ref(setpage_height(p));
24553 add_xdimen_ref(setpage_width(p));
24554 setpage_list(r)=copy_node_list(setpage_list(p));
24555 setpage_streams(r)=copy_node_list(setpage_streams(p));
24556 words=setpage_node_size-1;
24557 } @+break;
24558 case setstream_node:
24559 {@+r=get_node(setstream_node_size);
24560 add_xdimen_ref(setstream_max(p));
24561 add_xdimen_ref(setstream_width(p));
24562 add_glue_ref(setstream_topskip(p));
24563 add_glue_ref(setstream_height(p));
24564 setstream_before(r)=copy_node_list(setstream_before(p));
24565 setstream_after(r)=copy_node_list(setstream_after(p));
24566 words=setstream_node_size-1;
24567 } @+break;
24568 case ignore_node:
24569 r=get_node(ignore_node_size);
24570 ignore_info(r)=ignore_info(p);
24571 ignore_list(r)=copy_node_list(ignore_list(p));
24572 words=ignore_node_size-1;
24573 break;
24574 case start_link_node:
24575 r=get_node(link_node_size);
24576 if (label_has_name(as_label(p))) add_token_ref(label_ptr(as_label(p)));
24577 words=link_node_size;
24578 break;
24579 case end_link_node:
24580 r=get_node(link_node_size);
24581 words=link_node_size;
24582 break;
24583 case label_node:
24584 r=get_node(label_node_size);
24585 if (label_has_name(p)) add_token_ref(label_ptr(p));
24586 words=label_node_size;
24587 break;
24588 case outline_node:
24589 r=get_node(outline_node_size);
24590 if (label_has_name(p)) add_token_ref(label_ptr(p));
24591 outline_ptr(r)=copy_node_list(outline_ptr(p));
24592 outline_depth(r)=outline_depth(p);
24593 words=outline_node_size-1;
24594 break;
24595 case stream_node:
24596 r=get_node(stream_node_size);
24597 words=stream_node_size;
24598 break;
24599 case xdimen_node:
24600 r=get_node(xdimen_node_size);
24601 words=xdimen_node_size;
24602 break;
24603 default:confusion("ext2");
24604 @:this can't happen ext2}{\quad ext2@>
24605 }
24606
24607 @ @<Wipe out the whatsit...@>=
24608 {@+switch (subtype(p)) {
24609 case open_node: free_node(p, open_node_size);@+break;
24610 case write_node: case special_node: case latespecial_node: {@+delete_token_ref(write_tokens(p));
24611 free_node(p, write_node_size);goto done;
24612 }
24613 case close_node: case language_node: free_node(p, small_node_size);@+break;
24614 case param_node:
24615 if (param_type(p)==glue_type) fast_delete_glue_ref(param_value(p).i);
24616 free_node(p, param_node_size);@+break;
24617 case par_node:
24618 delete_xdimen_ref(par_extent(p));
24619 flush_node_list(par_params(p));
24620 flush_node_list(par_list(p));
24621 free_node(p, par_node_size);@+break;
24622 case disp_node:
24623 flush_node_list(display_eqno(p));
24624 flush_node_list(display_formula(p));
24625 flush_node_list(display_params(p));
24626 free_node(p, disp_node_size);@+break;
24627 case baseline_node:
24628 free_node(p, baseline_node_size);@+break;
24629 case hpack_node: case vpack_node:
24630 delete_xdimen_ref(pack_extent(p));
24631 flush_node_list(list_ptr(p));
24632 free_node(p, pack_node_size);@+break;
24633 case hset_node: case vset_node:
24634 delete_xdimen_ref(set_extent(p));
24635 flush_node_list(list_ptr(p));
24636 free_node(p, set_node_size);@+break;
24637 case image_node:
24638 delete_xdimen_ref(image_xwidth(p)); delete_xdimen_ref(image_xheight(p));
24639 flush_node_list(image_alt(p));
24640 free_node(p,image_node_size);@+break;
24641 case color_node:
24642 case no_color_node:
24643 case end_color_node:
24644 free_node(p,color_node_size);@+break;
24645 case align_node:
24646 delete_xdimen_ref(align_extent(p));
24647 flush_node_list(align_preamble(p));
24648 flush_node_list(align_list(p));
24649 free_node(p, align_node_size);@+break;
24650 case setpage_node:
24651 delete_glue_ref(setpage_topskip(p));
24652 delete_xdimen_ref(setpage_height(p));
24653 delete_xdimen_ref(setpage_width(p));
24654 flush_node_list(setpage_list(p));
24655 flush_node_list(setpage_streams(p));
24656 free_node(p, setpage_node_size);@+break;
24657 case setstream_node:
24658 delete_xdimen_ref(setstream_max(p));
24659 delete_xdimen_ref(setstream_width(p));
24660 delete_glue_ref(setstream_topskip(p));
24661 delete_glue_ref(setstream_height(p));
24662 flush_node_list(setstream_before(p));
24663 flush_node_list(setstream_after(p));
24664 free_node(p,setstream_node_size); @+break;
24665 case ignore_node:
24666 flush_node_list(ignore_list(p));
24667 free_node(p,ignore_node_size); @+break;
24668 case start_link_node:
24669 if (label_has_name(as_label(p))) delete_token_ref(label_ptr(as_label(p)));
24670 free_node(p,link_node_size);@+break;
24671 case end_link_node:
24672 free_node(p,link_node_size);@+break;
24673 case label_node:
24674 if (label_has_name(p)) delete_token_ref(label_ptr(p));
24675 free_node(p,label_node_size);@+break;
24676 case outline_node:
24677 if (label_has_name(p)) delete_token_ref(label_ptr(p));
24678 flush_node_list(outline_ptr(p));
24679 free_node(p,outline_node_size);@+break;
24680 case stream_node:
24681 free_node(p,stream_node_size); @+break;
24682 case xdimen_node:
24683 free_node(p,xdimen_node_size);
24684 @/@<Cases for wiping out the whatsit node@>@/
24685 default:confusion("ext3");
24686 @:this can't happen ext3}{\quad ext3@>
24687 } @/
24688 goto done;
24689 }
24690
24691 @ @d adv_past(A) @+if (subtype(A)==language_node)
24692 {@+cur_lang=what_lang(A);l_hyf=what_lhm(A);r_hyf=what_rhm(A);
24693 set_hyph_index;
24694 }
24695
24696 @<Advance \(p)past a whatsit node in the \(l)|line_break| loop@>=@+
24697 adv_past(cur_p)
24698
24699 @ @<Advance \(p)past a whatsit node in the \(p)pre-hyphenation loop@>=@+
24700 adv_past(s)
24701
24702 @ @<Process whatsit |p| in |vert_break| loop, |goto not_found|@>=
24703 goto not_found
24704
24705 @ After all this preliminary shuffling, we come finally to the routines
24706 that actually send out the requested data. Let's do \.{\\special} first
24707 (it's easier).
24708
24709 @<Declare procedures needed in |hlist_out|, |vlist_out|@>=
24710 static void special_out(pointer @!p)
24711 {@+pointer @!q, @!r; /*temporary variables for list manipulation*/
24712 int @!old_mode; /*saved |mode|*/
24713
24714 if (subtype(p)==latespecial_node)
24715 {@+@<Expand macros in the token list and make |link(def_ref)| point to the
24716 result@>;
24717 write_tokens(p)=def_ref;
24718 }
24719 }
24720
24721 @ To write a token list, we must run it through \TeX's scanner, expanding
24722 macros and \.{\\the} and \.{\\number}, etc. This might cause runaways,
24723 if a delimited macro parameter isn't matched, and runaways would be
24724 extremely confusing since we are calling on \TeX's scanner in the middle
24725 of a \.{\\shipout} command. Therefore we will put a dummy control sequence as
24726 a ``stopper,'' right after the token list. This control sequence is
24727 artificially defined to be \.{\\outer}.
24728 @:end\_write\_}{\.{\\endwrite}@>
24729
24730 @<Initialize table...@>=
24731 text(end_write)=s_no("endwrite");eq_level(end_write)=level_one;
24732 eq_type(end_write)=outer_call;equiv(end_write)=null;
24733
24734 @ @<Declare procedures needed in |hlist_out|, |vlist_out|@>=
24735 static void write_out(pointer @!p)
24736 {@+int old_setting; /*holds print |selector|*/
24737 int @!old_mode; /*saved |mode|*/
24738 small_number @!j; /*write stream number*/
24739 pointer @!q, @!r; /*temporary variables for list manipulation*/
24740 @<Expand macros in the token list and make |link(def_ref)| point to the result@>;
24741 old_setting=selector;j=write_stream(p);
24742 if (write_open[j]) selector=j;
24743 else{@+ /*write to the terminal if file isn't open*/
24744 if ((j==17)&&(selector==term_and_log)) selector=log_only;
24745 print_nl("");
24746 }
24747 token_show(def_ref);print_ln();
24748 flush_list(def_ref);selector=old_setting;
24749 }
24750
24751 @ The final line of this routine is slightly subtle; at least, the author
24752 didn't think about it until getting burnt! There is a used-up token list
24753 @^Knuth, Donald Ervin@>
24754 on the stack, namely the one that contained |end_write_token|. (We
24755 insert this artificial `\.{\\endwrite}' to prevent runaways, as explained
24756 above.) If it were not removed, and if there were numerous writes on a
24757 single page, the stack would overflow.
24758
24759 @d end_write_token cs_token_flag+end_write
24760
24761 @<Expand macros in the token list and...@>=
24762 q=get_avail();info(q)=right_brace_token+'}';@/
24763 r=get_avail();link(q)=r;info(r)=end_write_token;ins_list(q);@/
24764 begin_token_list(write_tokens(p), write_text);@/
24765 q=get_avail();info(q)=left_brace_token+'{';ins_list(q);
24766 /*now we're ready to scan
24767 `\.\{$\langle\,$token list$\,\rangle$\.{\} \\endwrite}'*/
24768 old_mode=mode;mode=0;
24769 /*disable \.{\\prevdepth}, \.{\\spacefactor}, \.{\\lastskip}, \.{\\prevgraf}*/
24770 cur_cs=write_loc;q=scan_toks(false, true); /*expand macros, etc.*/
24771 get_token();@+if (cur_tok!=end_write_token)
24772 @<Recover from an unbalanced write command@>;
24773 mode=old_mode;
24774 end_token_list() /*conserve stack space*/
24775
24776 @ @<Recover from an unbalanced write command@>=
24777 {@+print_err("Unbalanced write command");
24778 @.Unbalanced write...@>
24779 help2("On this page there's a \\write with fewer real {'s than }'s.",@/
24780 "I can't handle that very well; good luck.");error();
24781 @/do@+{get_token();
24782 }@+ while (!(cur_tok==end_write_token));
24783 }
24784
24785 @ @<Declare procedures needed in |hlist_out|, |vlist_out|@>=
24786
24787 static void out_what(pointer @!p)
24788 {@+small_number j; /*write stream number*/
24789 switch (subtype(p)) {
24790 case open_node: case write_node: case close_node: @<Do some work that has
24791 been queued up for \.{\\write}@>@;@+break;
24792 case special_node: case latespecial_node: special_out(p);@+break;
24793 case language_node:
24794 case save_pos_code: do_nothing;@+break;
24795 default:confusion("ext4");
24796 @:this can't happen ext4}{\quad ext4@>
24797 }
24798 }
24799
24800 @ We don't implement \.{\\write} inside of leaders. (The reason is that
24801 the number of times a leader box appears might be different in different
24802 implementations, due to machine-dependent rounding in the glue calculations.)
24803 @^leaders@>
24804
24805 @<Do some work that has been queued up...@>=
24806 if (!doing_leaders)
24807 {@+j=write_stream(p);
24808 if (subtype(p)==write_node) write_out(p);
24809 else{@+if (write_open[j]) a_close(&write_file[j]);
24810 if (subtype(p)==close_node) write_open[j]=false;
24811 else if (j < 16)
24812 {@+cur_name=open_name(p);cur_area=open_area(p);
24813 cur_ext=open_ext(p);
24814 pack_cur_name(".tex");
24815 while (!a_open_out(&write_file[j]))
24816 prompt_file_name("output file name",".tex");
24817 write_open[j]=true;
24818 }
24819 }
24820 }
24821
24822 @ The presence of `\.{\\immediate}' causes the |do_extension| procedure
24823 to descend to one level of recursion. Nothing happens unless \.{\\immediate}
24824 is followed by `\.{\\openout}', `\.{\\write}', or `\.{\\closeout}'.
24825 @^recursion@>
24826
24827 @<Implement \.{\\immediate}@>=
24828 {@+get_x_token();
24829 if ((cur_cmd==extension)&&(cur_chr <= close_node))
24830 {@+p=tail;do_extension(); /*append a whatsit node*/
24831 out_what(tail); /*do the action immediately*/
24832 flush_node_list(tail);tail=p;link(p)=null;
24833 }
24834 else back_input();
24835 }
24836
24837 @ The \.{\\language} extension is somewhat different.
24838 We need a subroutine that comes into play when a character of
24839 a non-|clang| language is being appended to the current paragraph.
24840
24841 @<Declare action...@>=
24842 static void fix_language(void)
24843 {@+int @!l; /*the new current language*/
24844 if (language <= 0) l=0;
24845 else if (language > max_language) l=0;
24846 else l=language;
24847 if (l!=clang)
24848 {@+new_whatsit(language_node, small_node_size);
24849 what_lang(tail)=l;clang=l;@/
24850 what_lhm(tail)=norm_min(left_hyphen_min);
24851 what_rhm(tail)=norm_min(right_hyphen_min);
24852 }
24853 }
24854
24855 @ @<Implement \.{\\setlanguage}@>=
24856 if (abs(mode)!=hmode) report_illegal_case();
24857 else{@+new_whatsit(language_node, small_node_size);
24858 scan_int();
24859 if (cur_val <= 0) clang=0;
24860 else if (cur_val > max_language) clang=0;
24861 else clang=cur_val;
24862 what_lang(tail)=clang;
24863 what_lhm(tail)=norm_min(left_hyphen_min);
24864 what_rhm(tail)=norm_min(right_hyphen_min);
24865 }
24866
24867 @ @<Finish the extensions@>=
24868 for (k=0; k<=15; k++) if (write_open[k]) a_close(&write_file[k])
24869
24870 @* The extended features of \eTeX.
24871 The program has three modes of operation: (1)~In \TeX\ compatibility mode
24872 it fully deserves the name \TeX\ and there are neither extended features
24873 nor additional primitive commands. There are, however, a few
24874 modifications that would be legitimate in any implementation of \TeX\
24875 such as, e.g., preventing inadequate results of the glue to \.{DVI}
24876 unit conversion during |ship_out|. (2)~In extended mode there are
24877 additional primitive commands and the extended features of \eTeX\ are
24878 available. (3)~In \Prote\ mode there are supplementary primitive
24879 commands that will be discussed in the section below.
24880
24881 The distinction between these three modes of operation initially takes
24882 place when a `virgin' \.{eINITEX} starts without reading a format file.
24883 Later on the values of all \eTeX\ state variables are inherited when
24884 \.{eVIRTEX} (or \.{eINITEX}) reads a format file.
24885
24886 The code below is designed to work for cases where `$|@t\#\&{ifdef} \.{INIT}@>|\ldots|@t\#\&{endif}@>|$'
24887 is a run-time switch.
24888
24889 @<Enable \eTeX\ and furthermore Prote, if requested@>=
24890 #ifdef @!INIT
24891 if (iniversion && (buffer[loc]=='*'||etexp)) /* \TeX\ Live */
24892 {@+no_new_control_sequence=false;
24893 @<Generate all \eTeX\ primitives@>@;
24894 if (buffer[loc]=='*') incr(loc); /* \TeX\ Live */
24895 eTeX_mode=1; /*enter extended mode*/
24896 @<Initialize variables for \eTeX\ extended mode@>@;
24897 if (buffer[loc]=='*'||ltxp) {@+
24898 @<Check \Prote\ ``constant'' values for consistency@>@;
24899 @<Generate all \Prote\ primitives@>@;
24900 if (buffer[loc]=='*')incr(loc);
24901 Prote_mode=1; /*enter \Prote\ mode*/
24902 }
24903 }
24904 #endif
24905 @;@/
24906 if (!no_new_control_sequence) /*just entered extended mode ?*/
24907 no_new_control_sequence=true;@+else
24908
24909 @ The \eTeX\ features available in extended mode are grouped into two
24910 categories: (1)~Some of them are permanently enabled and have no
24911 semantic effect as long as none of the additional primitives are
24912 executed. (2)~The remaining \eTeX\ features are optional and can be
24913 individually enabled and disabled. For each optional feature there is
24914 an \eTeX\ state variable named \.{\\...state}; the feature is enabled,
24915 resp.\ disabled by assigning a positive, resp.\ non-positive value to
24916 that integer.
24917
24918 @d eTeX_state_base (int_base+eTeX_state_code)
24919 @d eTeX_state(A) eqtb[eTeX_state_base+A].i /*an \eTeX\ state variable*/
24920 @#
24921 @d eTeX_version_code eTeX_int /*code for \.{\\eTeXversion}*/
24922
24923 @<Generate all \eTeX...@>=
24924 primitive("lastnodetype", last_item, last_node_type_code);
24925 @!@:last\_node\_type\_}{\.{\\lastnodetype} primitive@>
24926 primitive("eTeXversion", last_item, eTeX_version_code);
24927 @!@:eTeX\_version\_}{\.{\\eTeXversion} primitive@>
24928 primitive("eTeXrevision", convert, eTeX_revision_code);@/
24929 @!@:eTeX\_revision\_}{\.{\\eTeXrevision} primitive@>
24930
24931 @ @<Cases of |last_item| for |print_cmd_chr|@>=
24932 case last_node_type_code: print_esc("lastnodetype");@+break;
24933 case eTeX_version_code: print_esc("eTeXversion");@+break;
24934
24935 @ @<Cases for fetching an integer value@>=
24936 case eTeX_version_code: cur_val=eTeX_version;@+break;
24937
24938 @ @d eTeX_ex (eTeX_mode==1) /*is this extended mode?*/
24939
24940 @<Glob...@>=
24941 static int @!eTeX_mode; /*identifies compatibility and extended mode*/
24942
24943 @ @<Initialize table entries...@>=
24944 eTeX_mode=0; /*initially we are in compatibility mode*/
24945 @<Initialize variables for \eTeX\ compatibility mode@>@;
24946
24947 @ @<Dump the \eTeX\ state@>=
24948 dump_int(eTeX_mode);
24949 for (j=0; j<=eTeX_states-1; j++) eTeX_state(j)=0; /*disable all enhancements*/
24950
24951 @ @<Undump the \eTeX\ state@>=
24952 undump(0, 1, eTeX_mode);
24953 if (eTeX_ex)
24954 {@+@<Initialize variables for \eTeX\ extended mode@>;
24955 }
24956 else{@+@<Initialize variables for \eTeX\ compatibility mode@>;
24957 }
24958
24959 @ First we implement the additional \eTeX\ parameters in the table of
24960 equivalents.
24961
24962 @<Generate all \eTeX...@>=
24963 primitive("everyeof", assign_toks, every_eof_loc);
24964 @!@:every\_eof\_}{\.{\\everyeof} primitive@>
24965 primitive("tracingassigns", assign_int, int_base+tracing_assigns_code);@/
24966 @!@:tracing\_assigns\_}{\.{\\tracingassigns} primitive@>
24967 primitive("tracinggroups", assign_int, int_base+tracing_groups_code);@/
24968 @!@:tracing\_groups\_}{\.{\\tracinggroups} primitive@>
24969 primitive("tracingifs", assign_int, int_base+tracing_ifs_code);@/
24970 @!@:tracing\_ifs\_}{\.{\\tracingifs} primitive@>
24971 primitive("tracingscantokens", assign_int, int_base+tracing_scan_tokens_code);@/
24972 @!@:tracing\_scan\_tokens\_}{\.{\\tracingscantokens} primitive@>
24973 primitive("tracingnesting", assign_int, int_base+tracing_nesting_code);@/
24974 @!@:tracing\_nesting\_}{\.{\\tracingnesting} primitive@>
24975 primitive("savingvdiscards", assign_int, int_base+saving_vdiscards_code);@/
24976 @!@:saving\_vdiscards\_}{\.{\\savingvdiscards} primitive@>
24977 primitive("savinghyphcodes", assign_int, int_base+saving_hyph_codes_code);@/
24978 @!@:saving\_hyph\_codes\_}{\.{\\savinghyphcodes} primitive@>
24979 primitive("ignoreprimitiveerror", assign_int, int_base+ignore_primitive_error_code);@/
24980 @!@:ignore\_primitive\_error\_}{\.{\\ignoreprimitiveerror} primitive@>
24981
24982 @ @d every_eof equiv(every_eof_loc)
24983
24984 @<Cases of |assign_toks| for |print_cmd_chr|@>=
24985 case every_eof_loc: print_esc("everyeof");@+break;
24986
24987 @ @<Cases for |print_param|@>=
24988 case tracing_assigns_code: print_esc("tracingassigns");@+break;
24989 case tracing_groups_code: print_esc("tracinggroups");@+break;
24990 case tracing_ifs_code: print_esc("tracingifs");@+break;
24991 case tracing_scan_tokens_code: print_esc("tracingscantokens");@+break;
24992 case tracing_nesting_code: print_esc("tracingnesting");@+break;
24993 case saving_vdiscards_code: print_esc("savingvdiscards");@+break;
24994 case saving_hyph_codes_code: print_esc("savinghyphcodes");@+break;
24995 case ignore_primitive_error_code: print_esc("ignoreprimitiveerror");@+break;
24996
24997 @ In order to handle \.{\\everyeof} we need an array |eof_seen| of
24998 boolean variables.
24999
25000 @<Glob...@>=
25001 static bool @!eof_seen0[max_in_open],
25002 *const @!eof_seen = @!eof_seen0-1; /*has eof been seen?*/
25003
25004 @ The |print_group| procedure prints the current level of grouping and
25005 the name corresponding to |cur_group|.
25006
25007 @<Declare \eTeX\ procedures for tr...@>=
25008 static void print_group(bool @!e)
25009 {@+
25010 switch (cur_group) {
25011 case bottom_level: {@+print("bottom level");return;
25012 }
25013 case simple_group: case semi_simple_group:
25014 {@+if (cur_group==semi_simple_group) print("semi ");
25015 print("simple");
25016 } @+break;
25017 case hbox_group: case adjusted_hbox_group:
25018 {@+if (cur_group==adjusted_hbox_group) print("adjusted ");
25019 print("hbox");
25020 } @+break;
25021 case vbox_group: print("vbox");@+break;
25022 case vtop_group: print("vtop");@+break;
25023 case align_group: case no_align_group:
25024 {@+if (cur_group==no_align_group) print("no ");
25025 print("align");
25026 } @+break;
25027 case output_group: print("output");@+break;
25028 case disc_group: print("disc");@+break;
25029 case insert_group: print("insert");@+break;
25030 case vcenter_group: print("vcenter");@+break;
25031 case math_group: case math_choice_group:
25032 case math_shift_group: case math_left_group:
25033 {@+print("math");
25034 if (cur_group==math_choice_group) print(" choice");
25035 else if (cur_group==math_shift_group) print(" shift");
25036 else if (cur_group==math_left_group) print(" left");
25037 }
25038 } /*there are no other cases*/
25039 print(" group (level ");print_int(qo(cur_level));print_char(')');
25040 if (saved(-1)!=0)
25041 {@+if (e) print(" entered at line ");else print(" at line ");
25042 print_int(saved(-1));
25043 }
25044 }
25045
25046 @ The |group_trace| procedure is called when a new level of grouping
25047 begins (|e==false|) or ends (|e==true|) with |saved(-1)| containing the
25048 line number.
25049
25050 @<Declare \eTeX\ procedures for tr...@>=
25051 #ifdef @!STAT
25052 static void group_trace(bool @!e)
25053 {@+begin_diagnostic();print_char('{');
25054 if (e) print("leaving ");else print("entering ");
25055 print_group(e);print_char('}');end_diagnostic(false);
25056 }
25057 #endif
25058
25059 @ The \.{\\currentgrouplevel} and \.{\\currentgrouptype} commands return
25060 the current level of grouping and the type of the current group
25061 respectively.
25062
25063 @d current_group_level_code (eTeX_int+1) /*code for \.{\\currentgrouplevel}*/
25064 @d current_group_type_code (eTeX_int+2) /*code for \.{\\currentgrouptype}*/
25065
25066 @<Generate all \eTeX...@>=
25067 primitive("currentgrouplevel", last_item, current_group_level_code);
25068 @!@:current\_group\_level\_}{\.{\\currentgrouplevel} primitive@>
25069 primitive("currentgrouptype", last_item, current_group_type_code);
25070 @!@:current\_group\_type\_}{\.{\\currentgrouptype} primitive@>
25071
25072 @ @<Cases of |last_item| for |print_cmd_chr|@>=
25073 case current_group_level_code: print_esc("currentgrouplevel");@+break;
25074 case current_group_type_code: print_esc("currentgrouptype");@+break;
25075
25076 @ @<Cases for fetching an integer value@>=
25077 case current_group_level_code: cur_val=cur_level-level_one;@+break;
25078 case current_group_type_code: cur_val=cur_group;@+break;
25079
25080 @ The \.{\\currentiflevel}, \.{\\currentiftype}, and
25081 \.{\\currentifbranch} commands return the current level of conditionals
25082 and the type and branch of the current conditional.
25083
25084 @d current_if_level_code (eTeX_int+3) /*code for \.{\\currentiflevel}*/
25085 @d current_if_type_code (eTeX_int+4) /*code for \.{\\currentiftype}*/
25086 @d current_if_branch_code (eTeX_int+5) /*code for \.{\\currentifbranch}*/
25087
25088 @<Generate all \eTeX...@>=
25089 primitive("currentiflevel", last_item, current_if_level_code);
25090 @!@:current\_if\_level\_}{\.{\\currentiflevel} primitive@>
25091 primitive("currentiftype", last_item, current_if_type_code);
25092 @!@:current\_if\_type\_}{\.{\\currentiftype} primitive@>
25093 primitive("currentifbranch", last_item, current_if_branch_code);
25094 @!@:current\_if\_branch\_}{\.{\\currentifbranch} primitive@>
25095
25096 @ @<Cases of |last_item| for |print_cmd_chr|@>=
25097 case current_if_level_code: print_esc("currentiflevel");@+break;
25098 case current_if_type_code: print_esc("currentiftype");@+break;
25099 case current_if_branch_code: print_esc("currentifbranch");@+break;
25100
25101 @ @<Cases for fetching an integer value@>=
25102 case current_if_level_code: {@+q=cond_ptr;cur_val=0;
25103 while (q!=null)
25104 {@+incr(cur_val);q=link(q);
25105 }
25106 } @+break;
25107 case current_if_type_code: if (cond_ptr==null) cur_val=0;
25108 else if (cur_if < unless_code) cur_val=cur_if+1;
25109 else cur_val=-(cur_if-unless_code+1);@+break;
25110 case current_if_branch_code:
25111 if ((if_limit==or_code)||(if_limit==else_code)) cur_val=1;
25112 else if (if_limit==fi_code) cur_val=-1;
25113 else cur_val=0;@+break;
25114
25115 @ The \.{\\fontcharwd}, \.{\\fontcharht}, \.{\\fontchardp}, and
25116 \.{\\fontcharic} commands return information about a character in a
25117 font.
25118
25119 @d font_char_wd_code eTeX_dim /*code for \.{\\fontcharwd}*/
25120 @d font_char_ht_code (eTeX_dim+1) /*code for \.{\\fontcharht}*/
25121 @d font_char_dp_code (eTeX_dim+2) /*code for \.{\\fontchardp}*/
25122 @d font_char_ic_code (eTeX_dim+3) /*code for \.{\\fontcharic}*/
25123
25124 @<Generate all \eTeX...@>=
25125 primitive("fontcharwd", last_item, font_char_wd_code);
25126 @!@:font\_char\_wd\_}{\.{\\fontcharwd} primitive@>
25127 primitive("fontcharht", last_item, font_char_ht_code);
25128 @!@:font\_char\_ht\_}{\.{\\fontcharht} primitive@>
25129 primitive("fontchardp", last_item, font_char_dp_code);
25130 @!@:font\_char\_dp\_}{\.{\\fontchardp} primitive@>
25131 primitive("fontcharic", last_item, font_char_ic_code);
25132 @!@:font\_char\_ic\_}{\.{\\fontcharic} primitive@>
25133
25134 @ @<Cases of |last_item| for |print_cmd_chr|@>=
25135 case font_char_wd_code: print_esc("fontcharwd");@+break;
25136 case font_char_ht_code: print_esc("fontcharht");@+break;
25137 case font_char_dp_code: print_esc("fontchardp");@+break;
25138 case font_char_ic_code: print_esc("fontcharic");@+break;
25139
25140 @ @<Cases for fetching a dimension value@>=
25141 case font_char_wd_code:
25142 case font_char_ht_code:
25143 case font_char_dp_code:
25144 case font_char_ic_code: {@+scan_font_ident();q=cur_val;scan_char_num();
25145 if ((font_bc[q] <= cur_val)&&(font_ec[q] >= cur_val))
25146 {@+
25147 switch (m) {
25148 case font_char_wd_code: cur_val=char_width(q, qi(cur_val));@+break;
25149 case font_char_ht_code: cur_val=char_height(q, qi(cur_val));@+break;
25150 case font_char_dp_code: cur_val=char_depth(q, qi(cur_val));@+break;
25151 case font_char_ic_code: cur_val=char_italic(q, qi(cur_val));
25152 } /*there are no other cases*/
25153 }
25154 else cur_val=0;
25155 } @+break;
25156
25157 @ The \.{\\parshapedimen}, \.{\\parshapeindent}, and \.{\\parshapelength}
25158 commands return the indent and length parameters of the current
25159 \.{\\parshape} specification.
25160
25161 @d par_shape_length_code (eTeX_dim+4) /*code for \.{\\parshapelength}*/
25162 @d par_shape_indent_code (eTeX_dim+5) /*code for \.{\\parshapeindent}*/
25163 @d par_shape_dimen_code (eTeX_dim+6) /*code for \.{\\parshapedimen}*/
25164
25165 @<Generate all \eTeX...@>=
25166 primitive("parshapelength", last_item, par_shape_length_code);
25167 @!@:par\_shape\_length\_}{\.{\\parshapelength} primitive@>
25168 primitive("parshapeindent", last_item, par_shape_indent_code);
25169 @!@:par\_shape\_indent\_}{\.{\\parshapeindent} primitive@>
25170 primitive("parshapedimen", last_item, par_shape_dimen_code);
25171 @!@:par\_shape\_dimen\_}{\.{\\parshapedimen} primitive@>
25172
25173 @ @<Cases of |last_item| for |print_cmd_chr|@>=
25174 case par_shape_length_code: print_esc("parshapelength");@+break;
25175 case par_shape_indent_code: print_esc("parshapeindent");@+break;
25176 case par_shape_dimen_code: print_esc("parshapedimen");@+break;
25177
25178 @ @<Cases for fetching a dimension value@>=
25179 case par_shape_length_code:
25180 case par_shape_indent_code:
25181 case par_shape_dimen_code: {@+q=cur_chr-par_shape_length_code;scan_int();
25182 if ((par_shape_ptr==null)||(cur_val <= 0)) cur_val=0;
25183 else{@+if (q==2)
25184 {@+q=cur_val%2;cur_val=(cur_val+q)/2;
25185 }
25186 if (cur_val > info(par_shape_ptr)) cur_val=info(par_shape_ptr);
25187 cur_val=mem[par_shape_ptr+2*cur_val-q].sc;
25188 }
25189 cur_val_level=dimen_val;
25190 } @+break;
25191
25192 @ The \.{\\showgroups} command displays all currently active grouping
25193 levels.
25194
25195 @d show_groups 4 /* \.{\\showgroups} */
25196
25197 @<Generate all \eTeX...@>=
25198 primitive("showgroups", xray, show_groups);
25199 @!@:show\_groups\_}{\.{\\showgroups} primitive@>
25200
25201 @ @<Cases of |xray| for |print_cmd_chr|@>=
25202 case show_groups: print_esc("showgroups");@+break;
25203
25204 @ @<Cases for |show_whatever|@>=
25205 case show_groups: {@+begin_diagnostic();show_save_groups();
25206 } @+break;
25207
25208 @ @<Types...@>=
25209 typedef int32_t save_pointer; /*index into |save_stack|*/
25210
25211 @ The modifications of \TeX\ required for the display produced by the
25212 |show_save_groups| procedure were first discussed by Donald~E. Knuth in
25213 {\sl TUGboat\/} {\bf 11}, 165--170 and 499--511, 1990.
25214 @^Knuth, Donald Ervin@>
25215
25216 In order to understand a group type we also have to know its mode.
25217 Since unrestricted horizontal modes are not associated with grouping,
25218 they are skipped when traversing the semantic nest.
25219
25220 @<Declare \eTeX\ procedures for use...@>=
25221 static void show_save_groups(void)
25222 {@+
25223 int p; /*index into |nest|*/
25224 int @!m; /*mode*/
25225 save_pointer @!v; /*saved value of |save_ptr|*/
25226 quarterword @!l; /*saved value of |cur_level|*/
25227 group_code @!c; /*saved value of |cur_group|*/
25228 int @!a; /*to keep track of alignments*/
25229 int @!i;
25230 quarterword @!j;
25231 char *@!s;
25232 p=nest_ptr;nest[p]=cur_list; /*put the top level into the array*/
25233 v=save_ptr;l=cur_level;c=cur_group;
25234 save_ptr=cur_boundary;decr(cur_level);@/
25235 a=1;
25236 print_nl("");print_ln();
25237 loop@+{@+print_nl("### ");print_group(true);
25238 if (cur_group==bottom_level) goto done;
25239 @/do@+{m=nest[p].mode_field;
25240 if (p > 0) decr(p);else m=vmode;
25241 }@+ while (!(m!=hmode));
25242 print(" (");
25243 switch (cur_group) {
25244 case simple_group: {@+incr(p);goto found2;
25245 }
25246 case hbox_group: case adjusted_hbox_group: s="hbox";@+break;
25247 case vbox_group: s="vbox";@+break;
25248 case vtop_group: s="vtop";@+break;
25249 case align_group: if (a==0)
25250 {@+if (m==-vmode) s="halign";else s="valign";
25251 a=1;goto found1;
25252 }
25253 else{@+if (a==1) print("align entry");else print_esc("cr");
25254 if (p >= a) p=p-a;
25255 a=0;goto found;
25256 } @+break;
25257 case no_align_group:
25258 {@+incr(p);a=-1;print_esc("noalign");goto found2;
25259 }
25260 case output_group:
25261 {@+print_esc("output");goto found;
25262 }
25263 case math_group: goto found2;
25264 case disc_group: case math_choice_group:
25265 {@+if (cur_group==disc_group) print_esc("discretionary");
25266 else print_esc("mathchoice");
25267 for (i=1; i<=3; i++) if (i <= saved(-2)) print("{}");
25268 goto found2;
25269 }
25270 case insert_group:
25271 {@+if (saved(-2)==255) print_esc("vadjust");
25272 else{@+print_esc("insert");print_int(saved(-2));
25273 }
25274 goto found2;
25275 }
25276 case vcenter_group: {@+s="vcenter";goto found1;
25277 }
25278 case semi_simple_group: {@+incr(p);print_esc("begingroup");goto found;
25279 }
25280 case math_shift_group:
25281 {@+if (m==mmode) print_char('$');
25282 else if (nest[p].mode_field==mmode)
25283 {@+print_cmd_chr(eq_no, saved(-2));goto found;
25284 }
25285 print_char('$');goto found;
25286 }
25287 case math_left_group:
25288 {@+if (type(nest[p+1].eTeX_aux_field)==left_noad) print_esc("left");
25289 else print_esc("middle");
25290 goto found;
25291 }
25292 } /*there are no other cases*/
25293 @<Show the box context@>;
25294 found1: print_esc(s);@<Show the box packaging info@>;
25295 found2: print_char('{');
25296 found: print_char(')');decr(cur_level);
25297 cur_group=save_level(save_ptr);save_ptr=save_index(save_ptr);
25298 }
25299 done: save_ptr=v;cur_level=l;cur_group=c;
25300 }
25301
25302 @ @<Show the box packaging info@>=
25303 if (saved(-2)!=0)
25304 {@+print_char(' ');
25305 if (saved(-3)==exactly) print("to");else print("spread");
25306 print_scaled(saved(-2));print("pt");
25307 }
25308
25309 @ @<Show the box context@>=
25310 i=saved(-4);
25311 if (i!=0)
25312 if (i < box_flag)
25313 {@+if (abs(nest[p].mode_field)==vmode) j=hmove;else j=vmove;
25314 if (i > 0) print_cmd_chr(j, 0);else print_cmd_chr(j, 1);
25315 print_scaled(abs(i));print("pt");
25316 }
25317 else if (i < ship_out_flag)
25318 {@+if (i >= global_box_flag)
25319 {@+print_esc("global");i=i-(global_box_flag-box_flag);
25320 }
25321 print_esc("setbox");print_int(i-box_flag);print_char('=');
25322 }
25323 else print_cmd_chr(leader_ship, i-(leader_flag-a_leaders))
25324
25325 @ The |scan_general_text| procedure is much like |scan_toks(false, false)|,
25326 but will be invoked via |expand|, i.e., recursively.
25327 @^recursion@>
25328
25329 @<Declare \eTeX\ procedures for sc...@>=
25330 static void scan_general_text(void);
25331
25332 @ The token list (balanced text) created by |scan_general_text| begins
25333 at |link(temp_head)| and ends at |cur_val|. (If |cur_val==temp_head|,
25334 the list is empty.)
25335
25336 @<Declare \eTeX\ procedures for tok...@>=
25337 static void scan_general_text(void)
25338 {@+
25339 int s; /*to save |scanner_status|*/
25340 pointer @!w; /*to save |warning_index|*/
25341 pointer @!d; /*to save |def_ref|*/
25342 pointer @!p; /*tail of the token list being built*/
25343 pointer @!q; /*new node being added to the token list via |store_new_token|*/
25344 halfword @!unbalance; /*number of unmatched left braces*/
25345 s=scanner_status;w=warning_index;d=def_ref;
25346 scanner_status=absorbing;warning_index=cur_cs;
25347 def_ref=get_avail();token_ref_count(def_ref)=null;p=def_ref;
25348 scan_left_brace(); /*remove the compulsory left brace*/
25349 unbalance=1;
25350 loop@+{@+get_token();
25351 if (cur_tok < right_brace_limit)
25352 if (cur_cmd < right_brace) incr(unbalance);
25353 else{@+decr(unbalance);
25354 if (unbalance==0) goto found;
25355 }
25356 store_new_token(cur_tok);
25357 }
25358 found: q=link(def_ref);free_avail(def_ref); /*discard reference count*/
25359 if (q==null) cur_val=temp_head;@+else cur_val=p;
25360 link(temp_head)=q;
25361 scanner_status=s;warning_index=w;def_ref=d;
25362 }
25363
25364 @ The \.{\\showtokens} command displays a token list.
25365
25366 @d show_tokens 5 /* \.{\\showtokens} , must be odd! */
25367
25368 @<Generate all \eTeX...@>=
25369 primitive("showtokens", xray, show_tokens);
25370 @!@:show\_tokens\_}{\.{\\showtokens} primitive@>
25371
25372 @ @<Cases of |xray| for |print_cmd_chr|@>=
25373 case show_tokens: print_esc("showtokens");@+break;
25374
25375 @ The \.{\\unexpanded} primitive prevents expansion of tokens much as
25376 the result from \.{\\the} applied to a token variable. The
25377 \.{\\detokenize} primitive converts a token list into a list of
25378 character tokens much as if the token list were written to a file. We
25379 use the fact that the command modifiers for \.{\\unexpanded} and
25380 \.{\\detokenize} are odd whereas those for \.{\\the} and \.{\\showthe}
25381 are even.
25382
25383 @<Generate all \eTeX...@>=
25384 primitive("unexpanded", the, 1);@/
25385 @!@:unexpanded\_}{\.{\\unexpanded} primitive@>
25386 primitive("detokenize", the, show_tokens);@/
25387 @!@:detokenize\_}{\.{\\detokenize} primitive@>
25388
25389 @ @<Cases of |the| for |print_cmd_chr|@>=;
25390 else if (chr_code==1) print_esc("unexpanded");
25391 else print_esc("detokenize")
25392
25393 @ @<Handle \.{\\unexpanded} or \.{\\detokenize} and |return|@>=
25394 if (odd(cur_chr))
25395 {@+c=cur_chr;scan_general_text();
25396 if (c==1) return cur_val;
25397 else{@+old_setting=selector;selector=new_string;b=pool_ptr;
25398 p=get_avail();link(p)=link(temp_head);
25399 token_show(p);flush_list(p);
25400 selector=old_setting;return str_toks(b);
25401 }
25402
25403 }
25404
25405 @ The \.{\\showifs} command displays all currently active conditionals.
25406
25407 @d show_ifs 6 /* \.{\\showifs} */
25408
25409 @<Generate all \eTeX...@>=
25410 primitive("showifs", xray, show_ifs);
25411 @!@:show\_ifs\_}{\.{\\showifs} primitive@>
25412
25413 @ @<Cases of |xray| for |print_cmd_chr|@>=
25414 case show_ifs: print_esc("showifs");@+break;
25415
25416 @ @d print_if_line(A) if (A!=0)
25417 {@+print(" entered on line ");print_int(A);
25418 }
25419
25420 @<Cases for |show_whatever|@>=
25421 case show_ifs: {@+begin_diagnostic();print_nl("");print_ln();
25422 if (cond_ptr==null)
25423 {@+print_nl("### ");print("no active conditionals");
25424 }
25425 else{@+p=cond_ptr;n=0;
25426 @/do@+{incr(n);p=link(p);@+}@+ while (!(p==null));
25427 p=cond_ptr;t=cur_if;l=if_line;m=if_limit;
25428 @/do@+{print_nl("### level ");print_int(n);print(": ");
25429 print_cmd_chr(if_test, t);
25430 if (m==fi_code) print_esc("else");
25431 print_if_line(l);
25432 decr(n);t=subtype(p);l=if_line_field(p);m=type(p);p=link(p);
25433 }@+ while (!(p==null));
25434 }
25435 } @+break;
25436
25437 @ The \.{\\interactionmode} primitive allows to query and set the
25438 interaction mode.
25439
25440 @<Generate all \eTeX...@>=
25441 primitive("interactionmode", set_page_int, 2);
25442 @!@:interaction\_mode\_}{\.{\\interactionmode} primitive@>
25443
25444 @ @<Cases of |set_page_int| for |print_cmd_chr|@>=;
25445 else if (chr_code==2) print_esc("interactionmode")
25446
25447 @ @<Cases for `Fetch the |dead_cycles| or the |insert_penalties|'@>=;
25448 else if (m==2) cur_val=interaction
25449
25450 @ @<Declare \eTeX\ procedures for use...@>=
25451 static void new_interaction(void);
25452
25453 @ @<Cases for |alter_integer|@>=;
25454 else if (c==2)
25455 {@+if ((cur_val < batch_mode)||(cur_val > error_stop_mode))
25456 {@+print_err("Bad interaction mode");
25457 @.Bad interaction mode@>
25458 help2("Modes are 0=batch, 1=nonstop, 2=scroll, and",@/
25459 "3=errorstop. Proceed, and I'll ignore this case.");
25460 int_error(cur_val);
25461 }
25462 else{@+cur_chr=cur_val;new_interaction();
25463 }
25464 }
25465
25466 @ The |middle| feature of \eTeX\ allows one ore several \.{\\middle}
25467 delimiters to appear between \.{\\left} and \.{\\right}.
25468
25469 @<Generate all \eTeX...@>=
25470 primitive("middle", left_right, middle_noad);
25471 @!@:middle\_}{\.{\\middle} primitive@>
25472
25473 @ @<Cases of |left_right| for |print_cmd_chr|@>=;
25474 else if (chr_code==middle_noad) print_esc("middle")
25475
25476 @ The |scan_tokens| feature of \eTeX\ defines the \.{\\scantokens}
25477 primitive.
25478
25479 @<Generate all \eTeX...@>=
25480 primitive("scantokens", input, 2);
25481 @!@:scan\_tokens\_}{\.{\\scantokens} primitive@>
25482
25483 @ @<Cases of |input| for |print_cmd_chr|@>=;
25484 else if (chr_code==2) print_esc("scantokens")
25485
25486 @ @<Cases for |input|@>=;
25487 else if (cur_chr==2) pseudo_start()
25488
25489 @ The global variable |pseudo_files| is used to maintain a stack of
25490 pseudo files. The |info| field of each pseudo file points to a linked
25491 list of variable size nodes representing lines not yet processed: the
25492 |info| field of the first word contains the size of this node, all the
25493 following words contain ASCII codes.
25494
25495 @<Glob...@>=
25496 static pointer @!pseudo_files; /*stack of pseudo files*/
25497
25498 @ @<Set init...@>=
25499 pseudo_files=null;
25500
25501 @ The |pseudo_start| procedure initiates reading from a pseudo file.
25502
25503 @<Declare \eTeX\ procedures for ex...@>=
25504 static void pseudo_start(void);
25505
25506 @ @<Declare \eTeX\ procedures for tok...@>=
25507 static void pseudo_start(void)
25508 {@+int old_setting; /*holds |selector| setting*/
25509 str_number @!s; /*string to be converted into a pseudo file*/
25510 pool_pointer @!l, @!m; /*indices into |str_pool|*/
25511 pointer @!p, @!q, @!r; /*for list construction*/
25512 four_quarters @!w; /*four ASCII codes*/
25513 int @!nl, @!sz;
25514 scan_general_text();
25515 old_setting=selector;selector=new_string;
25516 token_show(temp_head);selector=old_setting;
25517 flush_list(link(temp_head));
25518 str_room(1);s=make_string();
25519 @<Convert string |s| into a new pseudo file@>;
25520 flush_string;
25521 @<Initiate input from new pseudo file@>;
25522 }
25523
25524 @ @<Convert string |s| into a new pseudo file@>=
25525 str_pool[pool_ptr]=' ';l=str_start[s];
25526 nl=new_line_char;
25527 p=get_avail();q=p;
25528 while (l < pool_ptr)
25529 {@+m=l;
25530 while ((l < pool_ptr)&&(str_pool[l]!=nl)) incr(l);
25531 sz=(l-m+7)/4;
25532 if (sz==1) sz=2;
25533 r=get_node(sz);link(q)=r;q=r;info(q)=hi(sz);
25534 while (sz > 2)
25535 {@+decr(sz);incr(r);
25536 w.b0=qi(str_pool[m]);w.b1=qi(str_pool[m+1]);
25537 w.b2=qi(str_pool[m+2]);w.b3=qi(str_pool[m+3]);
25538 mem[r].qqqq=w;m=m+4;
25539 }
25540 w.b0=qi(' ');w.b1=qi(' ');w.b2=qi(' ');w.b3=qi(' ');
25541 if (l > m)
25542 {@+w.b0=qi(str_pool[m]);
25543 if (l > m+1)
25544 {@+w.b1=qi(str_pool[m+1]);
25545 if (l > m+2)
25546 {@+w.b2=qi(str_pool[m+2]);
25547 if (l > m+3) w.b3=qi(str_pool[m+3]);
25548 }
25549 }
25550 }
25551 mem[r+1].qqqq=w;
25552 if (str_pool[l]==nl) incr(l);
25553 }
25554 info(p)=link(p);link(p)=pseudo_files;pseudo_files=p
25555
25556 @ @<Initiate input from new pseudo file@>=
25557 begin_file_reading(); /*set up |cur_file| and new level of input*/
25558 line=0;limit=start;loc=limit+1; /*force line read*/
25559 if (tracing_scan_tokens > 0)
25560 {@+if (term_offset > max_print_line-3) print_ln();
25561 else if ((term_offset > 0)||(file_offset > 0)) print_char(' ');
25562 name=19;print("( ");incr(open_parens);update_terminal;
25563 }
25564 else name=18
25565
25566 @ Here we read a line from the current pseudo file into |buffer|.
25567
25568 @<Declare \eTeX\ procedures for tr...@>=
25569 static bool pseudo_input(void) /*inputs the next line or returns |false|*/
25570 {@+pointer p; /*current line from pseudo file*/
25571 int @!sz; /*size of node |p|*/
25572 four_quarters @!w; /*four ASCII codes*/
25573 int @!r; /*loop index*/
25574 last=first; /*cf.\ Matthew 19\thinspace:\thinspace30*/
25575 p=info(pseudo_files);
25576 if (p==null) return false;
25577 else{@+info(pseudo_files)=link(p);sz=ho(info(p));
25578 if (4*sz-3 >= buf_size-last)
25579 @<Report overflow of the input buffer, and abort@>;
25580 last=first;
25581 for (r=p+1; r<=p+sz-1; r++)
25582 {@+w=mem[r].qqqq;
25583 buffer[last]=w.b0;buffer[last+1]=w.b1;
25584 buffer[last+2]=w.b2;buffer[last+3]=w.b3;
25585 last=last+4;
25586 }
25587 if (last >= max_buf_stack) max_buf_stack=last+1;
25588 while ((last > first)&&(buffer[last-1]==' ')) decr(last);
25589 free_node(p, sz);
25590 return true;
25591 }
25592 }
25593
25594 @ When we are done with a pseudo file we `close' it.
25595
25596 @<Declare \eTeX\ procedures for tr...@>=
25597 static void pseudo_close(void) /*close the top level pseudo file*/
25598 {@+pointer p, @!q;
25599 p=link(pseudo_files);q=info(pseudo_files);
25600 free_avail(pseudo_files);pseudo_files=p;
25601 while (q!=null)
25602 {@+p=q;q=link(p);free_node(p, ho(info(p)));
25603 }
25604 }
25605
25606 @ @<Dump the \eTeX\ state@>=
25607 while (pseudo_files!=null) pseudo_close(); /*flush pseudo files*/
25608
25609 @ @<Generate all \eTeX...@>=
25610 primitive("readline", read_to_cs, 1);@/
25611 @!@:read\_line\_}{\.{\\readline} primitive@>
25612
25613 @ @<Cases of |read| for |print_cmd_chr|@>=;
25614 else print_esc("readline")
25615
25616 @ @<Handle \.{\\readline} and |goto done|@>=
25617 if (j==1)
25618 {@+while (loc <= limit) /*current line not yet finished*/
25619 {@+cur_chr=buffer[loc];incr(loc);
25620 if (cur_chr==' ') cur_tok=space_token;
25621 @+else cur_tok=cur_chr+other_token;
25622 store_new_token(cur_tok);
25623 }
25624 goto done;
25625 }
25626
25627 @ Here we define the additional conditionals of \eTeX\ as well as the
25628 \.{\\unless} prefix.
25629
25630 @d if_def_code 17 /* `\.{\\ifdefined}' */
25631 @d if_cs_code 18 /* `\.{\\ifcsname}' */
25632 @d if_font_char_code 19 /* `\.{\\iffontchar}' */
25633 @d eTeX_last_if_test_cmd_mod if_font_char_code
25634 @d eTeX_last_expand_after_cmd_mod 1
25635
25636 @<Generate all \eTeX...@>=
25637 primitive("unless", expand_after, 1);@/
25638 @!@:unless\_}{\.{\\unless} primitive@>
25639 primitive("ifdefined", if_test, if_def_code);
25640 @!@:if\_defined\_}{\.{\\ifdefined} primitive@>
25641 primitive("ifcsname", if_test, if_cs_code);
25642 @!@:if\_cs\_name\_}{\.{\\ifcsname} primitive@>
25643 primitive("iffontchar", if_test, if_font_char_code);
25644 @!@:if\_font\_char\_}{\.{\\iffontchar} primitive@>
25645
25646 @ @<Cases of |expandafter| for |print_cmd_chr|@>=
25647 case 1: print_esc("unless");@+break;
25648
25649 @ @<Cases of |if_test| for |print_cmd_chr|@>=
25650 case if_def_code: print_esc("ifdefined");@+break;
25651 case if_cs_code: print_esc("ifcsname");@+break;
25652 case if_font_char_code: print_esc("iffontchar");@+break;
25653
25654 @ The result of a boolean condition is reversed when the conditional is
25655 preceded by \.{\\unless}.
25656
25657 @<Negate a boolean conditional and |goto reswitch|@>=
25658 {@+get_token();
25659 if ((cur_cmd==if_test)&&(cur_chr!=if_case_code))
25660 {@+cur_chr=cur_chr+unless_code;goto reswitch;
25661 }
25662 print_err("You can't use `");print_esc("unless");print("' before `");
25663 @.You can't use \\unless...@>
25664 print_cmd_chr(cur_cmd, cur_chr);print_char('\'');
25665 help1("Continue, and I'll forget that it ever happened.");
25666 back_error();
25667 }
25668
25669 @ The conditional \.{\\ifdefined} tests if a control sequence is
25670 defined.
25671
25672 We need to reset |scanner_status|, since \.{\\outer} control sequences
25673 are allowed, but we might be scanning a macro definition or preamble.
25674
25675 @<Cases for |conditional|@>=
25676 case if_def_code: {@+save_scanner_status=scanner_status;
25677 scanner_status=normal;
25678 get_next();b=(cur_cmd!=undefined_cs);
25679 scanner_status=save_scanner_status;
25680 } @+break;
25681
25682 @ The conditional \.{\\ifcsname} is equivalent to \.{\{\\expandafter}
25683 \.{\}\\expandafter} \.{\\ifdefined} \.{\\csname}, except that no new
25684 control sequence will be entered into the hash table (once all tokens
25685 preceding the mandatory \.{\\endcsname} have been expanded).
25686
25687 @<Cases for |conditional|@>=
25688 case if_cs_code: {@+n=get_avail();p=n; /*head of the list of characters*/
25689 @/do@+{get_x_token();
25690 if (cur_cs==0) store_new_token(cur_tok);
25691 }@+ while (!(cur_cs!=0));
25692 if (cur_cmd!=end_cs_name) @<Complain about missing \.{\\endcsname}@>;
25693 @<Look up the characters of list |n| in the hash table, and set |cur_cs|@>;
25694 flush_list(n);
25695 b=(eq_type(cur_cs)!=undefined_cs);
25696 } @+break;
25697
25698 @ @<Look up the characters of list |n| in the hash table...@>=
25699 m=first;p=link(n);
25700 while (p!=null)
25701 {@+if (m >= max_buf_stack)
25702 {@+max_buf_stack=m+1;
25703 if (max_buf_stack==buf_size)
25704 overflow("buffer size", buf_size);
25705 @:TeX capacity exceeded buffer size}{\quad buffer size@>
25706 }
25707 buffer[m]=info(p)%cmd_factor;incr(m);p=link(p); /* this is to be checked */
25708 }
25709 if (m==first) cur_cs=null_cs; /*the list is empty*/
25710 else if (m > first+1)
25711 cur_cs=id_lookup(first, m-first); /*|no_new_control_sequence| is |true|*/
25712 else cur_cs=single_base+buffer[first] /*the list has length one*/
25713
25714 @ The conditional \.{\\iffontchar} tests the existence of a character in
25715 a font.
25716
25717 @<Cases for |conditional|@>=
25718 case if_font_char_code: {@+scan_font_ident();n=cur_val;scan_char_num();
25719 if ((font_bc[n] <= cur_val)&&(font_ec[n] >= cur_val))
25720 b=char_exists(n, qi(cur_val));
25721 else b=false;
25722 } @+break;
25723
25724 @ The \.{protected} feature of \eTeX\ defines the \.{\\protected} prefix
25725 command for macro definitions. Such macros are protected against
25726 expansions when lists of expanded tokens are built, e.g., for \.{\\edef}
25727 or during \.{\\write}.
25728
25729 @<Generate all \eTeX...@>=
25730 primitive("protected", prefix, 8);
25731 @!@:protected\_}{\.{\\protected} primitive@>
25732
25733 @ @<Cases of |prefix| for |print_cmd_chr|@>=;
25734 else if (chr_code==8) print_esc("protected")
25735
25736 @ The |get_x_or_protected| procedure is like |get_x_token| except that
25737 protected macros are not expanded.
25738
25739 @<Declare \eTeX\ procedures for sc...@>=
25740 static void get_x_or_protected(void) /*sets |cur_cmd|, |cur_chr|, |cur_tok|,
25741 and expands non-protected macros*/
25742 {@+
25743 loop@+{@+get_token();
25744 if (cur_cmd <= max_command) return;
25745 if ((cur_cmd >= call)&&(cur_cmd < end_template))
25746 if (info(link(cur_chr))==protected_token) return;
25747 expand();
25748 }
25749 }
25750
25751 @ A group entered (or a conditional started) in one file may end in a
25752 different file. Such slight anomalies, although perfectly legitimate,
25753 may cause errors that are difficult to locate. In order to be able to
25754 give a warning message when such anomalies occur, \eTeX\ uses the
25755 |grp_stack| and |if_stack| arrays to record the initial |cur_boundary|
25756 and |cond_ptr| values for each input file.
25757
25758 @<Glob...@>=
25759 static save_pointer @!grp_stack[max_in_open+1]; /*initial |cur_boundary|*/
25760 static pointer @!if_stack[max_in_open+1]; /*initial |cond_ptr|*/
25761
25762 @ When a group ends that was apparently entered in a different input
25763 file, the |group_warning| procedure is invoked in order to update the
25764 |grp_stack|. If moreover \.{\\tracingnesting} is positive we want to
25765 give a warning message. The situation is, however, somewhat complicated
25766 by two facts: (1)~There may be |grp_stack| elements without a
25767 corresponding \.{\\input} file or \.{\\scantokens} pseudo file (e.g.,
25768 error insertions from the terminal); and (2)~the relevant information is
25769 recorded in the |name_field| of the |input_stack| only loosely
25770 synchronized with the |in_open| variable indexing |grp_stack|.
25771
25772 @<Declare \eTeX\ procedures for tr...@>=
25773 static void group_warning(void)
25774 {@+int i; /*index into |grp_stack|*/
25775 bool @!w; /*do we need a warning?*/
25776 base_ptr=input_ptr;input_stack[base_ptr]=cur_input;
25777 /*store current state*/
25778 i=in_open;w=false;
25779 while ((grp_stack[i]==cur_boundary)&&(i > 0))
25780 {@+@<Set variable |w| to indicate if this case should be reported@>;
25781 grp_stack[i]=save_index(save_ptr);decr(i);
25782 }
25783 if (w)
25784 {@+print_nl("Warning: end of ");print_group(true);
25785 @.Warning: end of...@>
25786 print(" of a different file");print_ln();
25787 if (tracing_nesting > 1) show_context();
25788 if (history==spotless) history=warning_issued;
25789 }
25790 }
25791
25792 @ This code scans the input stack in order to determine the type of the
25793 current input file.
25794
25795 @<Set variable |w| to...@>=
25796 if (tracing_nesting > 0)
25797 {@+while ((input_stack[base_ptr].state_field==token_list)||@|
25798 (input_stack[base_ptr].index_field > i)) decr(base_ptr);
25799 if (input_stack[base_ptr].name_field > 17) w=true;
25800 }
25801
25802 @ When a conditional ends that was apparently started in a different
25803 input file, the |if_warning| procedure is invoked in order to update the
25804 |if_stack|. If moreover \.{\\tracingnesting} is positive we want to
25805 give a warning message (with the same complications as above).
25806
25807 @<Declare \eTeX\ procedures for tr...@>=
25808 static void if_warning(void)
25809 {@+int i; /*index into |if_stack|*/
25810 bool @!w; /*do we need a warning?*/
25811 base_ptr=input_ptr;input_stack[base_ptr]=cur_input;
25812 /*store current state*/
25813 i=in_open;w=false;
25814 while (if_stack[i]==cond_ptr)
25815 {@+@<Set variable |w| to...@>;
25816 if_stack[i]=link(cond_ptr);decr(i);
25817 }
25818 if (w)
25819 {@+print_nl("Warning: end of ");print_cmd_chr(if_test, cur_if);
25820 @.Warning: end of...@>
25821 print_if_line(if_line);print(" of a different file");print_ln();
25822 if (tracing_nesting > 1) show_context();
25823 if (history==spotless) history=warning_issued;
25824 }
25825 }
25826
25827 @ Conversely, the |file_warning| procedure is invoked when a file ends
25828 and some groups entered or conditionals started while reading from that
25829 file are still incomplete.
25830
25831 @<Declare \eTeX\ procedures for tr...@>=
25832 static void file_warning(void)
25833 {@+pointer p; /*saved value of |save_ptr| or |cond_ptr|*/
25834 quarterword @!l; /*saved value of |cur_level| or |if_limit|*/
25835 quarterword @!c; /*saved value of |cur_group| or |cur_if|*/
25836 int @!i; /*saved value of |if_line|*/
25837 p=save_ptr;l=cur_level;c=cur_group;save_ptr=cur_boundary;
25838 while (grp_stack[in_open]!=save_ptr)
25839 {@+decr(cur_level);
25840 print_nl("Warning: end of file when ");
25841 @.Warning: end of file when...@>
25842 print_group(true);print(" is incomplete");@/
25843 cur_group=save_level(save_ptr);save_ptr=save_index(save_ptr);
25844 }
25845 save_ptr=p;cur_level=l;cur_group=c; /*restore old values*/
25846 p=cond_ptr;l=if_limit;c=cur_if;i=if_line;
25847 while (if_stack[in_open]!=cond_ptr)
25848 {@+print_nl("Warning: end of file when ");
25849 @.Warning: end of file when...@>
25850 print_cmd_chr(if_test, cur_if);
25851 if (if_limit==fi_code) print_esc("else");
25852 print_if_line(if_line);print(" is incomplete");@/
25853 if_line=if_line_field(cond_ptr);cur_if=subtype(cond_ptr);
25854 if_limit=type(cond_ptr);cond_ptr=link(cond_ptr);
25855 }
25856 cond_ptr=p;if_limit=l;cur_if=c;if_line=i; /*restore old values*/
25857 print_ln();
25858 if (tracing_nesting > 1) show_context();
25859 if (history==spotless) history=warning_issued;
25860 }
25861
25862 @ Here are the additional \eTeX\ primitives for expressions.
25863
25864 @<Generate all \eTeX...@>=
25865 primitive("numexpr", last_item, eTeX_expr-int_val+int_val);
25866 @!@:num\_expr\_}{\.{\\numexpr} primitive@>
25867 primitive("dimexpr", last_item, eTeX_expr-int_val+dimen_val);
25868 @!@:dim\_expr\_}{\.{\\dimexpr} primitive@>
25869 primitive("glueexpr", last_item, eTeX_expr-int_val+glue_val);
25870 @!@:glue\_expr\_}{\.{\\glueexpr} primitive@>
25871 primitive("muexpr", last_item, eTeX_expr-int_val+mu_val);
25872 @!@:mu\_expr\_}{\.{\\muexpr} primitive@>
25873
25874 @ @<Cases of |last_item| for |print_cmd_chr|@>=
25875 case eTeX_expr-int_val+int_val: print_esc("numexpr");@+break;
25876 case eTeX_expr-int_val+dimen_val: print_esc("dimexpr");@+break;
25877 case eTeX_expr-int_val+glue_val: print_esc("glueexpr");@+break;
25878 case eTeX_expr-int_val+mu_val: print_esc("muexpr");@+break;
25879
25880 @ This code for reducing |cur_val_level| and\slash or negating the
25881 result is similar to the one for all the other cases of
25882 |scan_something_internal|, with the difference that |scan_expr| has
25883 already increased the reference count of a glue specification.
25884
25885 @<Process an expression and |return|@>=
25886 {@+if (m < eTeX_mu)
25887 {@+switch (m) {
25888 @/@<Cases for fetching a glue value@>@/
25889 } /*there are no other cases*/
25890 cur_val_level=glue_val;
25891 }
25892 else if (m < eTeX_expr)
25893 {@+switch (m) {
25894 @/@<Cases for fetching a mu value@>@/
25895 } /*there are no other cases*/
25896 cur_val_level=mu_val;
25897 }
25898 else{@+cur_val_level=m-eTeX_expr+int_val;scan_expr();
25899 }
25900 while (cur_val_level > level)
25901 {@+if (cur_val_level==glue_val)
25902 {@+m=cur_val;cur_val=width(m);delete_glue_ref(m);
25903 }
25904 else if (cur_val_level==mu_val) mu_error();
25905 decr(cur_val_level);
25906 }
25907 if (negative)
25908 if (cur_val_level >= glue_val)
25909 {@+m=cur_val;cur_val=new_spec(m);delete_glue_ref(m);
25910 @<Negate all three glue components of |cur_val|@>;
25911 }
25912 else negate(cur_val);
25913 return;
25914 }
25915
25916 @ @<Declare \eTeX\ procedures for sc...@>=
25917 static void scan_expr(void);
25918
25919 @ The |scan_expr| procedure scans and evaluates an expression.
25920
25921 @<Declare procedures needed for expressions@>=
25922 @t\4@>@<Declare subprocedures for |scan_expr|@>@;
25923 static void scan_expr(void) /*scans and evaluates an expression*/
25924 {@+
25925 bool a, @!b; /*saved values of |arith_error|*/
25926 small_number @!l; /*type of expression*/
25927 small_number @!r; /*state of expression so far*/
25928 small_number @!s; /*state of term so far*/
25929 small_number @!o; /*next operation or type of next factor*/
25930 int @!e; /*expression so far*/
25931 int @!t; /*term so far*/
25932 int @!f; /*current factor*/
25933 int @!n; /*numerator of combined multiplication and division*/
25934 pointer @!p; /*top of expression stack*/
25935 pointer @!q; /*for stack manipulations*/
25936 l=cur_val_level;a=arith_error;b=false;p=null;
25937 @<Scan and evaluate an expression |e| of type |l|@>;
25938 if (b)
25939 {@+print_err("Arithmetic overflow");
25940 @.Arithmetic overflow@>
25941 help2("I can't evaluate this expression,",@/
25942 "since the result is out of range.");
25943 error();
25944 if (l >= glue_val)
25945 {@+delete_glue_ref(e);e=zero_glue;add_glue_ref(e);
25946 }
25947 else e=0;
25948 }
25949 arith_error=a;cur_val=e;cur_val_level=l;
25950 }
25951
25952 @ Evaluating an expression is a recursive process: When the left
25953 parenthesis of a subexpression is scanned we descend to the next level
25954 of recursion; the previous level is resumed with the matching right
25955 parenthesis.
25956
25957 @d expr_none 0 /*\.( seen, or \.( $\langle\it expr\rangle$ \.) seen*/
25958 @d expr_add 1 /*\.( $\langle\it expr\rangle$ \.+ seen*/
25959 @d expr_sub 2 /*\.( $\langle\it expr\rangle$ \.- seen*/
25960 @d expr_mult 3 /*$\langle\it term\rangle$ \.* seen*/
25961 @d expr_div 4 /*$\langle\it term\rangle$ \./ seen*/
25962 @d expr_scale 5 /*$\langle\it term\rangle$ \.*
25963 $\langle\it factor\rangle$ \./ seen*/
25964
25965 @<Scan and eval...@>=
25966 restart: r=expr_none;e=0;s=expr_none;t=0;n=0;
25967 resume: if (s==expr_none) o=l;@+else o=int_val;
25968 @<Scan a factor |f| of type |o| or start a subexpression@>;
25969 found: @<Scan the next operator and set |o|@>;
25970 arith_error=b;
25971 @<Make sure that |f| is in the proper range@>;
25972 switch (s) {@<Cases for evaluation of the current term@>@;
25973 } /*there are no other cases*/
25974 if (o > expr_sub) s=o;@+else@<Evaluate the current expression@>;
25975 b=arith_error;
25976 if (o!=expr_none) goto resume;
25977 if (p!=null) @<Pop the expression stack and |goto found|@>@;
25978
25979 @ @<Scan the next op...@>=
25980 @<Get the next non-blank non-call token@>;
25981 if (cur_tok==other_token+'+') o=expr_add;
25982 else if (cur_tok==other_token+'-') o=expr_sub;
25983 else if (cur_tok==other_token+'*') o=expr_mult;
25984 else if (cur_tok==other_token+'/') o=expr_div;
25985 else{@+o=expr_none;
25986 if (p==null)
25987 {@+if (cur_cmd!=relax) back_input();
25988 }
25989 else if (cur_tok!=other_token+')')
25990 {@+print_err("Missing ) inserted for expression");
25991 @.Missing ) inserted@>
25992 help1("I was expecting to see `+', `-', `*', `/', or `)'. Didn't.");
25993 back_error();
25994 }
25995 }
25996
25997 @ @<Scan a factor...@>=
25998 @<Get the next non-blank non-call token@>;
25999 if (cur_tok==other_token+'(')
26000 @<Push the expression stack and |goto restart|@>;
26001 back_input();
26002 if (o==int_val) scan_int();
26003 else if (o==dimen_val) scan_normal_dimen;
26004 else if (o==glue_val) scan_normal_glue();
26005 else scan_mu_glue();
26006 f=cur_val
26007
26008 @ @<Declare \eTeX\ procedures for sc...@>=
26009 static void scan_normal_glue(void);@/
26010 static void scan_mu_glue(void);
26011
26012 @ Here we declare two trivial procedures in order to avoid mutually
26013 recursive procedures with parameters.
26014
26015 @<Declare procedures needed for expressions@>=
26016 static void scan_normal_glue(void)
26017 {@+scan_glue(glue_val);
26018 }
26019 @#
26020 static void scan_mu_glue(void)
26021 {@+scan_glue(mu_val);
26022 }
26023
26024 @ Parenthesized subexpressions can be inside expressions, and this
26025 nesting has a stack. Seven local variables represent the top of the
26026 expression stack: |p| points to pushed-down entries, if any; |l|
26027 specifies the type of expression currently being evaluated; |e| is the
26028 expression so far and |r| is the state of its evaluation; |t| is the
26029 term so far and |s| is the state of its evaluation; finally |n| is the
26030 numerator for a combined multiplication and division, if any.
26031
26032 @d expr_node_size 4 /*number of words in stack entry for subexpressions*/
26033 @d expr_e_field(A) mem[A+1].i /*saved expression so far*/
26034 @d expr_t_field(A) mem[A+2].i /*saved term so far*/
26035 @d expr_n_field(A) mem[A+3].i /*saved numerator*/
26036
26037 @<Push the expression...@>=
26038 {@+q=get_node(expr_node_size);link(q)=p;type(q)=l;
26039 subtype(q)=4*s+r;
26040 expr_e_field(q)=e;expr_t_field(q)=t;expr_n_field(q)=n;
26041 p=q;l=o;goto restart;
26042 }
26043
26044 @ @<Pop the expression...@>=
26045 {@+f=e;q=p;
26046 e=expr_e_field(q);t=expr_t_field(q);n=expr_n_field(q);
26047 s=subtype(q)/4;r=subtype(q)%4;
26048 l=type(q);p=link(q);free_node(q, expr_node_size);
26049 goto found;
26050 }
26051
26052 @ We want to make sure that each term and (intermediate) result is in
26053 the proper range. Integer values must not exceed |infinity|
26054 ($2^{31}-1$) in absolute value, dimensions must not exceed |max_dimen|
26055 ($2^{30}-1$). We avoid the absolute value of an integer, because this
26056 might fail for the value $-2^{31}$ using 32-bit arithmetic.
26057
26058 @d num_error(A) /*clear a number or dimension and set |arith_error|*/
26059 {@+arith_error=true;A=0;
26060 }
26061 @d glue_error(A) /*clear a glue spec and set |arith_error|*/
26062 {@+arith_error=true;delete_glue_ref(A);A=new_spec(zero_glue);
26063 }
26064
26065 @<Make sure that |f|...@>=
26066 if ((l==int_val)||(s > expr_sub))
26067 {@+if ((f > infinity)||(f < -infinity)) num_error(f);
26068 }
26069 else if (l==dimen_val)
26070 {@+if (abs(f) > max_dimen) num_error(f);
26071 }
26072 else{@+if ((abs(width(f)) > max_dimen)||@|
26073 (abs(stretch(f)) > max_dimen)||@|
26074 (abs(shrink(f)) > max_dimen)) glue_error(f);
26075 }
26076
26077 @ Applying the factor |f| to the partial term |t| (with the operator
26078 |s|) is delayed until the next operator |o| has been scanned. Here we
26079 handle the first factor of a partial term. A glue spec has to be copied
26080 unless the next operator is a right parenthesis; this allows us later on
26081 to simply modify the glue components.
26082
26083 @d normalize_glue(A)
26084 if (stretch(A)==0) stretch_order(A)=normal;
26085 if (shrink(A)==0) shrink_order(A)=normal
26086
26087 @<Cases for evaluation of the current term@>=
26088 case expr_none: if ((l >= glue_val)&&(o!=expr_none))
26089 {@+t=new_spec(f);delete_glue_ref(f);normalize_glue(t);
26090 }
26091 else t=f;@+break;
26092
26093 @ When a term |t| has been completed it is copied to, added to, or
26094 subtracted from the expression |e|.
26095
26096 @d expr_add_sub(A, B, C) add_or_sub(A, B, C, r==expr_sub)
26097 @d expr_a(A, B) expr_add_sub(A, B, max_dimen)
26098
26099 @<Evaluate the current expression@>=
26100 {@+s=expr_none;
26101 if (r==expr_none) e=t;
26102 else if (l==int_val) e=expr_add_sub(e, t, infinity);
26103 else if (l==dimen_val) e=expr_a(e, t);
26104 else@<Compute the sum or difference of two glue specs@>;
26105 r=o;
26106 }
26107
26108 @ The function |add_or_sub(x, y, max_answer, negative)| computes the sum
26109 (for |negative==false|) or difference (for |negative==true|) of |x| and
26110 |y|, provided the absolute value of the result does not exceed
26111 |max_answer|.
26112
26113 @<Declare subprocedures for |scan_expr|@>=
26114 static int add_or_sub(int @!x, int @!y, int @!max_answer, bool @!negative)
26115 {@+int a; /*the answer*/
26116 if (negative) negate(y);
26117 if (x >= 0)
26118 if (y <= max_answer-x) a=x+y;@+else num_error(a)@;
26119 else if (y >= -max_answer-x) a=x+y;@+else num_error(a);
26120 return a;
26121 }
26122
26123 @ We know that |stretch_order(e) > normal| implies |stretch(e)!=0| and
26124 |shrink_order(e) > normal| implies |shrink(e)!=0|.
26125
26126 @<Compute the sum or diff...@>=
26127 {@+width(e)=expr_a(width(e), width(t));
26128 if (stretch_order(e)==stretch_order(t))
26129 stretch(e)=expr_a(stretch(e), stretch(t));
26130 else if ((stretch_order(e) < stretch_order(t))&&(stretch(t)!=0))
26131 {@+stretch(e)=stretch(t);stretch_order(e)=stretch_order(t);
26132 }
26133 if (shrink_order(e)==shrink_order(t))
26134 shrink(e)=expr_a(shrink(e), shrink(t));
26135 else if ((shrink_order(e) < shrink_order(t))&&(shrink(t)!=0))
26136 {@+shrink(e)=shrink(t);shrink_order(e)=shrink_order(t);
26137 }
26138 delete_glue_ref(t);normalize_glue(e);
26139 }
26140
26141 @ If a multiplication is followed by a division, the two operations are
26142 combined into a `scaling' operation. Otherwise the term |t| is
26143 multiplied by the factor |f|.
26144
26145 @d expr_m(A) A=nx_plus_y(A, f, 0)
26146
26147 @<Cases for evaluation of the current term@>=
26148 case expr_mult: if (o==expr_div)
26149 {@+n=f;o=expr_scale;
26150 }
26151 else if (l==int_val) t=mult_integers(t, f);
26152 else if (l==dimen_val) expr_m(t);
26153 else{@+expr_m(width(t));expr_m(stretch(t));expr_m(shrink(t));
26154 } @+break;
26155
26156 @ Here we divide the term |t| by the factor |f|.
26157
26158 @d expr_d(A) A=quotient(A, f)
26159
26160 @<Cases for evaluation of the current term@>=
26161 case expr_div: if (l < glue_val) expr_d(t);
26162 else{@+expr_d(width(t));expr_d(stretch(t));expr_d(shrink(t));
26163 } @+break;
26164
26165 @ The function |quotient(n, d)| computes the rounded quotient
26166 $q=\lfloor n/d+{1\over2}\rfloor$, when $n$ and $d$ are positive.
26167
26168 @<Declare subprocedures for |scan_expr|@>=
26169 static int quotient(int @!n, int @!d)
26170 {@+bool negative; /*should the answer be negated?*/
26171 int @!a; /*the answer*/
26172 if (d==0) num_error(a)@;
26173 else{@+if (d > 0) negative=false;
26174 else{@+negate(d);negative=true;
26175 }
26176 if (n < 0)
26177 {@+negate(n);negative=!negative;
26178 }
26179 a=n/d;n=n-a*d;d=n-d; /*avoid certain compiler optimizations!*/
26180 if (d+n >= 0) incr(a);
26181 if (negative) negate(a);
26182 }
26183 return a;
26184 }
26185
26186 @ Here the term |t| is multiplied by the quotient $n/f$.
26187
26188 @d expr_s(A) A=fract(A, n, f, max_dimen)
26189
26190 @<Cases for evaluation of the current term@>=
26191 case expr_scale: if (l==int_val) t=fract(t, n, f, infinity);
26192 else if (l==dimen_val) expr_s(t);
26193 else{@+expr_s(width(t));expr_s(stretch(t));expr_s(shrink(t));
26194 }
26195
26196 @ Finally, the function |fract(x, n, d, max_answer)| computes the integer
26197 $q=\lfloor xn/d+{1\over2}\rfloor$, when $x$, $n$, and $d$ are positive
26198 and the result does not exceed |max_answer|. We can't use floating
26199 point arithmetic since the routine must produce identical results in all
26200 cases; and it would be too dangerous to multiply by~|n| and then divide
26201 by~|d|, in separate operations, since overflow might well occur. Hence
26202 this subroutine simulates double precision arithmetic, somewhat
26203 analogous to \MF's |make_fraction| and |take_fraction| routines.
26204
26205 @<Declare subprocedures for |scan_expr|@>=
26206 static int fract(int @!x, int @!n, int @!d, int @!max_answer)
26207 {@+
26208 bool negative; /*should the answer be negated?*/
26209 int @!a; /*the answer*/
26210 int @!f; /*a proper fraction*/
26211 int @!h; /*smallest integer such that |2*h >= d|*/
26212 int @!r; /*intermediate remainder*/
26213 int @!t; /*temp variable*/
26214 if (d==0) goto too_big;
26215 a=0;
26216 if (d > 0) negative=false;
26217 else{@+negate(d);negative=true;
26218 }
26219 if (x < 0)
26220 {@+negate(x);negative=!negative;
26221 }
26222 else if (x==0) goto done;
26223 if (n < 0)
26224 {@+negate(n);negative=!negative;
26225 }
26226 t=n/d;
26227 if (t > max_answer/x) goto too_big;
26228 a=t*x;n=n-t*d;
26229 if (n==0) goto found;
26230 t=x/d;
26231 if (t > (max_answer-a)/n) goto too_big;
26232 a=a+t*n;x=x-t*d;
26233 if (x==0) goto found;
26234 if (x < n)
26235 {@+t=x;x=n;n=t;
26236 } /*now |0 < n <= x < d|*/
26237 @<Compute \(f)$f=\lfloor xn/d+{1\over2}\rfloor$@>@;
26238 if (f > (max_answer-a)) goto too_big;
26239 a=a+f;
26240 found: if (negative) negate(a);
26241 goto done;
26242 too_big: num_error(a);
26243 done: return a;
26244 }
26245
26246 @ The loop here preserves the following invariant relations
26247 between |f|, |x|, |n|, and~|r|:
26248 (i)~$f+\lfloor(xn+(r+d))/d\rfloor=\lfloor x_0n_0/d+{1\over2}\rfloor$;
26249 (ii)~|-d <= r < 0 < n <= x < d|, where $x_0$, $n_0$ are the original values of~$x$
26250 and $n$.
26251
26252 Notice that the computation specifies |(x-d)+x| instead of |(x+x)-d|,
26253 because the latter could overflow.
26254
26255 @<Compute \(f)$f=\lfloor xn/d+{1\over2}\rfloor$@>=
26256 f=0;r=(d/2)-d;h=-r;
26257 loop@+{@+if (odd(n))
26258 {@+r=r+x;
26259 if (r >= 0)
26260 {@+r=r-d;incr(f);
26261 }
26262 }
26263 n=n/2;
26264 if (n==0) goto found1;
26265 if (x < h) x=x+x;
26266 else{@+t=x-d;x=t+x;f=f+n;
26267 if (x < n)
26268 {@+if (x==0) goto found1;
26269 t=x;x=n;n=t;
26270 }
26271 }
26272 }
26273 found1:
26274
26275 @ The \.{\\gluestretch}, \.{\\glueshrink}, \.{\\gluestretchorder}, and
26276 \.{\\glueshrinkorder} commands return the stretch and shrink components
26277 and their orders of ``infinity'' of a glue specification.
26278
26279 @d glue_stretch_order_code (eTeX_int+6) /*code for \.{\\gluestretchorder}*/
26280 @d glue_shrink_order_code (eTeX_int+7) /*code for \.{\\glueshrinkorder}*/
26281 @d glue_stretch_code (eTeX_dim+7) /*code for \.{\\gluestretch}*/
26282 @d glue_shrink_code (eTeX_dim+8) /*code for \.{\\glueshrink}*/
26283
26284 @<Generate all \eTeX...@>=
26285 primitive("gluestretchorder", last_item, glue_stretch_order_code);
26286 @!@:glue\_stretch\_order\_}{\.{\\gluestretchorder} primitive@>
26287 primitive("glueshrinkorder", last_item, glue_shrink_order_code);
26288 @!@:glue\_shrink\_order\_}{\.{\\glueshrinkorder} primitive@>
26289 primitive("gluestretch", last_item, glue_stretch_code);
26290 @!@:glue\_stretch\_}{\.{\\gluestretch} primitive@>
26291 primitive("glueshrink", last_item, glue_shrink_code);
26292 @!@:glue\_shrink\_}{\.{\\glueshrink} primitive@>
26293
26294 @ @<Cases of |last_item| for |print_cmd_chr|@>=
26295 case glue_stretch_order_code: print_esc("gluestretchorder");@+break;
26296 case glue_shrink_order_code: print_esc("glueshrinkorder");@+break;
26297 case glue_stretch_code: print_esc("gluestretch");@+break;
26298 case glue_shrink_code: print_esc("glueshrink");@+break;
26299
26300 @ @<Cases for fetching an integer value@>=
26301 case glue_stretch_order_code: case glue_shrink_order_code:
26302 {@+scan_normal_glue();q=cur_val;
26303 if (m==glue_stretch_order_code) cur_val=stretch_order(q);
26304 else cur_val=shrink_order(q);
26305 delete_glue_ref(q);
26306 }
26307
26308 @ @<Cases for fetching a dimension value@>=
26309 case glue_stretch_code: case glue_shrink_code:
26310 {@+scan_normal_glue();q=cur_val;
26311 if (m==glue_stretch_code) cur_val=stretch(q);
26312 else cur_val=shrink(q);
26313 delete_glue_ref(q);
26314 }
26315
26316 @ The \.{\\mutoglue} and \.{\\gluetomu} commands convert ``math'' glue
26317 into normal glue and vice versa; they allow to manipulate math glue with
26318 \.{\\gluestretch} etc.
26319
26320 @d mu_to_glue_code eTeX_glue /*code for \.{\\mutoglue}*/
26321 @d glue_to_mu_code eTeX_mu /*code for \.{\\gluetomu}*/
26322
26323 @<Generate all \eTeX...@>=
26324 primitive("mutoglue", last_item, mu_to_glue_code);
26325 @!@:mu\_to\_glue\_}{\.{\\mutoglue} primitive@>
26326 primitive("gluetomu", last_item, glue_to_mu_code);
26327 @!@:glue\_to\_mu\_}{\.{\\gluetomu} primitive@>
26328
26329 @ @<Cases of |last_item| for |print_cmd_chr|@>=
26330 case mu_to_glue_code: print_esc("mutoglue");@+break;
26331 case glue_to_mu_code: print_esc("gluetomu");@+break;
26332
26333 @ @<Cases for fetching a glue value@>=
26334 case mu_to_glue_code: scan_mu_glue();
26335
26336 @ @<Cases for fetching a mu value@>=
26337 case glue_to_mu_code: scan_normal_glue();
26338
26339 @ \eTeX\ (in extended mode) supports 32768 (i.e., $2^{15}$) count,
26340 dimen, skip, muskip, box, and token registers. As in \TeX\ the first
26341 256 registers of each kind are realized as arrays in the table of
26342 equivalents; the additional registers are realized as tree structures
26343 built from variable-size nodes with individual registers existing only
26344 when needed. Default values are used for nonexistent registers: zero
26345 for count and dimen values, |zero_glue| for glue (skip and muskip)
26346 values, void for boxes, and |null| for token lists (and current marks
26347 discussed below).
26348
26349 Similarly there are 32768 mark classes; the command \.{\\marks}|n|
26350 creates a mark node for a given mark class |0 <= n <= 32767| (where
26351 \.{\\marks0} is synonymous to \.{\\mark}). The page builder (actually
26352 the |fire_up| routine) and the |vsplit| routine maintain the current
26353 values of |top_mark|, |first_mark|, |bot_mark|, |split_first_mark|, and
26354 |split_bot_mark| for each mark class. They are accessed as
26355 \.{\\topmarks}|n| etc., and \.{\\topmarks0} is again synonymous to
26356 \.{\\topmark}. As in \TeX\ the five current marks for mark class zero
26357 are realized as |cur_mark| array. The additional current marks are
26358 again realized as tree structure with individual mark classes existing
26359 only when needed.
26360
26361 @<Generate all \eTeX...@>=
26362 primitive("marks", mark, marks_code);
26363 @!@:marks\_}{\.{\\marks} primitive@>
26364 primitive("topmarks", top_bot_mark, top_mark_code+marks_code);
26365 @!@:top\_marks\_}{\.{\\topmarks} primitive@>
26366 primitive("firstmarks", top_bot_mark, first_mark_code+marks_code);
26367 @!@:first\_marks\_}{\.{\\firstmarks} primitive@>
26368 primitive("botmarks", top_bot_mark, bot_mark_code+marks_code);
26369 @!@:bot\_marks\_}{\.{\\botmarks} primitive@>
26370 primitive("splitfirstmarks", top_bot_mark, split_first_mark_code+marks_code);
26371 @!@:split\_first\_marks\_}{\.{\\splitfirstmarks} primitive@>
26372 primitive("splitbotmarks", top_bot_mark, split_bot_mark_code+marks_code);
26373 @!@:split\_bot\_marks\_}{\.{\\splitbotmarks} primitive@>
26374
26375 @ The |scan_register_num| procedure scans a register number that must
26376 not exceed 255 in compatibility mode resp.\ 32767 in extended mode.
26377
26378 @<Declare \eTeX\ procedures for ex...@>=
26379 static void scan_register_num(void);
26380
26381 @ @<Declare procedures that scan restricted classes of integers@>=
26382 static void scan_register_num(void)
26383 {@+scan_int();
26384 if ((cur_val < 0)||(cur_val > max_reg_num))
26385 {@+print_err("Bad register code");
26386 @.Bad register code@>
26387 help2(max_reg_help_line,"I changed this one to zero.");
26388 int_error(cur_val);cur_val=0;
26389 }
26390 }
26391
26392 @ @<Initialize variables for \eTeX\ comp...@>=
26393 max_reg_num=255;
26394 max_reg_help_line="A register number must be between 0 and 255.";
26395
26396 @ @<Initialize variables for \eTeX\ ext...@>=
26397 max_reg_num=32767;
26398 max_reg_help_line="A register number must be between 0 and 32767.";
26399
26400 @ @<Glob...@>=
26401 static halfword @!max_reg_num; /*largest allowed register number*/
26402 static char *@!max_reg_help_line; /*first line of help message*/
26403
26404 @ There are seven almost identical doubly linked trees, one for the
26405 sparse array of the up to 32512 additional registers of each kind and
26406 one for the sparse array of the up to 32767 additional mark classes.
26407 The root of each such tree, if it exists, is an index node containing 16
26408 pointers to subtrees for 4096 consecutive array elements. Similar index
26409 nodes are the starting points for all nonempty subtrees for 4096, 256,
26410 and 16 consecutive array elements. These four levels of index nodes are
26411 followed by a fifth level with nodes for the individual array elements.
26412
26413 Each index node is nine words long. The pointers to the 16 possible
26414 subtrees or are kept in the |info| and |link| fields of the last eight
26415 words. (It would be both elegant and efficient to declare them as
26416 array, unfortunately \PASCAL\ doesn't allow this.)
26417
26418 The fields in the first word of each index node and in the nodes for the
26419 array elements are closely related. The |link| field points to the next
26420 lower index node and the |sa_index| field contains four bits (one
26421 hexadecimal digit) of the register number or mark class. For the lowest
26422 index node the |link| field is |null| and the |sa_index| field indicates
26423 the type of quantity (|int_val|, |dimen_val|, |glue_val|, |mu_val|,
26424 |box_val|, |tok_val|, or |mark_val|). The |sa_used| field in the index
26425 nodes counts how many of the 16 pointers are non-null.
26426
26427 The |sa_index| field in the nodes for array elements contains the four
26428 bits plus 16 times the type. Therefore such a node represents a count
26429 or dimen register if and only if |sa_index < dimen_val_limit|; it
26430 represents a skip or muskip register if and only if
26431 |dimen_val_limit <= sa_index < mu_val_limit|; it represents a box register
26432 if and only if |mu_val_limit <= sa_index < box_val_limit|; it represents a
26433 token list register if and only if
26434 |box_val_limit <= sa_index < tok_val_limit|; finally it represents a mark
26435 class if and only if |tok_val_limit <= sa_index|.
26436
26437 The |new_index| procedure creates an index node (returned in |cur_ptr|)
26438 having given contents of the |sa_index| and |link| fields.
26439
26440 @d box_val 4 /*the additional box registers*/
26441 @d mark_val 6 /*the additional mark classes*/
26442 @#
26443 @d dimen_val_limit 0x20 /*$2^4\cdot(|dimen_val|+1)$*/
26444 @d mu_val_limit 0x40 /*$2^4\cdot(|mu_val|+1)$*/
26445 @d box_val_limit 0x50 /*$2^4\cdot(|box_val|+1)$*/
26446 @d tok_val_limit 0x60 /*$2^4\cdot(|tok_val|+1)$*/
26447 @#
26448 @d index_node_size 9 /*size of an index node*/
26449 @d sa_index(A) type(A) /*a four-bit address or a type or both*/
26450 @d sa_used(A) subtype(A) /*count of non-null pointers*/
26451
26452 @<Declare \eTeX\ procedures for ex...@>=
26453 static void new_index(quarterword @!i, pointer @!q)
26454 {@+int k; /*loop index*/
26455 cur_ptr=get_node(index_node_size);sa_index(cur_ptr)=i;
26456 sa_used(cur_ptr)=0;link(cur_ptr)=q;
26457 for (k=1; k<=index_node_size-1; k++) /*clear all 16 pointers*/
26458 mem[cur_ptr+k]=sa_null;
26459 }
26460
26461 @ The roots of the seven trees for the additional registers and mark
26462 classes are kept in the |sa_root| array. The first six locations must
26463 be dumped and undumped; the last one is also known as |sa_mark|.
26464
26465 @d sa_mark sa_root[mark_val] /*root for mark classes*/
26466
26467 @<Glob...@>=
26468 static pointer @!sa_root0[mark_val-int_val+1],
26469 *const @!sa_root = @!sa_root0-int_val; /*roots of sparse arrays*/
26470 static pointer @!cur_ptr; /*value returned by |new_index| and |find_sa_element|*/
26471 static memory_word @!sa_null; /*two |null| pointers*/
26472
26473 @ @<Set init...@>=
26474 sa_mark=null;sa_null.hh.lh=null;sa_null.hh.rh=null;
26475
26476 @ @<Initialize table...@>=
26477 for (i=int_val; i<=tok_val; i++) sa_root[i]=null;
26478
26479 @ Given a type |t| and a sixteen-bit number |n|, the |find_sa_element|
26480 procedure returns (in |cur_ptr|) a pointer to the node for the
26481 corresponding array element, or |null| when no such element exists. The
26482 third parameter |w| is set |true| if the element must exist, e.g.,
26483 because it is about to be modified. The procedure has two main
26484 branches: one follows the existing tree structure, the other (only used
26485 when |w| is |true|) creates the missing nodes.
26486
26487 We use macros to extract the four-bit pieces from a sixteen-bit register
26488 number or mark class and to fetch or store one of the 16 pointers from
26489 an index node.
26490
26491 @d if_cur_ptr_is_null_then_return_or_goto(A) /*some tree element is missing*/
26492 {@+if (cur_ptr==null)
26493 if (w) goto A;@+else return;
26494 }
26495 @#
26496 @d hex_dig1(A) A/4096 /*the fourth lowest hexadecimal digit*/
26497 @d hex_dig2(A) (A/256)%16 /*the third lowest hexadecimal digit*/
26498 @d hex_dig3(A) (A/16)%16 /*the second lowest hexadecimal digit*/
26499 @d hex_dig4(A) A%16 /*the lowest hexadecimal digit*/
26500 @#
26501 @d get_sa_ptr if (odd(i)) cur_ptr=link(q+(i/2)+1);
26502 else cur_ptr=info(q+(i/2)+1)
26503 /*set |cur_ptr| to the pointer indexed by |i| from index node |q|*/
26504 @d put_sa_ptr(A) if (odd(i)) link(q+(i/2)+1)=A;
26505 else info(q+(i/2)+1)=A
26506 /*store the pointer indexed by |i| in index node |q|*/
26507 @d add_sa_ptr {@+put_sa_ptr(cur_ptr);incr(sa_used(q));
26508 } /*add |cur_ptr| as the pointer indexed by |i| in index node |q|*/
26509 @d delete_sa_ptr {@+put_sa_ptr(null);decr(sa_used(q));
26510 } /*delete the pointer indexed by |i| in index node |q|*/
26511
26512 @<Declare \eTeX\ procedures for ex...@>=
26513 static void find_sa_element(small_number @!t, halfword @!n, bool @!w)
26514 /*sets |cur_val| to sparse array element location or |null|*/
26515 {@+
26516 pointer q; /*for list manipulations*/
26517 small_number @!i; /*a four bit index*/
26518 cur_ptr=sa_root[t];
26519 if_cur_ptr_is_null_then_return_or_goto(not_found);@/
26520 q=cur_ptr;i=hex_dig1(n);get_sa_ptr;
26521 if_cur_ptr_is_null_then_return_or_goto(not_found1);@/
26522 q=cur_ptr;i=hex_dig2(n);get_sa_ptr;
26523 if_cur_ptr_is_null_then_return_or_goto(not_found2);@/
26524 q=cur_ptr;i=hex_dig3(n);get_sa_ptr;
26525 if_cur_ptr_is_null_then_return_or_goto(not_found3);@/
26526 q=cur_ptr;i=hex_dig4(n);get_sa_ptr;
26527 if ((cur_ptr==null)&&w) goto not_found4;
26528 return;
26529 not_found: new_index(t, null); /*create first level index node*/
26530 sa_root[t]=cur_ptr;q=cur_ptr;i=hex_dig1(n);
26531 not_found1: new_index(i, q); /*create second level index node*/
26532 add_sa_ptr;q=cur_ptr;i=hex_dig2(n);
26533 not_found2: new_index(i, q); /*create third level index node*/
26534 add_sa_ptr;q=cur_ptr;i=hex_dig3(n);
26535 not_found3: new_index(i, q); /*create fourth level index node*/
26536 add_sa_ptr;q=cur_ptr;i=hex_dig4(n);
26537 not_found4: @<Create a new array element of type |t| with index |i|@>;
26538 link(cur_ptr)=q;add_sa_ptr;
26539 }
26540
26541 @ The array elements for registers are subject to grouping and have an
26542 |sa_lev| field (quite analogous to |eq_level|) instead of |sa_used|.
26543 Since saved values as well as shorthand definitions (created by e.g.,
26544 \.{\\countdef}) refer to the location of the respective array element,
26545 we need a reference count that is kept in the |sa_ref| field. An array
26546 element can be deleted (together with all references to it) when its
26547 |sa_ref| value is |null| and its value is the default value.
26548 @^reference counts@>
26549
26550 Skip, muskip, box, and token registers use two word nodes, their values
26551 are stored in the |sa_ptr| field.
26552 Count and dimen registers use three word nodes, their
26553 values are stored in the |sa_int| resp.\ |sa_dim| field in the third
26554 word; the |sa_ptr| field is used under the name |sa_num| to store
26555 the register number. Mark classes use four word nodes. The last three
26556 words contain the five types of current marks
26557
26558 @d sa_lev sa_used /*grouping level for the current value*/
26559 @d pointer_node_size 2 /*size of an element with a pointer value*/
26560 @d sa_type(A) (sa_index(A)/16) /*type part of combined type/index*/
26561 @d sa_ref(A) info(A+1) /*reference count of a sparse array element*/
26562 @d sa_ptr(A) link(A+1) /*a pointer value*/
26563 @#
26564 @d word_node_size 3 /*size of an element with a word value*/
26565 @d sa_num(A) sa_ptr(A) /*the register number*/
26566 @d sa_int(A) mem[A+2].i /*an integer*/
26567 @d sa_dim(A) mem[A+2].sc /*a dimension (a somewhat esoteric distinction)*/
26568 @#
26569 @d mark_class_node_size 4 /*size of an element for a mark class*/
26570 @#
26571 @d fetch_box(A) /*fetch |box(cur_val)|*/
26572 if (cur_val < 256) A=box(cur_val);
26573 else{@+find_sa_element(box_val, cur_val, false);
26574 if (cur_ptr==null) A=null;@+else A=sa_ptr(cur_ptr);
26575 }
26576
26577 @<Create a new array element...@>=
26578 if (t==mark_val) /*a mark class*/
26579 {@+cur_ptr=get_node(mark_class_node_size);
26580 mem[cur_ptr+1]=sa_null;mem[cur_ptr+2]=sa_null;mem[cur_ptr+3]=sa_null;
26581 }
26582 else{@+if (t <= dimen_val) /*a count or dimen register*/
26583 {@+cur_ptr=get_node(word_node_size);sa_int(cur_ptr)=0;
26584 sa_num(cur_ptr)=n;
26585 }
26586 else{@+cur_ptr=get_node(pointer_node_size);
26587 if (t <= mu_val) /*a skip or muskip register*/
26588 {@+sa_ptr(cur_ptr)=zero_glue;add_glue_ref(zero_glue);
26589 }
26590 else sa_ptr(cur_ptr)=null; /*a box or token list register*/
26591 }
26592 sa_ref(cur_ptr)=null; /*all registers have a reference count*/
26593 }
26594 sa_index(cur_ptr)=16*t+i;sa_lev(cur_ptr)=level_one
26595
26596 @ The |delete_sa_ref| procedure is called when a pointer to an array
26597 element representing a register is being removed; this means that the
26598 reference count should be decreased by one. If the reduced reference
26599 count is |null| and the register has been (globally) assigned its
26600 default value the array element should disappear, possibly together with
26601 some index nodes. This procedure will never be used for mark class
26602 nodes.
26603 @^reference counts@>
26604
26605 @d add_sa_ref(A) incr(sa_ref(A)) /*increase reference count*/
26606 @#
26607 @d change_box(A) /*change |box(cur_val)|, the |eq_level| stays the same*/
26608 if (cur_val < 256) box(cur_val)=A;@+else set_sa_box(A)
26609 @#
26610 @d set_sa_box(X) {@+find_sa_element(box_val, cur_val, false);
26611 if (cur_ptr!=null)
26612 {@+sa_ptr(cur_ptr)=X;add_sa_ref(cur_ptr);delete_sa_ref(cur_ptr);
26613 }
26614 }
26615
26616 @<Declare \eTeX\ procedures for tr...@>=
26617 static void delete_sa_ref(pointer @!q) /*reduce reference count*/
26618 {@+
26619 pointer p; /*for list manipulations*/
26620 small_number @!i; /*a four bit index*/
26621 small_number @!s; /*size of a node*/
26622 decr(sa_ref(q));
26623 if (sa_ref(q)!=null) return;
26624 if (sa_index(q) < dimen_val_limit)
26625 if (sa_int(q)==0) s=word_node_size;
26626 else return;
26627 else{@+if (sa_index(q) < mu_val_limit)
26628 if (sa_ptr(q)==zero_glue) delete_glue_ref(zero_glue);
26629 else return;
26630 else if (sa_ptr(q)!=null) return;
26631 s=pointer_node_size;
26632 }
26633 @/do@+{i=hex_dig4(sa_index(q));p=q;q=link(p);free_node(p, s);
26634 if (q==null) /*the whole tree has been freed*/
26635 {@+sa_root[i]=null;return;
26636 }
26637 delete_sa_ptr;s=index_node_size; /*node |q| is an index node*/
26638 }@+ while (!(sa_used(q) > 0));
26639 }
26640
26641 @ The |print_sa_num| procedure prints the register number corresponding
26642 to an array element.
26643
26644 @<Basic print...@>=
26645 static void print_sa_num(pointer @!q) /*print register number*/
26646 {@+halfword @!n; /*the register number*/
26647 if (sa_index(q) < dimen_val_limit) n=sa_num(q); /*the easy case*/
26648 else{@+n=hex_dig4(sa_index(q));q=link(q);n=n+16*sa_index(q);
26649 q=link(q);n=n+256*(sa_index(q)+16*sa_index(link(q)));
26650 }
26651 print_int(n);
26652 }
26653
26654 @ Here is a procedure that displays the contents of an array element
26655 symbolically. It is used under similar circumstances as is
26656 |restore_trace| (together with |show_eqtb|) for the quantities kept in
26657 the |eqtb| array.
26658
26659 @<Declare \eTeX\ procedures for tr...@>=
26660 #ifdef @!STAT
26661 static void show_sa(pointer @!p, char *@!s)
26662 {@+small_number t; /*the type of element*/
26663 begin_diagnostic();print_char('{');print(s);print_char(' ');
26664 if (p==null) print_char('?'); /*this can't happen*/
26665 else{@+t=sa_type(p);
26666 if (t < box_val) print_cmd_chr(internal_register, p);
26667 else if (t==box_val)
26668 {@+print_esc("box");print_sa_num(p);
26669 }
26670 else if (t==tok_val) print_cmd_chr(toks_register, p);
26671 else print_char('?'); /*this can't happen either*/
26672 print_char('=');
26673 if (t==int_val) print_int(sa_int(p));
26674 else if (t==dimen_val)
26675 {@+print_scaled(sa_dim(p));print("pt");
26676 }
26677 else{@+p=sa_ptr(p);
26678 if (t==glue_val) print_spec(p,"pt");
26679 else if (t==mu_val) print_spec(p,"mu");
26680 else if (t==box_val)
26681 if (p==null) print("void");
26682 else{@+depth_threshold=0;breadth_max=1;show_node_list(p);
26683 }
26684 else if (t==tok_val)
26685 {@+if (p!=null) show_token_list(link(p), null, 32);
26686 }
26687 else print_char('?'); /*this can't happen either*/
26688 }
26689 }
26690 print_char('}');end_diagnostic(false);
26691 }
26692 #endif
26693
26694 @ Here we compute the pointer to the current mark of type |t| and mark
26695 class |cur_val|.
26696
26697 @<Compute the mark pointer...@>=
26698 {@+find_sa_element(mark_val, cur_val, false);
26699 if (cur_ptr!=null)
26700 if (odd(t)) cur_ptr=link(cur_ptr+(t/2)+1);
26701 else cur_ptr=info(cur_ptr+(t/2)+1);
26702 }
26703
26704 @ The current marks for all mark classes are maintained by the |vsplit|
26705 and |fire_up| routines and are finally destroyed (for \.{INITEX} only)
26706 @.INITEX@>
26707 by the |final_cleanup| routine. Apart from updating the current marks
26708 when mark nodes are encountered, these routines perform certain actions
26709 on all existing mark classes. The recursive |do_marks| procedure walks
26710 through the whole tree or a subtree of existing mark class nodes and
26711 preforms certain actions indicted by its first parameter |a|, the action
26712 code. The second parameter |l| indicates the level of recursion (at
26713 most four); the third parameter points to a nonempty tree or subtree.
26714 The result is |true| if the complete tree or subtree has been deleted.
26715
26716 @d vsplit_init 0 /*action code for |vsplit| initialization*/
26717 @d fire_up_init 1 /*action code for |fire_up| initialization*/
26718 @d fire_up_done 2 /*action code for |fire_up| completion*/
26719 @d destroy_marks 3 /*action code for |final_cleanup|*/
26720 @#
26721 @d sa_top_mark(A) info(A+1) /*\.{\\topmarks}|n|*/
26722 @d sa_first_mark(A) link(A+1) /*\.{\\firstmarks}|n|*/
26723 @d sa_bot_mark(A) info(A+2) /*\.{\\botmarks}|n|*/
26724 @d sa_split_first_mark(A) link(A+2) /*\.{\\splitfirstmarks}|n|*/
26725 @d sa_split_bot_mark(A) info(A+3) /*\.{\\splitbotmarks}|n|*/
26726
26727 @<Declare the function called |do_marks|@>=
26728 static bool do_marks(small_number @!a, small_number @!l, pointer @!q)
26729 {@+int i; /*a four bit index*/
26730 if (l < 4) /*|q| is an index node*/
26731 {@+for (i=0; i<=15; i++)
26732 {@+get_sa_ptr;
26733 if (cur_ptr!=null) if (do_marks(a, l+1, cur_ptr)) delete_sa_ptr;
26734 }
26735 if (sa_used(q)==0)
26736 {@+free_node(q, index_node_size);q=null;
26737 }
26738 }
26739 else /*|q| is the node for a mark class*/
26740 {@+switch (a) {
26741 @<Cases for |do_marks|@>@;
26742 } /*there are no other cases*/
26743 if (sa_bot_mark(q)==null) if (sa_split_bot_mark(q)==null)
26744 {@+free_node(q, mark_class_node_size);q=null;
26745 }
26746 }
26747 return(q==null);
26748 }
26749
26750 @ At the start of the |vsplit| routine the existing |split_fist_mark|
26751 and |split_bot_mark| are discarded.
26752
26753 @<Cases for |do_marks|@>=
26754 case vsplit_init: if (sa_split_first_mark(q)!=null)
26755 {@+delete_token_ref(sa_split_first_mark(q));sa_split_first_mark(q)=null;
26756 delete_token_ref(sa_split_bot_mark(q));sa_split_bot_mark(q)=null;
26757 } @+break;
26758
26759 @ We use again the fact that |split_first_mark==null| if and only if
26760 |split_bot_mark==null|.
26761
26762 @<Update the current marks for |vsplit|@>=
26763 {@+find_sa_element(mark_val, mark_class(p), true);
26764 if (sa_split_first_mark(cur_ptr)==null)
26765 {@+sa_split_first_mark(cur_ptr)=mark_ptr(p);
26766 add_token_ref(mark_ptr(p));
26767 }
26768 else delete_token_ref(sa_split_bot_mark(cur_ptr));
26769 sa_split_bot_mark(cur_ptr)=mark_ptr(p);
26770 add_token_ref(mark_ptr(p));
26771 }
26772
26773 @ At the start of the |fire_up| routine the old |top_mark| and
26774 |first_mark| are discarded, whereas the old |bot_mark| becomes the new
26775 |top_mark|. An empty new |top_mark| token list is, however, discarded
26776 as well in order that mark class nodes can eventually be released. We
26777 use again the fact that |bot_mark!=null| implies |first_mark!=null|; it
26778 also knows that |bot_mark==null| implies |top_mark==first_mark==null|.
26779
26780 @<Cases for |do_marks|@>=
26781 case fire_up_init: if (sa_bot_mark(q)!=null)
26782 {@+if (sa_top_mark(q)!=null) delete_token_ref(sa_top_mark(q));
26783 delete_token_ref(sa_first_mark(q));sa_first_mark(q)=null;
26784 if (link(sa_bot_mark(q))==null) /*an empty token list*/
26785 {@+delete_token_ref(sa_bot_mark(q));sa_bot_mark(q)=null;
26786 }
26787 else add_token_ref(sa_bot_mark(q));
26788 sa_top_mark(q)=sa_bot_mark(q);
26789 } @+break;
26790
26791 @ @<Cases for |do_marks|@>=
26792 case fire_up_done: if ((sa_top_mark(q)!=null)&&(sa_first_mark(q)==null))
26793 {@+sa_first_mark(q)=sa_top_mark(q);add_token_ref(sa_top_mark(q));
26794 } @+break;
26795
26796 @ Here we use the fact that the five current mark pointers in a mark
26797 class node occupy the same locations as the first five pointers of
26798 an index node. For systems using a run-time switch to distinguish
26799 between \.{VIRTEX} and \.{INITEX}, the codewords `$|@t\#\&{ifdef} \.{INIT}@>|\ldots|@t\#\&{endif}@>|$'
26800 surrounding the following piece of code should be removed.
26801 @.INITEX@>
26802 @^system dependencies@>
26803
26804 @<Cases for |do_marks|@>=
26805 #ifdef @!INIT
26806 case destroy_marks: for (i=top_mark_code; i<=split_bot_mark_code; i++)
26807 {@+get_sa_ptr;
26808 if (cur_ptr!=null)
26809 {@+delete_token_ref(cur_ptr);put_sa_ptr(null);
26810 }
26811 }
26812 #endif
26813
26814 @ The command code |internal_register| is used for `\.{\\count}', `\.{\\dimen}',
26815 etc., as well as for references to sparse array elements defined by
26816 `\.{\\countdef}', etc.
26817
26818 @<Cases of |register| for |print_cmd_chr|@>=
26819 {@+if ((chr_code < mem_bot)||(chr_code > lo_mem_stat_max))
26820 cmd=sa_type(chr_code);
26821 else{@+cmd=chr_code-mem_bot;chr_code=null;
26822 }
26823 if (cmd==int_val) print_esc("count");
26824 else if (cmd==dimen_val) print_esc("dimen");
26825 else if (cmd==glue_val) print_esc("skip");
26826 else print_esc("muskip");
26827 if (chr_code!=null) print_sa_num(chr_code);
26828 }
26829
26830 @ Similarly the command code |toks_register| is used for `\.{\\toks}' as
26831 well as for references to sparse array elements defined by
26832 `\.{\\toksdef}'.
26833
26834 @<Cases of |toks_register| for |print_cmd_chr|@>=
26835 {@+print_esc("toks");
26836 if (chr_code!=mem_bot) print_sa_num(chr_code);
26837 }
26838
26839 @ When a shorthand definition for an element of one of the sparse arrays
26840 is destroyed, we must reduce the reference count.
26841
26842 @<Cases for |eq_destroy|@>=
26843 case toks_register: case internal_register:
26844 if ((equiv_field(w) < mem_bot)||(equiv_field(w) > lo_mem_stat_max))
26845 delete_sa_ref(equiv_field(w));@+break;
26846
26847 @ The task to maintain (change, save, and restore) register values is
26848 essentially the same when the register is realized as sparse array
26849 element or entry in |eqtb|. The global variable |sa_chain| is the head
26850 of a linked list of entries saved at the topmost level |sa_level|; the
26851 lists for lower levels are kept in special save stack entries.
26852
26853 @<Glob...@>=
26854 static pointer @!sa_chain; /*chain of saved sparse array entries*/
26855 static quarterword @!sa_level; /*group level for |sa_chain|*/
26856
26857 @ @<Set init...@>=
26858 sa_chain=null;sa_level=level_zero;
26859
26860 @ The individual saved items are kept in pointer or word nodes similar
26861 to those used for the array elements: a word node with value zero is,
26862 however, saved as pointer node with the otherwise impossible |sa_index|
26863 value |tok_val_limit|.
26864
26865 @d sa_loc(A) sa_ref(A) /*location of saved item*/
26866
26867 @<Declare \eTeX\ procedures for tr...@>=
26868 static void sa_save(pointer @!p) /*saves value of |p|*/
26869 {@+pointer q; /*the new save node*/
26870 quarterword @!i; /*index field of node*/
26871 if (cur_level!=sa_level)
26872 {@+check_full_save_stack;save_type(save_ptr)=restore_sa;
26873 save_level(save_ptr)=sa_level;save_index(save_ptr)=sa_chain;
26874 incr(save_ptr);sa_chain=null;sa_level=cur_level;
26875 }
26876 i=sa_index(p);
26877 if (i < dimen_val_limit)
26878 {@+if (sa_int(p)==0)
26879 {@+q=get_node(pointer_node_size);i=tok_val_limit;
26880 }
26881 else{@+q=get_node(word_node_size);sa_int(q)=sa_int(p);
26882 }
26883 sa_ptr(q)=null;
26884 }
26885 else{@+q=get_node(pointer_node_size);sa_ptr(q)=sa_ptr(p);
26886 }
26887 sa_loc(q)=p;sa_index(q)=i;sa_lev(q)=sa_lev(p);
26888 link(q)=sa_chain;sa_chain=q;add_sa_ref(p);
26889 }
26890
26891 @ @<Declare \eTeX\ procedures for tr...@>=
26892 static void sa_destroy(pointer @!p) /*destroy value of |p|*/
26893 {@+if (sa_index(p) < mu_val_limit) delete_glue_ref(sa_ptr(p));
26894 else if (sa_ptr(p)!=null)
26895 if (sa_index(p) < box_val_limit) flush_node_list(sa_ptr(p));
26896 else delete_token_ref(sa_ptr(p));
26897 }
26898
26899 @ The procedure |sa_def| assigns a new value to sparse array elements,
26900 and saves the former value if appropriate. This procedure is used only
26901 for skip, muskip, box, and token list registers. The counterpart of
26902 |sa_def| for count and dimen registers is called |sa_w_def|.
26903
26904 @d sa_define(A, B, C, D, E) if (e)
26905 if (global) gsa_def(A, B);@+else sa_def(A, B);
26906 else if (global) geq_define(C, D, E);@+else eq_define(C, D, E)
26907 @#
26908 @d sa_def_box /*assign |cur_box| to |box(cur_val)|*/
26909 {@+find_sa_element(box_val, cur_val, true);
26910 if (global) gsa_def(cur_ptr, cur_box);@+else sa_def(cur_ptr, cur_box);
26911 }
26912 @#
26913 @d sa_word_define(A, B) if (e)
26914 if (global) gsa_w_def(A, B);@+else sa_w_def(A, B);
26915 else word_define(A, B)
26916
26917 @<Declare \eTeX\ procedures for tr...@>=
26918 static void sa_def(pointer @!p, halfword @!e)
26919 /*new data for sparse array elements*/
26920 {@+add_sa_ref(p);
26921 if (sa_ptr(p)==e)
26922 {
26923 #ifdef @!STAT
26924 if (tracing_assigns > 0) show_sa(p,"reassigning");
26925 #endif
26926 @;@/
26927 sa_destroy(p);
26928 }
26929 else{
26930 #ifdef @!STAT
26931 if (tracing_assigns > 0) show_sa(p,"changing");
26932 #endif
26933 @;@/
26934 if (sa_lev(p)==cur_level) sa_destroy(p);@+else sa_save(p);
26935 sa_lev(p)=cur_level;sa_ptr(p)=e;
26936 #ifdef @!STAT
26937 if (tracing_assigns > 0) show_sa(p,"into");
26938 #endif
26939 @;@/
26940 }
26941 delete_sa_ref(p);
26942 }
26943 @#
26944 static void sa_w_def(pointer @!p, int @!w)
26945 {@+add_sa_ref(p);
26946 if (sa_int(p)==w)
26947 {
26948 #ifdef @!STAT
26949 if (tracing_assigns > 0) show_sa(p,"reassigning");
26950 #endif
26951 @;@/
26952 }
26953 else{
26954 #ifdef @!STAT
26955 if (tracing_assigns > 0) show_sa(p,"changing");
26956 #endif
26957 @;@/
26958 if (sa_lev(p)!=cur_level) sa_save(p);
26959 sa_lev(p)=cur_level;sa_int(p)=w;
26960 #ifdef @!STAT
26961 if (tracing_assigns > 0) show_sa(p,"into");
26962 #endif
26963 @;@/
26964 }
26965 delete_sa_ref(p);
26966 }
26967
26968 @ The |sa_def| and |sa_w_def| routines take care of local definitions.
26969 @^global definitions@>
26970 Global definitions are done in almost the same way, but there is no need
26971 to save old values, and the new value is associated with |level_one|.
26972
26973 @<Declare \eTeX\ procedures for tr...@>=
26974 static void gsa_def(pointer @!p, halfword @!e) /*global |sa_def|*/
26975 {@+add_sa_ref(p);
26976 #ifdef @!STAT
26977 if (tracing_assigns > 0) show_sa(p,"globally changing");
26978 #endif
26979 @;@/
26980 sa_destroy(p);sa_lev(p)=level_one;sa_ptr(p)=e;
26981 #ifdef @!STAT
26982 if (tracing_assigns > 0) show_sa(p,"into");
26983 #endif
26984 @;@/
26985 delete_sa_ref(p);
26986 }
26987 @#
26988 static void gsa_w_def(pointer @!p, int @!w) /*global |sa_w_def|*/
26989 {@+add_sa_ref(p);
26990 #ifdef @!STAT
26991 if (tracing_assigns > 0) show_sa(p,"globally changing");
26992 #endif
26993 @;@/
26994 sa_lev(p)=level_one;sa_int(p)=w;
26995 #ifdef @!STAT
26996 if (tracing_assigns > 0) show_sa(p,"into");
26997 #endif
26998 @;@/
26999 delete_sa_ref(p);
27000 }
27001
27002 @ The |sa_restore| procedure restores the sparse array entries pointed
27003 at by |sa_chain|
27004
27005 @<Declare \eTeX\ procedures for tr...@>=
27006 static void sa_restore(void)
27007 {@+pointer p; /*sparse array element*/
27008 @/do@+{p=sa_loc(sa_chain);
27009 if (sa_lev(p)==level_one)
27010 {@+if (sa_index(p) >= dimen_val_limit) sa_destroy(sa_chain);
27011 #ifdef @!STAT
27012 if (tracing_restores > 0) show_sa(p,"retaining");
27013 #endif
27014 @;@/
27015 }
27016 else{@+if (sa_index(p) < dimen_val_limit)
27017 if (sa_index(sa_chain) < dimen_val_limit) sa_int(p)=sa_int(sa_chain);
27018 else sa_int(p)=0;
27019 else{@+sa_destroy(p);sa_ptr(p)=sa_ptr(sa_chain);
27020 }
27021 sa_lev(p)=sa_lev(sa_chain);
27022 #ifdef @!STAT
27023 if (tracing_restores > 0) show_sa(p,"restoring");
27024 #endif
27025 @;@/
27026 }
27027 delete_sa_ref(p);
27028 p=sa_chain;sa_chain=link(p);
27029 if (sa_index(p) < dimen_val_limit) free_node(p, word_node_size);
27030 else free_node(p, pointer_node_size);
27031 }@+ while (!(sa_chain==null));
27032 }
27033
27034 @ When reading \.{\\patterns} while \.{\\savinghyphcodes} is positive
27035 the current |lc_code| values are stored together with the hyphenation
27036 patterns for the current language. They will later be used instead of
27037 the |lc_code| values for hyphenation purposes.
27038
27039 The |lc_code| values are stored in the linked trie analogous to patterns
27040 $p_1$ of length~1, with |hyph_root==trie_r[0]| replacing |trie_root| and
27041 |lc_code(p_1)| replacing the |trie_op| code. This allows to compress
27042 and pack them together with the patterns with minimal changes to the
27043 existing code.
27044
27045 @d hyph_root trie_r[0] /*root of the linked trie for |hyph_codes|*/
27046
27047 @<Initialize table entries...@>=
27048 hyph_root=0;hyph_start=0;
27049
27050 @ @<Store hyphenation codes for current language@>=
27051 {@+c=cur_lang;first_child=false;p=0;
27052 @/do@+{q=p;p=trie_r[q];
27053 }@+ while (!((p==0)||(c <= trie_c[p])));
27054 if ((p==0)||(c < trie_c[p]))
27055 @<Insert a new trie node between |q| and |p|, and make |p| point to it@>;
27056 q=p; /*now node |q| represents |cur_lang|*/
27057 @<Store all current |lc_code| values@>;
27058 }
27059
27060 @ We store all nonzero |lc_code| values, overwriting any previously
27061 stored values (and possibly wasting a few trie nodes that were used
27062 previously and are not needed now). We always store at least one
27063 |lc_code| value such that |hyph_index| (defined below) will not be zero.
27064
27065 @<Store all current |lc_code| values@>=
27066 p=trie_l[q];first_child=true;
27067 for (c=0; c<=255; c++)
27068 if ((lc_code(c) > 0)||((c==255)&&first_child))
27069 {@+if (p==0)
27070 @<Insert a new trie node between |q| and |p|, and make |p| point to
27071 it@>@;
27072 else trie_c[p]=c;
27073 trie_o[p]=qi(lc_code(c));
27074 q=p;p=trie_r[q];first_child=false;
27075 }
27076 if (first_child) trie_l[q]=0;@+else trie_r[q]=0
27077
27078 @ We must avoid to ``take'' location~1, in order to distinguish between
27079 |lc_code| values and patterns.
27080
27081 @<Pack all stored |hyph_codes|@>=
27082 {@+if (trie_root==0) for (p=0; p<=255; p++) trie_min[p]=p+2;
27083 first_fit(hyph_root);trie_pack(hyph_root);
27084 hyph_start=trie_ref[hyph_root];
27085 }
27086
27087 @ The global variable |hyph_index| will point to the hyphenation codes
27088 for the current language.
27089
27090 @d set_hyph_index /*set |hyph_index| for current language*/
27091 if (trie_char(hyph_start+cur_lang)!=qi(cur_lang)
27092 ) hyph_index=0; /*no hyphenation codes for |cur_lang|*/
27093 else hyph_index=trie_link(hyph_start+cur_lang)
27094 @#
27095 @d set_lc_code(A) /*set |hc[0]| to hyphenation or lc code for |A|*/
27096 if (hyph_index==0) hc[0]=lc_code(A);
27097 else if (trie_char(hyph_index+A)!=qi(A)) hc[0]=0;
27098 else hc[0]=qo(trie_op(hyph_index+A))
27099
27100 @<Glob...@>=
27101 static trie_pointer @!hyph_start; /*root of the packed trie for |hyph_codes|*/
27102 static trie_pointer @!hyph_index; /*pointer to hyphenation codes for |cur_lang|*/
27103
27104 @ When |saving_vdiscards| is positive then the glue, kern, and penalty
27105 nodes removed by the page builder or by \.{\\vsplit} from the top of a
27106 vertical list are saved in special lists instead of being discarded.
27107
27108 @d tail_page_disc disc_ptr[copy_code] /*last item removed by page builder*/
27109 @d page_disc disc_ptr[last_box_code] /*first item removed by page builder*/
27110 @d split_disc disc_ptr[vsplit_code] /*first item removed by \.{\\vsplit}*/
27111
27112 @<Glob...@>=
27113 static pointer @!disc_ptr0[vsplit_code-copy_code+1],
27114 *const @!disc_ptr = @!disc_ptr0-copy_code; /*list pointers*/
27115
27116 @ @<Set init...@>=
27117 page_disc=null;split_disc=null;
27118
27119 @ The \.{\\pagediscards} and \.{\\splitdiscards} commands share the
27120 command code |un_vbox| with \.{\\unvbox} and \.{\\unvcopy}, they are
27121 distinguished by their |chr_code| values |last_box_code| and
27122 |vsplit_code|. These |chr_code| values are larger than |box_code| and
27123 |copy_code|.
27124
27125 @<Generate all \eTeX...@>=
27126 primitive("pagediscards", un_vbox, last_box_code);@/
27127 @!@:page\_discards\_}{\.{\\pagediscards} primitive@>
27128 primitive("splitdiscards", un_vbox, vsplit_code);@/
27129 @!@:split\_discards\_}{\.{\\splitdiscards} primitive@>
27130
27131 @ @<Cases of |un_vbox| for |print_cmd_chr|@>=;
27132 else if (chr_code==last_box_code) print_esc("pagediscards");
27133 else if (chr_code==vsplit_code) print_esc("splitdiscards")
27134
27135 @ @<Handle saved items and |goto done|@>=
27136 {@+link(tail)=disc_ptr[cur_chr];disc_ptr[cur_chr]=null;
27137 goto done;
27138 }
27139
27140 @ The \.{\\interlinepenalties}, \.{\\clubpenalties}, \.{\\widowpenalties},
27141 and \.{\\displaywidowpenalties} commands allow to define arrays of
27142 penalty values to be used instead of the corresponding single values.
27143
27144 @d inter_line_penalties_ptr equiv(inter_line_penalties_loc)
27145 @<Generate all \eTeX...@>=
27146 primitive("interlinepenalties", set_shape, inter_line_penalties_loc);@/
27147 @!@:inter\_line\_penalties\_}{\.{\\interlinepenalties} primitive@>
27148 primitive("clubpenalties", set_shape, club_penalties_loc);@/
27149 @!@:club\_penalties\_}{\.{\\clubpenalties} primitive@>
27150 primitive("widowpenalties", set_shape, widow_penalties_loc);@/
27151 @!@:widow\_penalties\_}{\.{\\widowpenalties} primitive@>
27152 primitive("displaywidowpenalties", set_shape, display_widow_penalties_loc);@/
27153 @!@:display\_widow\_penalties\_}{\.{\\displaywidowpenalties} primitive@>
27154
27155 @ @<Cases of |set_shape| for |print_cmd_chr|@>=
27156 case inter_line_penalties_loc: print_esc("interlinepenalties");@+break;
27157 case club_penalties_loc: print_esc("clubpenalties");@+break;
27158 case widow_penalties_loc: print_esc("widowpenalties");@+break;
27159 case display_widow_penalties_loc: print_esc("displaywidowpenalties");
27160
27161 @ @<Fetch a penalties array element@>=
27162 {@+scan_int();
27163 if ((equiv(m)==null)||(cur_val < 0)) cur_val=0;
27164 else{@+if (cur_val > penalty(equiv(m))) cur_val=penalty(equiv(m));
27165 cur_val=penalty(equiv(m)+cur_val);
27166 }
27167 }
27168
27169 @ |expand_depth| and |expand_depth_count| are used in the \eTeX\ code
27170 above, but not defined. So we correct this in the following modules,
27171 |expand_depth| having been defined by us as an integer parameter (hence
27172 there is a new primitive to create in \eTeX\ mode), and
27173 |expand_depth_count| needing to be a global. Both have to be defined to
27174 some sensible value.
27175
27176 @<Glob...@>=
27177 static int @!expand_depth_count; /*current expansion depth*/
27178
27179 @ @<Generate all \eTeX...@>=
27180 primitive("expanddepth", assign_int, int_base+expand_depth_code);@/
27181 @!@:expand\_depth\_}{\.{\\expanddepth} primitive@>
27182
27183 @ @<Cases for |print_param|@>=
27184 case expand_depth_code: print_esc("expanddepth");@+break;
27185
27186 @ @<Initialize variables for \eTeX\ extended mode@>=
27187 expand_depth=10000; /*value taken for compatibility with Web2C*/
27188 expand_depth_count=0;
27189
27190 @* The extended features of \Prote.
27191 \Prote\ extends furthermore \eTeX\ i.e. \eTeX\ is thus required
27192 before adding \Prote\ own extensions. But if \eTeX\ mode has not
27193 be enabled, the engine is still compatible with \TeX\ with no added
27194 primitive commands and with a modification of code---from
27195 \eTeX\ exclusively for now---that is sufficiently minor so that
27196 the engine still deserves the name \TeX.
27197
27198 @d Prote_ex (Prote_mode==1) /*is this prote mode?*/
27199
27200 @<Glob...@>=
27201 static int @!Prote_mode; /*to be or not to be; but an int to dump*/
27202
27203 @ We begin in \TeX\ compatibility mode. The state |Prote_mode| will be
27204 set to $1$ only if activated by the supplementary `*' added to the one
27205 activating the \eTeX\ extensions (in fact, this means for the user two
27206 initial `*' in a row).
27207
27208 @<Initialize table entries...@>=
27209 Prote_mode=0; /*initially we are in compatibility mode*/
27210
27211 @ @<Dump the \Prote\ state@>=
27212 dump_int(Prote_mode);
27213
27214 @ @<Undump the \Prote\ state@>=
27215 undump(0, 1, Prote_mode);
27216
27217 @ In order to not clobber the global scope with variables that are
27218 locally used, the initializations for \Prote, if the mode is
27219 activated, are done in a dedicated procedure. These are not part of
27220 what is dumped.
27221
27222 @<Last-minute procedures@>=
27223 static void Prote_initialize(void)
27224 {@+int k; /*all-purpose index*/
27225 @<\Prote\ initializations@>;
27226 }
27227
27228 @ There are commands and command modifiers, these command modifiers
27229 maybe encoding too a type. So we must not step on each other toes.
27230
27231 @ When we are adding primitives that deal intimately with the variables
27232 of \TeX, in the |eqtb| regions (in our case regions 5 for integers, and
27233 6 for dimensions), the command modifier to the various
27234 \.{assign\_*} classes is simply the address. So we have interpolated
27235 our added variables above since this is done by the way of WEB
27236 pre-processing.
27237
27238 @ For the conditional primitives, the way is straightforward.
27239
27240 @d if_incsname_code (eTeX_last_if_test_cmd_mod+1) /* `\.{\\ifincsname}' */
27241 @d if_primitive_code (eTeX_last_if_test_cmd_mod+2) /* `\.{\\ifprimitive}' */
27242 @ The |last_item| class is for secondary internal values, that can be
27243 dereferenced by \.{\\the} but are read-only and are mainly related to
27244 the value of a current state or are such values but their assignation
27245 shall trigger an action, and we shall not hook in the \.{assign\_*}
27246 processing.
27247
27248 The command modifiers for the |last_item| class were, originally,
27249 encoding too the type of the item (see m.410). But \eTeX\ has added its
27250 extensions and we won't try to be smart: the type |cur_val_level| will
27251 be set by switching between contiguous ranges of values of the same
27252 type.
27253
27254 And we will define here all the instances of |last_item| that we add
27255 in order to keep our number assignations gathered.
27256
27257 @d Prote_version_code (eTeX_last_last_item_cmd_mod+1)
27258 /*code for \.{\\Proteversion}*/
27259 @d random_seed_code (eTeX_last_last_item_cmd_mod+2) /* \.{\\randomseed} */
27260 @d elapsed_time_code (eTeX_last_last_item_cmd_mod+3) /* \.{\\elapsedtime} */
27261 @d shell_escape_code (eTeX_last_last_item_cmd_mod+4) /* \.{\\shellescape} */
27262 @d last_xpos_code (eTeX_last_last_item_cmd_mod+5) /* \.{\\lastxpos} */
27263 @d last_ypos_code (eTeX_last_last_item_cmd_mod+6) /* \.{\\lastypos} */
27264 @<Fetch a \Prote\ item@>=
27265 {@+switch (m) {
27266 @/@<Cases for fetching a \Prote\ int value@>@/
27267 } /*there are no other cases*/
27268 cur_val_level=int_val;
27269 }
27270
27271 @ The \.{convert} class is for conversion of some external stuff to put
27272 it, as a token list, into the scanner. It is not an internal value that
27273 could be dereferenced by \.{\\the} and it is obviously not settable: it
27274 expands to the token list.
27275
27276 @d Prote_revision_code (eTeX_last_convert_cmd_mod+1) /* \.{\\Proterevision}*/
27277 @d strcmp_code (eTeX_last_convert_cmd_mod+2) /* \.{\\strcmp} */
27278 @d set_random_seed_code (eTeX_last_convert_cmd_mod+3) /* \.{\\setrandomseed} */
27279 @d normal_deviate_code (eTeX_last_convert_cmd_mod+4) /* \.{\\normaldeviate} */
27280 @d uniform_deviate_code (eTeX_last_convert_cmd_mod+5) /* \.{\\uniformdeviate} */
27281 @d creation_date_code (eTeX_last_convert_cmd_mod+6) /* \.{\\creationdate} */
27282 @d file_size_code (eTeX_last_convert_cmd_mod+7) /* \.{\\filesize} */
27283 @d file_mod_date_code (eTeX_last_convert_cmd_mod+8) /* \.{\\filemodedate} */
27284 @d file_dump_code (eTeX_last_convert_cmd_mod+9) /* \.{\\filedump} */
27285 @d mdfive_sum_code (eTeX_last_convert_cmd_mod+10) /* \.{\\mdfivesum} */
27286 @ When modifying the meaning of something---in this case, for now,
27287 switching to the primitive meaning if it exists---or modifying the
27288 way expansion is done, it seems that it can be thought as a special
27289 case of expansion, hence a variant of |expand_after|.
27290
27291 @d primitive_code (eTeX_last_expand_after_cmd_mod+1) /* `\.{\\primitive}' */
27292 @d expanded_code (eTeX_last_expand_after_cmd_mod+2) /* `\.{\\expanded}' */
27293 @ When the primitive manipulate something really external, whether
27294 trying to insert something in the output format---\.{DVI} for
27295 us---or dealing with the system, it doesn't fit in any cmd group and
27296 could be called an exception. So it will be a variant of the |extension|
27297 cmd group.
27298
27299 \eTeX\ didn't add new primitives to the extension command group, so we
27300 add a related macro, equal to |TeX_last_extension_cmd_mod|, simply so
27301 that it is locally obvious.
27302
27303 @d eTeX_last_extension_cmd_mod TeX_last_extension_cmd_mod /*none added*/
27304 @d reset_timer_code (eTeX_last_extension_cmd_mod+1) /* `\.{\\resettimer}' */
27305 @d save_pos_code (eTeX_last_extension_cmd_mod+2) /* `\.{\\savepos}' */
27306 @*1 Identifying \Prote.
27307
27308 We will start by giving a mean to test that \Prote\ is activated and
27309 to identify the version.
27310
27311 @<Generate all \Prote\ primitives@>=
27312 primitive("Proteversion", last_item, Prote_version_code);
27313 @!@:Prote\_version\_}{\.{\\Proteversion} primitive@>
27314 primitive("Proterevision", convert, Prote_revision_code);@/
27315 @!@:Prote\_revision\_}{\.{\\Proterevision} primitive@>
27316
27317 @ We use the different hooks added to insert our cases.
27318
27319 @<Cases of |last_item| for |print_cmd_chr|@>=
27320 case Prote_version_code: print_esc("Proteversion");@+break;
27321
27322 @ @<Cases for fetching a \Prote\ int value@>=
27323 case Prote_version_code: cur_val=Prote_version;@+break;
27324
27325 @ @<Cases of |convert| for |print_cmd_chr|@>=
27326 case Prote_revision_code: print_esc("Proterevision");@+break;
27327
27328 @ @<Cases of `Scan the argument for command |c|'@>=
27329 case Prote_revision_code: do_nothing;@+break;
27330
27331 @ @<Cases of `Print the result of command |c|'@>=
27332 case Prote_revision_code: print(Prote_revision);@+break;
27333
27334 @*1 \Prote\ added token lists routines.
27335
27336 We will, more than once, convert a general normally expanded text
27337 to a string. Due to the infelicity of \PASCAL\ about forward
27338 declarations of functions, we declare procedures that do their task
27339 by defining global variables. In this case, |garbage| is used.
27340
27341 |link(garbage)| will hold the pointer to the head of the token list,
27342 |info(garbage)| to the tail. If the two are equals, then the list is
27343 empty. The routine making a string will take |link(garbage)| and
27344 put the number in |info(garbage)|.
27345
27346 @ The first procedure scan a general text (normally) expanded. The
27347 head of the reference count is returned in |link(garbage)|, the
27348 tail in |info(garbage)| and if the two are equals, the list is empty.
27349 User must keep in mind that this has to be flushed when done with!
27350
27351 @<Forward declarations@>=
27352 static void scan_general_x_text(void);
27353
27354 @ @<Declare \Prote\ procedures for token lists@>=
27355 static void scan_general_x_text(void)
27356 {@+pointer d; /*to save |def_ref|*/
27357 d=def_ref;info(garbage)=scan_toks(false, true);
27358 link(garbage)=def_ref;
27359 def_ref=d; /*restore whatever*/
27360 }
27361
27362 @ The second procedure takes a token list defined in |link(garbage)|
27363 and converts it to a string number that is returned in |info(garbage)|.
27364 Neither the token list nor the string (obviously) are flushed.
27365
27366 @<Forward declarations@>=
27367 static void toks_to_str(void);
27368
27369 @ Here we are using |token_show| that has to take a reference count.
27370
27371 @<Declare \Prote\ procedures for token lists@>=
27372 static void toks_to_str(void)
27373 {@+int old_setting; /*holds |selector| setting*/
27374 old_setting=selector;selector=new_string;
27375 token_show(link(garbage));selector=old_setting;
27376 str_room(1); /*flirting with the limit means probably truncation*/
27377 info(garbage)=make_string();
27378 }
27379
27380 @*1 \Prote\ added strings routines.
27381
27382 The next procedure sets |name_of_file| from the string given as an
27383 argument, mimicking the |input| primitive by adding an |.tex| extension
27384 if there is none. It silently truncates if the length of the string
27385 exceeds the size of the name buffer and doesn't use |cur_area| and
27386 |cur_ext|, but |name_length| is set to the real name length (without
27387 truncating) so a test about |k <= file_name_size| allows to detect the
27388 impossibility of opening the file without having to call external code.
27389 The string is not flushed: it is the responsibility of the code calling
27390 the procedure to flush it if wanted.
27391
27392 @<Declare \Prote\ procedures for strings@>=
27393 static void str_to_name(str_number @!s)
27394 {@+int k; /*number of positions filled in |name_of_file|*/
27395 UTF8_code @!c; /*character being packed*/
27396 int @!j; /*index into |str_pool|*/
27397 k=0;for (j=str_start[s]; j<=str_start[s+1]-1; j++) {@+
27398 c=str_pool[j];incr(k);
27399 if (k <= file_name_size) name_of_file[k]=c;
27400 }
27401 name_length=k;
27402 name_of_file[name_length+1]=0;
27403 }
27404
27405 @*1 Exchanging data with external routines.
27406
27407 In order to try to sever external handling from our core, we
27408 introduce an all purpose exchange buffer |xchg_buffer|, that will
27409 be an array of bytes (these can be interpreted as \.{text\_char}
27410 or \.{ASCII\_char} or \.{eight\_bits}).
27411
27412 The data to be used starts at index $1$ and ends at index
27413 |xchg_buffer_length|.
27414
27415 For the moment, this buffer must accommodate a numerical MD5
27416 hash value, i.e. $16$ bytes long; will also be used to exchange $64$
27417 bytes chunks to feed MD5 hash generation, and will have to accommodate
27418 too the maximal size of the date returned by \.{\\creationdate} or
27419 \.{\\filemoddate} that is $23$ \.{text\_char}. So at least $64$ for now.
27420
27421 @<Global...@>=
27422 static eight_bits @!xchg_buffer0[xchg_buffer_size],
27423 *const @!xchg_buffer = @!xchg_buffer0-1;
27424 /*exchange buffer for interaction with system routines*/
27425 static int @!xchg_buffer_length; /*last valid index in this buf; 0 means no data*/
27426 @ @<Check \Prote\ ``constant'' values for consistency@>=
27427 if (xchg_buffer_size < 64) bad=51;
27428
27429 @ When there is data in the exchange buffer, the length of the data has
27430 to be set. When an external routine has consumed the data, it shall
27431 reset the length to $0$.
27432
27433 @<\Prote\ initializations@>=
27434 xchg_buffer_length=0;
27435
27436 @*1 \Prote\ states.
27437
27438 \.{\\shellescape} depends on a pdf\TeX\ feature, namely the ability to
27439 escape to shell. There is no such thing in \Prote. So it expands to $0$.
27440 Note: this a status primitive; it does not allow to set the status but
27441 simply expands to a read-only integer reflecting it. In \Prote, it is
27442 always $0$.
27443
27444 @<Generate all \Prote\ primitives@>=
27445 primitive("shellescape", last_item, shell_escape_code);
27446 @!@:shellescape\_}{\.{\\shellescape} primitive@>
27447
27448 @ @<Cases of |last_item| for |print_cmd_chr|@>=
27449 case shell_escape_code: print_esc("shellescape");@+break;
27450
27451 @ @<Cases for fetching a \Prote\ int value@>=
27452 case shell_escape_code: cur_val=0;@+break;
27453
27454 @*1 \Prote\ conditionals.
27455
27456 We add the following conditionals, that are susceptible of the same
27457 expansion rules as the other |if_test| ones.
27458
27459 @<Generate all \Prote\ primitives@>=
27460 primitive("ifincsname", if_test, if_incsname_code);
27461 @!@:if\_incsname\_}{\.{\\if} primitive@>
27462 primitive("ifprimitive", if_test, if_primitive_code);
27463 @!@:if\_primitive\_}{\.{\\if} primitive@>
27464
27465 @ @<Cases of |if_test| for |print_cmd_chr|@>=
27466 case if_incsname_code: print_esc("ifincsname");@+break;
27467 case if_primitive_code: print_esc("ifprimitive");@+break;
27468
27469 @ The conditional \.{\\ifincsname} is simple since we increment a global
27470 variable |incsname_state| when we enter the \.{\\csname} command and
27471 decrement it when we have reached and passed the \.{\\endcsname}---a
27472 scope depth index.
27473
27474 @<\Prote\ initializations@>=
27475 incsname_state=0;
27476
27477 @ @<Cases for |conditional|@>=
27478 case if_incsname_code: b=(incsname_state > 0);@+break;
27479
27480 @ The conditional \.{\\ifprimitive} is true when the following control
27481 sequence is a primitive; false otherwise. |id_lookup| can return
27482 |undefined_control_sequence| (for a control sequence not entered in the
27483 hash since |no_new_control_sequence| is |true|), but since it has the
27484 \.{eq\_type} set to |undefined_cs|, the test of this latter works as
27485 for a control sequence entered but never defined.
27486
27487 @ @<Cases for |conditional|@>=
27488 case if_primitive_code: {@+@/do@+{get_token();}@+ while (!(cur_tok!=space_token));
27489 if ((cur_cs!=0)&&(cur_cmd!=undefined_cs)&&(cur_cmd < call)) b=true;else b=false;
27490 } @+break;
27491
27492 @*1 \Prote\ primitives changing definition or expansion.
27493
27494 The next primitives, here, are more involved since they are whether
27495 changing the definition of a control sequence, or modifying how the
27496 tokens will be treated.
27497
27498 @ Since a user level control sequence can give a new definition to a
27499 primitive, the \.{primitive}... primitive, if the argument is a control
27500 sequence whose name is the name of a primitive, will make this primitive
27501 meaning the meaning of the control sequence {\it hic et nunc}. If there
27502 was no primitive meaning, no error is raised and nothing is changed.
27503 It can be seen as a kind of \.{expand\_after} command since it is in the
27504 external handling of the token list creation.
27505
27506 Since we need to redefine the token and hence give a valid control
27507 sequence in the |eqtb|, we have defined |frozen_primitive|. This
27508 ``frozen'' is, actually, not quite frozen by itself since we will
27509 redefine its values according to the primitive definition we have
27510 to reestablish momentarily. But it is indeed ``permanent'' since
27511 it only refers to the permanently defined meanings. Hence, the
27512 initialization of the |frozen_primitive| address is just to document
27513 the code: these values will be overwritten on each actual call.
27514
27515 @<Generate all \Prote\ primitives@>=
27516 primitive("primitive", expand_after, primitive_code);
27517 @!@:primitive\_}{\.{\\primitive} primitive@>
27518 text(frozen_primitive)=text(cur_val);eqtb[frozen_primitive]=eqtb[cur_val];
27519
27520 @ @<Cases of |expandafter| for |print_cmd_chr|@>=
27521 case primitive_code: print_esc("primitive");@+break;
27522
27523 @ The problem is that the primitives are added at |level_one| and that a
27524 redefinition as a macro at this same level by a user simply overwrites
27525 the definition. We need then to keep these definitions.
27526
27527 Primitives are only added by \.{INITEX}. So we can consider what we will
27528 call a |ROM|, since it can be only ``flashed'' by \.{INITEX} and is
27529 read-only afterwards, a kind of BIOS table holding initial system calls
27530 (primitives).
27531
27532 Since primitives are not macros (they don't need to expand or to
27533 evaluate parameters since their definition is directly in the code),
27534 the definition of a primitive is a couple: the command class (|cur_cmd|)
27535 and the modifier (|cur_chr|) to distinguish between the cases---the
27536 instances. But since, at the user level, a primitive is identified by
27537 its name, and that a redefinition is, mandatorily, a homonym, the
27538 location of the macro shadowing the primitive is at the same address as
27539 was the primitive in the |eqtb|. So in order to speed-up the check, we
27540 should organize things so that the address in the |eqtb| of a control
27541 sequence (one character or multiletter) can be readily
27542 converted in an address in the |ROM| array.
27543
27544 This array will be an array of memory word, of type |two_halves|, in
27545 order to re-use the macro definitions set for the table of equivalents.
27546
27547 The one character primitives are added by direct addressing relative to
27548 |single_base|. The multiletter primitives are added starting at
27549 |frozen_control_sequence-1|, downwards; but there are only, at the
27550 moment, $322$ multiletter primitives defined by \TeX, $78$ such
27551 primitives defined by \eTeX, and we are adding $24$ more. It is clear
27552 that, looking at primitives, region 2 of |eqtb| is really a sparse array
27553 and that, when |hash_size| is increased for format needs, there will be
27554 a fair amount of space wasted if we simply copy, in fact, second part
27555 of region 1 and region 2 in the |ROM|.
27556
27557 Yes, but it is simpler as a first approach---premature optimization is
27558 the root of all evil. So a simple translation scheme will be enough.
27559
27560 The index in |ROM| will start at $1$ and will go up to $256 + 1 +
27561 hash\_size$, that is a simple translation from |single_base| to
27562 |ROM_base|, but only for addresses of interest, the other pointing to
27563 an |ROM_undefined_primitive| that will allow an easy test.
27564
27565 @d ROM_base 1
27566 @d ROM_size (256+1+hash_size) /*256 oc, undefined and ml*/
27567 @d ROM_undefined_primitive 257
27568 @d ROM_type_field(A) A.hh.b0
27569 @d ROM_equiv_field(X) X.hh.rh
27570 @d ROM_type(A) ROM_type_field(ROM[A]) /*command code for equivalent*/
27571 @d set_ROM_p_from_cs(A) if ((A >= single_base)
27572 &&(A < frozen_control_sequence))
27573 p=A-single_base+ROM_base;
27574 else p=ROM_undefined_primitive
27575
27576 @<Global...@>=
27577 static memory_word @!ROM0[ROM_size-ROM_base+1],
27578 *const @!ROM = @!ROM0-ROM_base;
27579
27580 @ Even if it will be unused in \TeX\ or \eTeX\ modes, we will initialize
27581 it since we add code to the |primitive| procedure and we need \TeX\
27582 and \eTeX\ ones to be registered as well, whether \.{INITEX} switches to
27583 \Prote\ mode later or not.
27584
27585 @<Initialize table entries...@>=
27586 ROM[ROM_undefined_primitive]=eqtb[undefined_control_sequence];
27587 for (k=ROM_base; k<=256; k++) ROM[k]=ROM[ROM_undefined_primitive];
27588 for (k=ROM_undefined_primitive+1; k<=ROM_size; k++)
27589 ROM[k]=ROM[ROM_undefined_primitive];
27590
27591 @ When a primitive is added---and this only happens in \.{INITEX}---we
27592 have to define the corresponding address in the \.{ROM}.
27593
27594 @ |cur_val| has the pointer in second part of region 1 or in region 2
27595 of |eqtb|.
27596
27597 @<Add primitive definition to the |ROM| array@>=
27598 set_ROM_p_from_cs(cur_val);
27599 ROM[p]=eqtb[cur_val];
27600
27601 @ This array has to be dumped since it is only defined by \.{INITEX}. It
27602 is always dumped even if it is unused unless in \Prote\ mode.
27603
27604 @<Dump the |ROM| array@>=
27605 for (k=ROM_base; k<=ROM_size; k++) dump_wd(ROM[k]);
27606
27607 @ And what has been dumped shall be undumped.
27608
27609 @<Undump the |ROM| array@>=
27610 for (k=ROM_base; k<=ROM_size; k++) undump_wd(ROM[k]);
27611
27612 @ Once all this is done, the processing of \.{\\primitive} is simple:
27613 we read the next token that has to be a control sequence. If this
27614 control sequence belongs to region 1 or 2 and is defined in |ROM|, we
27615 redefine the token to be the |frozen_primitive| control sequence,
27616 redefining its codes from the |ROM| and setting the text associated for
27617 printing purposes. If not, the token is unchanged. Then we put back the
27618 token so that it will be processed again, maybe redefined.
27619
27620 @<Cases for |expandafter|@>=
27621 case primitive_code: {@+get_token();
27622 set_ROM_p_from_cs(cur_cs);
27623 if ((p!=ROM_undefined_primitive)&&(ROM_type(p)!=undefined_cs)) {@+
27624 eqtb[frozen_primitive]=ROM[p];
27625 text(frozen_primitive)=text(cur_cs);
27626 cur_tok=cs_token_flag+frozen_primitive;
27627 }
27628 back_input();
27629 } @+break;
27630
27631 @ The next primitive changes the expansion of its argument that is like
27632 a general text expanded, except that protected macros (an \eTeX\
27633 extension) are not extended.
27634
27635 @ @<Generate all \Prote\ primitives@>=
27636 primitive("expanded", expand_after, expanded_code);@/
27637 @!@:expanded\_}{\.{\\expanded} primitive@>
27638
27639 @ @<Cases of |expandafter| for |print_cmd_chr|@>=
27640 case expanded_code: print_esc("expanded");
27641
27642 @ This intervenes in |expand| and we must substitute a token list to our
27643 current token, putting it back for further reprocessing.
27644
27645 @<Cases for |expandafter|@>=
27646 case expanded_code: {@+scan_general_x_text();
27647 back_list(link(link(garbage)));
27648 free_avail(link(garbage)); /*drop reference count*/
27649 }
27650
27651 @*1 \Prote\ strings related primitives.
27652
27653 The primitive \.{\\strcmp} text two parameters that are general text
27654 without expansion. The two token lists created are converted to strings
27655 and this couple of strings is then compared, character by character. If
27656 the first string is lexicographically sorted before the second, the
27657 expansion is $-1$; if the two strings are equal, the expansion is $0$;
27658 if the first string is lexicographically sorted after the second, the
27659 expansion is $1$.
27660
27661 @<Generate all \Prote\ primitives@>=
27662 primitive("strcmp", convert, strcmp_code);
27663 @!@:strcmp\_}{\.{\\strcmp} primitive@>
27664
27665 @ @<Cases of |convert| for |print_cmd_chr|@>=
27666 case strcmp_code: print_esc("strcmp");@+break;
27667
27668 @ It should be noted that the strings comparison is \TeX\ strings
27669 comparison: the arguments are subject to the manipulation done when
27670 scanning a general text (squeezing non escaped blanks).
27671 Null strings are valid.
27672
27673 @<Cases of `Scan the argument for command |c|'@>=
27674 case strcmp_code: {@+scan_general_x_text();toks_to_str();
27675 s=info(garbage);flush_list(link(garbage));
27676 scan_general_x_text();toks_to_str();
27677 t=info(garbage);flush_list(link(garbage));
27678 if ((length(s)==0)&&(length(t)==0)) cur_val=0;
27679 else if (length(s)==0) cur_val=-1;
27680 else if (length(t)==0) cur_val=1;
27681 else{@+m=str_start[s];n=str_start[t];r=false;
27682 while ((!r)&&(m < str_start[s+1])&&(n < str_start[t+1])) {@+
27683 cur_val=str_pool[m]-str_pool[n];if (cur_val!=0) r=true;
27684 incr(m);incr(n);
27685 }
27686 if (cur_val==0) {@+if (length(s)!=length(t))
27687 if (m!=str_start[s+1]) cur_val=1;else cur_val=-1;
27688 }
27689 else cur_val=cur_val/(double)abs(cur_val);
27690 }
27691 flush_string;flush_string;
27692 } @+break;
27693
27694 @ @<Cases of `Print the result of command |c|'@>=
27695 case strcmp_code: print_int(cur_val);@+break;
27696
27697 @*1 \Prote\ date and time related primitives.
27698
27699 The following primitives are related to the time elapsed since a
27700 defined moment in time. The creation date is fixed at the moment when
27701 |fix_date_and_time| has been called and stays fixed afterwards. This
27702 moment is also, by default, the reference moment for computing the time
27703 elapsed.
27704
27705 @ The creation date is retrieved by the \.{\\creationdate} primitive. As
27706 explained above, the date corresponds to the moment when
27707 |fix_date_and_time| was called taking into account |FORCE_SOURCE_DATE|
27708 and |SOURCE_DATE_EPOCH| (see above, m.241). If the creation date is
27709 forced, the string will be UTC related.
27710
27711 The format of the string is |D: YYYYMMDDHHmmSSOHH"mm"|, `O' being the
27712 relationship of local time to UT, that is `-' (minus), `+' or `Z';
27713 HH followed by a single quote being the absolute value of the offset
27714 from UT in hours (00--23), mm followed by a single quote being the
27715 absolute value of the offset from UT in minutes (00--59). All fields
27716 after the year are optional and default to zero values.
27717
27718 @ @<Generate all \Prote\ primitives@>=
27719 primitive("creationdate", convert, creation_date_code);@/
27720 @!@:creationdate\_}{\.{\\creationdate} primitive@>
27721
27722 @ @<Cases of |convert| for |print_cmd_chr|@>=
27723 case creation_date_code: print_esc("creationdate");@+break;
27724
27725 @ |get_creation_date| has to be provided by the system.
27726 @^system dependencies@>
27727
27728 @<Cases of `Scan the argument for command |c|'@>=
27729 case creation_date_code: get_creation_date();@+break;
27730
27731 @ The date is in the |time_str| so we have simply to convert the
27732 characters.
27733
27734 @<Cases of `Print the result of command |c|'@>=
27735 case creation_date_code: for (k=0; time_str[k]!='\0'; k++)
27736 print_char(time_str[k]);@+break;
27737
27738 @ The time elapsed is a scaled integer the unit being scaled seconds,
27739 i.e. $1/65536$ of a second. Since our scaled integers have a
27740 defined range, the value can not reach or pass, in plain seconds,
27741 $32767$.
27742
27743 The elapsed time returned is relative to some defined moment. At
27744 start, the reference moment is the time the date was set for
27745 |fix_date_and_time|. This requires system support and the default
27746 implementation here will then fix this moment at noon on 4 July 1776
27747 and what would be returned by the function is here simply defined by
27748 a macro: with this reference time and this basic code, |infinity| is
27749 the permanent answer.
27750 @^system dependencies@>
27751
27752 @d get_elapsed_time infinity /*a function should be implemented*/
27753
27754 @ @<Generate all \Prote\ primitives@>=
27755 primitive("resettimer", extension, reset_timer_code);@/
27756 @!@:resettimer\_}{\.{\\resettimer} primitive@>
27757 primitive("elapsedtime", last_item, elapsed_time_code);@/
27758 @!@:elapsedtime\_}{\.{\\elapsedtime} primitive@>
27759
27760 @ @<Cases of |last_item| for |print_cmd_chr|@>=
27761 case elapsed_time_code: print_esc("elapsedtime");@+break;
27762
27763 @ @<Cases of |extension| for |print_cmd_chr|@>=
27764 case reset_timer_code: print_esc("resettimer");@+break;
27765
27766 @ @<Cases for fetching a \Prote\ int value@>=
27767 case elapsed_time_code: cur_val=get_elapsed_time;@+break;
27768
27769 @ The reference moment can be reset by a call to the primitive
27770 \.{\\resettimer}. It simply resets the reference moment to the moment
27771 the primitive was called. The counter is not regularly incremented.
27772 When asked about the time elapsed what is returned is the difference, in
27773 scaled seconds, from the moment of the call to the moment of reference.
27774 So there is no persistent variable neither a kind of clock implemented.
27775 @^system dependencies@>
27776
27777 Standard \PASCAL\ doesn't provide related routines so our
27778 syntactically correct but semantically useless routines are implemented
27779 here: the |reset_timer| does nothing, while the |get_elapsed_time|
27780 simply returns, even when |reset_timer| has been called, the invalid
27781 value |infinity|.
27782
27783 @d reset_timer do_nothing
27784
27785 @ Since to reset the timer a simple call to the routine is necessary,
27786 we simply add it to \.{main\_control} by adding it to the cases handled
27787 by \.{do\_extension}. It contributes nothing to the token list: it is a
27788 ``fire and forget'', so no need to handle the special \.{subtype} in the
27789 other hooks.
27790
27791 @<Cases for |do_extension|@>=
27792 case reset_timer_code: reset_timer;@+break;
27793
27794 @*1 \Prote\ file related primitives.
27795
27796 The presence of the following primitives in the engine can be
27797 questioned. Since they are very external, and their implementation, for
27798 example in C, requires things that are not in the C standard (the
27799 date of modification of the file, for example). So these should not be
27800 multiplied.
27801
27802 @ The \.{\\filesize} primitive expands to the size, in bytes, of the
27803 file.
27804
27805 @<Generate all \Prote\ primitives@>=
27806 primitive("filesize", convert, file_size_code);
27807 @!@:filesize\_}{\.{\\filesize} primitive@>
27808
27809 @ @<Cases of |convert| for |print_cmd_chr|@>=
27810 case file_size_code: print_esc("filesize");@+break;
27811
27812 @ In order to be able to treat the problem when trying to open the file,
27813 we open here and pass the file pointer, if success, to a dedicated
27814 function in order to get its size. In case of problem, nothing is
27815 returned.
27816 @^system dependencies@>
27817
27818 @<Cases of `Scan the argument for command |c|'@>=
27819 case file_size_code: {@+scan_general_x_text();toks_to_str();
27820 s=info(garbage);flush_list(link(garbage));str_to_name(s);
27821 cur_val=-1; /*invalid value if error*/
27822 cur_val=get_file_size();
27823 flush_string;
27824 } @+break;
27825
27826 @ @<Cases of `Print the result of command |c|'@>=
27827 case file_size_code: if (cur_val!=-1) print_int(cur_val);@+break;
27828
27829 @ The \.{\\filemoddate} expands to a date with the same format as the
27830 creation date (see \.{\\creationdate}).
27831
27832 @<Generate all \Prote\ primitives@>=
27833 primitive("filemoddate", convert, file_mod_date_code);
27834 @!@:filemoddate\_}{\.{\\filemoddate} primitive@>
27835
27836 @ @<Cases of |convert| for |print_cmd_chr|@>=
27837 case file_mod_date_code: print_esc("filemoddate");@+break;
27838
27839 @ For getting the argument, the treatment resembles that of
27840 \.{\\filesize} obviously, since it is only the type of information
27841 returned that changes. The availability of this information in system
27842 dependent. The information shall be set in |xchg_buffer|.
27843 @^system dependencies@>
27844
27845 In this basic implementation, we set the string to the empty one by
27846 simply setting |xchg_buffer_length| to $0$.
27847
27848 @d get_file_mtime xchg_buffer_length=0
27849
27850 @<Cases of `Scan the argument for command |c|'@>=
27851 case file_mod_date_code: {@+scan_general_x_text();toks_to_str();
27852 s=info(garbage);flush_list(link(garbage));str_to_name(s);
27853 get_file_mod_date();
27854 flush_string;
27855 } @+break;
27856
27857 @ Printing the result consists simply in printing every
27858 |text_char| in |time_str|.
27859 If the length is $0$, nothing is printed.
27860
27861 @<Cases of `Print the result of command |c|'@>=
27862 case file_mod_date_code: for (k=0; time_str[k]!='\0'; k++)
27863 print_char(time_str[k]);@+break;
27864
27865 @ The primitive \.{\\filedump} expands to the dump of the first
27866 \.{length} bytes of the file, starting from \.{offset}. Offset and
27867 length are optional integers given, in that order, introduced resp.
27868 by the keywords ``offset'' and ``length''. If not specified, they
27869 default to $0$. A length of $0$ expands to nothing (it is not an error).
27870 The file name is given as a |general text|.
27871
27872 @<Generate all \Prote\ primitives@>=
27873 primitive("filedump", convert, file_dump_code);
27874 @!@:filedump\_}{\.{\\filedump} primitive@>
27875
27876 @ @<Cases of |convert| for |print_cmd_chr|@>=
27877 case file_dump_code: print_esc("filedump");@+break;
27878
27879 @ The scanning of the arguments is obvious from the syntax above.
27880
27881 Since ``offset'' and ``length'' may be given in that order, we assign
27882 the variables \.{k} and \.{l}, in alphabetical order. These have to be
27883 positive or null values.
27884
27885 Contrary to other blocks, and for optimization purposes (in order not to
27886 clobber the string pool with data that we can read, when necessary, one
27887 byte at a time), \.{k}, \.{l} and \.{f} will be defined here and used
27888 when printing.
27889
27890 @<Cases of `Scan the argument for command |c|'@>=
27891 case file_dump_code: {@+k=0;l=0; /*defaults*/
27892 if (scan_keyword("offset")) {@+scan_int();
27893 if (cur_val < 0) {@+print_err("Bad ");print_esc("filedump");
27894 @.Bad \\filedump@>
27895 help2("I allow only nonnegative values here.",@/
27896 "I changed this one to zero.");int_error(cur_val);
27897 }
27898 else k=cur_val;
27899 }
27900 if (scan_keyword("length")) {@+scan_int();
27901 if (cur_val < 0) {@+print_err("Bad ");print_esc("filedump");
27902 @.Bad \\filedump@>
27903 help2("I allow only nonnegative values here.",@/
27904 "I changed this one to zero.");int_error(cur_val);
27905 }
27906 else l=cur_val;
27907 }
27908 scan_general_x_text();toks_to_str();s=info(garbage);
27909 flush_list(link(garbage));str_to_name(s);
27910 flush_string; /*this one was the filename argument*/
27911 } @+break;
27912
27913 @ The variables have been set, and the file name has been defined. We
27914 simply print the uppercase hexadecimal transcription of every byte
27915 requested before closing the file. Here we deal with bytes
27916 (\.{eight\_bits} values) so there is no transcription.
27917
27918 @<Cases of `Print the result of command |c|'@>=
27919 case file_dump_code:
27920 { FILE *f=fopen((char*)name_of_file0,"rb");
27921 if (f!=NULL) {@+
27922 fseek(f,k,SEEK_SET);
27923 do@+{i=fgetc(f); if (i==EOF) break;
27924 dig[0]=i%16;dig[1]=i/16;
27925 print_the_digs(2);decr(l);
27926 }@+ while (!(feof(f)||(l==0)));
27927 fclose(f);
27928 }
27929 } @+break;
27930
27931 @ The \.{\\mdfivesum} is obviously a variant of the \.{convert} class since
27932 it takes values from external and put them as a token list in the
27933 stream.
27934
27935 @<Generate all \Prote\ primitives@>=
27936 primitive("mdfivesum", convert, mdfive_sum_code);
27937 @!@:mdfivesum\_}{\.{\\mdfivesum} primitive@>
27938
27939 @ @<Cases of |convert| for |print_cmd_chr|@>=
27940 case mdfive_sum_code: print_esc("mdfivesum");@+break;
27941
27942 @ There is an optional keyword "file" that will tell us if the | < general
27943 text > | is to be taken as a filename or just as the string to hash. The
27944 | < balanced text > | is expanded in both cases.
27945
27946 Once this is done, we ask to init the MD5 state; then fill the exchange
27947 buffer with chunks of data and update the MD5 hash with every chunk
27948 until source is exhausted and ask for the final ($16$ bytes numerical
27949 value) result that will be put in the |xchg_buffer|.
27950
27951 Since we are looking for a ``general text'', that must be enclosed (at
27952 least: ended; the opening brace can be implicit) by a |right_brace|,
27953 an error will be caught with runaways.
27954
27955 The general text is converted to a string. It is legal to have an empty
27956 string if the argument is not a file.
27957
27958 @<Cases of `Scan the argument for command |c|'@>=
27959 case mdfive_sum_code: {@+r=scan_keyword("file");scan_general_x_text();
27960 toks_to_str();s=info(garbage);flush_list(link(garbage));
27961 l=get_md5_sum(s,r);
27962 flush_string; /*done with the filename or string to hash*/
27963 } @+break;
27964
27965 @ As a result, there is $16$ bytes in the |md5_digest| representing the
27966 MD5 hash. We simply print, byte by byte, the uppercase hexadecimal
27967 representation of this hash.
27968
27969 @<Cases of `Print the result of command |c|'@>=
27970 case mdfive_sum_code: for (k=0; k<l; k++)
27971 {@+dig[0]=md5_digest[k]%16;@+dig[1]=md5_digest[k]/16;print_the_digs(2);
27972 } @+break;
27973
27974 @*1 Pseudo-random number generation.
27975
27976 These routines come from John Hobby's \MP\ and generate pseudo-random
27977 numbers with the additive scheme recommended in Section 3.6 of
27978 {\sl The Art of Computer Programming}; however, the results are
27979 random fractions between 0 and |mpfract_one-1|, inclusive.
27980
27981 \MP\ uses 28~significant bits of precision and we have kept this in
27982 order for the routines to behave the same way as in \MP. So the name
27983 |mpfract| will be used instead of |scaled|, while the two are integers,
27984 in the range defined by \TeX.
27985
27986 @d double(A) A=A+A /*multiply a variable by two*/
27987 @d halfp(A) (A)/2 /*when quantity is known to be positive or zero*/
27988
27989 @ The subroutines for logarithm and exponential involve two tables.
27990 The first is simple: |two_to_the[k]| equals $2^k$. The second involves
27991 a bit more calculation, which the author claims to have done correctly:
27992 |spec_log[k]| is $2^{27}$ times $\ln\bigl(1/(1-2^{-k})\bigr)=
27993 2^{-k}+{1\over2}2^{-2k}+{1\over3}2^{-3k}+\cdots\,$, rounded to the
27994 nearest integer.
27995
27996 @<Glob...@>=
27997 static int @!two_to_the[31]; /*powers of two*/
27998 static int @!spec_log0[28], *const @!spec_log = @!spec_log0-1; /*special logarithms*/
27999
28000 @ @<\Prote\ initializations@>=
28001 two_to_the[0]=1;
28002 for (k=1; k<=30; k++) two_to_the[k]=2*two_to_the[k-1];
28003 spec_log[1]=93032640;
28004 spec_log[2]=38612034;
28005 spec_log[3]=17922280;
28006 spec_log[4]=8662214;
28007 spec_log[5]=4261238;
28008 spec_log[6]=2113709;
28009 spec_log[7]=1052693;
28010 spec_log[8]=525315;
28011 spec_log[9]=262400;
28012 spec_log[10]=131136;
28013 spec_log[11]=65552;
28014 spec_log[12]=32772;
28015 spec_log[13]=16385;
28016 for (k=14; k<=27; k++) spec_log[k]=two_to_the[27-k];
28017 spec_log[28]=1;
28018
28019 @ Here is the routine that calculates $2^8$ times the natural logarithm
28020 of a |scaled| quantity; it is an integer approximation to $2^{24}\ln(x/2^{16})$,
28021 when |x| is a given positive integer.
28022
28023 The method is based on exercise 1.2.2--25 in {\sl The Art of Computer
28024 Programming\/}: During the main iteration we have $1\L 2^{-30}x<1/(1-2^{1-k})$,
28025 and the logarithm of $2^{30}x$ remains to be added to an accumulator
28026 register called~$y$. Three auxiliary bits of accuracy are retained in~$y$
28027 during the calculation, and sixteen auxiliary bits to extend |y| are
28028 kept in~|z| during the initial argument reduction. (We add
28029 $100\cdot2^{16}=6553600$ to~|z| and subtract 100 from~|y| so that |z| will
28030 not become negative; also, the actual amount subtracted from~|y| is~96,
28031 not~100, because we want to add~4 for rounding before the final division by~8.)
28032
28033 @<Declare \Prote\ arithmetic routines@>=
28034 static scaled m_log(scaled @!x)
28035 {@+int @!y, @!z; /*auxiliary registers*/
28036 int @!k; /*iteration counter*/
28037 if (x <= 0) @<Handle non-positive logarithm@>@;
28038 else{@+y=1302456956+4-100; /*$14\times2^{27}\ln2\approx1302456956.421063$*/
28039 z=27595+6553600; /*and $2^{16}\times .421063\approx 27595$*/
28040 while (x < mpfract_four)
28041 {@+double(x);y=y-93032639;z=z-48782;
28042 } /*$2^{27}\ln2\approx 93032639.74436163$
28043 and $2^{16}\times.74436163\approx 48782$*/
28044 y=y+(z/unity);k=2;
28045 while (x > mpfract_four+4)
28046 @<Increase |k| until |x| can be multiplied by a factor of $2^{-k}$, and
28047 adjust $y$ accordingly@>;
28048 return y/8;
28049 }
28050 }
28051
28052 @ @<Increase |k| until |x| can...@>=
28053 {@+z=((x-1)/two_to_the[k])+1; /*$z=\lceil x/2^k\rceil$*/
28054 while (x < mpfract_four+z)
28055 {@+z=halfp(z+1);k=k+1;
28056 }
28057 y=y+spec_log[k];x=x-z;
28058 }
28059
28060 @ @<Handle non-positive logarithm@>=
28061 {@+print_err("Logarithm of ");
28062 @.Logarithm...replaced by 0@>
28063 print_scaled(x);print(" has been replaced by 0");
28064 help2("Since I don't take logs of non-positive numbers,",@/
28065 "I'm zeroing this one. Proceed, with fingers crossed.");
28066 error();return 0;
28067 }
28068
28069 @ Here is introduced the special 28bits significant |mpfract|.
28070
28071 @d el_gordo 017777777777 /*$2^{31}-1$, the largest value that \TeX\ likes*/
28072 @d mpfract_half 01000000000 /*$2^{27}$, represents 0.50000000*/
28073 @d mpfract_one 02000000000 /*$2^{28}$, represents 1.00000000*/
28074 @d mpfract_four 010000000000 /*$2^{30}$, represents 4.00000000*/
28075
28076 @<Types...@>=
28077 typedef int mpfract; /*this type is used for pseudo-random numbers*/
28078
28079 @ The |make_mpfract| routine produces the |mpfract| equivalent of
28080 |p/(double)q|, given integers |p| and~|q|; it computes the integer
28081 $f=\lfloor2^{28}p/q+{1\over2}\rfloor$, when $p$ and $q$ are
28082 positive. If |p| and |q| are both of the same scaled type |t|,
28083 the ``type relation'' |make_mpfract(t, t)==mpfract| is valid;
28084 and it's also possible to use the subroutine ``backwards,'' using
28085 the relation |make_mpfract(t, mpfract)==t| between scaled types.
28086
28087 If the result would have magnitude $2^{31}$ or more, |make_mpfract|
28088 sets |arith_error=true|. Most of \TeX's internal computations have
28089 been designed to avoid this sort of error.
28090
28091 If this subroutine were programmed in assembly language on a typical
28092 machine, we could simply compute |(@t$2^{28}$@>*p)/q|, since a
28093 double-precision product can often be input to a fixed-point division
28094 instruction. But when we are restricted to \PASCAL\ arithmetic it
28095 is necessary either to resort to multiple-precision maneuvering
28096 or to use a simple but slow iteration. The multiple-precision technique
28097 would be about three times faster than the code adopted here, but it
28098 would be comparatively long and tricky, involving about sixteen
28099 additional multiplications and divisions.
28100
28101 The present implementation is highly portable, but slow; it avoids
28102 multiplication and division except in the initial stage. But since it is
28103 not part of \TeX\ inner loop, it doesn't matter.
28104
28105 @<Declare \Prote\ arithmetic routines@>=
28106 static mpfract make_mpfract(int @!p, int @!q)
28107 {@+int @!f; /*the fraction bits, with a leading 1 bit*/
28108 int @!n; /*the integer part of $\vert p/q\vert$*/
28109 bool @!negative; /*should the result be negated?*/
28110 int @!be_careful; /*disables certain compiler optimizations*/
28111 if (p >= 0) negative=false;
28112 else{@+negate(p);negative=true;
28113 }
28114 if (q <= 0)
28115 {
28116 #ifdef @!DEBUG
28117 if (q==0) confusion("/");@;
28118 #endif
28119 @;@/
28120 @:this can't happen /}{\quad \./@>
28121 negate(q);negative=!negative;
28122 }
28123 n=p/q;p=p%q;
28124 if (n >= 8)
28125 {@+arith_error=true;
28126 if (negative) return-el_gordo;@+else return el_gordo;
28127 }
28128 else{@+n=(n-1)*mpfract_one;
28129 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>;
28130 if (negative) return-(f+n);@+else return f+n;
28131 }
28132 }
28133
28134 @ The |@/do@+{| loop here preserves the following invariant relations
28135 between |f|, |p|, and~|q|:
28136 (i)~|0 <= p < q|; (ii)~$fq+p=2^k(q+p_0)$, where $k$ is an integer and
28137 $p_0$ is the original value of~$p$.
28138
28139 Notice that the computation specifies
28140 |(p-q)+p| instead of |(p+p)-q|, because the latter could overflow.
28141 Let us hope that optimizing compilers do not miss this point; a
28142 special variable |be_careful| is used to emphasize the necessary
28143 order of computation. Optimizing compilers should keep |be_careful|
28144 in a register, not store it in memory.
28145 @^inner loop@>
28146
28147 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>=
28148 f=1;
28149 @/do@+{be_careful=p-q;p=be_careful+p;
28150 if (p >= 0) f=f+f+1;
28151 else{@+double(f);p=p+q;
28152 }
28153 }@+ while (!(f >= mpfract_one));
28154 be_careful=p-q;
28155 if (be_careful+p >= 0) incr(f)
28156
28157 @ The dual of |make_mpfract| is |take_mpfract|, which multiplies a
28158 given integer~|q| by a fraction~|f|. When the operands are positive, it
28159 computes $p=\lfloor qf/2^{28}+{1\over2}\rfloor$, a symmetric function
28160 of |q| and~|f|.
28161
28162 @<Declare \Prote\ arithmetic routines@>=
28163 static int take_mpfract(int @!q, mpfract @!f)
28164 {@+int @!p; /*the fraction so far*/
28165 bool @!negative; /*should the result be negated?*/
28166 int @!n; /*additional multiple of $q$*/
28167 int @!be_careful; /*disables certain compiler optimizations*/
28168 @<Reduce to the case that |f>=0| and |q>0|@>;
28169 if (f < mpfract_one) n=0;
28170 else{@+n=f/mpfract_one;f=f%mpfract_one;
28171 if (q <= el_gordo/n) n=n*q;
28172 else{@+arith_error=true;n=el_gordo;
28173 }
28174 }
28175 f=f+mpfract_one;
28176 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>;
28177 be_careful=n-el_gordo;
28178 if (be_careful+p > 0)
28179 {@+arith_error=true;n=el_gordo-p;
28180 }
28181 if (negative) return-(n+p);
28182 else return n+p;
28183 }
28184
28185 @ @<Reduce to the case that |f>=0| and |q>0|@>=
28186 if (f >= 0) negative=false;
28187 else{@+negate(f);negative=true;
28188 }
28189 if (q < 0)
28190 {@+negate(q);negative=!negative;
28191 }
28192
28193 @ The invariant relations in this case are (i)~$\lfloor(qf+p)/2^k\rfloor
28194 =\lfloor qf_0/2^{28}+{1\over2}\rfloor$, where $k$ is an integer and
28195 $f_0$ is the original value of~$f$; (ii)~$2^k\L f<2^{k+1}$.
28196 @^inner loop@>
28197
28198 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>=
28199 p=mpfract_half; /*that's $2^{27}$; the invariants hold now with $k=28$*/
28200 if (q < mpfract_four)
28201 @/do@+{if (odd(f)) p=halfp(p+q);@+else p=halfp(p);
28202 f=halfp(f);
28203 }@+ while (!(f==1));
28204 else@/do@+{if (odd(f)) p=p+halfp(q-p);@+else p=halfp(p);
28205 f=halfp(f);
28206 }@+ while (!(f==1))
28207
28208 @ There's an auxiliary array |randoms| that contains 55 pseudo-random
28209 fractions. Using the recurrence $x_n=(x_{n-55}-x_{n-31})\bmod 2^{28}$,
28210 we generate batches of 55 new $x_n$'s at a time by calling |new_randoms|.
28211 The global variable |j_random| tells which element has most recently
28212 been consumed.
28213
28214 @<Glob...@>=
28215 static mpfract @!randoms[55]; /*the last 55 random values generated*/
28216 static int @!j_random; /*the number of unused |randoms|*/
28217
28218 @ This array of pseudo-random numbers is set starting from a seed value,
28219 that is kept in the global integer |random_seed|.
28220
28221 @<Global...@>=
28222 static int @!random_seed; /*seed for pseudo-random number generation*/
28223
28224 @ @<Generate all \Prote\ primitives@>=
28225 primitive("randomseed", last_item, random_seed_code);@/
28226 @!@:randomseed\_}{\.{\\randomseed} primitive@>
28227
28228 @ @<Cases of |last_item| for |print_cmd_chr|@>=
28229 case random_seed_code: print_esc("randomseed");@+break;
28230
28231 @ @<Cases for fetching a \Prote\ int value@>=
28232 case random_seed_code: cur_val=random_seed;@+break;
28233
28234 @ We set the initial value from the system time. System integrators
28235 could provide a better source of pseudo-randomness.
28236
28237 Every time a new seed value is assigned, the array has to be
28238 regenerated for consumption by routines explained a little later.
28239
28240 @<\Prote\ initializations@>=
28241 random_seed=sys_time;
28242 init_randoms();
28243
28244 @ Since changing the value must trigger the redefinition of the array,
28245 a dedicated primitive is defined to take the new seed and call
28246 |init_randoms|.
28247
28248 @<Generate all \Prote\ primitives@>=
28249 primitive("setrandomseed", convert, set_random_seed_code);@/
28250 @!@:setrandomseed\_}{\.{\\setrandomseed} primitive@>
28251
28252 @ @<Cases of |convert| for |print_cmd_chr|@>=
28253 case set_random_seed_code: print_esc("setrandomseed");@+break;
28254
28255 @ Once we have retrieved and redefined |random_seed|, we must regenerate
28256 the |randoms| array.
28257
28258 @<Cases of `Scan the argument for command |c|'@>=
28259 case set_random_seed_code: {@+scan_int();random_seed=cur_val;
28260 init_randoms();
28261 } @+break;
28262
28263 @ @<Cases of `Print the result of command |c|'@>=
28264 case set_random_seed_code: print_int(random_seed);@+break;
28265
28266 @ To consume a random fraction, the program below will say `|next_random|'
28267 and then it will fetch |randoms[j_random]|.
28268
28269 @d next_random if (j_random==0) new_randoms();
28270 else decr(j_random)
28271
28272 @<Declare \Prote\ arithmetic routines@>=
28273 static void new_randoms(void)
28274 {@+int @!k; /*index into |randoms|*/
28275 int @!x; /*accumulator*/
28276 for (k=0; k<=23; k++)
28277 {@+x=randoms[k]-randoms[k+31];
28278 if (x < 0) x=x+mpfract_one;
28279 randoms[k]=x;
28280 }
28281 for (k=24; k<=54; k++)
28282 {@+x=randoms[k]-randoms[k-24];
28283 if (x < 0) x=x+mpfract_one;
28284 randoms[k]=x;
28285 }
28286 j_random=54;
28287 }
28288
28289 @ To initialize the |randoms| table, we call the following routine.
28290
28291 @<Declare \Prote\ arithmetic routines@>=
28292 static void init_randoms(void)
28293 {@+mpfract @!j, @!jj, @!k; /*more or less random integers*/
28294 int @!i; /*index into |randoms|*/
28295 j=abs(random_seed);
28296 while (j >= mpfract_one) j=halfp(j);
28297 k=1;
28298 for (i=0; i<=54; i++)
28299 {@+jj=k;k=j-k;j=jj;
28300 if (k < 0) k=k+mpfract_one;
28301 randoms[(i*21)%55]=j;
28302 }
28303 new_randoms();new_randoms();new_randoms(); /*``warm up'' the array*/
28304 }
28305
28306 @ To produce a uniform random number in the range |0 <= u < x| or |0 >= u > x|
28307 or |0==u==x|, given a |scaled| value~|x|, we proceed as shown here.
28308
28309 Note that the call of |mult_integers| will produce the values 0 and~|x|
28310 with about half the probability that it will produce any other particular
28311 values between 0 and~|x|, because it rounds its answers.
28312
28313 @<Declare \Prote\ arithmetic routines@>=
28314 static scaled unif_rand(scaled @!x)
28315 {@+scaled @!y; /*trial value*/
28316 next_random;y=take_mpfract(abs(x), randoms[j_random]);
28317 if (y==abs(x)) return 0;
28318 else if (x > 0) return y;
28319 else return-y;
28320 }
28321
28322 @ This can be used by calling the following primitive.
28323
28324 @<Generate all \Prote\ primitives@>=
28325 primitive("uniformdeviate", convert, uniform_deviate_code);@/
28326 @!@:uniformdeviate\_}{\.{\\uniformdeviate} primitive@>
28327
28328 @ @<Cases of |convert| for |print_cmd_chr|@>=
28329 case uniform_deviate_code: print_esc("uniformdeviate");@+break;
28330
28331 @ It takes one integer argument obviously that will be the argument
28332 to the function.
28333
28334 @<Cases of `Scan the argument for command |c|'@>=
28335 case uniform_deviate_code: {@+scan_int();
28336 cur_val=unif_rand(cur_val);
28337 } @+break;
28338
28339 @ @<Cases of `Print the result of command |c|'@>=
28340 case uniform_deviate_code: print_int(cur_val);@+break;
28341
28342 @ The following somewhat different subroutine tests rigorously if $ab$ is
28343 greater than, equal to, or less than~$cd$,
28344 given integers $(a,b,c,d)$. In most cases a quick decision is reached.
28345 The result is $+1$, 0, or~$-1$ in the three respective cases.
28346
28347 @d return_sign(A) {@+return A;
28348 }
28349
28350 @<Declare \Prote\ arithmetic routines@>=
28351 static int ab_vs_cd(int @!a, int b, int c, int d)
28352 {@+
28353 int @!q, @!r; /*temporary registers*/
28354 @<Reduce to the case that |a,c>=0|, |b,d>0|@>;
28355 loop@+{@+q=a/d;r=c/b;
28356 if (q!=r)
28357 if (q > r) return_sign(1)@;@+else return_sign(-1);
28358 q=a%d;r=c%b;
28359 if (r==0)
28360 if (q==0) return_sign(0)@;@+else return_sign(1);
28361 if (q==0) return_sign(-1);
28362 a=b;b=q;c=d;d=r;
28363 } /*now |a > d > 0| and |c > b > 0|*/
28364 }
28365
28366 @ @<Reduce to the case that |a...@>=
28367 if (a < 0)
28368 {@+negate(a);negate(b);
28369 }
28370 if (c < 0)
28371 {@+negate(c);negate(d);
28372 }
28373 if (d <= 0)
28374 {@+if (b >= 0)
28375 if (((a==0)||(b==0))&&((c==0)||(d==0))) return_sign(0)@;
28376 else return_sign(1);
28377 if (d==0)
28378 if (a==0) return_sign(0)@;@+else return_sign(-1);
28379 q=a;a=c;c=q;q=-b;b=-d;d=q;
28380 }
28381 else if (b <= 0)
28382 {@+if (b < 0) if (a > 0) return_sign(-1);
28383 if (c==0) return_sign(0)@;else return_sign(-1);
28384 }
28385
28386 @ Finally, a normal deviate with mean zero and unit standard deviation
28387 can readily be obtained with the ratio method (Algorithm 3.4.1R in
28388 {\sl The Art of Computer Programming\/}).
28389
28390 @<Declare \Prote\ arithmetic routines@>=
28391 static scaled norm_rand(void)
28392 {@+int @!x, @!u, @!l; /*what the book would call $2^{16}X$, $2^{28}U$,
28393 and $-2^{24}\ln U$*/
28394 @/do@+{
28395 @/do@+{next_random;
28396 x=take_mpfract(112429, randoms[j_random]-mpfract_half);
28397 /*$2^{16}\sqrt{8/e}\approx 112428.82793$*/
28398 next_random;u=randoms[j_random];
28399 }@+ while (!(abs(x) < u));
28400 x=make_mpfract(x, u);
28401 l=139548960-m_log(u); /*$2^{24}\cdot12\ln2\approx139548959.6165$*/
28402 }@+ while (!(ab_vs_cd(1024, l, x, x) >= 0));
28403 return x;
28404 }
28405
28406 @ This can be used by calling the following primitive.
28407
28408 @<Generate all \Prote\ primitives@>=
28409 primitive("normaldeviate", convert, normal_deviate_code);@/
28410 @!@:normaldeviate\_}{\.{\\normaldeviate} primitive@>
28411
28412 @ @<Cases of |convert| for |print_cmd_chr|@>=
28413 case normal_deviate_code: print_esc("normaldeviate");
28414
28415 @ @<Cases of `Scan the argument for command |c|'@>=
28416 case normal_deviate_code: cur_val=norm_rand();
28417
28418 @ @<Cases of `Print the result of command |c|'@>=
28419 case normal_deviate_code: print_int(cur_val);
28420
28421 @*1 DVI related primitives.
28422
28423 @ But the paper size is not specified in the DVI file and is not being
28424 dealt with by \TeX.
28425
28426 In order to have a common reference point, and since the \.{\\lastxpos}
28427 and \.{\\lastypos} primitives originated in pdf\TeX, these two
28428 primitives give positions, in scaled points, relative to the lower left
28429 corner of the paper.
28430
28431 Hence the need, for these primitive, to define the paper size, with the
28432 (misnamed) \.{\\pagewidth} and \.{\\pageheight}.
28433
28434 \.{\\pagewidth} and \.{\\pageheight} are dimension parameters,
28435 initialized to $0$ by the generic \TeX\ code.
28436
28437 @<Generate all \Prote\ primitives@>=
28438 primitive("pagewidth", assign_dimen, dimen_base+page_width_code);@/
28439 @!@:pagewidth\_}{\.{\\pagewidth} primitive@>
28440 primitive("pageheight", assign_dimen, dimen_base+page_height_code);@/
28441 @!@:pageheight\_}{\.{\\pageheight} primitive@>
28442
28443 @ When instructed to, the \.{h} and \.{v} last values are transformed,
28444 in the coordinates system defined above and saved in the global
28445 variables |last_saved_xpos| and |last_saved_ypos|. They are
28446 initialized to $0$ and we do not make any verification that a
28447 call to the \.{\\savepos} primitive---to come---has been made before
28448 retrieving their values.
28449
28450 @<Global...@>=
28451 static scaled @!last_saved_xpos, last_saved_ypos; /*last (x,y) DVI pos saved*/
28452
28453 @ @<\Prote\ initializations@>=
28454 last_saved_xpos=0;last_saved_ypos=0;
28455
28456 @ @<Generate all \Prote\ primitives@>=
28457 primitive("lastxpos", last_item, last_xpos_code);@/
28458 @!@:lastxpos\_}{\.{\\lastxpos} primitive@>
28459 primitive("lastypos", last_item, last_ypos_code);@/
28460 @!@:lastypos\_}{\.{\\lastypos} primitive@>
28461
28462 @ @<Cases of |last_item| for |print_cmd_chr|@>=
28463 case last_xpos_code: print_esc("lastxpos");@+break;
28464 case last_ypos_code: print_esc("lastypos");@+break;
28465
28466 @ @<Cases for fetching a \Prote\ int value@>=
28467 case last_xpos_code: cur_val=last_saved_xpos;@+break;
28468 case last_ypos_code: cur_val=last_saved_ypos;
28469
28470 @ |last_saved_xpos| and |last_saved_ypos| are only defined when
28471 instructed to by the call to the \.{\\savepos} primitive. Since the
28472 real work has to be done at \.{shipout} time, it is a case to be treated
28473 like the \.{\\special} primitive, that is it belongs to the
28474 \.{extension} class.
28475
28476 We will add something more in the handling of the primitive: it will
28477 insert a \.{whatsit} in the DVI file so that one, using the program
28478 |dvitype|, could retrieve more than one {\it hic}. So there is a counter
28479 incremented whenever the primitive is called.
28480
28481 @<Global...@>=
28482 static int last_save_pos_number; /*identifying the order of the call*/
28483
28484 @ @<\Prote\ initializations@>=
28485 last_save_pos_number=0; /*i.e. none*/
28486
28487 @ @<Generate all \Prote\ primitives@>=
28488 primitive("savepos", extension, save_pos_code);@/
28489 @!@:savepos\_}{\.{\\savepos} primitive@>
28490
28491 @ @<Cases of |extension| for |print_cmd_chr|@>=
28492 case save_pos_code: print_esc("savepos");@+break;
28493
28494 @ @<Cases for |do_extension|@>=
28495 case save_pos_code: @<Implement \.{\\savepos}@>@;@+break;
28496
28497 @ We need the basic two words node, since we don't pass any parameter
28498 and it is just an instruction to do something. So the \.{whatsit} node
28499 is just the call.
28500
28501 @<Implement \.{\\savepos}@>=
28502 {@+new_whatsit(save_pos_code, small_node_size);write_stream(tail)=null;
28503 write_tokens(tail)=null;
28504 }
28505
28506 @ @<Cases for displaying the |whatsit| node@>=
28507 case save_pos_code: print_esc("savepos");@+break;
28508
28509 @ @<Cases for making a partial copy of the whatsit node@>=
28510 case save_pos_code: {@+r=get_node(small_node_size);
28511 words=small_node_size;
28512 } @+break;
28513
28514 @ @<Cases for wiping out the whatsit node@>=
28515 case save_pos_code: free_node(p, small_node_size);@+break;
28516
28517 @* Hi\TeX.
28518 In the following we present macros, variables, and routines that
28519 implement the various features that have been used above to replace
28520 \TeX's native behavior.
28521
28522 @ Following the implementation of other engines,
28523 the new engine returns a version number as an integer
28524 extending the cases for |last_item|. Since the additional
28525 primitives that we define are specific to the \HINT\ format,
28526 we return major and minor version of the \HINT\ file
28527 format that this program will generate.
28528
28529 @d HINT_version_code (eTeX_last_last_item_cmd_mod+7) /* \.{\\HINTversion} */
28530 @d HINT_minor_version_code (eTeX_last_last_item_cmd_mod+8) /* \.{\\HINTminorversion} */
28531
28532 @<Put each...@>=
28533 primitive("HINTversion", last_item, HINT_version_code);
28534 @!@:HINT\_version\_}{\.{\\HINTversion} primitive@>
28535 primitive("HINTminorversion", last_item, HINT_minor_version_code);
28536 @!@:HINT\_minor\_version\_}{\.{\\HINTminorversion} primitive@>
28537
28538
28539 @ Now this new primitive needs its implementation.
28540
28541 @<Cases of |last_item| for |print_cmd_chr|@>=
28542 case HINT_version_code: print_esc("HINTversion");@+break;
28543 case HINT_minor_version_code: print_esc("HINTminorversion");@+break;
28544
28545 @ @<Cases for fetching a \Prote\ int value@>=
28546 case HINT_version_code: cur_val=HINT_VERSION;@+break;
28547 case HINT_minor_version_code: cur_val=HINT_MINOR_VERSION;@+break;
28548
28549
28550 @ The implementation reuses code that has been written as part of
28551 the \HINT\ file format specification; therefore we start with three
28552 include files containing the necessary declarations.
28553
28554 @<Header files and function declarations@>=
28555 #include "hierror.h"
28556 #include "hiformat.h"
28557 #include "hiput.h"
28558
28559 @ @p
28560 @<Hi\TeX\ macros@>@;
28561 @<Hi\TeX\ variables@>@;
28562 @<Hi\TeX\ function declarations@>@;
28563
28564 @<Hi\TeX\ auxiliary routines@>@;
28565
28566 @<Hi\TeX\ routines@>@;
28567
28568 @ This is a list of forward declarations for all the functions
28569 and variables that are used above but are defined below.
28570
28571
28572 @<Forward declarations@>=
28573 static void hout_allocate(void);
28574 static void hint_open(void);
28575 static void hint_close(void);
28576
28577 static void hyphenate_word(void);
28578 static void hline_break(int final_widow_penalty);
28579 static void execute_output(pointer p);
28580 static void hout_node(pointer p);
28581
28582 static int hget_stream_no(int i);
28583 static void hfinish_stream_group(void);
28584 static void hfinish_page_group(void);
28585 static void hfinish_stream_before_group(void);
28586 static void hfinish_stream_after_group(void);
28587 static void hfinish_outline_group(void);
28588
28589
28590 static pointer new_xdimen(scaled w, scaled h, scaled v);
28591 static pointer new_baseline_node(pointer bs, pointer ls, scaled lsl);
28592 static void print_baseline_skip(int i);
28593 static pointer new_set_node(void);
28594 static pointer new_setstream_node(eight_bits n);
28595 static pointer new_setpage_node(eight_bits k, str_number n);
28596 static pointer new_disp_node(void);
28597 static pointer new_image_node(str_number n, str_number a, str_number e);
28598 static void new_param_node(eight_bits t, eight_bits n, int v);
28599
28600
28601 @*1 Creating new whatsit nodes.
28602 The following functions create nodes for paragraphs, displayed equations, baseline skips,
28603 hpack nodes, vpack nodes, hset nodes, and vset nodes.
28604
28605 @<Hi\TeX\ routines@>=
28606 static pointer new_par_node(void)
28607 { @+ pointer p;
28608 p=get_node(par_node_size);
28609 type(p)=whatsit_node;
28610 subtype(p)=par_node;
28611 par_params(p)= par_list(p)= par_extent(p)=null;
28612 depth(p)=0;
28613 return p;
28614 }
28615
28616
28617 static pointer new_disp_node(void)
28618 { @+ pointer p;
28619 p=get_node(disp_node_size);
28620 type(p)=whatsit_node;
28621 subtype(p)=disp_node;
28622 display_params(p)= display_formula(p)= display_eqno(p)=null;
28623 return p;
28624 }
28625
28626 static pointer new_baseline_node(pointer bs, pointer ls, scaled lsl)
28627 { @+pointer p;
28628 p=get_node(baseline_node_size);
28629 type(p)=whatsit_node;
28630 subtype(p)=baseline_node;
28631 baseline_node_no(p)=hget_baseline_no(bs, ls, lsl);
28632 return p;
28633 }
28634
28635 static pointer new_pack_node(void)
28636 { @+pointer p;
28637 p=get_node(pack_node_size);
28638 type(p)=whatsit_node;
28639 subtype(p)=hpack_node;
28640 width(p)=depth(p)=height(p)=shift_amount(p)=0;
28641 pack_limit(p)=max_dimen;
28642 pack_extent(p)= list_ptr(p)=null;
28643 return p;
28644 }
28645
28646 static pointer new_set_node(void)
28647 { @+pointer p;
28648 p=get_node(set_node_size);
28649 type(p)=whatsit_node;
28650 subtype(p)=hset_node;
28651 width(p)=depth(p)=height(p)=shift_amount(p)=set_stretch(p)=set_shrink(p)=0;
28652 set_extent(p)= list_ptr(p)=null;
28653 return p;
28654 }
28655
28656
28657 @ When creating a new image node, we could use the |kpse_find_tex|
28658 function to get image files from the same directory, where we also
28659 get the \TeX\ input files. Here we use the simpler method from plain \TeX.
28660
28661 @<Hi\TeX\ routines@>=
28662 static pointer new_image_node( str_number n, str_number a, str_number e)
28663 { pointer p;
28664 int i;
28665 char *fn;
28666
28667 p=get_node(image_node_size);type(p)=whatsit_node;subtype(p)=image_node;
28668 image_name(p)=n;
28669 image_area(p)=a;
28670 image_ext(p)=e;
28671 fn=hfile_name(n,a,e);
28672 i=hnew_file_section(fn);
28673 image_no(p)=i;
28674 image_xwidth(p)=image_xheight(p)=image_alt(p)=null;
28675 image_aspect(p)=0;
28676 return p;
28677 }
28678
28679 @*1 Creating parameter nodes.
28680 The |new_param_node| function
28681 adds parameter nodes to the current list.
28682 It should be possible to check the parameter values against those
28683 stored in the definition section and remove the ones that
28684 are unchanged. It would make the parameter lists shorter, saving
28685 some time when setting and restoring them later.
28686 There is probably not much savings in memory space, because
28687 most of the time a reference number is found for the parameter list.
28688
28689
28690 @<Hi\TeX\ routines@>=
28691 static void new_param_node(uint8_t t, uint8_t n, int v)
28692 { @+pointer p;
28693 @<Create the parameter node@>@;
28694 @<Initialize the parameter node@>@;
28695 link(p)=link(temp_head);
28696 link(temp_head)=p;
28697 }
28698
28699 @ @<Create the parameter node@>=
28700 p=get_node(param_node_size);
28701 type(p)=whatsit_node;
28702 subtype(p)=param_node;
28703 param_type(p)=t;
28704 param_no(p)=n;
28705
28706 @ @<Initialize the parameter node@>=
28707 if (t==int_type) param_value(p).i=v;
28708 else if (t==dimen_type) param_value(p).sc=v;
28709 else if (t==glue_type)
28710 {@+ param_value(p).i=v;add_glue_ref(param_value(p).i); @+}
28711 else
28712 { free_node(p, param_node_size);
28713 QUIT("Undefined parameter type %d",t);
28714 }
28715
28716 @*1 Hyphenation.
28717 While the breaking of a paragraph into lines must be postponed because
28718 {\tt hsize} is not known, hyphenation should be done as part of Hi\TeX\
28719 because we want to keep hyphenation out of the viewer. Therefore
28720 Hi\TeX\ will do hyphenation for all words within a paragraph.
28721
28722 There is a fine point to observe here: \TeX\ will consider a word as
28723 a candidate for automatic hyphenation only if the world ``follows'' after a
28724 glue. (For the exact rules, see Appendix H of the \TeX-book.)
28725 As a consequence, \TeX\ usually does not submit the first word of a
28726 paragraph to its hyphenation routine.
28727 Viewing paragraphs that start with a lengthy word on a narrow display
28728 therefore often look more unsightly than necessary: the long word sticks out
28729 into the right margin as much as it can. To remedy this situation,
28730 Hi\TeX\ has a ``{\tt [-no]-hyphenate-first-word}'' option.
28731 If set, which is the default, Hi\TeX\ will deviate from
28732 \TeX's rules and submit the first word of a paragraph
28733 to the hyphenation algorithm.
28734
28735 The next problem arises from \TeX's multipass approach to line breaking
28736 and the attempt to have Hi\TeX\ choose exactly the same line breaks as
28737 \TeX\ does:
28738 \TeX\ distinguishes between discretionary breaks inserted by the author of a
28739 text, and discretionary breaks discovered by the hyphenation routine.
28740 The latter, called here ``automatic'', are used only in pass two and three
28741 of the line breaking routine.
28742
28743 The function |hline_break| follows:
28744
28745
28746 @<Hi\TeX\ routines@>=
28747 static void hline_break(int final_widow_penalty)
28748 {@+ bool auto_breaking; /*is node |cur_p| outside a formula?*/
28749 pointer r, s ; /*miscellaneous nodes of temporary interest*/
28750 pointer pp;
28751 scaled par_max_depth=0;
28752 bool par_shape_fix=false;
28753 @<initialize the color stack@>@,
28754 #ifdef DEBUG
28755 if (DBGTEX&debugflags)
28756 { print_ln();print("Before hline_break:\n");
28757 breadth_max=200;
28758 depth_threshold=200;
28759 show_node_list(link(head));print_ln();
28760 }
28761 #endif
28762 if (dimen_par_hfactor(hsize_code)==0 && dimen_par_vfactor(hsize_code)==0)
28763 { line_break(final_widow_penalty); /* the easy case */
28764 return;
28765 }
28766 /* Get ready to start line breaking */
28767 pp=new_par_node();
28768 par_penalty(pp)=final_widow_penalty;
28769 if(par_shape_ptr==null)
28770 par_extent(pp)=new_xdimen(dimen_par(hsize_code),
28771 dimen_par_hfactor(hsize_code),dimen_par_vfactor(hsize_code));
28772 else
28773 @<fix simple use of parshape@>@;
28774 link(temp_head)=link(head);
28775 if (is_char_node(tail))
28776 { tail_append(new_penalty(inf_penalty))@;
28777 tail_append(new_param_glue(par_fill_skip_code));
28778 }
28779 else if (type(tail)!=whatsit_node || subtype(tail)!=disp_node)
28780 { if (type(tail)!=glue_node) tail_append(new_penalty(inf_penalty))@;
28781 else
28782 {@+type(tail)=penalty_node;delete_glue_ref(glue_ptr(tail));
28783 flush_node_list(leader_ptr(tail));penalty(tail)=inf_penalty;
28784 }
28785 link(tail)=new_param_glue(par_fill_skip_code);
28786 }
28787 DBG(DBGTEX,"\nCalling line_break:\n"
28788 "hang_indent=0x%08X hang_after=%d",hang_indent,hang_after);
28789 if (line_skip_limit!=0)
28790 DBG(DBGTEX," line_skip_limit=0x%08X",line_skip_limit);
28791 DBG(DBGTEX," prev_graf=0x%08X",prev_graf);
28792
28793 init_cur_lang=prev_graf%0200000;
28794 init_l_hyf=prev_graf/020000000;
28795 init_r_hyf=(prev_graf/0200000)%0100;
28796 pop_nest();
28797 DBG(DBGTEX," prev_graf=0x%08X",prev_graf);
28798
28799 /* Initialize for hyphenating...*/
28800 #ifdef INIT
28801 if (trie_not_ready) init_trie();
28802 #endif
28803 cur_lang=init_cur_lang;l_hyf=init_l_hyf;r_hyf=init_r_hyf;
28804 if (DBGTEX&debugflags)
28805 { print_ln();print("Before hyphenation:\n");
28806 breadth_max=200;
28807 depth_threshold=200;
28808 show_node_list(link(temp_head));print_ln();
28809 }
28810 auto_breaking=true;
28811 if (option_hyphen_first && is_char_node(link(temp_head)))
28812 { pointer p = new_glue(zero_glue);
28813 link(p)=link(temp_head);
28814 link(temp_head) =p;
28815 }
28816 cur_p=link(temp_head);
28817 while (cur_p!=null)
28818 { /*Call |try_break| if |cur_p| is a legal breakpoint...*/
28819 if (is_char_node(cur_p))
28820 { /* Advance |cur_p| to the node following the present string...*/
28821 do { int f=font(cur_p);
28822 scaled d = char_depth(f,character(cur_p));
28823 if (d>par_max_depth) par_max_depth=d;
28824 cur_p=link(cur_p);
28825 } while (is_char_node(cur_p));
28826 if (cur_p==null) goto done5; /* mr: no glue and penalty at the end */
28827 }
28828 switch (type(cur_p))
28829 { case whatsit_node:
28830 { pointer p=cur_p; /* reusing code written for |p| */
28831 switch (subtype(cur_p))
28832 { @<cases that flatten the color stack@>
28833 default: adv_past(cur_p); break;
28834 }
28835 break;
28836 }
28837 case glue_node:
28838 if (auto_breaking) /* Try to hyphenate the following word*/
28839 hyphenate_word();
28840 break;
28841 case ligature_node:
28842 break;
28843 case disc_node:
28844 /* Try to break after a discretionary fragment...*/
28845 r=replace_count(cur_p);s=link(cur_p);
28846 while (r > 0)
28847 { decr(r);s=link(s);
28848 }
28849 cur_p=s;
28850 goto done5;
28851 case math_node:
28852 auto_breaking=(subtype(cur_p)==after);
28853 break;
28854 case hlist_node: case vlist_node:
28855 if (depth(cur_p)>par_max_depth) par_max_depth=depth(cur_p);
28856 break;
28857 default:
28858 break;
28859 }
28860 cur_p=link(cur_p);
28861 done5:;
28862 }
28863 if (DBGTEX&debugflags)
28864 { print_ln();print("After hline_break:\n");
28865 breadth_max=200;
28866 depth_threshold=200;
28867 show_node_list(link(temp_head));print_ln();
28868 }
28869 depth(pp)=par_max_depth;
28870 par_list(pp)=link(temp_head);
28871 /* adding parameter nodes */
28872 link(temp_head)=null;
28873
28874 new_param_node(int_type,pretolerance_code,pretolerance);
28875 new_param_node(int_type,tolerance_code,tolerance);
28876 new_param_node(dimen_type,emergency_stretch_code,emergency_stretch);
28877
28878 new_param_node(int_type,line_penalty_code,line_penalty);
28879 new_param_node(int_type,hyphen_penalty_code,hyphen_penalty);
28880 new_param_node(int_type,ex_hyphen_penalty_code,ex_hyphen_penalty);
28881 new_param_node(int_type,club_penalty_code,club_penalty);
28882 new_param_node(int_type,widow_penalty_code,widow_penalty);
28883 new_param_node(int_type,broken_penalty_code,broken_penalty);
28884 new_param_node(int_type,inter_line_penalty_code,inter_line_penalty);
28885 new_param_node(int_type,double_hyphen_demerits_code,double_hyphen_demerits);
28886 new_param_node(int_type,final_hyphen_demerits_code,final_hyphen_demerits);
28887 new_param_node(int_type,adj_demerits_code,adj_demerits);
28888 new_param_node(int_type,looseness_code,looseness);
28889
28890 if (par_shape_fix)
28891 { new_param_node(int_type,hang_after_code,0);
28892 new_param_node(dimen_type,hang_indent_code,second_indent);
28893 }
28894 else
28895 { new_param_node(int_type,hang_after_code,hang_after);
28896 new_param_node(dimen_type,hang_indent_code, hang_indent);
28897 }
28898
28899 new_param_node(dimen_type,line_skip_limit_code,line_skip_limit);
28900 new_param_node(glue_type,line_skip_code,line_skip);
28901 new_param_node(glue_type,baseline_skip_code,baseline_skip);
28902
28903 new_param_node(glue_type,left_skip_code,left_skip);
28904 new_param_node(glue_type,right_skip_code,right_skip);
28905 new_param_node(glue_type,par_fill_skip_code,par_fill_skip);
28906
28907
28908 /* |par_shape| is not yet supported */
28909 par_params(pp)=link(temp_head);
28910 link(temp_head)=null;
28911 append_to_vlist(pp);
28912 }
28913
28914 @ Currently Hi\TeX\ dos not implement the parshape feature of \TeX.
28915 The implementation of {\tt \BS list} in \LaTeX\ does, however, depend
28916 on a simple use of parshape where all lines have the same length
28917 and indentation. We cover this special case be using a hanging
28918 indentation and adjusting the paragraph width by the difference
28919 of the normal {\tt \BS hsize} and the given length.
28920
28921 @<fix simple use of parshape@>=
28922 { last_special_line= info(par_shape_ptr)-1;
28923 if (last_special_line!=0)
28924 DBG(DBGTEX,"Warning parshape with n=%d not yet implemented",info(par_shape_ptr));
28925 second_width= mem[par_shape_ptr+2*(last_special_line+1)].sc;
28926 second_indent= mem[par_shape_ptr+2*last_special_line+1].sc;
28927
28928 par_extent(pp)=new_xdimen(second_indent+second_width,
28929 par_shape_hfactor,par_shape_vfactor);
28930 second_width=second_width+ round((double)par_shape_hfactor*hhsize/unity
28931 +(double)par_shape_vfactor*hvsize/unity);
28932 par_shape_fix=true;
28933 }
28934
28935 @*1 Colors.
28936 Hi\TeX\ adds these primitives to handle colors:
28937
28938 @<Put each...@>=
28939 primitive("HINTcolor", extension, color_node);@/
28940 @!@:HINTcolor\_}{\.{\\HINTcolor} primitive@>
28941 primitive("HINTendcolor", extension, end_color_node);@/
28942 @!@:HINTendcolor\_}{\.{\\HINTendcolor} primitive@>
28943 primitive("HINTdefaultcolor", extension, default_color_node);@/
28944 @!@:HINTdefaultcolor\_}{\.{\\HINTdefaultcolor} primitive@>
28945 primitive("HINTlinkcolor", extension, link_color_node);@/
28946 @!@:HINTlinkcolor\_}{\.{\\HINTlinkcolor} primitive@>
28947 primitive("HINTdefaultlinkcolor", extension, default_link_color_node);@/
28948 @!@:HINTdefaultlinkcolor\_}{\.{\\HINTdefaultlinkcolor} primitive@>
28949
28950 @ To begin with the implementation,
28951 we need the function |scan_scaled| which is a simpler version of |scan_dimen|.
28952 It will just scan a pure number without any units.
28953 We need this function to scan colors.
28954
28955 @<Declare procedures needed in |do_extension|@>=
28956 static void scan_scaled(void)
28957 {@+
28958 bool negative=false; /*should the answer be negated?*/
28959 int @!f; /*numerator of a fraction whose denominator is $2^{16}$*/
28960 int @!k, @!kk; /*number of digits in a decimal fraction*/
28961 pointer @!p, @!q; /*top of decimal digit stack*/
28962 f=0;arith_error=false;cur_order=normal;negative=false;
28963 @<Get the next non-blank non-call token@>;
28964 if (cur_tok==other_token+'-') negative=true;
28965 else if (cur_tok==other_token+'+') negative=false;
28966 else back_input();
28967 if (cur_tok==continental_point_token) cur_tok=point_token;
28968 if (cur_tok!=point_token) scan_int();
28969 else {@+radix=10;cur_val=0; }
28970 if (cur_tok==continental_point_token) cur_tok=point_token;
28971 if ((radix==10)&&(cur_tok==point_token)) @<Scan decimal fraction@>;
28972 if (cur_val < 0) /*in this case |f==0|*/
28973 {@+negative=!negative;negate(cur_val);}
28974 if (cur_val >= 040000) arith_error=true;
28975 else cur_val=cur_val*unity+f;
28976 @<Scan an optional space@>;
28977 if (arith_error||(abs(cur_val) >= 010000000000))
28978 @<Report that this dimension is out of range@>;
28979 if (negative) negate(cur_val);
28980 }
28981
28982 @ A color specification starting with ``FG'' or ``BG'' expects
28983 integers in the range 0 to |0xFF|;
28984 a color specification starting with ``fg'' or ``bg'' expects
28985 real numbers in the range 0 to 1.
28986 The last component for the alpha value is optional and its default value is |0xFF| respectively 1.0.
28987 The color components are enclosed in braces.
28988 After the initial brace the keyword \.{rgb} specifies color values encoded with red/green/blue/alpha values;
28989 the keyword \.{cmyk} specifies color values encoded with cyan/magenta/yellow/black/alpha values.
28990 Giving no keyword is equivalent to giving the keyword \.{rgb}.
28991
28992 @<Declare procedures needed in |do_extension|@>=
28993 static uint8_t scan_rgb_component(bool expect_reals)
28994 { if (expect_reals)
28995 { scan_scaled(); cur_val=(cur_val*0xFF+0x1000)>>16; }
28996 else
28997 scan_int();
28998 if (cur_val>0xFF) return 0xFF;
28999 else if (cur_val<0) return 0x00;
29000 else return cur_val;
29001 }
29002
29003 static uint32_t scan_rgb_color(bool expect_reals)
29004 { uint8_t r,g,b,a;
29005 r=scan_rgb_component(expect_reals);
29006 g=scan_rgb_component(expect_reals);
29007 b=scan_rgb_component(expect_reals);
29008 a=0xFF;
29009 @<Get the next non-blank non-relax...@>;
29010 if (cur_cmd!=right_brace)
29011 { back_input();
29012 a=scan_rgb_component(expect_reals);
29013 @<Get the next non-blank non-call token@>;
29014 if (cur_cmd!=right_brace)
29015 { back_input();
29016 print_err("Missing right brace after color definition");
29017 }
29018 }
29019 return (r<<24)|(g<<16)|(b<<8)|a;
29020 }
29021
29022 static double scan_cmyk_component(bool expect_reals)
29023 { double c;
29024 if (expect_reals)
29025 { scan_scaled(); c=cur_val/(double)ONE;
29026 }
29027 else
29028 { scan_int(); c=cur_val/255.0;
29029 }
29030 if (c>1.0) return 1.0;
29031 else if (c<0.0) return 0.0;
29032 else return c;
29033 }
29034
29035
29036 static uint32_t scan_cmyk_color(bool expect_reals)
29037 { uint8_t r,g,b,a;
29038 double c,m,y,k;
29039 c=scan_cmyk_component(expect_reals);
29040 m=scan_cmyk_component(expect_reals);
29041 y=scan_cmyk_component(expect_reals);
29042 k=scan_cmyk_component(expect_reals);
29043 a=0xFF;
29044 @<Get the next non-blank non-relax...@>;
29045 if (cur_cmd!=right_brace)
29046 { back_input();
29047 a=scan_cmyk_component(expect_reals)*0xFF+0.5;
29048 @<Get the next non-blank non-call token@>;
29049 if (cur_cmd!=right_brace)
29050 { back_input();
29051 print_err("Missing right brace after color definition");
29052 }
29053 }
29054 r=(1-c)*(1-k)*255+0.5;
29055 g=(1-m)*(1-k)*255+0.5;
29056 b=(1-y)*(1-k)*255+0.5;
29057 return (r<<24)|(g<<16)|(b<<8)|a;
29058 }
29059
29060 static uint32_t scan_color(bool expect_reals)
29061 { scan_left_brace();
29062 if (scan_keyword("cmyk"))
29063 return scan_cmyk_color(expect_reals);
29064 else if (scan_keyword("rgb"))
29065 return scan_rgb_color(expect_reals);
29066 else
29067 return scan_rgb_color(expect_reals);
29068 }
29069
29070 @ Colors are specified in pairs of a foreground color, prefixed
29071 by ``FG'' or ``fg'', followed by an optional background color
29072 prefixed by ``BG'' or ``bg''.
29073 Up to three color pairs, for normal text, highlighted text, and focus text
29074 make up a color set. A color specification can contain two
29075 color sets the first one for ``day mode'' the second, prefixed
29076 by the keyword ``dark'' for ``night mode''.
29077
29078 @<Declare procedures needed in |do_extension|@>=
29079 static void colorset_copy(ColorSet to, ColorSet from)
29080 { int i;
29081 for (i=0;i<sizeof(ColorSet)/sizeof(uint32_t);i++)
29082 to[i]=from[i];
29083 }
29084
29085 static bool scan_color_pair(ColorSet c, int m, int s)
29086 { if (scan_keyword("FG")) c[m*6+s*2+0] =scan_color(false);
29087 else if (scan_keyword("fg")) c[6*m+2*s+0]=scan_color(true);
29088 else return false;
29089 if (scan_keyword("BG")) c[m*6+s*2+1]=scan_color(false);
29090 else if (scan_keyword("bg")) c[m*6+s*2+1]=scan_color(true);
29091 return true;
29092 }
29093
29094 static void scan_color_triple(ColorSet c, int m)
29095 { if (!scan_color_pair(c,m,0))
29096 { print_err("Missing color specification");
29097 return;
29098 }
29099 if (scan_color_pair(c,m,1)) scan_color_pair(c,m,2);
29100 }
29101
29102 static void scan_color_spec(ColorSet c, int i)
29103 { colorset_copy(c,colors[i]); /* initialize with defaults */
29104 scan_left_brace();
29105 scan_color_triple(c,0);
29106 if (scan_keyword("dark")) scan_color_triple(c,1);
29107 @<Get the next non-blank non-relax non-call token@>;
29108 if (cur_cmd!=right_brace)
29109 {@+print_err("A color specification must end with }");
29110 back_error();
29111 }
29112 }
29113
29114 @ We store color sets in a dynamic array
29115
29116 @<Forward declarations@>=
29117 static ColorSet *colors=NULL;
29118 static int max_color=-1, colors_allocated=0;
29119 static bool default_color_frozen=false, default_link_color_frozen=false;
29120 static int cur_link_color=1;
29121 static int next_colorset(ColorSet c);
29122
29123 @ @<Hi\TeX\ auxiliary routines@>=
29124 static bool colorset_equal(ColorSet old, ColorSet new)
29125 { int i;
29126 for (i=0;i<sizeof(ColorSet)/sizeof(uint32_t);i++)
29127 if (old[i]!=new[i]) return false;
29128 return true;
29129 }
29130
29131
29132 static int next_colorset(ColorSet c)
29133 { int i;
29134 for (i=0; i<=max_color; i++)
29135 if (colorset_equal(colors[i],c)) return i;
29136 if (max_color<0xFF) max_ref[color_kind]=++max_color;
29137 else overflow("colors",0xFF);
29138 if (max_color>=colors_allocated)
29139 RESIZE(colors,colors_allocated,ColorSet);
29140 colorset_copy(colors[max_color],c);
29141 #ifdef DEBUG
29142 if (debugflags&DBGDEF)
29143 { print_nl("HINT Defining new color "); print_int(max_color);print(": ");
29144 print_color_spec(max_color); }
29145 #endif
29146 return max_color;
29147 }
29148
29149 @ @<Initialize definitions for colors@>=
29150 colors_allocated=8;
29151 ALLOCATE(colors,colors_allocated,ColorSet);
29152 max_ref[color_kind]=max_color=MAX_COLOR_DEFAULT;
29153 memcpy(colors,color_defaults,sizeof(ColorSet)*(max_color+1));
29154
29155
29156 @ Next we implement a procedure to print a color specification.
29157
29158 @ @<Hi\TeX\ auxiliary routines@>=
29159 #ifdef DEBUG
29160 static bool is_default_color_pair(ColorSet c, int m, int s)
29161 { return c[6*m+2*s] == colors[0][6*m+2*s]
29162 && c[6*m+2*s+1] == colors[0][6*m+2*s+1];
29163 }
29164
29165 static void print_color(uint32_t c)
29166 { print_char('{');
29167 print_hex((c>>24)&0xFF);print_char(' ');
29168 print_hex((c>>16)&0xFF);print_char(' ');
29169 print_hex((c>>8)&0xFF);print_char(' ');
29170 if ((c&0xFF)!=0xFF) print_hex(c&0xFF);
29171 print_char('}');
29172 }
29173
29174 static void print_color_pair(ColorSet c, int m, int s)
29175 { print("FG"); print_color(c[6*m+2*s+0]);
29176 print(" BG"); print_color(c[6*m+2*s+1]);
29177 }
29178
29179 static void print_color_triple(ColorSet c, int m)
29180 { bool diff_high, diff_focus;
29181 print_color_pair(c,m,0);
29182 diff_high= is_default_color_pair(c,m,1);
29183 diff_focus= is_default_color_pair(c,m,2);
29184 if (diff_high || diff_focus)
29185 { print_char(' '); print_color_pair(c,m,1); }
29186 if (diff_focus)
29187 { print_char(' '); print_color_pair(c,m,2); }
29188 }
29189
29190
29191 static void print_color_spec(int i)
29192 { if (i>max_color) {print("undefined color "); print_int(i);}
29193 else if (i<0 || i>0xFF) { print("illegal color "); print_int(i);}
29194 else
29195 { print_color_triple(colors[i],0);
29196 if (is_default_color_pair(colors[i],1,0) &&
29197 is_default_color_pair(colors[i],1,1) &&
29198 is_default_color_pair(colors[i],1,2))
29199 return;
29200 print(" dark "); print_color_triple(colors[i],1);
29201 }
29202 }
29203 #endif
29204
29205 @ To create a color node you can use the following function:
29206 @<Hi\TeX\ auxiliary routines@>=
29207 static pointer new_color_node(uint8_t c)
29208 { pointer r = get_node(color_node_size);
29209 type(r)=whatsit_node;subtype(r)=color_node;
29210 color_ref(r)=c; color_link(r)=null;
29211 return r;
29212 }
29213
29214 @ @<Forward declarations@>=
29215 #ifdef DEBUG
29216 static void print_color_spec(int i);
29217 #endif
29218 static pointer new_color_node(uint8_t c);
29219
29220 @ Writing a color node to the output is simple.
29221 When we come to the output routine, every |end_color_node|
29222 should have been replaced by a |color_node|.
29223 To switch back to the color of the enclosing box,
29224 a |color_node| uses the color reference |0xFF|.
29225 An |end_color_node| is converted to a |color_node|
29226 when flattening the color stack.
29227 If an |end_color_node| does not have
29228 a matching |color_node| it is converted
29229 into a |no_color_node| which is silently ignored.
29230 If an |end_color_node| remains, it is ignored as well.
29231
29232 @<cases to output whatsit content nodes@>=
29233 case color_node:
29234 HPUT8(color_ref(p));
29235 tag=TAG(color_kind,b000);
29236 break;
29237 case no_color_node:
29238 case end_color_node:
29239 hpos--;
29240 return;
29241
29242 @ For the top level color nodes we provide a function to output colors
29243 without the need to construct (and destroy) a color node.
29244
29245 @<Hi\TeX\ auxiliary routines@>=
29246 static void hout_color_ref(uint8_t c)
29247 { uint8_t tag=TAG(color_kind,b000);
29248 HPUTNODE;
29249 HPUT8(tag);
29250 HPUT8(c);
29251 HPUT8(tag);
29252 }
29253
29254 @ The output of color definitions is more complex:
29255
29256 @<Output color definitions@>=
29257 DBG(DBGDEF,"Defining %d color references\n",max_ref[color_kind]);
29258 HPUTX((1+1+1+sizeof(ColorSet)+1)*(max_ref[color_kind]+1));
29259 for (i=max_fixed[color_kind]+1;i<=max_default[color_kind]; i++)
29260 { if (!colorset_equal(colors[i],color_defaults[i]))
29261 HPUTDEF(hout_color_def(colors[i]),i);
29262 }
29263 for (;i<=max_ref[color_kind]; i++)
29264 HPUTDEF(hout_color_def(colors[i]),i);
29265
29266 @ @<Hi\TeX\ auxiliary routines@>=
29267 static Tag hout_color_def(ColorSet c)
29268 { int i;
29269 // HPUTX(3+12*4);
29270 HPUT8(6);
29271 for (i=0;i<sizeof(ColorSet)/sizeof(uint32_t);i++)
29272 HPUT32(c[i]);
29273 return TAG(color_kind,b000);
29274 }
29275
29276 @ Hi\TeX\ treats colors different than \HINT\ files:
29277 Hi\TeX\ maintains a color stack inside a box while \HINT\
29278 files implement only a flat sequence of colors inside a box.
29279 As a consequence an |end_color_node| must be converted to a
29280 plain |color_node|. An |end_color_node| without a matching
29281 |color_node| is converted to a |no_color_node|, so that after
29282 flattening a node list no |end_color_node| remains.
29283 It will make flattening a list idempotent.
29284 Since link nodes are part of the color change
29285 mechanism they are part of the color stack.
29286 The color stack is a linked stack using the |color_link| field
29287 of color and link nodes. A pointer to the top node on this stack
29288 is in the variable |color_tos|. A pointer to the top link node
29289 on this stack (if any) is in the variable |link_tos|.
29290 Note that links are not nested, hence the |link_tos| variable
29291 is not strictly necessary but it avoids searching the color
29292 stack for a link node.
29293
29294 @<Global variables@>=
29295 static pointer color_tos=null;
29296 static pointer link_tos=null;
29297
29298 @ @<initialize the color stack@>=
29299 color_tos=null;
29300 link_tos=null;
29301
29302 @ @<Incorporate a |color_node| into the box@>=
29303 color_link(p)=color_tos;
29304 color_tos=p;
29305
29306 @ @<Incorporate an |end_color_node| into the box@>=
29307 if (color_tos==link_tos)
29308 subtype(p)=no_color_node;
29309 else if (color_tos!=null)
29310 { color_tos=color_link(color_tos);
29311 subtype(p)=color_node;
29312 if (color_tos!=null)
29313 color_ref(p)=color_ref(color_tos);
29314 else
29315 color_ref(p)=0xFF;
29316 }
29317 else
29318 subtype(p)=no_color_node;
29319
29320 @ In contrast, link nodes must not be nested, and an |end_link_node|
29321 is mandatory. So a link stack is not necessary. Hi\TeX\ just maintains
29322 a pointer to current |start_link_node| to be able to restore the color stack.
29323
29324 @<Incorporate a |start_link_node| into the box@>=
29325 if (link_tos!=null)
29326 {@+begin_diagnostic();
29327 print_err("This link is preceded by a \\HINTlink without \\HINTendlink:");
29328 end_diagnostic(true);
29329 }
29330 @<Incorporate a |color_node| into the box@>@;
29331 link_tos= color_tos;
29332
29333 @ @<Incorporate an |end_link_node| into the box@>=
29334 if (link_tos==null)
29335 {@+begin_diagnostic();
29336 print_err("\\HINTendlink without matching \\HINTlink:");
29337 end_diagnostic(true);
29338 }
29339 else
29340 { color_tos=color_link(link_tos);
29341 link_tos=null;
29342 if (color_tos!=null)
29343 color_ref(p)=color_ref(color_tos);
29344 else
29345 color_ref(p)=0xFF;
29346 }
29347
29348 @ Together these routines flatten the color stack.
29349 @<cases that flatten the color stack@>=
29350 case color_node:
29351 @<Incorporate a |color_node| into the box@>@; break;
29352 case end_color_node:
29353 @<Incorporate an |end_color_node| into the box@>@; break;
29354 case start_link_node:
29355 @<Incorporate a |start_link_node| into the box@>@; break;
29356 case end_link_node:
29357 @<Incorporate an |end_link_node| into the box@>@; break;
29358 case no_color_node: break;
29359
29360 @ Special care is needed for color changes in the top level vertical
29361 list. Because this list can grow quite large, nodes are deallocated
29362 right after being written to the output file. Therefore maintaining
29363 the color stack in the color nodes contained in the vertical list
29364 is not quite possible. Further page breaks can occur at many different
29365 places and to switch to the correct color, we might need to insert color
29366 nodes at all points where a new page might start.
29367
29368 Page breaks are possible
29369 at glue nodes if the preceding node was discardable
29370 (a node is discardable if its type is less than |math_node|),
29371 at kern nodes if they precede a glue node
29372 and at penalty nodes. It is inconvenient to test whether a kern node is
29373 followed by glue node; but because the kern node will disappear
29374 in the page break, it is sufficient to postpone the color information
29375 and insert it after the following glue node. If there are several
29376 glue or kern nodes in a row, it is sufficient to insert the color
29377 information only once at the beginning.
29378
29379 We keep track of the possible breaks
29380 and the color stack using four static variables.
29381
29382 @<Define the top level color stack@>=
29383 #define MAX_COLOR_STACK 256 /* a power of two */
29384 #define COLOR_STACK_MASK (MAX_COLOR_STACK-1)
29385 static uint8_t color_stack[MAX_COLOR_STACK];
29386 static int color_sp=0, color_stack_depth=0;
29387 static bool possible_break=true;
29388
29389
29390 @ Penalties and glue nodes but also baseline skips are possible page breaks.
29391
29392 @<|p| might be a page break@>=
29393 ( type(p)==penalty_node ||
29394 type(p)==glue_node ||
29395 (type(p)==whatsit_node && subtype(p)==baseline_node))
29396
29397 @ After a possible page break, we need to output the current color
29398 if a non discardable node shows up. Of course no such output is needed
29399 if that node is a color change itself.
29400
29401 @<Output the current color if needed@>=
29402 if (non_discardable(p))
29403 { if (color_stack_depth>0 && possible_break)
29404 { if (!(type(p)==whatsit_node &&
29405 (subtype(p)==color_node || subtype(p)==end_color_node)))
29406 hout_color_ref(color_stack[color_sp]);
29407 }
29408 possible_break=false;
29409 }
29410
29411
29412 @ It remains to organize the color stack.
29413 There are two possible cases to consider: A \TeX\ file might use
29414 nested colors on the top level with color nodes and matching end
29415 color nodes; or alternatively, a \TeX\ file might use color nodes without
29416 matching |end_color| nodes. Of course a \TeX\ file might also mix both approaches.
29417 In the first case, a limited nesting level can be assumed and a small
29418 color stack should suffice. In the second case, even a very large
29419 color stack will overflow sooner or later. To be as flexible as
29420 possible, we implement the color stack as a circular buffer.
29421 It is able to restore colors up to a limited nesting depth, but
29422 an overflow will not cause big problems.
29423
29424 @<Record the current top level color@>=
29425 if (type(p)==whatsit_node)
29426 { if (subtype(p)==color_node)
29427 { color_stack_depth++;
29428 color_sp = (color_sp+1)&COLOR_STACK_MASK;
29429 if (color_stack_depth>=MAX_COLOR_STACK)
29430 { static bool stackoverflow_printed=false;
29431 if (!stackoverflow_printed)
29432 { print_err("Overflow of top level color stack");
29433 stackoverflow_printed=true;
29434 }
29435 }
29436 color_stack[color_sp]=color_ref(p);
29437 }
29438 else if (subtype(p)==end_color_node)
29439 { if (color_stack_depth>0)
29440 { color_stack_depth--;
29441 color_sp = (color_sp-1)&COLOR_STACK_MASK;
29442 subtype(p)=color_node;
29443 color_ref(p)=color_stack[color_sp];
29444 }
29445 }
29446 }
29447 if (@<|p| might be a page break@>) possible_break=true;
29448
29449
29450 @*1 Links, Labels, and Outlines.
29451 The \HINT\ format knows about labels, links, and outlines.
29452
29453 @<Put each...@>=
29454 primitive("HINTdest", extension, label_node);@/
29455 @!@:HINTdest\_}{\.{\\HINTdest} primitive@>
29456 primitive("HINTstartlink", extension, start_link_node);@/
29457 @!@:HINTstartlink\_}{\.{\\HINTstartlink} primitive@>
29458 primitive("HINTendlink", extension, end_link_node);@/
29459 @!@:HINTendlink\_}{\.{\\HINTendlink} primitive@>
29460 primitive("HINToutline", extension, outline_node);@/
29461 @!@:HINToutline\_}{\.{\\HINToutline} primitive@>
29462
29463 @ When generating a short format \HINT\ file, links are part of
29464 the content section, where as labels and outlines are found in
29465 the definition section. Because labels are defined while
29466 writing the content section, the writing of labels and outlines
29467 must be postponed. For that reason,
29468 we store information about labels and outlines in dynamic arrays,
29469 and map labels, which are identified by a name or a number,
29470 to their index using a dynamic hash table.
29471
29472 We start with two functions that allocate new entries in the
29473 dynamic arrays increasing their size if necessary.
29474 @<Hi\TeX\ auxiliary routines@>=
29475 static int next_label(void)
29476 { static int label_no=-1;
29477 static int labels_allocated =0;
29478 label_no++;
29479 if (label_no>0xFFFF)
29480 overflow("labels",0xFFFF);
29481 if (label_no>=labels_allocated)
29482 { if (labels_allocated==0)
29483 { labels_allocated=32; ALLOCATE(labels,labels_allocated,Label); }
29484 else RESIZE(labels,labels_allocated,Label);
29485 }
29486 max_ref[label_kind]=label_no;
29487 return label_no;
29488 }
29489
29490 static int next_outline(void)
29491 { static int outlines_allocated =0;
29492 static int outline_no=-1;
29493 outline_no++;
29494 if (outline_no>0xFFFF)
29495 overflow("outlines",0xFFFF);
29496 if (outline_no>=outlines_allocated)
29497 { if (outlines_allocated==0)
29498 { outlines_allocated=32; ALLOCATE(outlines,outlines_allocated,Outline); }
29499 else RESIZE(outlines,outlines_allocated,Outline);
29500 }
29501 max_outline=outline_no;
29502 return outline_no;
29503 }
29504 @ While processing the content nodes, access to the labels is provided either
29505 by name or by number through a hash table. We store table entries in linked
29506 lists starting with a reasonably sized table of pointers. This keeps
29507 the fixed costs low and guards against overflow and rapidly increasing
29508 inefficiency. We start with a function to insert a new entry into
29509 the hash table.
29510
29511 @<Hi\TeX\ auxiliary routines@>=
29512 typedef struct hash_entry
29513 {int num; char *nom; uint16_t n; struct hash_entry *next;} HashEntry;
29514 #define LABEL_HASH 1009 /* MIX a prime number */
29515 static HashEntry *label_hash[LABEL_HASH]={NULL};
29516
29517 static int insert_hash(int h, int num, char *nom)
29518 { HashEntry *e;
29519 ALLOCATE(e,1,HashEntry);
29520 e->n= next_label();
29521 if (nom!=NULL) e->nom=strdup(nom);
29522 else e->num=num;
29523 e->next= label_hash[h];
29524 label_hash[h]=e;
29525 if (e->nom!=NULL)
29526 DBG(DBGLABEL,"Creating new label hash *%d: name='%s'\n",e->n,e->nom);
29527 else
29528 DBG(DBGLABEL,"Creating new label hash *%d: num=%d\n",e->n,e->num);
29529 return e->n;
29530 }
29531 @ There are two cases: finding a label by name or by number.
29532 We start with the simpler case where the number is given.
29533 The process is straight forward:
29534
29535 @<Hi\TeX\ auxiliary routines@>=
29536 static int find_label_by_number(int p)
29537 { unsigned int h=(unsigned int)p%LABEL_HASH;
29538 HashEntry *e= label_hash[h];
29539 DBG(DBGLABEL,"Looking up label num %d\n",(unsigned int)p);
29540 while (e!=NULL)
29541 if (e->nom==NULL && e->num==p) return e->n;
29542 else e=e->next;
29543 return insert_hash(h,p,NULL);
29544 }
29545 @ To look up a label by its name as given by a token list,
29546 we prepare ourselves by implementing two functions:
29547 one to extract the character codes from the token list
29548 forming the ``name''
29549 and one to compute the hash value for a name.
29550 The routine to find the label by name is then equivalent to the
29551 routine we have just seen. Given a pointer |p| to
29552 either a label, a link, or an outline node, the function |find_label|
29553 returns the correct label reference.
29554 Currently, we limit label names to at most 255 significant byte.
29555
29556 @<Hi\TeX\ auxiliary routines@>=
29557 static char *tokens_to_name(pointer p)
29558 { static char s[256];
29559 int i=0;
29560 bool skip_space=0;
29561 while (i<255 && p!=0)@/
29562 { int m = info(p)/cmd_factor;@+
29563 int c = info(p)%cmd_factor;
29564 if (m==spacer && ! skip_space) @/
29565 { s[i++]=' '; skip_space=true;@+}
29566 else if ((m==letter || m==other_char) && ' '< c && c < 0x7F)@/
29567 {@+ s[i++]=c; skip_space=false;@+}
29568 p=link(p);
29569 }
29570 s[i]=0;
29571 return s;
29572 }
29573
29574 static unsigned int name_hash(char *s)
29575 { unsigned int h=0;
29576 while (*s!=0)
29577 h=(h<<2)+*(s++);
29578 return h;
29579 }
29580
29581 static int find_label_by_name(pointer p)
29582 { char *s=tokens_to_name(link(p));
29583 unsigned int h=name_hash(s)%LABEL_HASH;
29584 HashEntry *e= label_hash[h];
29585 DBG(DBGLABEL,"Looking up label name %s\n", s);
29586 while (e!=NULL)
29587 if (e->nom!=NULL && strcmp(e->nom,s)==0) return e->n;
29588 else e=e->next;
29589 return insert_hash(h,0,s);
29590 }
29591 @ We combine both ways of finding a label reference in the following function:
29592
29593 @<Hi\TeX\ auxiliary routines@>=
29594 static int find_label(pointer p)
29595 {@+ if (label_has_name(p)) return find_label_by_name(label_ptr(p));
29596 else return find_label_by_number(label_ptr(p));
29597 }
29598 @
29599 After these preparations, we can implement the functions needed
29600 when labels, links, and outlines are delivered to the page builder.
29601
29602 We start with looking at the labels:
29603 When a labels is defined, the current position is recorded.
29604 Further labels are linked together in order of descending positions,
29605 to allow the efficient adjustment of label positions when
29606 moving lists.
29607
29608 @<Hi\TeX\ auxiliary routines@>=
29609 static void new_label(pointer p)
29610 { int n;
29611 DBG(DBGLABEL,"Label at pos=0x%x\n",(unsigned int)(hpos-hstart));
29612 n=find_label(p);
29613 if (n!=zero_label_no && labels[n].where!=LABEL_UNDEF)
29614 { MESSAGE("WARNING: Ignoring duplicate definition of label ");
29615 if (label_has_name(p)) MESSAGE("name %s\n",tokens_to_name(link(label_ptr(p))));
29616 else MESSAGE("num %d\n",label_ptr(p));
29617 }
29618 else
29619 { labels[n].where=label_where(p);
29620 labels[n].pos=hpos-hstart;
29621 labels[n].pos0=hpos0-hstart;
29622 labels[n].next=first_label;
29623 first_label=n;
29624 DBG(DBGLABEL,"Defining label *%d: pos=0x%x\n",n,labels[n].pos);
29625 }
29626 }
29627 @ When a link node is written to the output, we can check
29628 that start links and end links properly match.
29629
29630 @<Hi\TeX\ auxiliary routines@>=
29631 static int last_link=-1;
29632 static int new_start_link(pointer p)
29633 { int n=find_label(as_label(p));
29634 if (last_link>=0)
29635 fatal_error("Missing end link before start link");
29636 labels[n].used=true;
29637 last_link=n;
29638 DBG(DBGLABEL,"New link to label *%d\n",n);
29639 return n;
29640 }
29641
29642 static int new_end_link(void)
29643 { int n;
29644 if (last_link<0)
29645 fatal_error("Missing start link before end link");
29646 n=last_link;
29647 last_link=-1;
29648 return n;
29649 }
29650 @ For outline nodes, we use the next two functions.
29651 The node list representing the title can be an arbitrary
29652 list in horizontal mode.
29653 In general, the front end should be able to render such a
29654 horizontal list, but at least it should be able to extract
29655 the UTF8 character codes and display those.
29656
29657 @<Hi\TeX\ auxiliary routines@>=
29658 static void new_outline(pointer p)
29659 { int r=find_label(p);
29660 int m=next_outline();
29661 List l;
29662 uint32_t pos;
29663 pos=hpos-hstart;
29664 l.t=TAG(list_kind,b001); /* this eventually should be a text */
29665 hout_list_node(outline_ptr(p),pos,&l);
29666 hset_outline(m,r,outline_depth(p),pos);
29667 DBG(DBGLABEL,"New outline for label *%d\n",r);
29668 }
29669 @ One last function is needed which is called when the |outline_group| ends
29670 that was started after scanning the {\tt\BS HINToutline} primitive.
29671 @<Hi\TeX\ routines@>=
29672 static void hfinish_outline_group(void)
29673 { pointer s=link(head);
29674 unsave();
29675 pop_nest();
29676 outline_ptr(tail)=s;
29677 }
29678 @*1 The New Page Builder.
29679 Here is the new |build_page| routine of Hi\TeX:
29680
29681 @<Hi\TeX\ routines@>=
29682 static void build_page(void)
29683 { @<Define the top level color stack@>@;
29684 if(link(contrib_head)==null||output_active)return;
29685 do
29686 { pointer p= link(contrib_head);
29687 pointer q=null; /* for output nodes */
29688 pointer *t=NULL; /*the tail of the output nodes*/
29689 bool eject=(type(p)==penalty_node && penalty(p)<=eject_penalty);
29690 int page_penalty=0;
29691 if (eject) page_penalty=penalty(p);
29692 @<Record the bottom mark@>@;
29693 @<Record the current top level color@>@;
29694 @<Suppress empty pages if requested@>@;
29695 link(contrib_head)= link(p);link(p)= null;
29696 if (link(contrib_head)==null)
29697 { @<Make the contribution list empty by setting its tail to |contrib_head|@>;
29698 }
29699 update_last_values(p);
29700 @<Freeze the page specs if called for@>@;
29701 page_goal=0x3fffffff; /* maximum dimension */
29702 t=collect_output(&p,&q);
29703 if (p!=null)
29704 { hpos0=hpos; hout_node(p);
29705 @<Output the current color if needed@>@;
29706 }
29707 recycle_p:
29708 flush_node_list(p);
29709 if (q!=null||(eject&&page_contents>=box_there))
29710 {
29711 geq_word_define(int_base+output_penalty_code, page_penalty);
29712 empty_output:
29713 @<Fire up the output routine for |q|@>@;
29714 }
29715 } while(link(contrib_head)!=null);
29716 DBG(DBGBUFFER,"after build page dyn_used= %d\n", dyn_used);
29717 }
29718 @ When the |page_contents| changes from |empty| to not |empty|,
29719 the function |hint_open| will open the output file.
29720 While the output file is needed only much later in the
29721 function |hput_hint|, this place was chosen to match,
29722 as close as possible, the behavior of the
29723 original \TeX.
29724
29725 @<Freeze the page specs if called for@>=
29726 if (page_contents<box_there)
29727 { switch(type(p))
29728 { case whatsit_node:
29729 if (subtype(p)==baseline_node) goto recycle_p;
29730 else if (subtype(p)!=hset_node && subtype(p)!=vset_node &&
29731 subtype(p)!=hpack_node && subtype(p)!=vpack_node &&
29732 subtype(p)!=par_node && subtype(p)!=disp_node &&
29733 subtype(p)!=image_node && subtype(p)!=align_node)
29734 break; /* else fall through */
29735 case hlist_node: case vlist_node: case rule_node:
29736 if (page_contents==empty)
29737 { hint_open();
29738 freeze_page_specs(box_there);
29739 hfix_defaults();
29740 }
29741 else page_contents=box_there;
29742 break;
29743 case ins_node:
29744 if (page_contents==empty)
29745 { hint_open();
29746 freeze_page_specs(inserts_only);
29747 hfix_defaults();
29748 }
29749 break;
29750 case kern_node:
29751 case penalty_node:
29752 case glue_node: goto recycle_p;
29753 default:
29754 break;
29755 }
29756 }
29757 @ Users of \TeX\ often force the generation of empty pages for example to start
29758 a new chapter on a right hand page with an odd page number.
29759 This makes sense for a printed book but not for a screen reader where
29760 there are no page numbers nor right or left hand pages.
29761 Using a screen reader, empty pages are just annoying.
29762 The common way to achieve an empty page is the use of {\tt \BS eject}
29763 followed by a an empty box, a fill glue, and another {\tt \BS eject}.
29764
29765 The following code tries to detect such a sequence of nodes and will eliminate
29766 them if requested. To do so, we delay the output of nodes after
29767 an eject penalty until either something gets printed on the page or
29768 another eject penalty comes along. To override the delayed output,
29769 a penalty less or equal to a double |eject_penalty| can be used.
29770 The function |its_all_over| is an example for such a use.
29771 It seems that the eliminated nodes do not contain anything of value
29772 for the output routine, but the output routine might have other
29773 resources, like the first column of a two column page, which it might
29774 put back on the contribution list. So it is wise to call the output routine
29775 and give it a chance.
29776
29777 @<Suppress empty pages if requested@>=
29778 if (option_no_empty_page &&
29779 ((eject && penalty(p)>2*(eject_penalty)) ||
29780 (page_contents==empty && !is_visible(p))))
29781 { pointer r, prev_r = p;
29782 while (true)
29783 { r =link(prev_r);
29784 if (r==null) return;
29785 else if (is_visible(r)) break;
29786 else if (type(r)==penalty_node && penalty(r)<=eject_penalty)
29787 { q=p;
29788 link(prev_r)=null;
29789 link(contrib_head)=r;
29790 DBG(DBGPAGE,"Eliminating empty page preceding penalty %d\n",penalty(r));
29791 geq_word_define(int_base+output_penalty_code, penalty(r));
29792 goto empty_output;
29793 }
29794 prev_r=r;
29795 }
29796 }
29797
29798 @ It remains to test a node for visibility. This is a quick (and dirty) test
29799 because the test will not look inside boxes; it simply tests whether
29800 the list pointer is |null|. We consider an |open_node|, |write_node|,
29801 |close_node|, |label_node|, or |outline_node| as visible
29802 because deleting them could cause unwanted
29803 side effects. Possibly it would be better to regard them as invisible,
29804 but still pass them on to the rest of the output routine.
29805
29806 @<Hi\TeX\ auxiliary routines@>=
29807 static bool is_visible(pointer p)
29808 { switch (type(p))
29809 { case penalty_node:
29810 case kern_node:
29811 case glue_node:
29812 case mark_node:
29813 return false;
29814 case ins_node:
29815 return ins_ptr(p)!=null;
29816 case adjust_node:
29817 return adjust_ptr(p)!=null;
29818 case hlist_node:
29819 case vlist_node:
29820 return list_ptr(p)!=null;
29821 case whatsit_node:
29822 if (subtype(p)==image_node || subtype(p)==align_node || subtype(p)==disp_node ||
29823 subtype(p)==open_node ||subtype(p)==write_node ||subtype(p)==close_node ||
29824 subtype(p)==label_node || subtype(p)==outline_node )
29825 return true;
29826 else if (subtype(p)==hset_node || subtype(p)==vset_node ||
29827 subtype(p)==hpack_node || subtype(p)==vpack_node)
29828 return list_ptr(p)!=null;
29829 else if (subtype(p)==par_node)
29830 return par_list(p)!=null;
29831 else
29832 return false;
29833 default: return true;
29834 }
29835 }
29836
29837 @ Because we will need this procedure in the |its_all_over| function.
29838 We add a forward declaration
29839
29840 @<Forward declarations@>=
29841 static bool is_visible(pointer p);
29842
29843
29844 @ An important feature of the new routine is the call to
29845 |hfix_defaults|. It occurs when the first ``visible mark'' is placed
29846 in the output. At that point we record the current values of \TeX's
29847 parameters which we will use to generate the definition section of the
29848 \HINT\ file. It is still possible to specify alternative values for
29849 these parameters by using parameter lists but only at an additional
29850 cost in space and time.
29851
29852 Furthermore, this is the point where we freeze the definition of
29853 |hsize| and |vsize|. The current values will be regarded as the sizes
29854 as recommended by the author.
29855
29856 From then on |hsize| and |vsize| are replaced by the equivalent
29857 extended dimensions and any attempt to modify them on the global level
29858 will be ignored. |hhsize| and |hvsize| will contain the sizes that a
29859 regular \TeX\ engine would use.
29860
29861 We also compute the total page size from the page template defined
29862 last.
29863
29864
29865 @<Compute the page size@>=
29866 { pointer p;
29867 p=link(setpage_head);
29868 if (p==null)
29869 { scaled margin;
29870 if (hhsize<hvsize) margin=hhsize; else margin=hvsize;
29871 margin = margin/6 -6*unity;
29872 if (margin<0) margin=0;
29873 page_h=hhsize+2*margin;
29874 page_v=hvsize+2*margin;
29875 }
29876 else
29877 { pointer x;
29878 x=setpage_height(p);
29879 page_v=xdimen_width(x)
29880 +round(((double)xdimen_hfactor(x)*hhsize+(double)xdimen_vfactor(x)*hvsize)/unity);
29881 x=setpage_width(p);
29882 page_h=xdimen_width(x)
29883 +round(((double)xdimen_hfactor(x)*hhsize+(double)xdimen_vfactor(x)*hvsize)/unity);
29884 }
29885 }
29886 @ @<Hi\TeX\ variables@>=
29887 static scaled page_h, page_v;
29888 @ @<Switch |hsize| and |vsize| to extended dimensions@>=
29889 hsize=0; vsize=0;
29890 dimen_par_hfactor(hsize_code)= unity;
29891 dimen_par_vfactor(vsize_code)= unity;
29892 @ There is one point where we can not simply forgo the
29893 output routine: \.{\\write} commands. Unless the \.{\\write} is
29894 decorated with an \.{\\immediate}, the whatsit node generated from it
29895 will lay dormant in the contribution list (and later the page) until
29896 the output routine passes it as part of the finished page to the |ship_out|
29897 routine. There it will come to life and write its token list out.
29898 The whatsit nodes from \.{\\openout} and \.{\\closeout} commands
29899 behave similarly.
29900
29901 It is not possible to ignore the output routine
29902 because the output routine may change the environment in which the
29903 token list of a \.{\\write} will be expanded.
29904 For example \LaTeX\ redefines \.{\\protect} to be \.{\\noexpand}.
29905 As a consequence we have to implement a simplified version
29906 of \TeX's usual process to fire up the output routine.
29907
29908 The |collect_output| routine takes a node list |*p|,
29909 removes the output nodes and appends them to |*q|, with |q|
29910 always pointing to the tail pointer.
29911
29912 @<Hi\TeX\ auxiliary routines@>=
29913 static pointer *collect_output(pointer *p, pointer *q)
29914 { while (*p!=null)
29915 { @<Collect output nodes from |*p|@>@;
29916 p=&(link(*p));
29917 }
29918 return q;
29919 }
29920 @ \TeX\ does not permit output nodes in leaders, so we don't check them;
29921 further we do not check the pre- and post-break lists of
29922 discretionary breaks.
29923
29924 @<Collect output nodes from |*p|@>=
29925 if (!is_char_node(*p))
29926 { pointer r=*p;
29927 switch (type(r))
29928 {
29929 #if 0
29930 case glue_node: /* possibly the output routine might like these */
29931 case penalty_node:
29932 { *p=link(r); link(r)=null; *q=r; q=&(link(r));
29933 if (*p==null) return q;
29934 }
29935 break;
29936 #endif
29937 case whatsit_node:
29938 switch (subtype(r))
29939 { case open_node: case write_node: case close_node:
29940 case special_node: case latespecial_node:
29941 { *p=link(r); link(r)=null; *q=r; q=&(link(r));
29942 if (*p==null) return q;
29943 }
29944 break;
29945 case par_node: q=collect_output(&par_list(r),q);
29946 break;
29947 case disp_node:
29948 if (display_left(r)) q=collect_output(&display_eqno(r),q);
29949 q=collect_output(&display_formula(r),q);
29950 if (!display_left(r)) q=collect_output(&display_eqno(r),q);
29951 break;
29952 case hset_node: case vset_node: case hpack_node: case vpack_node:
29953 q=collect_output(&list_ptr(r),q);
29954 break;
29955 case align_node:
29956 q=collect_output(&align_list(r),q);
29957 break;
29958 default: break;
29959 }
29960 break;
29961 case hlist_node: case vlist_node:
29962 q=collect_output(&list_ptr(r),q);
29963 break;
29964 case ins_node:
29965 q=collect_output(&ins_ptr(r),q);
29966 break;
29967 case adjust_node:
29968 q=collect_output(&adjust_ptr(r),q);
29969 break;
29970 default: break;
29971 }
29972 }
29973
29974
29975 @ @<Fire up the output routine for |q|@>=
29976 { pointer r=new_null_box();type(r)=vlist_node;
29977 subtype(r)=0;shift_amount(r)=0;height(r)=hvsize;
29978 if (t==NULL) list_ptr(r)=null; /* or |new_glue(fill_glue);| ? */
29979 else { list_ptr(r)=q; *t=new_glue(fill_glue); }
29980 flush_node_list(box(255)); /* just in case \dots */
29981 box(255)=r;
29982 if (output_routine!=null)
29983 {@+output_active=true;
29984 if (bot_mark!=null)
29985 {@+if (top_mark!=null) delete_token_ref(top_mark);
29986 top_mark=bot_mark;add_token_ref(top_mark);
29987 if (first_mark!=null) delete_token_ref(first_mark);
29988 first_mark=bot_mark;add_token_ref(first_mark);
29989 }
29990 DBG(DBGPAGE,"Starting the output routine (output penalty=%d)\n",output_penalty);
29991 push_nest();mode=-vmode;prev_depth=ignore_depth;mode_line=-line;
29992 begin_token_list(output_routine, output_text);
29993 new_save_level(output_group);normal_paragraph();
29994 scan_left_brace();
29995 return;
29996 }
29997 else
29998 {
29999 ship_out(box(255)); box(255)=null;
30000 }
30001 }
30002
30003 @ The |ship_out| routine just calls |execute_output|.
30004 Because the output routine might have added plenty
30005 of decorations around the list of output nodes,
30006 we have to find them again.
30007
30008 @<Hi\TeX\ routines@>=
30009 static void execute_output(pointer p)
30010 {@+while (p!=null)
30011 { @<Execute output nodes from |p|@>@;
30012 p=link(p);
30013 }
30014 }
30015 @ @<Execute output nodes from |p|@>=
30016 if (!is_char_node(p))
30017 switch (type(p))
30018 { case whatsit_node:
30019 switch (subtype(p))
30020 { case open_node: case write_node: case close_node:
30021 case special_node: case latespecial_node:
30022 out_what(p);
30023 break;
30024 case par_node: execute_output(par_list(p));
30025 break;
30026 case disp_node:
30027 if (display_left(p)) execute_output(display_eqno(p));
30028 execute_output(display_formula(p));
30029 if (!display_left(p)) execute_output(display_eqno(p));
30030 break;
30031 case hset_node: case vset_node: case hpack_node: case vpack_node:
30032 execute_output(list_ptr(p));
30033 break;
30034 case align_node:
30035 execute_output(align_list(p));
30036 break;
30037 default: break;
30038 }
30039 break;
30040 case hlist_node: case vlist_node:
30041 execute_output(list_ptr(p));
30042 break;
30043 case ins_node:
30044 execute_output(ins_ptr(p));
30045 break;
30046 case adjust_node:
30047 execute_output(adjust_ptr(p));
30048 break;
30049 default: break;
30050 }
30051 @ Invoking the user's output routine is a risky endeavor
30052 if marks are not initialized properly. In our case
30053 we will have always |top_mark| equal to |first_mark| and
30054 |bot_mark|.
30055
30056 @<Record the bottom mark@>=
30057 if (type(p)==mark_node)
30058 { if (bot_mark!=null) delete_token_ref(bot_mark);
30059 bot_mark=mark_ptr(p);add_token_ref(bot_mark);
30060 }
30061
30062
30063
30064 @*1 Replacing {\tt hpack} and {\tt vpack}.
30065 The following routines extend \TeX's original routines. They check for
30066 any dependency of the box size on {\tt hsize} or {\tt vsize} and
30067 create an hset node or hpack node if such a dependency was found.
30068 The |keep_cs| variable will prevent the initialization of the color
30069 stack; this is needed in the |line_break| routine, where the color
30070 stack is maintained for the whole paragraph not for the individual lines.
30071
30072 @<Hi\TeX\ routines@>=
30073 static pointer hpack(pointer p,scaled w, scaled hf, scaled vf, small_number m, bool keep_cs)
30074 {
30075 pointer r; /*the box node that will be returned*/
30076 pointer q; /*trails behind |p|*/
30077 scaled h,d,x; /*height, depth, and natural width*/
30078 scaled s; /*shift amount*/
30079 pointer g; /*points to a glue specification*/
30080 glue_ord o, sto, sho; /*order of infinity*/
30081 internal_font_number f; /*the font in a |char_node|*/
30082 bool repack=false; /* whether repacking is necessary */
30083 if (!keep_cs) { @<initialize the color stack@>@;}
30084 last_badness= 0;r= get_node(box_node_size);type(r)= hlist_node;
30085 subtype(r)= min_quarterword;shift_amount(r)= 0;
30086 q= r+list_offset;link(q)= p;
30087 h= 0;@<Clear dimensions to zero@>;
30088 while(p!=null) {
30089 reswitch:
30090 while(is_char_node(p))
30091 @<Incorporate character dimensions into the dimensions of the hbox that will contain~it,
30092 then move to the next node@>;
30093 if (p!=null)
30094 { switch(type(p)){
30095 case hlist_node: case vlist_node: case rule_node: case unset_node: case unset_set_node: case unset_pack_node:
30096 @<Incorporate box dimensions into the dimensions of the hbox that will contain~it@>@;@+break;
30097 case ins_node: case mark_node: case adjust_node: if (adjust_tail!=null)
30098 @<Transfer node |p| to the adjustment list@>@;@+break;
30099 case glue_node: @<Incorporate glue into the horizontal totals@>@;@+break;
30100 case kern_node: case math_node: x=x+width(p);@+break;
30101 case ligature_node: @<Make node |p| look like a |char_node| and |goto reswitch|@>@;
30102 case whatsit_node: @<Incorporate the various whatsit nodes into an hbox@>@;@+break;
30103 default:do_nothing;
30104 }
30105 if (link(p)==null && keep_cs && link_tos!=null)
30106 { pointer r;
30107 r=get_node(link_node_size);
30108 type(r)=whatsit_node; subtype(r)=end_link_node;
30109 if (color_link(color_tos)!=null)
30110 color_ref(r)=color_ref(color_link(color_tos));
30111 else
30112 color_ref(r)=0xFF;
30113 link(r)=null; link(p)=r; p=r;
30114 }
30115 p= link(p);
30116 }
30117 }
30118
30119 if (adjust_tail!=null) link(adjust_tail)= null;
30120 height(r)= h;depth(r)= d;
30121 if (repack) /* convert to a |hpack_node| */
30122 { q=new_pack_node();
30123 height(q)=h;
30124 depth(q)=d;
30125 width(q)=x;
30126 subtype(q)=hpack_node;
30127 list_ptr(q)=list_ptr(r);
30128 list_ptr(r)=null;
30129 free_node(r, box_node_size);
30130 pack_limit(q)=max_dimen; /* no limit, not used */
30131 pack_m(q)=m;
30132 pack_extent(q)=new_xdimen(w,hf,vf);
30133 return q;
30134 }
30135 else if (hf!=0 || vf!=0 ) /* convert to a hset node */
30136 { if (total_stretch[filll]!=0)sto= filll;
30137 else if (total_stretch[fill]!=0)sto= fill;
30138 else if (total_stretch[fil]!=0)sto= fil;
30139 else sto= normal;
30140
30141 if (total_shrink[filll]!=0)sho= filll;
30142 else if (total_shrink[fill]!=0)sho= fill;
30143 else if (total_shrink[fil]!=0)sho= fil;
30144 else sho= normal;
30145 q=new_set_node();
30146 subtype(q)=hset_node;
30147 height(q)=h;
30148 depth(q)=d;
30149 width(q)=x; /* the natural width */
30150 shift_amount(q)=shift_amount(r);
30151 list_ptr(q)=list_ptr(r);
30152 list_ptr(r)=null;
30153 free_node(r, box_node_size);
30154 if (m==exactly)
30155 set_extent(q)=new_xdimen(w,hf,vf);
30156 else
30157 set_extent(q)=new_xdimen(x+w,hf,vf);
30158 set_stretch_order(q)=sto;
30159 set_shrink_order(q)=sho;
30160 set_stretch(q)=total_stretch[sto];
30161 set_shrink(q)=total_shrink[sho];
30162 return q;
30163 }
30164
30165 @<Determine the value of |width(r)| and the appropriate glue setting; then |return|
30166 or |goto common_ending|@>;
30167 common_ending:
30168 if (pack_begin_line!=0)
30169 { if (pack_begin_line> 0)print(") in paragraph at lines ");
30170 else print(") in alignment at lines ");
30171 print_int(abs(pack_begin_line));
30172 print("--");
30173 }
30174 else print(") detected at line ");
30175 print_int(line);
30176 print_ln();
30177 font_in_short_display= null_font;short_display(list_ptr(r));print_ln();
30178 begin_diagnostic();show_box(r);end_diagnostic(true);
30179 end:return r;
30180 }
30181
30182 @ Now we consider the various whatsit nodes that are new in Hi\TeX.
30183 In most cases, it is no longer possible to determine the dimensions so that
30184 the |hpack| function is forced to return a hpack node. The hpack nodes cause
30185 special trouble when converting mlists to hlists because there the dimensions
30186 are necessary for positioning the parts of the formulas.
30187 A clean solution requires to postpone such computations to the \HINT\ viewer.
30188 For now we adopt a simpler solution and supply an educated guess which is
30189 reasonable since the boxes that occur in math formulas are often not very
30190 complicated. | graph_node|s should not be in a horizontal list, and |disp_node|s
30191 should be only inside |graph_node|s.
30192
30193 @<Incorporate the various whatsit nodes into an hbox@>=
30194 switch (subtype(p))
30195 { case par_node: if (depth(p)> d) d=depth(p); break;
30196 case disp_node: break;
30197 case vpack_node:
30198 case hpack_node:
30199 case hset_node:
30200 case vset_node:
30201 @<Incorporate box dimensions into the dimensions of the hbox...@>@;
30202 repack=true; break;
30203 case stream_node: repack=true; break; /* streams are for page templates only */
30204 case image_node:
30205 if (image_xheight(p)!=null)
30206 { pointer r=image_xheight(p);
30207 if (xdimen_hfactor(r)==0 && xdimen_vfactor(r)==0)
30208 { if (xdimen_width(r)> h) h= xdimen_width(r);}
30209 else { repack=true; break;}
30210 }
30211 if (image_xwidth(p)!=null)
30212 { pointer r=image_xwidth(p);
30213 if (xdimen_hfactor(r)==0 && xdimen_vfactor(r)==0)
30214 x = x+ xdimen_width(r);
30215 else { repack=true; break;}
30216 }
30217 break;
30218 @<cases that flatten the color stack@>@;
30219 default: break;
30220 }
30221
30222 @ @<Hi\TeX\ routines@>=
30223 static pointer vpackage(pointer p, scaled h, scaled hf, scaled vf, small_number m, bool keep_cs, scaled l)
30224 { pointer r; /*the box node that will be returned*/
30225 scaled w,d,x; /*width, depth, and natural height*/
30226 scaled s=0; /*shift amount*/
30227 pointer g; /*points to a glue specification*/
30228 glue_ord sho, sto; /*order of infinity*/
30229 if (!keep_cs) {@<initialize the color stack@>@;}
30230 last_badness= 0; r= get_node(box_node_size); type(r)= vlist_node;
30231 subtype(r)= min_quarterword; shift_amount(r)= 0;
30232 list_ptr(r)= p;
30233 w= 0;
30234 d= 0;x= 0;
30235 total_stretch[normal]= 0;total_shrink[normal]= 0;
30236 total_stretch[fil]= 0;total_shrink[fil]= 0;
30237 total_stretch[fill]= 0;total_shrink[fill]= 0;
30238 total_stretch[filll]= 0;total_shrink[filll]= 0;
30239 while(p!=null)
30240 { if (is_char_node(p))
30241 confusion("vpack");
30242 else
30243 switch(type(p))
30244 { case hlist_node:case vlist_node:case rule_node:case unset_node:
30245 x= x+d+height(p);d= depth(p);
30246 if (type(p)>=rule_node) s= 0;
30247 else s= shift_amount(p);
30248 if (width(p)+s> w) w= width(p)+s;
30249 break;
30250 case unset_set_node: case unset_pack_node:
30251 goto repack;
30252 case whatsit_node:
30253 switch(subtype(p))
30254 { case par_node:
30255 if (depth(p) > d) d=depth(p);
30256 goto repack;
30257 case disp_node:
30258 case vpack_node:
30259 case hpack_node:
30260 case hset_node:
30261 case vset_node:
30262 case stream_node:
30263 goto repack;
30264 case image_node:
30265 if (image_xwidth(p)!=null)
30266 { pointer r=image_xwidth(p);
30267 if (xdimen_hfactor(r)==0 && xdimen_vfactor(r)==0)
30268 { if (xdimen_width(r)> w) w= xdimen_width(r); }
30269 else goto repack;
30270 }
30271 if (image_xheight(p)!=null)
30272 { pointer r=image_xheight(p);
30273 if (xdimen_hfactor(r)==0 && xdimen_vfactor(r)==0)
30274 { x= x+d+xdimen_width(r);d=0;}
30275 else goto repack;
30276 }
30277 break;
30278 @<cases that flatten the color stack@>
30279 }
30280 break;
30281 case glue_node:
30282 { glue_ord o;
30283 x= x+d;d= 0;
30284 g= glue_ptr(p);x= x+width(g);
30285 o= stretch_order(g); total_stretch[o]= total_stretch[o]+stretch(g);
30286 o= shrink_order(g); total_shrink[o]= total_shrink[o]+shrink(g);
30287 if (subtype(p)>=a_leaders)
30288 { g= leader_ptr(p);
30289 if (width(g)> w) w= width(g);
30290 }
30291 }
30292 break;
30293 case kern_node:
30294 x= x+d+width(p);d= 0;
30295 break;
30296 default:do_nothing;
30297 }
30298 p= link(p);
30299 }
30300 width(r)= w;
30301
30302
30303 if (total_stretch[filll]!=0) sto= filll;
30304 else if (total_stretch[fill]!=0) sto= fill;
30305 else if (total_stretch[fil]!=0) sto= fil;
30306 else sto= normal;
30307
30308 if (total_shrink[filll]!=0) sho= filll;
30309 else if (total_shrink[fill]!=0) sho= fill;
30310 else if (total_shrink[fil]!=0) sho= fil;
30311 else sho= normal;
30312
30313 if (hf!=0 || vf!=0) /* convert to a vset node */
30314 { pointer q;
30315 q=new_set_node();
30316 subtype(q)=vset_node;
30317 width(q)=w;
30318 if (d> l)
30319 { x= x+d-l;depth(r)= l;
30320 }
30321 else depth(r)= d;
30322 height(q)=x;
30323 depth(q)=d;
30324 shift_amount(q)=shift_amount(r);
30325 list_ptr(q)=list_ptr(r);
30326 list_ptr(r)=null;
30327 free_node(r, box_node_size);
30328 if (m==exactly)
30329 set_extent(q)=new_xdimen(h,hf,vf);
30330 else
30331 set_extent(q)=new_xdimen(x+h,hf,vf);
30332 set_stretch_order(q)=sto;
30333 set_shrink_order(q)=sho;
30334 set_stretch(q)=total_stretch[sto];
30335 set_shrink(q)=total_shrink[sho];
30336 return q;
30337 }
30338
30339 if (d> l)
30340 { x= x+d-l;depth(r)= l;
30341 }
30342 else depth(r)= d;
30343 if (m==additional)
30344 h= x+h;
30345 height(r)= h; x= h-x; /*now |x| is the excess to be made up*/
30346 if (x==0)
30347 { glue_sign(r)= normal; glue_order(r)= normal;
30348 set_glue_ratio_zero(glue_set(r));
30349 goto end;
30350 }
30351 else if (x> 0)
30352 { glue_order(r)= sto;glue_sign(r)= stretching;
30353 if (total_stretch[sto]!=0)glue_set(r)= fix(x/(double)total_stretch[sto]);
30354 else
30355 { glue_sign(r)= normal;
30356 set_glue_ratio_zero(glue_set(r));
30357 }
30358 if (sto==normal)
30359 { if (list_ptr(r)!=null)
30360 { last_badness= badness(x,total_stretch[normal]);
30361 if (last_badness> vbadness)
30362 { print_ln();
30363 if (last_badness> 100)print_nl("Underfull");else print_nl("Loose");
30364 print(" \\vbox (badness ");print_int(last_badness);
30365 goto common_ending;
30366 }
30367 }
30368 }
30369 goto end;
30370 }
30371 else /* if (x<0) */
30372 {
30373 glue_order(r)= sho;glue_sign(r)= shrinking;
30374 if (total_shrink[sho]!=0)glue_set(r)= fix((-x)/(double)total_shrink[sho]);
30375 else
30376 { glue_sign(r)= normal;
30377 set_glue_ratio_zero(glue_set(r));
30378 }
30379 if ((total_shrink[sho]<-x)&&(sho==normal)&&(list_ptr(r)!=null))
30380 { last_badness= 1000000;
30381 set_glue_ratio_one(glue_set(r));
30382 if ((-x-total_shrink[normal]> vfuzz)||(vbadness<100))
30383 { print_ln();print_nl("Overfull \\vbox (");
30384 print_scaled(-x-total_shrink[normal]);print("pt too high");
30385 goto common_ending;
30386 }
30387 }
30388 else if (sho==normal)
30389 { if (list_ptr(r)!=null)
30390 { last_badness= badness(-x,total_shrink[normal]);
30391 if (last_badness> vbadness)
30392 { print_ln();print_nl("Tight \\vbox (badness ");print_int(last_badness);
30393 goto common_ending;
30394 }
30395 }
30396 }
30397 goto end;
30398 }
30399
30400
30401 common_ending:
30402 if (pack_begin_line!=0)
30403 { print(") in alignment at lines ");
30404 print_int(abs(pack_begin_line));
30405 print("--");
30406 }
30407 else
30408 print(") detected at line ");
30409 print_int(line);
30410 print_ln();
30411
30412 begin_diagnostic();show_box(r);end_diagnostic(true);
30413 end:
30414 return r;
30415
30416
30417 repack:
30418 { /* convert the box to a |vpack_node| */
30419 pointer q;
30420 q=new_pack_node();
30421 subtype(q)=vpack_node;
30422 height(q)=x;
30423 depth(q)=d;
30424 width(q)=w;
30425 list_ptr(q)=list_ptr(r);
30426 list_ptr(r)=null;
30427 free_node(r, box_node_size);
30428 pack_limit(q)=l;
30429 pack_m(q)=m;
30430 pack_extent(q)=new_xdimen(h,hf,vf);
30431 return q;
30432 }
30433 }
30434
30435 @*1 Streams.
30436 \HINT\ stream numbers start at 0 for the main text and continue
30437 upwards. \TeX, on the other hand, numbers insertions starting with
30438 {\tt box255} for the main text and continues downwards. Some mapping is
30439 needed, and we use the array |insert2stream| to map \TeX's insert
30440 numbers to \HINT\ stream numbers.
30441 The predefined stream for the main content has stream number 0.
30442
30443 @<Hi\TeX\ variables@>=
30444 static int insert2stream[0x100]={0};
30445 @ The following function returns the stream number for a given insert number $i$
30446 with $255>|i|\ge 0$. A new stream number is allocated if necessary.
30447 Note that no overflow test is necessary since \TeX\ allocates less
30448 than 233 inserts.
30449 The initial value of |max_ref[stream_kind]| is 0 and therefore
30450 stream number 0, reserved for the main content,
30451 is never allocated. Stream definitions might also be loaded
30452 as part of a format file. Then the maximum stream number is stored in |max_stream|.
30453 So if we do not find a stream number
30454 in the |insert2stream| array, we scan the stream definitions
30455 once and cache the associations found there.
30456
30457 @<Hi\TeX\ routines@>=
30458 static int hget_stream_no(int i)
30459 { static bool init=false;
30460 int s;
30461 if (i==0) return 0;
30462 s=insert2stream[i];
30463 if (s!=0) return s;
30464 if (!init)
30465 { pointer t,s;
30466 for (t=link(setpage_head); t!=null; t=link(t))
30467 for(s=setpage_streams(t); s!=null; s=link(s))
30468 insert2stream[setstream_insertion(s)]=setstream_number(s);
30469 max_ref[stream_kind]=max_stream;
30470 init=true;
30471 }
30472 s=insert2stream[i];
30473 if (s==0)
30474 s=insert2stream[i]=max_ref[stream_kind]=++max_stream;
30475 return s;
30476 }
30477 @*1 Stream Definitions.
30478
30479 A stream definition is stored as a whatsit node with subtype |setstream_node|.
30480 Given a pointer |p| to such a node, here are the macros used to access the data stored there:
30481 \def\item{\par\noindent\hbox to 0pt{$\bullet$\hss}\quad\ignorespaces }
30482 \item |setstream_number(p)| the \HINT\ stream number $n$.
30483 \item |setstream_insertion(p)| the corresponding \TeX\ insertion number $i$.
30484 \item |setstream_max(p)| the maximum height $x$:
30485 This extended dimension is the maximum size
30486 per page for this insertion.
30487 \item |setstream_mag(p)| the magnification factor $f$:
30488 Inserting a box of height $h$ will contribute $h*f/1000$
30489 to the main page.
30490 \item |setstream_preferred(p)| the preferred stream $p$:
30491 If $p\ge0$ we move the insert to stream $p$ if possible.
30492 \item |setstream_next(p)| the next stream $n$:
30493 If $n\ge0$ we move the insert to stream $n$ if it can not be
30494 accommodated otherwise.
30495 \item |setstream_ratio(p)| the split ratio $r$:
30496 If $r>0$ split the final contribution of this stream between
30497 stream $p$ and $n$ in the ratio $r/1000$ for $p$ and $1-r/1000$ for $n$
30498 before contributing streams $p$ and $n$ to the page.
30499 \item |setstream_before(p)| the ``before'' list $b$:
30500 For a nonempty stream the material that is added before the stream content.
30501 \item |setstream_after(p)| the ``after'' list $a$:
30502 For a nonempty stream the material that is added after the stream content.
30503 \item |setstream_topskip(p)| the top skip glue $t$: This glue is inserted between
30504 the $b$ list and the stream content and adjusted for the height for
30505 the first box of the stream content.
30506 \item |setstream_width(p)| the width $w$:
30507 This extended dimension is the width used for example
30508 to break paragraphs in the stream content into lines.
30509 \item |setstream_height(p)| a glue specification $h$ reflecting the total height,
30510 stretchability and shrinkability of the material in lists $a$ and $b$.
30511
30512
30513 Currently Hi\TeX\ handles only normal streams. First or last streams will come later.
30514
30515 The stream definition nodes are created and initialized with the following function:
30516 @<Hi\TeX\ routines@>=
30517 static pointer new_setstream_node(uint8_t n)
30518 { pointer p=get_node(setstream_node_size);
30519 type(p)=whatsit_node;subtype(p)=setstream_node;
30520 setstream_insertion(p)=n;
30521 setstream_number(p)=hget_stream_no(n);
30522 setstream_mag(p)=1000;
30523 setstream_preferred(p)=255;
30524 setstream_next(p)=255;
30525 setstream_ratio(p)=0;
30526 setstream_max(p)=new_xdimen(0,0,ONE);
30527 setstream_width(p)=new_xdimen(0,ONE,0);
30528 setstream_topskip(p)=zero_glue; add_glue_ref(zero_glue);
30529 setstream_height(p)=zero_glue; add_glue_ref(zero_glue);
30530 setstream_before(p)=null;
30531 setstream_after(p)=null;
30532
30533 return p;
30534 }
30535 @ The preferred stream, the next stream, and the split ratio are scanned as part of the
30536 {\tt \BS setstream} primitive.
30537 When \TeX\ finds the right brace that terminates the stream definition,
30538 it calls |handle_right_brace|. Then it is time to obtain the remaining parts of the
30539 stream definition.
30540 For insertion class $i$,
30541 we can extract the maximum height $x$ of the insertions from
30542 the corresponding {\tt dimen$i$} register
30543 the magnification factor $f$ from the {\tt count$i$} register,
30544 and the total height $h$ from the {\tt skip$i$} register.
30545 The width $w$ is taken from {\tt \BS hsize} and the
30546 topskip $t$ from {\tt \BS topskip}.
30547
30548 @<Hi\TeX\ routines@>=
30549 static void hfinish_stream_group(void)
30550 { pointer s;
30551 end_graf();
30552 s=hget_current_stream();
30553 if (s!=null)
30554 { pointer t;
30555 uint8_t i;
30556 i= setstream_insertion(s);
30557 setstream_mag(s)=count(i);
30558 setstream_width(s)=new_xdimen(dimen_par(hsize_code),
30559 dimen_par_hfactor(hsize_code),dimen_par_vfactor(hsize_code));
30560 t=zero_glue;add_glue_ref(t);delete_glue_ref(setstream_topskip(s)); setstream_topskip(s)=t;
30561 t=skip(i);add_glue_ref(t);delete_glue_ref(setstream_height(s)); setstream_height(s)=t;
30562 setstream_max(s)=new_xdimen(dimen(i),
30563 dimen_hfactor(i),dimen_vfactor(i));
30564 }
30565 unsave();
30566 flush_node_list(link(head));
30567 pop_nest();
30568 }
30569 @ The before list $b$ and the after list $a$ are defined using the
30570 {\tt \BS HINTbefore} and {\tt \BS HINTafter} primitives. When the corresponding list
30571 has ended with a right brace, \TeX\ calls |handle_right_brace| and we can store
30572 the lists.
30573
30574 @<Hi\TeX\ routines@>=
30575 static void hfinish_stream_before_group(void)
30576 { pointer s;
30577 end_graf();
30578 s=hget_current_stream();
30579 if (s!=null)
30580 setstream_before(s)=link(head);
30581 unsave();
30582 pop_nest();
30583 }
30584
30585 static void hfinish_stream_after_group(void)
30586 { pointer s;
30587 end_graf();
30588 s=hget_current_stream();
30589 if (s!=null)
30590 setstream_after(s)=link(head);
30591 unsave();
30592 pop_nest();
30593 }
30594 @*1 Page Template Definitions.
30595 These are the primitives needed to implement page templates:
30596
30597 @<Put each...@>=
30598 primitive("HINTsetpage", extension, setpage_node);@/
30599 @!@:setpage\_}{\.{\\setpage} primitive@>
30600
30601 primitive("HINTstream", extension, stream_node);@/
30602 @!@:stream\_}{\.{\\stream} primitive@>
30603
30604 primitive("HINTsetstream", extension, setstream_node);@/
30605 @!@:setstream\_}{\.{\\setstream} primitive@>
30606
30607 primitive("HINTbefore", extension, stream_before_node);@/
30608 @!@:before\_}{\.{\\before} primitive@>
30609
30610 primitive("HINTafter", extension, stream_after_node);@/
30611 @!@:after\_}{\.{\\after} primitive@>
30612
30613 @ The data describing a page template is stored in a whatsit node with subtype
30614 |setpage_node|.
30615 Given a pointer |p| to such a node, here are the macros used to access the data stored there:
30616
30617 \item |setpage_name(p)|: The name of the page template
30618 can be used in the user interface of a \HINT\ viewer.
30619 \item |setpage_number(p)|: The number of the page template that is used in the \HINT\
30620 file to reference this page template.
30621 \item |setpage_id(p)|: The number of the page template that is used in \TeX\
30622 to reference this page template.
30623 \item |setpage_priority(p)|: The priority helps in selecting a page template.
30624 \item |setpage_topskip(p)|: The topskip glue is added at the top of a page and
30625 adjusted by the height of the first box on the page.
30626 \item |setpage_height(p)|: The height of the full page including the margins.
30627 \item |setpage_width(p)|: The width of the full page including the margins.
30628 \item |setpage_depth(p)|: The maximum depth of the page content. If the last box is deeper
30629 than this maximum, the difference is subtracted from the height of the page body.
30630 \item |setpage_list(p)|: The list that defines the page template. After the page builder
30631 has completed a page this list is scanned and page body and nonempty streams
30632 are added at the corresponding insertion points.
30633 \item |setpage_streams(p)|: The list of stream definitions that
30634 belong to this page template.
30635
30636
30637 To allow \TeX\ to use arbitrary numbers between 1 and 255 for the page templates
30638 while in \HINT\ the numbers of page templates are best consecutive
30639 from 1 to |max_ref[page_kind]==max_page|, we let \TeX\ assign an id and generate
30640 the template number. Because templates might be in format files, the variable
30641 |max_page| will hold the true number.
30642
30643 The function |new_setpage_node| is called with the page template id
30644 $0<|i|<256$ and a string number for the name |n|.
30645 It allocates and initializes a node if necessary and moves it to the front of the
30646 list of templates.
30647
30648 @<Hi\TeX\ routines@>=
30649 static pointer new_setpage_node(uint8_t i, str_number n)
30650 { pointer p, prev_p;
30651 prev_p=setpage_head;
30652 for (p=link(prev_p); p!=null; prev_p=p,p=link(p))
30653 if (setpage_id(p)==i) break;
30654 if (p==null)
30655 @<allocate a new |setpage_node| |p|@>@;
30656 else
30657 link(prev_p)=link(p);
30658 link(p)=link(setpage_head);
30659 link(setpage_head)=p;
30660 return p;
30661 }
30662 @
30663 @<allocate a new |setpage_node| |p|@>=
30664 { p=get_node(setpage_node_size);type(p)=whatsit_node;subtype(p)=setpage_node;
30665 setpage_number(p)=max_ref[page_kind]=++max_page;
30666 setpage_id(p)=i;
30667 setpage_name(p)=n;
30668 setpage_priority(p)=1;
30669 setpage_topskip(p)=zero_glue; add_glue_ref(zero_glue);
30670 setpage_height(p)=new_xdimen(0,0,ONE);
30671 setpage_width(p)=new_xdimen(0,ONE,0);
30672 setpage_depth(p)=max_depth;
30673 setpage_list(p)=null;
30674 setpage_streams(p)=null;
30675 }
30676 @ The default values are replaced by parameters given to the {\tt\BS setpage}
30677 primitive and by the current values of certain
30678 \TeX\ registers when finishing the page template.
30679
30680 @<Hi\TeX\ routines@>=
30681 static void hfinish_page_group(void)
30682 { pointer p;
30683 end_graf();
30684 p=hget_current_page();
30685 if (p!=null)
30686 { delete_glue_ref(setpage_topskip(p));
30687 setpage_topskip(p)=top_skip;add_glue_ref(top_skip);
30688 setpage_depth(p)=max_depth;
30689 flush_node_list(setpage_list(p));
30690 setpage_list(p)=link(head);
30691 }
30692 unsave();
30693 pop_nest();
30694 }
30695 @ @<Hi\TeX\ auxiliary routines@>=
30696
30697 static pointer hget_current_page(void)
30698 { pointer p=link(setpage_head);
30699 if (p==null)
30700 print_err("end of output group without setpage node");
30701 return p;
30702 }
30703
30704 static pointer hget_current_stream(void)
30705 { pointer p,s;
30706 p=hget_current_page();
30707 if (p==null) return null;
30708 s=setpage_streams(p);
30709 if (s==null)
30710 print_err("end of setstream group without setstream node");
30711 return s;
30712 }
30713
30714 @* \HINT\ Output.
30715 Here are the routines to initialize and terminate the output.
30716 The initialization is done in three steps:
30717 First we allocate the data structures to write nodes into buffers;
30718 this requires a directory and buffers for sections 0, 1, and 2.
30719
30720 @ @<Hi\TeX\ routines@>=
30721 static void hout_allocate(void)
30722 { new_directory(dir_entries);
30723 new_output_buffers();
30724 max_section_no=2;
30725 hdef_init();
30726 hput_content_start();
30727 @<insert an initial language node@>@;
30728 }
30729
30730 @ Second we initialize the definitions and start the content section
30731 before the first content node is written; this is done when the
30732 |page_contents| is about to change from |empty| to not |empty|.
30733 Finally, the actual output file |hout| needs to be opened; this
30734 must be done before calling |hput_hint| which is already
30735 part of the termination routines. It is placed, however, much earlier
30736 because asking for the output file name---according to \TeX's
30737 conventions---should come before the first item is put on the first
30738 page by the page builder.
30739
30740 @<Hi\TeX\ routines@>=
30741 static void hint_open(void)
30742 { if (job_name==0) open_log_file();
30743 pack_job_name(".hnt");
30744 while (!(hout=open_out((char *)name_of_file+1,"wb")))
30745 prompt_file_name("file name for output",".hnt");
30746 output_file_name=make_name_string();
30747 DBG(DBGBASIC,"Output file %s opened\n",(char *)name_of_file+1);
30748 }
30749
30750 static void hput_definitions();
30751 extern int option_global;
30752 static void hout_terminate(void)
30753 { size_t s;
30754 if (hout==NULL) return;
30755 hput_content_end();
30756 hput_definitions();
30757 option_global=true; /* use global names in the directory */
30758 @<record the names of files in optional sections@>@;
30759 @<Compute subset fonts if requested@>@;
30760 hput_directory();
30761 s = hput_hint("created by HiTeX Version " HITEX_VERSION);
30762 print_nl("Output written on "); slow_print(output_file_name);
30763 @.Output written on x@>
30764 print(" (1 page, "); print_int(s); print(" bytes).");
30765 }
30766
30767 static void hint_close(void)
30768 { hout_terminate();
30769 if (hout!=NULL)
30770 fclose(hout);
30771 hout=NULL;
30772 }
30773
30774 @ The file name recording feature of Hi\TeX\ makes it necessary to
30775 record the names of the files that are added as optional sections.
30776 This feature is not part of the |hput_optional_sections| function
30777 which is called from |hput_hint|. The following simple
30778 loop will achieve this.
30779
30780 @<record the names of files in optional sections@>=
30781 { int i;
30782 for(i= 3;i<=max_section_no;i++)
30783 recorder_record_input(dir[i].file_name);
30784 }
30785
30786 @* The \HINT\ Directory.
30787 There is not much to do here: some code to find a new or existing directory entry,
30788 a variable to hold the number of directory entries allocated,
30789 a function to allocate a new file section, and an auxiliary function to
30790 convert \TeX's file names to ordinary \CEE/ strings.
30791
30792 @<Find an existing directory entry@>=
30793 for (i=3; i<= max_section_no;i++)
30794 if (dir[i].file_name!=NULL && strcmp(dir[i].file_name,file_name)==0)
30795 return i;
30796
30797 @ @<Allocate a new directory entry@>=
30798 i = max_section_no;
30799 i++;
30800 if (i>0xFFFF) QUIT("Too many file sections");
30801 if (i>=dir_entries)
30802 RESIZE(dir,dir_entries,Entry);
30803 max_section_no=i;
30804 if (max_section_no>0xFFFF) QUIT("Too many sections");
30805 dir[i].section_no=i;
30806
30807
30808 @ @<Hi\TeX\ macros@>=
30809 #define @[RESIZE(P,S,T)@] \
30810 { int _n = (S)*1.4142136 +0.5; \
30811 if (_n<32) _n=32; \
30812 { REALLOCATE(P,_n,T); \
30813 memset((P)+(S),0,(_n-(S))*sizeof(T)); \
30814 (S)=_n; \
30815 } \
30816 }
30817
30818
30819 @ @<Hi\TeX\ variables@>=
30820 static int dir_entries=4;
30821
30822 @ @<Hi\TeX\ auxiliary routines@>=
30823 static uint16_t hnew_file_section(char *file_name)
30824 { uint16_t i;
30825 @<Find an existing directory entry@>@;
30826 @<Allocate a new directory entry@>@;
30827 dir[i].file_name=strdup(file_name);
30828 return i;
30829 }
30830
30831 @ The following function uses \TeX's function |pack_file_name|
30832 to create a new filename from a name |n|, a directory or ``area'' |a|,
30833 and an extension |e|. \TeX\ will truncate the new filename
30834 to |file_name_size| characters without warning. The new function
30835 will take a |name_length| equal to | file_name_size| as an
30836 indication that truncation has taken place and terminates the
30837 program. The return value converts a {\mc Pascal} array, starting with index 1,
30838 into a \CEE/ array starting with index 0.
30839
30840 @<Hi\TeX\ auxiliary routines@>=
30841 static char *hfile_name(str_number n, str_number a, str_number e)
30842 { pack_file_name(n,a,e,NULL);
30843 if (name_length>=file_name_size)
30844 QUIT("File name too long %d >= %d",name_length,file_name_size);
30845 return (char *)name_of_file+1;
30846 }
30847
30848 @* \HINT\ Definitions.
30849 Definitions are used for two reasons: they provide default values for the parameters
30850 that drive \TeX's algorithms running in the \HINT\ viewer, and they provide a compact notation
30851 for \HINT\ content nodes.
30852
30853 To find the optimal coding for a \HINT\ file, a global knowledge of the \HINT\ file is necessary.
30854 This would require a two pass process:
30855 in the first pass Hi\TeX\ could gather statistics on the use of parameter values and content
30856 nodes as a basis for making definitions and in the second pass it could encode the content using
30857 these definitions. I consider it, however, more reasonable to write such a two pass optimizer
30858 as a separate program which can be used on any \HINT\ file.
30859 Hence Hi\TeX\ uses a much simpler one pass approach:
30860
30861 Hi\TeX\ generates definitions for \TeX-parameters using the
30862 values they have when the first non discardable item appears in
30863 |build_page|. This is usually the case after initial style files have
30864 been processed and we can expect that they set useful default values.
30865
30866 The procedure that generates these definitions is called |hfix_defaults|:
30867
30868 @<Hi\TeX\ auxiliary routines@>=
30869 static void hfix_defaults(void)
30870 { @+int i;
30871 DBG(DBGDEF,"Freezing HINT file defaults\n");
30872 @<Compute the page size@>@;
30873 @<Fix definitions for integer parameters@>@;
30874 @<Fix definitions for dimension parameters@>@;
30875 @<Fix definitions for glue parameters@>@;
30876 @<Fix definitions of page templates@>@;
30877 }
30878
30879 @ Further, Hi\TeX\ generates definitions to be used in content nodes on the fly:
30880 Whenever a routine outputs an item for which a definition might be available,
30881 it calls a {\it hget\_\,\dots\_no} function. This function returns, if possible,
30882 the reference number of a suitable definition.
30883 If no definition is available, the function will try to allocate a new one,
30884 only if all reference numbers from 0 to |0xFF| are already in use, a $-1$ is
30885 returned to indicate failure.
30886
30887 There are two possible problems with this approach: We might miss a
30888 very common item because it occurs for the first time late in the
30889 input when all reference numbers are already in use. For example an
30890 extensive index might repeat a certain pattern for each entry. And second, we
30891 might make a definition for an item that occurs only once. Taken
30892 together the definition plus the reference to it requires more space
30893 than the same item without a definition.
30894
30895 We can hope that the first effect does not occur too often, especially if the
30896 \TeX\ file is short, and we know that the second effect is limited by the
30897 total number of definitions we can make plus four byte of overhead per instance.
30898
30899
30900 Here we initialize the necessary data structures for definitions.
30901 @<Hi\TeX\ auxiliary routines@>=
30902 static void hdef_init(void)
30903 {@+ int i;
30904 @<Switch |hsize| and |vsize| to extended dimensions@>@;
30905 @<Initialize definitions for extended dimensions@>@;
30906 @<Initialize definitions for baseline skips@>@;
30907 @<Initialize definitions for fonts@>@;
30908 @<Initialize definitions for labels@>@;
30909 @<Initialize definitions for colors@>@;
30910 #if 0
30911 overfull_rule=0; /* no overfull rules please */
30912 #endif
30913 }
30914 @ After all definitions are ready, we write them using the function
30915 |hput_definitions|. When we output the definitions,
30916 we have to make sure to define references before we use them.
30917 This is achieved by using a specific ordering of the
30918 definitions in the function |hput_definitions| and by preventing
30919 the allocation of new definitions as soon as the output of the definition
30920 section has started. The latter has the additional benefit that the
30921 maximum values do no longer change.
30922
30923 @<Hi\TeX\ routines@>=
30924 static void hput_definitions()
30925 /* write the definitions into the definitions buffer */
30926 { int i;
30927 hput_definitions_start();
30928 hput_max_definitions();
30929 @<Output language definitions@>@;
30930 @<Output font definitions@>@;
30931 @<Output integer definitions@>@;
30932 @<Output dimension definitions@>@;
30933 @<Output extended dimension definitions@>@;
30934 @<Output glue definitions@>@;
30935 @<Output baseline skip definitions@>@;
30936 @<Output parameter list definitions@>@;
30937 @<Output discretionary break definitions@>@;
30938 @<Output color definitions@>@;
30939 @<Output page template definitions@>@;
30940 hput_definitions_end();
30941 hput_range_defs(); /* expects the definitions section to be ended */
30942 hput_label_defs();
30943 }
30944 @ In the following, we present for each node type the code to generate
30945 the definitions, using a common schema: We define a data structure
30946 called {\it\dots\_defined}, to hold the definitions; we define, if
30947 applicable, the \TeX-parameters; we add an {\it hget\_\,\dots\_no}
30948 function to allocate new definitions; and we finish with the code to
30949 output the collected definitions.
30950
30951 Lets start with the most simple case: integers.
30952
30953 @*1 Integers.
30954 The data structure to hold the integer definitions is a simple array with |0x100| entries.
30955 A more complex data structure, for example a hash table, could speed up searching for
30956 existing definitions but lets keep things simple for now.
30957
30958 @<Hi\TeX\ variables@>=
30959 static int32_t int_defined[0x100]={0};
30960 @ Before we can generate definitions for \TeX-parameters, we have to map \TeX's
30961 parameter numbers to \HINT\ definition numbers. While it seems more convenient here
30962 to have the reverse mapping, we need the mapping only once to record parameter definitions,
30963 but we will need it repeatedly in the function |hdef_param_node| and the overhead here does
30964 not warrant having the mapping in both directions.
30965
30966 @<Hi\TeX\ variables@>=
30967 static const int hmap_int[] ={@/
30968 pretolerance_no, /* |pretolerance_code| 0 */
30969 tolerance_no, /* |tolerance_code| 1 */
30970 line_penalty_no, /* |line_penalty_code| 2 */
30971 hyphen_penalty_no, /* |hyphen_penalty_code| 3 */
30972 ex_hyphen_penalty_no, /* |ex_hyphen_penalty_code| 4 */
30973 club_penalty_no, /* |club_penalty_code| 5 */
30974 widow_penalty_no, /* |widow_penalty_code| 6 */
30975 display_widow_penalty_no, /* |display_widow_penalty_code| 7 */
30976 broken_penalty_no, /* |broken_penalty_code| 8 */
30977 -1, /* |bin_op_penalty_code| 9 */
30978 -1, /* |rel_penalty_code| 10 */
30979 pre_display_penalty_no, /* |pre_display_penalty_code| 11 */
30980 post_display_penalty_no, /* |post_display_penalty_code| 12 */
30981 inter_line_penalty_no, /* |inter_line_penalty_code| 13 */
30982 double_hyphen_demerits_no, /* |double_hyphen_demerits_code| 14 */
30983 final_hyphen_demerits_no, /* |final_hyphen_demerits_code| 15 */
30984 adj_demerits_no, /* |adj_demerits_code| 16 */
30985 -1, /* |mag_code| 17 */
30986 -1, /* |delimiter_factor_code| 18 */
30987 looseness_no, /* |looseness_code| 19 */
30988 time_no, /* |time_code| 20 */
30989 day_no, /* |day_code| 21 */
30990 month_no, /* |month_code| 22 */
30991 year_no, /* |year_code| 23 */
30992 -1, /* |show_box_breadth_code| 24 */
30993 -1, /* |show_box_depth_code| 25 */
30994 -1, /* |hbadness_code| 26 */
30995 -1, /* |vbadness_code| 27 */
30996 -1, /* |pausing_code| 28 */
30997 -1, /* |tracing_online_code| 29 */
30998 -1, /* |tracing_macros_code| 30 */
30999 -1, /* |tracing_stats_code| 31 */
31000 -1, /* |tracing_paragraphs_code| 32 */
31001 -1, /* |tracing_pages_code| 33 */
31002 -1, /* |tracing_output_code| 34 */
31003 -1, /* |tracing_lost_chars_code| 35 */
31004 -1, /* |tracing_commands_code| 36 */
31005 -1, /* |tracing_restores_code| 37 */
31006 -1, /* |uc_hyph_code| 38 */
31007 -1, /* |output_penalty_code| 39 */
31008 -1, /* |max_dead_cycles_code| 40 */
31009 hang_after_no, /* |hang_after_code| 41*/
31010 floating_penalty_no /* |floating_penalty_code| 42*/
31011 };
31012
31013
31014 @ Now we can generate the definitions for integer parameters:
31015
31016 @<Fix definitions for integer parameters@>=
31017 int_defined[zero_int_no]=0;
31018 for (i=pretolerance_code; i<=floating_penalty_code;i++)
31019 if ( hmap_int[i]>=0) int_defined[hmap_int[i]]=int_par(i);
31020 max_ref[int_kind]=MAX_INT_DEFAULT;
31021 @ The function |hget_int_no| tries to allocate a predefined integer number;
31022 if not successful, it returns $-1$.
31023
31024 @<Hi\TeX\ auxiliary routines@>=
31025 static int hget_int_no(int32_t n)
31026 { int i;
31027 int m =max_ref[int_kind];
31028 for (i=0; i<=m; i++)
31029 if (n== int_defined[i]) return i;
31030 if (m<0xFF && section_no==2)
31031 { m=++max_ref[int_kind]; int_defined[m]=n; return m; }
31032 else
31033 return -1;
31034 }
31035 @ Before we give the code to output an integer definition, we declare a macro that
31036 is useful for all the definitions. |HPUTDEF| takes a function |F| and a reference number |R|.
31037 It is assumed that |F| writes a definition into the output and returns a tag. The macro
31038 will then add the reference number and both tags to the output.
31039 @<Hi\TeX\ macros@>=
31040 #define HPUTDEF(F,R) \
31041 { uint32_t _p; \
31042 uint8_t _f; \
31043 HPUTNODE; /* allocate */ \
31044 _p=hpos-hstart; \
31045 HPUT8(0); /* tag */ \
31046 HPUT8(R); /* reference */ \
31047 _f=F; \
31048 hstart[_p]=_f; DBGTAG(_f,hstart+_p); \
31049 DBGTAG(_f,hpos); HPUT8(_f); \
31050 }
31051 @ Definitions are written to the output only if they differ from Hi\TeX's built in defaults.
31052 @<Output integer definitions@>=
31053 DBG(DBGDEF,"Maximum int reference: %d\n",max_ref[int_kind]);
31054 for (i=max_fixed[int_kind]+1;i<=max_default[int_kind]; i++)
31055 { if (int_defined[i]!=int_defaults[i])@/
31056 HPUTDEF(hput_int(int_defined[i]),i);
31057 }
31058 for (;i<=max_ref[int_kind]; i++)@/
31059 HPUTDEF(hput_int(int_defined[i]),i);
31060 @*1 Dimensions.
31061 We proceed as we did for integers, starting with the array that holds the defined dimensions.
31062 @<Hi\TeX\ variables@>=
31063 static scaled dimen_defined[0x100]={0};
31064 @ @<Hi\TeX\ variables@>=
31065 static const int hmap_dimen[] ={@/
31066 -1, /* |par_indent_code| 0 */
31067 -1, /* |math_surround_code| 1 */
31068 line_skip_limit_no, /* |line_skip_limit_code| 2 */
31069 hsize_dimen_no, /* |hsize_code| 3 */
31070 vsize_dimen_no, /* |vsize_code| 4 */
31071 max_depth_no, /* |max_depth_code| 5 */
31072 split_max_depth_no, /* |split_max_depth_code| 6 */
31073 -1, /* |box_max_depth_code| 7 */
31074 -1, /* |hfuzz_code| 8 */
31075 -1, /* |vfuzz_code| 9 */
31076 -1, /* |delimiter_shortfall_code| 10 */
31077 -1, /* |null_delimiter_space_code| 11 */
31078 -1, /* |script_space_code| 12 */
31079 -1, /* |pre_display_size_code| 13 */
31080 -1, /* |display_width_code| 14 */
31081 -1, /* |display_indent_code| 15 */
31082 -1, /* |overfull_rule_code| 16 */
31083 hang_indent_no, /* |hang_indent_code| 17 */
31084 -1, /* |h_offset_code| 18 */
31085 -1, /* |v_offset_code| 19 */
31086 emergency_stretch_no /* |emergency_stretch_code| 20 */
31087 };
31088 @ @<Fix definitions for dimension parameters@>=
31089 dimen_defined[zero_dimen_no]=0;
31090 for (i=par_indent_code; i<=emergency_stretch_code;i++)
31091 if ( hmap_dimen[i]>=0) dimen_defined[hmap_dimen[i]]=dimen_par(i);
31092 dimen_defined[hsize_dimen_no]=page_h;
31093 dimen_defined[vsize_dimen_no]=page_v;
31094 dimen_defined[quad_no]=quad(cur_font);
31095 dimen_defined[math_quad_no]=math_quad(text_size);
31096 max_ref[dimen_kind]=MAX_DIMEN_DEFAULT;
31097 @ @<Hi\TeX\ auxiliary routines@>=
31098 static int hget_dimen_no(scaled s)
31099 /* tries to allocate a predefined dimension number in the range 0 to 0xFF
31100 if not successful return -1 */
31101 { int i;
31102 int m =max_ref[dimen_kind];
31103 for (i=0; i<=m; i++)
31104 if (s== dimen_defined[i]) return i;
31105 if (m<0xFF && section_no==2)
31106 { m=++max_ref[dimen_kind]; dimen_defined[m]=s; return m; }
31107 else
31108 return -1;
31109 }
31110 @ @<Output dimension definitions@>=
31111 DBG(DBGDEF,"Maximum dimen reference: %d\n",max_ref[dimen_kind]);
31112 for (i=max_fixed[dimen_kind]+1;i<=max_default[dimen_kind]; i++)
31113 { if (dimen_defined[i]!=dimen_defaults[i])
31114 HPUTDEF(hput_dimen(dimen_defined[i]),i);
31115 }
31116 for (;i<=max_ref[dimen_kind]; i++)
31117 HPUTDEF(hput_dimen(dimen_defined[i]),i);
31118 @*1 Extended Dimensions.
31119
31120 @<Hi\TeX\ variables@>=
31121 static struct {
31122 scaled w,h,v; } xdimen_defined[0x100];
31123 @ @<Initialize definitions for extended dimensions@>=
31124 for (i=0; i<=max_fixed[xdimen_kind]; i++)
31125 { xdimen_defined[i].w = xdimen_defaults[i].w;
31126 xdimen_defined[i].h = ONE*xdimen_defaults[i].h;
31127 xdimen_defined[i].v = ONE*xdimen_defaults[i].v;
31128 }
31129
31130 @ To obtain a reference number for an extended dimension, we search the
31131 array and if no match was found, we allocate a new entry,
31132 reallocating the array if needed.
31133
31134 @<Hi\TeX\ auxiliary routines@>=
31135 static int hget_xdimen_no(pointer p)
31136 { int i;
31137 for (i=0;i<=max_ref[xdimen_kind];i++)
31138 { if (xdimen_defined[i].w== xdimen_width(p) &&
31139 xdimen_defined[i].h== xdimen_hfactor(p) &&
31140 xdimen_defined[i].v== xdimen_vfactor(p))
31141 return i;
31142 }
31143 if (section_no!=2) return -1;
31144 if (i>=0x100) return -1;
31145 max_ref[xdimen_kind]=i;
31146 xdimen_defined[i].w= xdimen_width(p);
31147 xdimen_defined[i].h= xdimen_hfactor(p);
31148 xdimen_defined[i].v= xdimen_vfactor(p);
31149 return i;
31150 }
31151 @ @<Hi\TeX\ routines@>=
31152 static pointer new_xdimen(scaled w, scaled h, scaled v)
31153 { pointer p=get_node(xdimen_node_size);
31154 type(p)=whatsit_node;subtype(p)=xdimen_node;
31155 xdimen_width(p)=w;
31156 xdimen_hfactor(p)=h;
31157 xdimen_vfactor(p)=v;
31158 return p;
31159 }
31160 @ @<Output extended dimension definitions@>=
31161 DBG(DBGDEF,"Maximum xdimen reference: %d\n",max_ref[xdimen_kind]);
31162 for (i=max_fixed[xdimen_kind]+1;i<=max_default[xdimen_kind]; i++)
31163 { Xdimen x;
31164 x.w=xdimen_defined[i].w;
31165 x.h=xdimen_defined[i].h/(double)ONE;
31166 x.v=xdimen_defined[i].v/(double)ONE;
31167
31168 if (x.w!=xdimen_defaults[i].w ||
31169 x.h!=xdimen_defaults[i].h ||
31170 x.v!=xdimen_defaults[i].v)
31171 HPUTDEF(hput_xdimen(&x),i);
31172 }
31173 for (;i<=max_ref[xdimen_kind]; i++)
31174 { Xdimen x;
31175 x.w=xdimen_defined[i].w;
31176 x.h=xdimen_defined[i].h/(double)ONE;
31177 x.v=xdimen_defined[i].v/(double)ONE;
31178 HPUTDEF(hput_xdimen(&x),i);
31179 }
31180
31181 @*1 Glues.
31182 In general there are two choices on how to store a definition: We can use the data structures used by \TeX\
31183 or we can use the data structures defined by \HINT. If we are lucky, both of them are the same
31184 as we have seen for integers and dimensions. For extended dimensions, we had to use the \HINT\ data type
31185 |Xdimen| because \TeX\ has no corresponding data type and uses only reference numbers.
31186 In the case of glue, we definitely have a choice. We decide to use \TeX's pointers to glue specifications
31187 in the hope to save some work when comparing glues for equality, because \TeX\ already reuses
31188 glue specifications and often a simple comparison of pointers might suffice.
31189 @<Hi\TeX\ variables@>=
31190 static pointer glue_defined[0x100];
31191 @ @<Hi\TeX\ variables@>=
31192 static int hmap_glue[] ={
31193
31194 line_skip_no, /* |line_skip_code| 0 */
31195 baseline_skip_no, /* |baseline_skip_code| 1 */
31196 -1, /* |par_skip_code| 2 */
31197 above_display_skip_no, /* |above_display_skip_code| 3 */
31198 below_display_skip_no, /* |below_display_skip_code| 4 */
31199 above_display_short_skip_no, /* |above_display_short_skip_code| 5 */
31200 below_display_short_skip_no, /* |below_display_short_skip_code| 6 */
31201 left_skip_no, /* |left_skip_code| 7 */
31202 right_skip_no, /* |right_skip_code| 8 */
31203 top_skip_no, /* |top_skip_code| 9 */
31204 split_top_skip_no, /* |split_top_skip_code| 10 */
31205 tab_skip_no, /* |tab_skip_code| 11 */
31206 -1, /* |space_skip_code| 12 */
31207 -1, /* |xspace_skip_code| 13 */
31208 par_fill_skip_no /* |par_fill_skip_code| 14 */
31209 };
31210 @ @<Fix definitions for glue parameters@>=
31211 glue_defined[zero_skip_no]=zero_glue; incr(glue_ref_count(zero_glue));
31212 for (i=line_skip_code; i<=par_fill_skip_code;i++)
31213 if ( hmap_glue[i]>=0)
31214 { glue_defined[hmap_glue[i]]=glue_par(i); incr(glue_ref_count(glue_par(i)));}
31215 max_ref[glue_kind]=MAX_GLUE_DEFAULT;
31216 @ Next we define some auxiliary routines to compare glues for equality and to convert glues between the different representations.
31217
31218 @<Hi\TeX\ auxiliary routines@>=
31219 static int glue_spec_equal(pointer p, pointer q)
31220 { return (width(q)==width(p) && stretch(q)==stretch(p) && shrink(q)==shrink(p) &&
31221 (stretch_order(q)==stretch_order(p) || stretch(q)==0) &&
31222 (shrink_order(q)==shrink_order(p)|| shrink(q)==0));
31223 }
31224
31225 static int glue_equal(pointer p, pointer q)
31226 { return p==q || glue_spec_equal(p,q);
31227 }
31228
31229 static int Glue_equal(Glue *p, Glue *q)
31230 { return(p->w.w==q->w.w && p->w.h==q->w.h && p->w.v==q->w.v &&
31231 p->p.f== q->p.f && p->m.f==q->m.f &&
31232 (p->p.o==q->p.o || p->p.f==0.0) &&
31233 (p->m.o==q->m.o || q->m.f==0.0));
31234 }
31235
31236 @ To find a matching glue we make two passes over the defined glues:
31237 on the first pass we just compare pointers and on the second pass
31238 we also compare values. An alternative approach to speed up searching
31239 is used for parameter lists as described below.
31240
31241 @<Hi\TeX\ auxiliary routines@>=
31242 static int hget_glue_no(pointer p)
31243 { static int rover=0;
31244 int i;
31245 if (p==zero_glue) return zero_skip_no;
31246 for(i=0; i<= max_ref[glue_kind] ; i++)
31247 { if (p==glue_defined[rover]) return rover;
31248 else if (rover==0)
31249 rover=max_ref[glue_kind];
31250 else
31251 rover--;
31252 }
31253 for(i=0; i<= max_ref[glue_kind] ; i++)
31254 { pointer q=glue_defined[rover];
31255 if (glue_spec_equal(p,q))
31256 return rover;
31257 else if (rover==0)
31258 rover=max_ref[glue_kind];
31259 else
31260 rover--;
31261 }
31262 if (max_ref[glue_kind]<0xFF && section_no==2)
31263 { rover=++max_ref[glue_kind];
31264 glue_defined[rover]=p;
31265 incr(glue_ref_count(p));
31266 DBG(DBGDEF,"Defining new glue %d\n",rover);
31267 return rover;
31268 }
31269 else
31270 return -1;
31271 }
31272 @ @<Output glue definitions@>=
31273 DBG(DBGDEF,"Maximum glue reference: %d\n",max_ref[glue_kind]);
31274 for (i=max_fixed[glue_kind]+1;i<=max_default[glue_kind]; i++)
31275 { Glue g;
31276 to_Glue(glue_defined[i],&g);
31277 if (!Glue_equal(&g,&glue_defaults[i]))
31278 HPUTDEF(hput_glue(&g),i);
31279 }
31280 for (;i<=max_ref[glue_kind]; i++)
31281 HPUTDEF(hout_glue_spec(glue_defined[i]),i);
31282 @ The above code uses the following conversion routine.
31283 While \HINT\ supports glue that depends on {\tt hsize} and {\tt vsize},
31284 this is currently not supported by Hi\TeX.
31285 Future versions of Hi\TeX\ should extend glue spec nodes (and kern nodes)
31286 by fields for |hfactor| and |vfactor| which are zero by default.
31287 This would leave most parts of \TeX\ unchanged.
31288 As a work-around one can combine a box with an extended dimension with
31289 a regular glue or kern.
31290 % Care should be taken for the statically allocated glue specs
31291 % deallocation of glue specs is relatively simple
31292 % extended glue and kern values can be restricted to non math mode
31293 @<Hi\TeX\ auxiliary routines@>=
31294 static void to_Glue(pointer p, Glue *g)
31295 { g->w.w=width(p);
31296 g->w.h=g->w.v=0.0;
31297 g->p.f=stretch(p)/(double)ONE; g->p.o= stretch_order(p);
31298 g->m.f=shrink(p)/(double)ONE; g->m.o= shrink_order(p);
31299 }
31300 @*1 Baseline Skips.
31301 TeX's baseline nodes just store a baseline skip reference number.
31302 We have seen this situation before when dealing with extended dimensions
31303 and the solution here is the same: a dynamically allocated array.
31304 @<Hi\TeX\ variables@>=
31305 typedef struct {
31306 pointer ls, bs; /* line skip and baselineskip gluespecs */
31307 scaled lsl; /* lineskip limit */
31308 } bl_definition;
31309
31310 static bl_definition *bl_defined=NULL;
31311 static int bl_used=0,bl_allocated=0;
31312
31313 @ The zero baseline skip is predefined which prevents an ambiguous info value of zero
31314 in a baseline node.
31315
31316 @<Initialize definitions for baseline skips@>=
31317 bl_allocated=8;
31318 ALLOCATE(bl_defined,bl_allocated,bl_definition);
31319 bl_defined[zero_baseline_no].bs=zero_glue; incr(glue_ref_count(zero_glue));
31320 bl_defined[zero_baseline_no].ls=zero_glue; incr(glue_ref_count(zero_glue));
31321 bl_defined[zero_baseline_no].lsl=0;
31322 bl_used= MAX_BASELINE_DEFAULT+1;
31323 max_ref[baseline_kind]= MAX_BASELINE_DEFAULT;
31324 @ @<Hi\TeX\ auxiliary routines@>=
31325 static int hget_baseline_no(pointer bs, pointer ls, scaled lsl)
31326 {
31327 static int rover=0;
31328 int i;
31329 for(i=0; i< bl_used; i++) /* search for an existing spec */
31330 { bl_definition *q=&(bl_defined[rover]);
31331 if (glue_equal(bs,q->bs) && glue_equal(ls,q->ls) && lsl==q->lsl)
31332 return rover;
31333 else if (rover==0)
31334 rover=bl_used-1;
31335 else
31336 rover--;
31337 }
31338 if (bl_used>=bl_allocated)
31339 RESIZE(bl_defined,bl_allocated, bl_definition);
31340 rover=bl_used++;
31341 if (rover<0x100 && section_no==2) max_ref[baseline_kind]=rover;
31342 if (glue_equal(bs,zero_glue))
31343 { bl_defined[rover].bs=zero_glue; incr(glue_ref_count(zero_glue)); }
31344 else
31345 { bl_defined[rover].bs=bs; incr(glue_ref_count(bs));}
31346 if (glue_equal(ls,zero_glue))
31347 { bl_defined[rover].ls=zero_glue; incr(glue_ref_count(zero_glue)); }
31348 else
31349 { bl_defined[rover].ls=ls; incr(glue_ref_count(ls));}
31350 bl_defined[rover].lsl=lsl;
31351 return rover;
31352 }
31353
31354 @ The following routine does not allocate a new glue definition, because the
31355 baseline definitions are output after the glue definitions. This is not perfect.
31356 @<Hi\TeX\ auxiliary routines@>=
31357 static uint8_t hout_glue_spec(pointer p);
31358 static uint8_t hout_baselinespec(int n)
31359 { Info i=b000;
31360 pointer p;
31361 scaled s;
31362 s=bl_defined[n].lsl;
31363 if (s!=0) {HPUT32(s); i|=b001;}
31364 p=bl_defined[n].bs;
31365 if (p!=zero_glue)
31366 { uint8_t *pos;
31367 uint8_t tag;
31368 HPUTNODE; /* allocate */
31369 pos=hpos;
31370 hpos++; /* tag */
31371 tag=hout_glue_spec(p);
31372 *pos=tag; DBGTAG(tag,pos);
31373 DBGTAG(tag,hpos); HPUT8(tag);
31374 i|=b100;
31375 }
31376 p=bl_defined[n].ls;
31377 if (p!=zero_glue)
31378 { uint8_t *pos;
31379 uint8_t tag;
31380 HPUTNODE; /* allocate */
31381 pos=hpos;
31382 hpos++; /* tag */
31383 tag=hout_glue_spec(p);
31384 *pos=tag; DBGTAG(tag,pos);
31385 DBGTAG(tag,hpos); HPUT8(tag);
31386 i|=b010;
31387 }
31388 return TAG(baseline_kind,i);
31389 }
31390 @ @<Output baseline skip definitions@>=
31391 DBG(DBGDEF,"Defining %d baseline skips\n",max_ref[baseline_kind]);
31392 for (i=1;i<=max_ref[baseline_kind]; i++)
31393 { uint32_t pos=hpos-hstart;
31394 uint8_t tag;
31395 hpos++; /* space for the tag */
31396 HPUT8(i); /* reference */
31397 tag=hout_baselinespec(i);
31398 hstart[pos]=tag;
31399 HPUT8(tag);
31400 }
31401 @ The following function is needed in Hi\TeX\ to produce debugging output if needed.
31402 @<Hi\TeX\ routines@>=
31403 static void print_baseline_skip(int i)
31404 { if (0<=i && i < bl_used)
31405 { print_spec(bl_defined[i].bs,0); print_char(',');
31406 print_spec(bl_defined[i].ls,0); print_char(',');
31407 print_scaled(bl_defined[i].lsl);
31408 }
31409 else
31410 print("unknown");
31411 }
31412 @*1 Discretionary breaks.
31413 For discretionary breaks, we use again the pointer representation.
31414 @<Hi\TeX\ variables@>=
31415 static pointer dc_defined[0x100];
31416 @ There are no predefined discretionary breaks and so we start with
31417 three auxiliary functions and the
31418 function to get a ``disc'' number.
31419
31420 The first two routines are used to compare discretionary breaks
31421 in order to reuse already defined disc numbers.
31422 The pre and post break lists must consist entirely of character,
31423 kern, box, rule, and ligature nodes.
31424 Unfortunately a box node might contain all kinds of nodes
31425 and its content might be huge and deeply nested.
31426 The following routine will not make a complete comparison but will give
31427 up if the box content is ``too complex''.
31428
31429 @<Hi\TeX\ auxiliary routines@>=
31430 static bool list_equal(pointer p, pointer q);
31431 static bool node_equal(pointer p, pointer q)
31432 { if (is_char_node(p) && is_char_node(q) &&
31433 font(p)==font(q) && character(p)==character(q))
31434 return true;
31435 if (!is_char_node(p) && !is_char_node(q))
31436 { if (type(p)!=type(q)) return false;
31437 if (type(p)==kern_node &&
31438 subtype(p)==subtype(q) && width(p)==width(q))
31439 return true;
31440 if (type(p)==ligature_node &&
31441 character(lig_char(p)) == character(lig_char(q)) &&
31442 font(lig_char(p)) == font(lig_char(q)))
31443 return true;
31444 if (type(p)==rule_node &&
31445 width(p)==width(q) && height(p)==height(q) && depth(p)==depth(q))
31446 return true;
31447 if ((type(p)==hlist_node || type(p)==vlist_node) &&
31448 width(p)==width(q) && height(p)==height(q) && depth(p)==depth(q) &&
31449 shift_amount(p)==shift_amount(q) &&
31450 glue_sign(p) == glue_sign(q) &&
31451 glue_order(p) == glue_order(q) &&
31452 glue_set(p) == glue_set(q) &&
31453 list_equal(list_ptr(p),list_ptr(q)))
31454 return true;
31455 }
31456 return false;
31457 }
31458
31459 static bool list_equal(pointer p, pointer q)
31460 {@+while (true)
31461 { if (p==q) return true;
31462 if (p==null || q==null) return false;
31463 if (!node_equal(p,q)) return false;
31464 p=link(p);q=link(q);
31465 }
31466 }
31467
31468 static pointer copy_disc_node(pointer p)
31469 { pointer q;
31470 q=get_node(small_node_size);
31471 pre_break(q)=copy_node_list(pre_break(p));
31472 post_break(q)=copy_node_list(post_break(p));
31473 type(q)=type(p);
31474 subtype(q)=subtype(p); /* replace count and explicit bit */
31475 return q;
31476 }
31477 @ @<Hi\TeX\ routines@>=
31478 static int hget_disc_no(pointer p)
31479 {
31480 static int rover=0;
31481 int i;
31482 for(i=0; i<= max_ref[disc_kind]; i++)
31483 { pointer q=dc_defined[rover];
31484 if ( is_auto_disc(p)==is_auto_disc(q) && replace_count(p)==replace_count(q) &&
31485 list_equal(pre_break(p),pre_break(q)) &&
31486 list_equal(post_break(p),post_break(q)))
31487 return rover;
31488 else if (rover==0)
31489 rover=max_ref[disc_kind];
31490 else
31491 rover--;
31492 }
31493 if (max_ref[disc_kind]>=0xFF || section_no!=2) return -1;
31494
31495 rover=++max_ref[disc_kind];
31496 dc_defined[rover]=copy_disc_node(p);
31497 @<Allocate font numbers for glyphs in the pre- and post-break lists@>@;
31498 return rover;
31499 }
31500 @ When we allocate disc numbers we might have fonts inside the pre-
31501 or post-break list, that never show up anywhere else in the content.
31502 These fonts would then be undefined once we start the definition section.
31503 So we have to make sure, all necessary fonts get defined.
31504
31505 @<Allocate font numbers for glyphs in the pre- and post-break lists@>=
31506 ensure_font_no(pre_break(p));
31507 ensure_font_no(post_break(p));
31508 @ @<Output discretionary break definitions@>=
31509 DBG(DBGDEF,"Maximum disc reference: %d\n",max_ref[disc_kind]);
31510 for (i=0;i<=max_ref[disc_kind]; i++)
31511 HPUTDEF(hout_disc(dc_defined[i]),i);
31512
31513 @*1 Parameter Lists.
31514 We store predefined parameter lists in a hash table in order to speed up
31515 finding existing parameter lists. The parameter list itself is stored as
31516 a byte sequence using the short \HINT\ file format.
31517 We link the table entries in order of increasing reference numbers to be able
31518 to output them in a more ``orderly'' fashion.
31519
31520 @<Hi\TeX\ variables@>=
31521
31522 #define PLH_SIZE 313 /* a prime number $\approx2^8\times 1.2$. */
31523
31524 static struct {int l; /* link */
31525 uint32_t h; /* hash */
31526 uint32_t n; /* number */
31527 uint32_t s; /* size */
31528 uint8_t *p; /* pointer */} pl_defined[PLH_SIZE]={{0}};
31529 static int pl_head=0, *pl_tail=&pl_head;
31530
31531 @ Next we define three short auxiliary routines and the |hget_param_list_no| function.
31532
31533 @<Hi\TeX\ routines@>=
31534
31535 static uint32_t hparam_list_hash(List *l)
31536 { uint32_t h=0;
31537 uint32_t i;
31538 for (i=0;i<l->s;i++)
31539 h=3*h+hstart[l->p+i];
31540 return h;
31541 }
31542
31543 static bool pl_equal(List *l, uint8_t *p)
31544 { uint8_t *q=hstart+l->p;
31545 uint32_t i;
31546 for (i=0; i<l->s; i++)
31547 if (q[i]!=p[i]) return false;
31548 return true;
31549 }
31550
31551 static void pl_copy(List *l, uint8_t *p)
31552 { uint8_t *q=hstart+l->p;
31553 memcpy(p,q,l->s);
31554 }
31555
31556 static int hget_param_list_no(List *l)
31557 { uint32_t h;
31558 int i;
31559 if (l->s<=0) return 0;
31560 h= hparam_list_hash(l);
31561 i = h%PLH_SIZE;
31562 while (pl_defined[i].p!=NULL)
31563 { if (pl_defined[i].h==h && pl_equal(l,pl_defined[i].p))
31564 return pl_defined[i].n;
31565 i=i+199; /* some other prime */
31566 if (i>=PLH_SIZE) i=i-PLH_SIZE;
31567 }
31568 if (max_ref[param_kind]>=0xFF || section_no!=2) return -1;
31569 pl_defined[i].n=++max_ref[param_kind];
31570 *pl_tail=i; pl_tail=&(pl_defined[i].l);
31571 pl_defined[i].l=0;
31572 pl_defined[i].h=h;
31573 pl_defined[i].s=l->s;
31574 ALLOCATE(pl_defined[i].p,l->s,uint8_t);
31575 pl_copy(l,pl_defined[i].p);
31576 return pl_defined[i].n;
31577 }
31578 @ To output parameter lists, we need a function to output a parameter node:
31579
31580 @<Hi\TeX\ routines@>=
31581 static void hdef_param_node(int ptype, int pnumber,int pvalue)
31582 {
31583 if (ptype==int_type)
31584 { if (pvalue==int_defined[hmap_int[pnumber]]) return;
31585 else HPUTDEF(hput_int(pvalue),hmap_int[pnumber]);
31586 }
31587 else if (ptype==dimen_type)
31588 { if (pvalue==dimen_defined[hmap_dimen[pnumber]]) return;
31589 else HPUTDEF(hput_dimen(pvalue),hmap_dimen[pnumber]);
31590 }
31591 else if (ptype==glue_type)
31592 { if (glue_equal(pvalue,glue_defined[hmap_glue[pnumber]])) return;
31593 else HPUTDEF(hout_glue_spec((pointer)pvalue),hmap_glue[pnumber]);
31594 }
31595 else QUIT("Unexpected parameter type %d",ptype);
31596 }
31597 @ Now we use the linked list starting with |pl_head| to output the predefined
31598 parameter lists sorted by their reference number.
31599
31600 @<Output parameter list definitions@>=
31601 DBG(DBGDEF,"Defining %d parameter lists\n",max_ref[param_kind]);
31602 for (i=pl_head;i>0;i=pl_defined[i].l)
31603 { int j,k;
31604 DBG(DBGDEF,"Defining parameter list %d, size 0x%x\n",i,pl_defined[i].s);
31605 j=hsize_bytes(pl_defined[i].s);
31606 HPUTX(1+1+j+1+pl_defined[i].s+1+j+1);
31607 if (j==4) k=3; else k=j;
31608 HPUTTAG(param_kind,k);
31609 HPUT8(pl_defined[i].n);
31610 hput_list_size(pl_defined[i].s,j);
31611 HPUT8(0x100-k);
31612 memcpy(hpos,pl_defined[i].p,pl_defined[i].s);
31613 hpos=hpos+pl_defined[i].s;
31614 HPUT8(0x100-k);
31615 hput_list_size(pl_defined[i].s,j);
31616 HPUTTAG(param_kind,k);
31617 }
31618 @*1 Fonts.
31619 To store a font definition, we define the data type |Font|
31620 and an array |hfonts| of pointers indexed by \HINT\ font numbers.
31621 To map \HINT\ font numbers to \TeX\ font numbers, the |Font| contains
31622 the |i| field; to map \TeX\ font numbers to \HINT\ font numbers,
31623 we use the array |hmap_font|.
31624
31625 @<Hi\TeX\ variables@>=
31626 #define MAX_FONTS 0x100
31627
31628 typedef struct {
31629 uint8_t i; /* the \TeX\ font number */
31630 pointer g; /* space glue */
31631 pointer h; /* default hyphen */
31632 pointer p[MAX_FONT_PARAMS]; /* font parameters */
31633 int m; /* section number of font metric file */
31634 uint16_t y; /* section number of font glyph file */
31635 } Font;
31636
31637 static Font *hfonts[MAX_FONTS]={NULL};
31638 static int hmap_font[MAX_FONTS];
31639 @ @<Initialize definitions for fonts@>=
31640 for (i=0;i<0x100;i++) hmap_font[i]=-1;
31641 max_ref[font_kind]=-1;
31642
31643 @ Allocation of a |Font| record takes place when we translate a \TeX\ font
31644 number to a \HINT\ font number using the function |hget_font_no|, and while
31645 doing so discover that the corresponding \HINT\ font number does not yet exist.
31646 Because the |Font| structure must be initialized after allocating it,
31647 we start with some auxiliary routines for that purpose.
31648
31649 @<Hi\TeX\ auxiliary routines@>=
31650 static pointer find_space_glue(internal_font_number f)
31651 {@+font_index @!main_k;
31652 pointer main_p=font_glue[f];
31653 if (main_p==null)
31654 {@+main_p=new_spec(zero_glue);main_k=param_base[f]+space_code;
31655 width(main_p)=font_info[main_k].sc; /*that's |space(f)|*/
31656 stretch(main_p)=font_info[main_k+1].sc; /*and |space_stretch(f)|*/
31657 shrink(main_p)=font_info[main_k+2].sc; /*and |space_shrink(f)|*/
31658 font_glue[f]=main_p;
31659 }
31660 return main_p;
31661 }
31662 static pointer hget_font_space(uint8_t f)
31663 { pointer p;
31664 if (space_skip==zero_glue)
31665 p = find_space_glue(f);
31666 else
31667 p=glue_par(space_skip_code);
31668 add_glue_ref(p);
31669 return p;
31670 }
31671
31672
31673 static pointer hget_font_hyphen(uint8_t f)
31674 { pointer p;
31675 int c;
31676 p=new_disc();
31677 c= hyphen_char[f];
31678 if (c >= 0 && c < 256) pre_break(p)=new_character(f, c);
31679 return p;
31680 }
31681
31682
31683 static void hdef_font_params(pointer p[MAX_FONT_PARAMS])
31684 { /* used only for texts */
31685 }
31686
31687 @ In the following code, |f| is a \TeX\ internal font number
31688 and |g| is the corresponding \HINT\ font number.
31689 \TeX's null-font, a kind of undefined font containing no characters
31690 is replaced by \HINT's font number zero. Actually the nullfont should
31691 never appear in the output, but if it does so, either an error message
31692 or a more sensible replacement font might be in order.
31693
31694 Finding the right font file based on the name of the name of the {\tt .tfm} file
31695 might require finding a {\tt .map} file using |kpse_find_file(name,kpse_fontmap_format,false)|.
31696 This is currently not implemented.
31697
31698 %It seems I need: (see email by Karl)
31699 %|kpse_find_file(name,kpse_fontmap_format,false);|
31700 %with name "ps2pk.map" or "psfonts.map" or "ttfonts.map" or cmfonts.map
31701 %to get from the tfm name the postscript name.
31702 %then I get the |psfont_name| usually its the same font name
31703 %with .pfb appended
31704 %so I can skip it
31705 %#ifdef HAVE_KPSE_ENC_FORMATS
31706 % enc_file=kpse_find_file(encoding,kpse_enc_format,false);
31707 %#else
31708 % enc_file=kpse_find_file(encoding,kpse_tex_ps_header_format,false);
31709 %#endif
31710 %reading the encoding is found in dvipng/dvipnd-src/enc.c
31711
31712 @<Hi\TeX\ auxiliary routines@>=
31713 static char *hfind_glyphs(char *filename)
31714 { char *fname=NULL;
31715 kpse_glyph_file_type file_ret;
31716 fname=kpse_find_file(filename,kpse_type1_format,true);
31717 /* the unlikely case of a TrueType/OpenType font with TFM file */
31718 if (fname==NULL) fname=kpse_find_file(filename,kpse_truetype_format,true);
31719 if (fname==NULL) fname=kpse_find_file(filename,kpse_opentype_format,true);
31720 if (fname==NULL) fname = kpse_find_glyph(filename, option_dpi,kpse_pk_format, &file_ret);
31721 return fname;
31722 }
31723
31724 static uint8_t hget_font_no(uint8_t f)
31725 { int g;
31726 char *n;
31727 if (f==0)
31728 { DBG(DBGFONT,"TeX nullfont -> 0\n");
31729 return 0;@+
31730 }
31731 g=hmap_font[f];
31732 if (g>=0) return g;
31733 DBG(DBGDEF,"New TeX font %d\n",f);
31734 if (max_ref[font_kind]>=0x100)
31735 QUIT("too many fonts in use");
31736 g = ++(max_ref[font_kind]);
31737 ALLOCATE(hfonts[g],1,Font);
31738 hfonts[g]->i=f;
31739 hmap_font[f]=g;
31740 hfonts[g]->g=hget_font_space(f);
31741 hfonts[g]->h=hget_font_hyphen(f);
31742 if (IS_X_FONT(f))
31743 { hfonts[g]->m= -1;
31744 pack_file_name(font_area[f], empty_string, empty_string,"");
31745 hfonts[g]->y= hnew_file_section((char*)name_of_file+1);
31746 }
31747 else
31748 { pack_file_name(font_name[f], empty_string,empty_string,".tfm");
31749 n = kpse_find_tfm((char*)name_of_file+1);
31750 if (n==NULL)
31751 QUIT("Unable to find .tfm file for font %s",(char*)name_of_file+1);
31752 hfonts[g]->m= hnew_file_section(n);
31753 free(n);
31754 pack_file_name(font_name[f], empty_string,empty_string,"");
31755 n= hfind_glyphs((char*)name_of_file+1);
31756 if (n==NULL)
31757 QUIT("Unable to find glyph file for font %s",(char*)name_of_file+1);
31758 hfonts[g]->y= hnew_file_section(n);
31759 free(n);
31760 }
31761 DBG(DBGFONT,"Mapping TeX font %d->%d\n",f,g);
31762 return g;
31763 }
31764
31765 @ Surprisingly, not all characters that occur in a \HINT\ file are inside the
31766 content section; some characters might hide in the definition section
31767 inside the pre- or post-break list of a predefined discretionary break.
31768 To make sure that the fonts necessary for these characters are included
31769 in the final \HINT\ file, we check these lists to make sure all \TeX\ font
31770 numbers have a corresponding \HINT\ font number.
31771
31772 @<Hi\TeX\ auxiliary routines@>=
31773 static void ensure_font_no(pointer p)
31774 { while (p!=null)
31775 { if (is_char_node(p))
31776 hget_font_no(font(p));
31777 else if (type(p)==hlist_node||type(p)==vlist_node)
31778 ensure_font_no(list_ptr(p));
31779 p=link(p);
31780 }
31781 }
31782 @ @<Output font definitions@>=
31783 { int f;
31784 DBG(DBGDEF,"Defining %d fonts\n",max_ref[font_kind]+1);
31785 for (f=0;f<=max_ref[font_kind];f++)
31786 { Font *hf=hfonts[f];
31787 internal_font_number g=hf->i;
31788 uint32_t pos=hpos-hstart;
31789 Info i;
31790 DBG(DBGDEF,"Defining font %d size 0x%x\n",f,font_size[g]);
31791 hpos++; HPUTNODE; /* space for the tag and the node */
31792 HPUT8(f); /* reference */
31793 hout_string(font_id_text(g));
31794 if(font_size[g]>0) HPUT32(font_size[g]);
31795 else HPUT32(font_dsize[g]);
31796 if (hf->m>=0) { i=b000; HPUT16(hf->m);} else i=b001;
31797 HPUT16(hf->y);
31798 DBG(DBGDEF,"Defining font space\n");
31799 HPUTCONTENT(hout_glue_spec,hf->g);
31800 DBG(DBGDEF,"Defining font hyphen\n");
31801 HPUTCONTENT(hout_disc,hf->h);
31802 hdef_font_params(hf->p);
31803 DBG(DBGDEF,"End of font %d\n",f);
31804 hput_tags(pos,TAG(font_kind,i));
31805 }
31806 }
31807 @ We used the following function to write a \TeX\ string to the \HINT\ file:
31808 @<Hi\TeX\ auxiliary routines@>=
31809 static void hout_string(int s)
31810 { pool_pointer j;
31811 uint8_t c;
31812 j= str_start[s];
31813 while(j<str_start[s+1])
31814 { c= str_pool[j++];
31815 if (c=='%' || c < 0x20 ||c >= 0x7F)
31816 { char str[4];
31817 snprintf(str,4,"%%%02X",c);/* convert to printable ASCII */
31818 HPUTX(3);
31819 HPUT8(str[0]); HPUT8(str[1]); HPUT8(str[2]);
31820 }
31821 else
31822 { HPUTX(1);
31823 HPUT8(c);
31824 }
31825 }
31826 HPUT8(0);
31827 }
31828 @ We used the following macro to add tags around the font glue and the font hyphen:
31829
31830
31831 @<Hi\TeX\ macros@>=
31832
31833 #define HPUTCONTENT(F,D) \
31834 { uint32_t _p; \
31835 uint8_t _f; \
31836 HPUTNODE; /* allocate */ \
31837 _p=hpos++-hstart; /* tag */ \
31838 _f=F(D); \
31839 *(hstart+_p)=_f; DBGTAG(_f,hstart+_p); \
31840 DBGTAG(_f,hpos); HPUT8(_f); \
31841 }
31842
31843 @*1 Labels.
31844 The only label that must always exist is the zero label. It is used
31845 to mark the ``home'' position of a document.
31846
31847 We allocate the zero label with the first call to |next_label|
31848 and initialize it with the value from |label_defaults|.
31849 We then make sure it can be found under the name ``HINT.home''.
31850
31851 @<Initialize definitions for labels@>=
31852 { char nom[]="HINT.home";
31853 unsigned int h=name_hash(nom)%LABEL_HASH;
31854 int i=insert_hash(h,0,nom);
31855 if (i!=zero_label_no)
31856 QUIT("Trying to allocate the zero label, got %d",i);
31857 labels[zero_label_no]=label_defaults[zero_label_no];
31858 labels[zero_label_no].next=first_label;
31859 first_label=zero_label_no;
31860 DBG(DBGLABEL,"Defining zero label: pos=0x%x\n",labels[zero_label_no].pos);
31861 }
31862 @*1 Page Templates.
31863
31864 Once we start producing content nodes, we update the maximum numbers
31865 of page templates and streams from |max_page| and |max_stream|.
31866 These values might have changed because templates were loaded from a
31867 format file.
31868
31869 @<Fix definitions of page templates@>=
31870 max_ref[page_kind]=max_page;
31871 max_ref[stream_kind]=max_stream;
31872 @ As part of a page template, we will see stream insertion nodes.
31873 When we encounter an |stream_node| inside a template definition,
31874 we output a stream insertion point.
31875
31876 @<cases to output whatsit content nodes@>=
31877 case stream_node:
31878 HPUT8(setstream_number(p));
31879 tag=TAG(stream_kind,b100);
31880 break;
31881 @ @<Output page template definitions@>=
31882 DBG(DBGDEF,"Maximum page template reference: %d\n",max_page);
31883 { pointer t;
31884 for (t=link(setpage_head);t!=null;t=link(t))
31885 { uint32_t pos=hpos-hstart;
31886 DBG(DBGDEF,"Defining page template %d\n",setpage_number(i));@/
31887 hpos++; HPUTNODE; /* space for the tag and the node */
31888 HPUT8(setpage_number(t));
31889 hout_string(setpage_name(t));
31890 HPUT8(setpage_priority(t));
31891 hout_glue_node(setpage_topskip(t));
31892 hput_dimen(setpage_depth(t));
31893 hout_xdimen_node(setpage_height(t));
31894 hout_xdimen_node(setpage_width(t));
31895 hout_list_node2(setpage_list(t));
31896 @<output stream definitions@>@;
31897 hput_tags(pos,TAG(page_kind,0));
31898 }
31899 }
31900 @ As part of the output of page template definitions, we output
31901 stream definitions:
31902
31903 @<output stream definitions@>=
31904 { pointer p,q;
31905 p = setpage_streams(t);
31906 while (p!=null)
31907 { uint8_t n;
31908 n=setstream_number(p);
31909 DBG(DBGDEF,"Defining stream %d at " SIZE_F "\n",n,hpos-hstart);
31910 HPUTTAG(stream_kind,b100);
31911 HPUT8(n);
31912 hout_xdimen_node(setstream_max(p)); /* maximum height */
31913 HPUT16(setstream_mag(p)); /* factor */
31914 HPUT8(setstream_preferred(p)); /* preferred */
31915 HPUT8(setstream_next(p)); /* next */
31916 HPUT16(setstream_ratio(p)); /* ratio */
31917 q=setstream_before(p);setstream_before(p)=null;
31918 hout_list_node2(q);flush_node_list(q);
31919 hout_xdimen_node(setstream_width(p));
31920 q=setstream_topskip(p);
31921 hout_glue_node(q); delete_glue_ref(q);
31922 q=setstream_after(p);setstream_after(p)=null;
31923 hout_list_node2(q);flush_node_list(q);
31924 q=setstream_height(p);
31925 hout_glue_node(q); delete_glue_ref(q);
31926 HPUTTAG(stream_kind,b100);
31927 p=link(p);
31928 }
31929 }
31930 @* \HINT\ Content.
31931 \TeX\ puts content nodes on the contribution list and once in a while calls |build_page| to
31932 move nodes from the contribution list to the current page. Hi\TeX\ has a special version of
31933 |build_page| that will simply remove nodes from the contribution list and passes them
31934 to the function |hout_node|.
31935 The actual output of \HINT\ nodes is accomplished with functions defined in {\tt put.c}
31936 (see~Martin Ruckert, The \HINT\ file format).
31937
31938 @<Hi\TeX\ routines@>=
31939 static void hout_node(pointer p)
31940 { uint32_t pos=hpos-hstart;
31941 uint8_t tag;
31942 HPUTNODE;
31943 hpos++;
31944 if(is_char_node(p))
31945 @<output a character node@>@;
31946 else switch(type(p)) @/
31947 { @<cases to output content nodes@>@t\1@>@;
31948 default:
31949 MESSAGE("\nOutput of node type=%d subtype=%d not implemented\n", type(p),subtype(p));
31950 hpos--;
31951 return;@t\2@>@;
31952 }
31953 hput_tags(pos,tag);
31954 }
31955
31956 @*1 Characters.
31957 The processing of a character node consist of three steps: checking for definitions, converting the
31958 \TeX\ node pointed to by |p| to a \HINT\ data type, here a |Glyph|, and using the
31959 corresponding {\tt hput\_\,\dots} function to output the node and return the |tag|.
31960 In the following, we will see the same approach in many
31961 small variations for all kinds of nodes.
31962
31963 @<output a character node@>=
31964 { Glyph g;
31965 g.f=hget_font_no(font(p));
31966 g.c = character(p);
31967 @<Register character node |p| in the font subset@>@;
31968 tag=hput_glyph(&g);
31969 }
31970 @*1 Penalties.
31971 Integer nodes, which as content nodes are used for penalties, come next.
31972 Except for the embedding between |case| and |break|, the
31973 processing of penalty nodes follows the same pattern we have just seen.
31974 @<cases to output content nodes@>=
31975 case penalty_node:
31976 { int n,i;
31977 i = penalty(p);
31978 if (i>20000) i=20000;
31979 else if (i<-20000) i=-20000;
31980 n=hget_int_no(i);
31981 if (n<0) tag=hput_int(i);
31982 else { HPUT8(n); tag=TAG(penalty_kind,0);}
31983 }
31984 break;
31985 @*1 Kerns.
31986 The kern nodes of \TeX\ contain a single dimension and a flag to mark ``explicit'' kerns.
31987 @<cases to output content nodes@>=
31988 case kern_node:
31989 { int n;
31990 n=hget_dimen_no(width(p));
31991 if (n<0)
31992 { Kern k;
31993 k.x=(subtype(p)==explicit);
31994 k.d.w=width(p);
31995 k.d.h=k.d.v=0.0;
31996 tag=hput_kern(&k);
31997 }
31998 else
31999 { HPUT8(n);
32000 if (subtype(p)==explicit) tag=TAG(kern_kind,b100); else tag=TAG(kern_kind,b000);
32001 }
32002 }
32003 break;
32004 @*1 Extended Dimensions.
32005 Extended dimensions do not constitute content on their own, but nodes
32006 containing an extended dimension are part of other nodes. Here we
32007 define an auxiliary function that checks for a predefined extended
32008 dimension and if found outputs the reference number and returns false;
32009 otherwise it outputs the extended dimension and returns true.
32010
32011
32012 @<Hi\TeX\ auxiliary routines@>=
32013 static void hout_xdimen_node(pointer p)
32014 { Xdimen x;
32015 x.w=xdimen_width(p);
32016 x.h=xdimen_hfactor(p)/(double)ONE;
32017 x.v=xdimen_vfactor(p)/(double)ONE;
32018 hput_xdimen_node(&x);
32019 }
32020
32021 static bool hout_xdimen(pointer p)
32022 {int n = hget_xdimen_no(p);
32023 if (n>=0) { HPUT8(n); return false; @+}
32024 else
32025 { hout_xdimen_node(p); return true;@+}
32026 }
32027
32028 @*1 Languages.
32029 The |hlanguage| array maps the language numbers of \TeX\ to \HINT\ language numbers.
32030 @<Hi\TeX\ variables@>=
32031 static struct {
32032 uint8_t n;
32033 str_number s;
32034 } hlanguage[0x100];
32035 @ For any language number of \TeX, the following function returns
32036 the corresponding \HINT\ language number.
32037 Since \TeX\ knows about a maximum of 255 languages, there is
32038 no need for overflow checking. The next function writes a language
32039 node to the output stream.
32040
32041 @<Hi\TeX\ auxiliary routines@>=
32042 static uint8_t hget_language_no(uint8_t n)
32043 { int i;
32044 for (i=0;i<=max_ref[language_kind]; i++)
32045 if (hlanguage[i].n==n) return i;
32046 i=++max_ref[language_kind];
32047 hlanguage[i].n=n;
32048 hlanguage[i].s=0; /* language unknown*/
32049 return i;
32050 }
32051
32052 static uint8_t hout_language(uint8_t n)
32053 { n=hget_language_no(n);
32054 if (n<7) return TAG(language_kind,n+1);
32055 else
32056 { HPUT8(n); return TAG(language_kind,0); }
32057 }
32058 @ After these preparations, the output of a language node is
32059 simple:
32060
32061 @<cases to output whatsit content nodes@>=
32062 case language_node:
32063 tag=hout_language(what_lang(p));
32064 break;
32065
32066 @ Normally \TeX\ does not produce an initial language node and
32067 then the language in the \HINT\ file would not be known until
32068 it changes for the first time.
32069
32070 @<insert an initial language node@>=
32071 { uint32_t pos = hpos-hstart;
32072 hpos++;
32073 hput_tags(pos,hout_language(language));
32074 }
32075 @ \TeX\ offers currently no simple way to obtain a standardized
32076 language identifier for the current language. So if the
32077 string number of the language is zero, we output the string |"unknown"|;
32078 if somehow the language is known, we output the corresponding string
32079 from \TeX's string pool.
32080
32081 @<Output language definitions@>=
32082 DBG(DBGDEF,"Maximum language reference: %d\n",max_ref[language_kind]);
32083 for (i=max_fixed[language_kind]+1;i<=max_ref[language_kind]; i++)
32084 { HPUTNODE;
32085 HPUT8(TAG(language_kind,0));
32086 HPUT8(i);
32087 if (hlanguage[i].s==0)
32088 hput_string("unknown");
32089 else
32090 hout_string(hlanguage[i].s);
32091 HPUT8(TAG(language_kind,0));
32092 }
32093 @*1 Mathematics.
32094 \TeX's math nodes have an optional width---a copy of the mathsurround parameter---while
32095 \HINT\ math nodes do not. Therefore we have to add an explicit kern node if
32096 the width is nonzero. We add it before a ``math on'' node or after a ``math off''
32097 to get the same behavior in respect to line breaking.
32098
32099 @<cases to output content nodes@>=
32100 case math_node:
32101 { Kern k;
32102 k.x=true;
32103 k.d.w=width(p);
32104 k.d.h=k.d.v=0.0;
32105 if (subtype(p)==before)
32106 { tag=TAG(math_kind,b111);
32107 if (width(p)!=0)
32108 { hput_tags(pos,hput_kern(&k));
32109 pos=hpos-hstart;
32110 HPUTNODE;
32111 hpos++;
32112 }
32113 }
32114 else
32115 { tag=TAG(math_kind,b011);
32116 if (width(p)!=0)
32117 { hput_tags(pos,tag);
32118 pos=hpos-hstart;
32119 HPUTNODE;
32120 hpos++;
32121 tag=hput_kern(&k);
32122 }
32123 }
32124 }
32125 break;
32126 @*1 Glue and Leaders.
32127 Because glue specifications and glue nodes are sometimes part of other
32128 nodes, we start with three auxiliary functions: The first simply
32129 converts a Hi\TeX\ glue node into a \HINT\ |Glue|, outputs it and
32130 returns the tag; the second checks for predefined glues, and the third
32131 outputs a complete glue node including tags.
32132 @<Hi\TeX\ auxiliary routines@>=
32133
32134 static uint8_t hout_glue_spec(pointer p)
32135 { @+Glue g;
32136 to_Glue(p,&g);
32137 return hput_glue(&g);@+
32138 }
32139
32140 static uint8_t hout_glue(pointer p)
32141 { int n;
32142 n = hget_glue_no(p);
32143 if (n<0)
32144 return hout_glue_spec(p);
32145 else
32146 {@+ HPUT8(n); return TAG(glue_kind,0);@+}
32147 }
32148
32149 static void hout_glue_node(pointer p)
32150 { uint8_t *pos;
32151 uint8_t tag;
32152 HPUTNODE; /* allocate */
32153 pos=hpos;
32154 hpos++; /* tag */
32155 tag=hout_glue(p);
32156 *pos=tag; DBGTAG(tag,pos);
32157 DBGTAG(tag,hpos); HPUT8(tag);
32158 }
32159 @ Since \TeX\ implements leaders as a kind of glue, we have one case statement covering glue and leaders.
32160
32161 @<cases to output content nodes@>=
32162 case glue_node:
32163 if (subtype(p)<= cond_math_glue) /* normal glue */
32164 tag= hout_glue(glue_ptr(p));
32165 else if (a_leaders<=subtype(p) && subtype(p)<=x_leaders) /*leaders */
32166 { hout_glue_node(glue_ptr(p));
32167 { bool outer_doing_leaders=doing_leaders;
32168 doing_leaders=true;
32169 hout_node(leader_ptr(p));
32170 doing_leaders=outer_doing_leaders;
32171 }
32172 tag=TAG(leaders_kind,b100|(subtype(p)-a_leaders+1));
32173 }
32174 else
32175 QUIT("glue subtype %d not implemented\n", subtype(p));
32176 break;
32177 @*1 Discretionary breaks.
32178 Discretionary breaks are needed in font descriptions.
32179 Therefore we define a function that converts \TeX's |disc_node| pointers
32180 to \HINT's |Disc|, outputs the discretionary break, and returns the tag.
32181
32182 @<Hi\TeX\ auxiliary routines@>=
32183 static uint8_t hout_disc(pointer p)
32184 { Disc h;
32185 h.x=!is_auto_disc(p);
32186 h.r=replace_count(p);
32187 if (h.x) h.r|=0x80;
32188 if (h.r!=0) HPUT8(h.r);
32189 if (pre_break(p)==null && post_break(p)==null)
32190 h.p.s=h.q.s=0;
32191 else
32192 { uint32_t lpos;
32193 lpos=hpos-hstart;
32194 h.p.t=TAG(list_kind,b001);
32195 hout_list_node(pre_break(p),lpos,&(h.p));
32196 if (post_break(p)==null)
32197 h.q.s=0;
32198 else
32199 { uint32_t lpos;
32200 lpos=hpos-hstart;
32201 h.q.t=TAG(list_kind,b001);
32202 hout_list_node(post_break(p),lpos,&(h.q));
32203 }
32204 }
32205 return hput_disc(&h);
32206 }
32207
32208 @ @<cases to output content nodes@>=
32209 case disc_node:
32210 { int n;
32211 n=hget_disc_no(p);
32212 if (n<0)
32213 tag=hout_disc(p);
32214 else { HPUT8(n); tag=TAG(disc_kind,0);}
32215 }
32216 break;
32217 @*1 Ligatures.
32218 The subtype giving information on left and right boundary characters
32219 is ignored since the \HINT\ viewer will not do ligature or kerning
32220 programs and neither attempt hyphenation.
32221
32222 @<cases to output content nodes@>=
32223 case ligature_node:
32224 { Lig l;
32225 pointer q;
32226 l.f=hget_font_no(font(lig_char(p)));
32227 HPUT8(l.f);
32228 l.l.p=hpos-hstart;
32229 hput_utf8(qo(character(lig_char(p))));
32230 q=lig_ptr(p);
32231 while(q> null)
32232 { hput_utf8(qo(character(q)));
32233 q=link(q);
32234 }
32235 l.l.s=(hpos-hstart)-l.l.p;
32236 tag=hput_ligature(&l);
32237 }
32238 break;
32239 @*1 Rules.
32240 @<cases to output content nodes@>=
32241 case rule_node:
32242 { Rule r;
32243 if (is_running(height(p))) r.h=RUNNING_DIMEN; else r.h=height(p);
32244 if (is_running(depth(p))) r.d=RUNNING_DIMEN; else r.d=depth(p);
32245 if (is_running(width(p))) r.w=RUNNING_DIMEN; else r.w=width(p);
32246 tag=hput_rule(&r);
32247 }
32248 break;
32249 @*1 Boxes.
32250 @<cases to output content nodes@>=
32251 case hlist_node:
32252 case vlist_node:
32253 if (type(p)==hlist_node) tag=TAG(hbox_kind,0);
32254 else tag=TAG(vbox_kind,0);
32255 tag |= hput_box_dimen(height(p),depth(p),width(p));
32256 tag |= hput_box_shift(shift_amount(p));
32257 tag |= hput_box_glue_set((glue_sign(p)==stretching)?+1:-1,glue_set(p),glue_order(p));
32258 hout_list_node2(list_ptr(p));
32259 break;
32260 @*1 Adjustments.
32261 @<cases to output content nodes@>=
32262 case adjust_node:
32263 hout_list_node2(adjust_ptr(p));
32264 tag=TAG(adjust_kind,1);
32265 break;
32266 @*1 Insertions.
32267 \TeX's insertions are mapped to \HINT\ streams.
32268
32269 @<cases to output content nodes@>=
32270 case ins_node:
32271 @<output stream content@>@;
32272 break;
32273 @ Here we consider stream content and come back to stream
32274 definitions in a later section.
32275 In a \HINT\ stream content node the stream
32276 parameters |floating_penalty|, |split_max_depth|, and
32277 |split_top_skip| are optional. If omitted, the defaults from the stream definition are
32278 used. This is probably also for \TeX\ the most common situation.
32279 It is, however, possible to supply more than one page template with different defaults
32280 and while not very common, \TeX\ might change the parameters at any time.
32281 Because we don't know which is the current page template,
32282 it is not possible to compare the current parameter values against the defaults,
32283 and we have to supply all the parameters always.
32284 In a future version, we might have a \TeX\ primitive that allows us to
32285 signal ``use the defaults''.
32286
32287 @<output stream content@>=
32288 { int k,n;
32289 uint32_t pos;
32290 List l;
32291 Info i=b000;
32292 k=subtype(p);
32293 n=hget_stream_no(k);
32294 HPUT8(n);
32295 link(temp_head)=null;
32296 new_param_node(int_type,floating_penalty_code,float_cost(p));
32297 new_param_node(dimen_type,split_max_depth_code,depth(p));
32298 new_param_node(glue_type,split_top_skip_code,split_top_ptr(p));
32299 pos=hpos-hstart;
32300 l.t=TAG(param_kind,b001);
32301 n=hout_param_list(link(temp_head),pos,&l);
32302 flush_node_list(link(temp_head));@+ link(temp_head)=null;
32303 if (n>=0) HPUT8(n); else i=b010;
32304 hout_list_node2(ins_ptr(p));
32305 tag=TAG(stream_kind,i);
32306 }
32307 @*1 Marks.
32308 We currently ignore Marks.
32309
32310 @<cases to output content nodes@>=
32311 case mark_node: hpos--; return;
32312 @*1 Whatsit Nodes.
32313 We have added custom whatsit nodes and now we switch based on the subtype.
32314
32315 @<cases to output content nodes@>=
32316 case whatsit_node:
32317 switch(subtype(p))
32318 { @<cases to output whatsit content nodes@>@;
32319 default:
32320 if (subtype(p)>=hitex_ext)
32321 { MESSAGE("\nOutput of whatsit nodes subtype=%d not implemented\n", subtype(p));
32322 }
32323 hpos--; /* remove tag */
32324 return;
32325 }
32326 break;
32327
32328 @ For \TeX's whatsit nodes that handle output files, no code is generated;
32329 hence, we call |out_what| and simply remove the tag byte that is already
32330 in the output.
32331 When the \.{\\write} node arrives here, it is normally handled
32332 in |hlist_out| or |vlist_out| in an environment determined by
32333 the output routine. For example \LaTeX\ redefines \.{\\protect}
32334 as \.{\\noexpand} and these redefinitions need to be made
32335 before calling |out_what| which expands the token list.
32336 We should therefore add the definitions contained in the output routine
32337 to mimic expanding inside an output routine.
32338
32339
32340 @<cases to output whatsit content nodes@>=
32341 case open_node: case write_node: case close_node:
32342 case special_node: case latespecial_node: out_what(p); hpos--; return;
32343
32344 @*1 Paragraphs.
32345 When we output a paragraph node, we have to consider a special case:
32346 The parameter list is given by a reference number but the extended dimension
32347 needs an |xdimen| node. In this case the reference number for the parameter
32348 list comes first, while otherwise the extended dimension would come first.
32349 To determine whether there is a reference number for the parameter list,
32350 the function |hout_param_list| is writing the parameter list to the output.
32351 \noindent
32352 @<cases to output whatsit content nodes@>=
32353 case par_node:
32354 { uint32_t pos, xpos, xsize;
32355 List l;
32356 pointer q;
32357 int n,m;
32358 Info i=b000;
32359 q=par_extent(p);
32360 n=hget_xdimen_no(q);
32361 if (n>=0) HPUT8(n);
32362 else
32363 { xpos=hpos-hstart; hout_xdimen_node(p); xsize=(hpos-hstart)-xpos; i|=b100; }
32364 pos=hpos-hstart;
32365 l.t=TAG(param_kind,b001);
32366 m=hout_param_list(par_params(p),pos,&l);
32367 if (m>=0)
32368 { if (i&b100)
32369 { HPUTX(1);
32370 memmove(hstart+xpos+1,hstart+xpos,xsize);
32371 hpos++;
32372 hstart[xpos]=m;
32373 }
32374 else
32375 HPUT8(m);
32376 }
32377 else i|=b010;
32378 hout_list_node2(par_list(p));
32379 tag=TAG(par_kind,i);
32380 }
32381 break;
32382 @*1 Baseline Skips.
32383 @<cases to output whatsit content nodes@>=
32384 case baseline_node:
32385 { int n;
32386 n= baseline_node_no(p);
32387 if (n>0xFF) tag=hout_baselinespec(n);
32388 else
32389 { HPUT8(n);
32390 tag=TAG(baseline_kind,b000);
32391 }
32392 }
32393 break;
32394 @*1 Displayed Equations.
32395 @<cases to output whatsit content nodes@>=
32396 case disp_node:
32397 { uint32_t pos;
32398 List l;
32399 int n;
32400 Info i=b000;
32401 pos=hpos-hstart;
32402 l.t=TAG(param_kind,b001);
32403 n=hout_param_list(display_params(p),pos,&l);
32404 if (n>=0) HPUT8(n); else i|=b100;
32405 if (display_eqno(p)!=null && display_left(p))
32406 { hout_node(display_eqno(p)); i|=b010; }
32407 hout_list_node2(display_formula(p));
32408 if (display_eqno(p)!=null && !display_left(p))
32409 { hout_node(display_eqno(p)); i|=b001; }
32410 tag=TAG(math_kind,i);
32411 /* the |display_no_bs(p)| tells whether the baseline skip is ignored */
32412 }
32413 break;
32414 @*1 Extended Boxes.
32415 When we output an extended box, we have to consider a special case: the page templates.
32416 Page templates are boxes that contain insertion points. These insertion points look
32417 like regular insertions but with an empty content list. As a result the |hpack| and
32418 |vpackage| routines might believe that they can compute the dimensions of the box
32419 content when in fact they can not.
32420
32421
32422 @<cases to output whatsit content nodes@>=
32423 case hset_node:
32424 case vset_node:
32425 { Kind k= subtype(p)==hset_node?hset_kind:vset_kind;
32426 Info i=b000;
32427 Stretch s;
32428 int n=set_extent(p);
32429 i|=hput_box_dimen(height(p),depth(p),width(p));
32430 i|=hput_box_shift(shift_amount(p));
32431 s.f=set_stretch(p)/(double)ONE; s.o=set_stretch_order(p);
32432 hput_stretch(&s);
32433 s.f=set_shrink(p)/(double)ONE; s.o=set_shrink_order(p);
32434 hput_stretch(&s);
32435 if (hout_xdimen(n)) i|=b001;
32436 hout_list_node2(list_ptr(p));
32437 tag=TAG(k,i);
32438 }
32439 break;
32440 case hpack_node:
32441 case vpack_node:
32442 { Kind k= (subtype(p)==hpack_node?hpack_kind:vpack_kind);
32443 Info i=b000;
32444 int n=pack_extent(p);
32445 if (pack_m(p)==additional) i|=b001;
32446 if (shift_amount(p)!=0) { HPUT32(shift_amount(p)); i|=b010; }
32447 if (k==vpack_kind) HPUT32(pack_limit(p));
32448 if (hout_xdimen(n)) i|=b100;
32449 hout_list_node2(list_ptr(p));
32450 tag=TAG(k,i);
32451 }
32452 break;
32453
32454 @*1 Extended Alignments.
32455 @<cases to output whatsit content nodes@>=
32456 case align_node:
32457 { Info i=b000;
32458 if (align_m(p)==additional) i|=b001;
32459 if (align_v(p)) i|=b010;
32460 if (hout_xdimen(align_extent(p))) i|=b100;
32461 hout_preamble(align_preamble(p));
32462 hout_align_list(align_list(p),align_v(p));
32463 tag=TAG(table_kind,i);
32464 }
32465 break;
32466 @ In the preamble, we remove the unset nodes and retain only the list of tabskip glues.
32467 @<Hi\TeX\ auxiliary routines@>=
32468 static void hout_preamble(pointer p)
32469 { pointer q,r;
32470 DBG(DBGBASIC,"Writing Preamble\n");
32471 q=p;
32472 if (q!=null) r=link(q); else r=null;
32473 while (r!=null)
32474 { if (type(r)==unset_node)
32475 { link(q)=link(r);
32476 link(r)=null; flush_node_list(r);
32477 }
32478 else
32479 q=r;
32480 r=link(q);
32481 }
32482 hout_list_node2(p);
32483 DBG(DBGBASIC,"End Preamble\n");
32484 }
32485 @ In the |align_list| we have to convert the unset nodes back to box nodes or extended box nodes
32486 packaged inside an item node.
32487 When the viewer reads an item node, it will package the extended boxes to their natural size.
32488 This is the size that is needed to compute the maximum width of a column.
32489
32490 @<Hi\TeX\ auxiliary routines@>=
32491
32492 static void hout_item(pointer p, uint8_t t, uint8_t s)
32493 { Info i=b000;
32494 uint8_t n;
32495 n=span_count(p)+1;
32496 DBG(DBGBASIC,"Writing Item %d/%d->%d/%d\n",type(p),n,t,s);
32497 if (n==0) QUIT("Span count of item must be positive");
32498 if (n<7) i=n; else i=7;
32499 HPUTTAG(item_kind,i);
32500 if (i==7) HPUT8(n);
32501 type(p)=t; subtype(p)=s;
32502 hout_node(p);
32503 HPUTTAG(item_kind,i);
32504 DBG(DBGBASIC,"End Item\n");
32505 }
32506
32507
32508 static void hout_item_list(pointer p, bool v)
32509 { List l;
32510 uint32_t pos;
32511 DBG(DBGBASIC,"Writing Item List\n");
32512 l.t=TAG(list_kind,b001);
32513 HPUTTAG(item_kind,b000);
32514 pos=hpos-hstart;
32515 HPUTX(2);
32516 HPUT8(0); /* space for the list tag */
32517 HPUT8(0); /* space for the list size */
32518 l.p=hpos-hstart;
32519 while(p> mem_min)
32520 { if (is_char_node(p)) hout_node(p);
32521 else if (type(p)==unset_node) hout_item(p,v?vlist_node:hlist_node,0);
32522 else if (type(p)==unset_set_node) hout_item(p,whatsit_node,v?vset_node:hset_node);
32523 else if (type(p)==unset_pack_node) hout_item(p,whatsit_node,v?vpack_node:hpack_node);
32524 else hout_node(p);
32525 p=link(p);
32526 }
32527 l.s=(hpos-hstart)-l.p;
32528 hput_tags(pos,hput_list(pos+1,&l));
32529 HPUTTAG(item_kind,b000);
32530 DBG(DBGBASIC,"End Item List\n");
32531 }
32532
32533 static void hout_align_list(pointer p, bool v)
32534 { List l;
32535 uint32_t pos;
32536 DBG(DBGBASIC,"Writing Align List\n");
32537 l.t=TAG(list_kind,b001);
32538 pos=hpos-hstart;
32539 HPUTX(2);
32540 HPUT8(0); /* space for the tag */
32541 HPUT8(0); /* space for the list size */
32542 l.p=pos+2;
32543 while(p> mem_min)
32544 { if (!is_char_node(p) && (type(p)==unset_node||type(p)==unset_set_node||type(p)==unset_pack_node))
32545 hout_item_list(list_ptr(p),v);
32546 else
32547 hout_node(p);
32548 p=link(p);
32549 }
32550 l.s=(hpos-hstart)-l.p;
32551 hput_tags(pos,hput_list(pos+1,&l));
32552 DBG(DBGBASIC,"End Align List\n");
32553 }
32554
32555 @ Inside the alignment list we will find various types of unset nodes, we convert them back
32556 to regular nodes and put them inside an item node.
32557
32558 @<cases to output content nodes@>=
32559 case unset_node:
32560 case unset_set_node:
32561 case unset_pack_node: /* not yet implemented, fall through to the default case */
32562
32563
32564 @*1 Lists.
32565 Two functions are provided here:
32566 |hout_list| will write a list given by the pointer |p| to the
32567 output at the current position |hpos|.
32568 After the list has finished, the call to |hput_list| will move the list, if necessary,
32569 adding tag, size information, and boundary bytes
32570 so that the final list will be at position |pos|.
32571
32572 |hout_list_node| uses |hout_list| but reserves the space needed for the tag, size, and
32573 boundary byte.
32574
32575 For convenience, there is also the function |hout_list_node2| which supplies a default
32576 |pos| and |l| value to |hout_list_node|.
32577
32578 @<Hi\TeX\ routines@>=
32579
32580 static uint8_t hout_list(pointer p, uint32_t pos, List *l)
32581 { l->p=hpos-hstart;
32582 while(p> mem_min)
32583 { hout_node(p);
32584 p=link(p);
32585 }
32586 l->s=(hpos-hstart)-l->p;
32587 return hput_list(pos,l);
32588 }
32589
32590 static void hout_list_node(pointer p, uint32_t pos, List *l)
32591 {
32592 hpos=hstart+pos;
32593 HPUTX(3);
32594 HPUT8(0); /* space for the tag */
32595 HPUT8(0); /* space for the list size */
32596 HPUT8(0); /* space for the size boundary byte */
32597 hput_tags(pos,hout_list(p,pos+1,l));
32598 }
32599
32600
32601 static void hout_list_node2(pointer p)
32602 { List l;
32603 uint32_t pos;
32604 pos=hpos-hstart;
32605 l.t=TAG(list_kind,b001);
32606 hout_list_node(p,pos,&l);
32607 }
32608 @ @<Hi\TeX\ function declarations@>=
32609 static void hout_list_node(pointer p, uint32_t pos, List *l);
32610 static void hout_list_node2(pointer p);
32611 static uint8_t hout_list(pointer p, uint32_t pos, List *l);
32612
32613 @*1 Parameter Lists.
32614 The next function is like |hout_list_node| but restricted to parameter nodes.
32615 The parameter |p| is a pointer to a param node list.
32616 The function either finds a reference number to a predefined parameter list
32617 and returns the reference number,
32618 or it outputs the node list at position pos (that's where the tag goes),
32619 sets |l->t|, |l->p| and |l->s|, and returns $-1$.
32620
32621 @<Hi\TeX\ routines@>=
32622 static int hout_param_list(pointer p, uint32_t pos, List *l)
32623 { int n;
32624 hpos=hstart+pos;
32625 if (p==null) return 0;
32626 HPUTX(3);
32627 HPUT8(0); /* space for the tag */
32628 HPUT8(0); /* space for the list size */
32629 HPUT8(0); /* space for the size boundary byte*/
32630 l->p=hpos-hstart;
32631 while(p> mem_min)
32632 { hdef_param_node(param_type(p),param_no(p),param_value(p).i);
32633 p=link(p);
32634 }
32635 l->s=(hpos-hstart)-l->p;
32636 n=hget_param_list_no(l);
32637 if (n>=0)
32638 hpos=hstart+pos;
32639 else
32640 hput_tags(pos,hput_list(pos+1,l));
32641 return n;
32642 }
32643 @ @<Hi\TeX\ function declarations@>=
32644 static int hout_param_list(pointer p, uint32_t pos, List *l);
32645
32646
32647 @*1 Labels, Links, and Outlines.
32648 Here we provide only the code for content nodes.
32649 The routines to put labels and outlines into the definition section
32650 are defined in {\tt put.c}.
32651
32652 @<cases to output whatsit content nodes@>=
32653 case label_node: hpos--; new_label(p); return;
32654 case start_link_node:
32655 { Info i;
32656 int n=new_start_link(p);
32657 i=b010;
32658 if (n>0xFF) { i|=b001; HPUT16(n);@+} @+else HPUT8(n);
32659 if (color_ref(p)!=1) {i|=b100; HPUT8(color_ref(p)); }
32660 tag= TAG(link_kind,i);
32661 }
32662 break;
32663 case end_link_node:
32664 { Info i;
32665 int n=new_end_link();
32666 i=b000;
32667 if (n>0xFF) { i|=b001; HPUT16(n);@+} @+else HPUT8(n);
32668 if (color_ref(p)!=0xFF) {i|=b100; HPUT8(color_ref(p)); }
32669 tag= TAG(link_kind,i);
32670 }
32671 break;
32672 case outline_node: hpos--; new_outline(p); return;
32673
32674 @*1 Images.
32675 There is a single primitive to handle images:
32676 @<Put each...@>=
32677 primitive("HINTimage", extension, image_node);@/
32678 @!@:HINTimage\_}{\.{\\HINTimage} primitive@>
32679
32680 @ @<cases to output whatsit content nodes@>=
32681 case image_node:
32682 { Xdimen w={0},h={0};
32683 if (image_xwidth(p)!=null)
32684 { pointer r=image_xwidth(p);
32685 w.w=xdimen_width(r);
32686 w.h=xdimen_hfactor(r)/(double)ONE;
32687 w.v=xdimen_vfactor(r)/(double)ONE;
32688 }
32689 if (image_xheight(p)!=null)
32690 { pointer r=image_xheight(p);
32691 h.w=xdimen_width(r);
32692 h.h=xdimen_hfactor(r)/(double)ONE;
32693 h.v=xdimen_vfactor(r)/(double)ONE;
32694 }
32695 tag=TAG(image_kind,hput_image_spec(image_no(p),image_aspect(p)/(double)ONE,0,&w,0,&h));
32696 hout_list_node2(image_alt(p)); /* should eventually become a text */
32697 }
32698 break;
32699 @*1 Text.
32700 The routines in this section are not yet ready.
32701
32702 @<Hi\TeX\ routines@>=
32703
32704 #if 0
32705 static void hchange_text_font(internal_font_number f)
32706 { uint8_t g;
32707 if (f!=hfont)
32708 { g=get_font_no(f);
32709 if (g<8)
32710 hputcc(FONT0_CHAR+g);
32711 else
32712 { hputcc(FONTN_CHAR);
32713 hputcc(g);
32714 }
32715 hfont=f;
32716 }
32717 }
32718
32719 static void hprint_text_char(pointer p)
32720 { uint8_t f,c;
32721 f = font(p);
32722 c = character(p);
32723 hchange_text_font(f);
32724 if (c<=SPACE_CHAR) hputcc(ESC_CHAR);
32725 hputcc(c);
32726 }
32727
32728
32729 static void hprint_text_node(pointer p)
32730 { switch(type(p))
32731 { case hlist_node:
32732 /* this used to be the |par_indent| case */
32733 goto nodex;
32734 case glue_node:
32735 if (subtype(p)> cond_math_glue) goto nodex;
32736 else
32737 { pointer q=glue_ptr(p);
32738 int i;
32739 if (glue_equal(f_space_glue[hfont],q))
32740 { hputc(SPACE_CHAR); return; }
32741 if (glue_equal(f_xspace_glue[hfont],q))
32742 { hputcc(XSPACE_CHAR); return; }
32743 if (f_1_glue[hfont]==0 && (subtype(p)-1==space_skip_code))
32744 { pointer r=glue_par(subtype(p)-1);
32745 add_glue_ref(r);
32746 f_1_glue[hfont]=r;
32747 }
32748 if (f_1_glue[hfont]!=0 && glue_equal(f_1_glue[hfont],q))
32749 { hputcc(GLUE1_CHAR); return; }
32750 if (f_2_glue[hfont]==0 && (subtype(p)-1==space_skip_code || subtype(p)-1==xspace_skip_code))
32751 { pointer r=glue_par(subtype(p)-1);
32752 add_glue_ref(r);
32753 f_2_glue[hfont]=r;
32754 }
32755 if (f_2_glue[hfont]!=0 && glue_equal(f_2_glue[hfont],q))
32756 { hputcc(GLUE2_CHAR); return; }
32757 if (f_3_glue[hfont]==0)
32758 { f_3_glue[hfont]=q;
32759 add_glue_ref(q);
32760 }
32761 if (f_3_glue[hfont]!=0 && glue_equal(f_3_glue[hfont],q))
32762 { hputcc(GLUE3_CHAR); return; }
32763 i = hget_glue_no(q);
32764 if (i>=0)
32765 { hputcc(GLUEN_CHAR); hputcc(i); return; }
32766 }
32767 break;
32768 case ligature_node:
32769 { int n;
32770 pointer q;
32771 for (n=0,q=lig_ptr(p); n<5 && q!=null; n++,q=link(q)) continue;
32772 if (n==2) hputcc(LIG2_CHAR);
32773 else if (n==3) hputcc(LIG3_CHAR);
32774 else if (n==0) hputcc(LIG0_CHAR);
32775 else goto nodex;
32776 hprint_text_char(lig_char(p));
32777 for (q=lig_ptr(p);q!=null; q=link(q)) hprint_text_char(q);
32778 return;
32779 }
32780 case disc_node:
32781 if (post_break(p)==null && pre_break(p)!=null && replace_count(p)==0)
32782 { pointer q;
32783 q=pre_break(p);
32784 if (is_char_node(q) && link(q)==null && font(q)==hfont && character(q)== hyphen_char[hfont])
32785 { if (is_auto_disc(p)) hputcc(DISC1_CHAR);
32786 else hputcc(DISC2_CHAR);
32787 return;
32788 }
32789 }
32790 else if (post_break(p)==null && pre_break(p)==null && replace_count(p)==0 && !is_auto_disc(p))
32791 { hputcc(DISC3_CHAR); return; }
32792 break;
32793 case math_node:
32794 if(width(p)!=0) goto nodex;
32795 if(subtype(p)==before) hputcc(MATHON_CHAR);
32796 else hputcc(MATHOFF_CHAR);
32797 return;
32798 default:
32799 break;
32800 }
32801 nodex:
32802 hout_node(p);
32803 }
32804
32805 static void hprint_text(pointer p)
32806 { internal_font_number f=hfont;
32807 nesting++;
32808 hprint_nesting();
32809 hprintf("<text ");
32810 while(p> mem_min)
32811 { if (is_char_node(p))
32812 hprint_text_char(p);
32813 else
32814 hprint_text_node(p);
32815 p=link(p);
32816 }
32817 hchange_text_font(f);
32818 hprintf(">\n");
32819 nesting--;
32820 }
32821 #endif
32822
32823 @* Hi\TeX\ Limitations.
32824
32825 \item Kerns and glues using a width that depends on \.{\\hsize} or
32826 \.{\\vsize} are not yet supported.
32827
32828 \item Tables where the width of a column depends on \.{\\hsize} or
32829 \.{\\vsize} are not tested and probably not yet supported.
32830
32831 \item \.{\\vcenter} will not work if any dimension of the
32832 vertical list depends on \.{\\hsize} or \.{\\vsize}.
32833
32834 \item The encoding of horizontal lists as texts is not yet supported,
32835 but it would make the \HINT\ file shorter and much better to read
32836 when stretched into long \HINT\ format.
32837
32838
32839
32840
32841 @* System-dependent changes.
32842 This section should be replaced, if necessary, by any special
32843 modifications of the program
32844 that are necessary to make \TeX\ work at a particular installation.
32845 It is usually best to design your change file so that all changes to
32846 previous sections preserve the section numbering; then everybody's version
32847 will be consistent with the published program. More extensive changes,
32848 which introduce new sections, can be inserted here; then only the index
32849 itself will get a new section number.
32850 @^system dependencies@>
32851
32852 @* \TeX\ Live Integration.
32853 A \TeX\ engine that aspires
32854 to become a member of the \TeX\ Live family of programs
32855 must
32856
32857 $-$ respect the \TeX\ Live conventions for command line parameters,\par
32858 $-$ find its input files using the \.{kpathsearch} library, and\par
32859 $-$ implement \TeX\ primitives to support
32860 \LaTeX.
32861
32862 \noindent Naturally, the functions that follow here are taken, with small
32863 modifications, from the \TeX\ Live sources. What is
32864 added here, or rather subtracted here, are the parts that are specific
32865 to some of the \TeX\ engines included in \TeX\ Live. New is also
32866 that the code is presented in literate programming style.
32867
32868 The code that follows is organized in three parts.
32869 Some code for \TeX\ Live must come before
32870 the definition of \TeX's macros because
32871 it uses include files containing identifiers that are in conflict
32872 with \TeX's macros or modify these macros. For example
32873 \TeX's |banner| is modified by adding the \TeX\ Live version.
32874
32875 @<Header files and function declarations@>=
32876 #ifdef WEB2CVERSION
32877 #define TL_VERSION "(TeX Live "WEB2CVERSION")"
32878 #else
32879 #define TL_VERSION
32880 #endif
32881
32882 @ The remaining two parts are first auxiliary functions and then
32883 those functions that are called from the ``classic'' \TeX\ code.
32884
32885 @p @<\TeX\ Live auxiliary functions@>@;
32886 @<\TeX\ Live functions@>@;
32887
32888 @
32889 Most of the code that we present next comes together in the
32890 function |main_init|
32891 which is the first function called in the main program of a \TeX\ engine
32892 belonging to \TeX\ Live. Before doing so, we make copies of
32893 argument count and argument vector putting them in global variables.
32894 @<Global...@>=
32895 static char **argv;
32896 static int argc;
32897
32898 @ @<\TeX\ Live functions@>=
32899 static void main_init(int ac, char *av[])
32900 {@+
32901 char* main_input_file;
32902 argc = ac;
32903 argv = av;
32904 interaction = error_stop_mode;
32905 kpse_record_input = recorder_record_input;
32906 kpse_record_output = recorder_record_output;
32907
32908 @<parse options@>@;
32909 @<set the program and engine name@>@;
32910 @<activate configuration lines@>@;
32911 @<set the input file name@>@;
32912 @<set defaults from the {\tt texmf.cfg} file@>@;
32913 @<set the format name@>@;
32914 @<enable the generation of input files@>@;
32915 }
32916
32917 @ @<Forward declarations@>=
32918 static void main_init(int ac, char *av[]);
32919
32920
32921 @*1 Command Line.
32922 Let's begin with the beginning: the command line.
32923 To see how a command line is structured, we first look at the
32924 help text that is displayed if the user asks for it (or if \TeX\
32925 decides that the user needs it). The help text is produced by the
32926 function |usage_help|.
32927 \def\SP{ }% disable visible spaces in strings.
32928
32929 @<\TeX\ Live auxiliary functions@>=
32930 static void usage_help(void)
32931 {@+@<explain the command line@>@;
32932 @<explain the options@>@;
32933 fprintf(stdout,"\nFor further information and reporting bugs see https://hint.userweb.mwn.de/\n");
32934 exit(0);
32935 }
32936
32937 @ The command line comes in three slightly different versions:
32938
32939 @<explain the command line@>=
32940 fprintf(stdout,@/
32941 "Usage: %s [OPTION]... [TEXNAME[.tex]] [COMMANDS]\n"@/
32942 " or: %s [OPTION]... \\FIRST-LINE\n"@/
32943 " or: %s [OPTION]... &FMT ARGS\n\n",@/
32944 argv[0],argv[0],argv[0]);@/
32945 fprintf(stdout,@/
32946 " Run HiTeX on TEXNAME, creating TEXNAME.hnt.\n"@/
32947 " Any remaining COMMANDS are processed\n"@/
32948 " as TeX input after TEXNAME is read.\n"@/
32949 " If the first line of TEXNAME starts with %%&FMT, and FMT is\n"@/
32950 " an existing .fmt file, use it. Else use `NAME.fmt', where\n"@/
32951 " NAME is the program invocation name.\n"@/
32952 "\n"@/
32953 " Alternatively, if the first non-option argument begins\n"@/
32954 " with a backslash, interpret all non-option arguments as\n"@/
32955 " a line of TeX input.\n"@/
32956 "\n"@/
32957 " Alternatively, if the first non-option argument begins\n"@/
32958 " with a &, the next word is taken as the FMT to read,\n"@/
32959 " overriding all else. Any remaining arguments are\n"@/
32960 " processed as above.\n"@/
32961 "\n"@/
32962 " If no arguments or options are specified, prompt for input.\n"@/
32963 "\n");
32964
32965
32966 @*1 Options.
32967 Here is the list of possible options and their explanation:
32968
32969 @<explain the options@>=
32970 fprintf(stdout,
32971 "Options:\n"@/
32972 " -help "@/
32973 @t\qquad@>"\t display this help and exit\n"@/
32974 " -version "@/
32975 @t\qquad@>"\t output version information and exit\n"@/
32976 " -etex "@/
32977 @t\qquad@>"\t enable e-TeX extensions\n"@/
32978 " -ltx "@/
32979 @t\qquad@>"\t enable LaTeX extensions, implies -etex\n"@/
32980 " -ini "@/
32981 @t\qquad@>"\t be initex for dumping formats; this is\n"@/
32982 @t\qquad@>"\t\t\t also true if the program name is `hinitex'\n"@/
32983 " -progname=STRING "@/
32984 @t\qquad@>"\t set program (and fmt) name to STRING\n"@/
32985 " -fmt=FMTNAME "@/
32986 @t\qquad@>"\t use FMTNAME instead of program name or a %%& line\n"@/
32987 " -output-directory=DIR "@/
32988 @t\qquad@>"\t use existing DIR as the directory to write files to\n"@/
32989 " -jobname=STRING "@/
32990 @t\qquad@>"\t set the TeX \\jobname to STRING\n"@/
32991 " [-no]-mktex=FMT "@/
32992 @t\qquad@>"\t disable/enable mktexFMT generation (FMT=tex/tfm/fmt/pk)\n"@/
32993 " -interaction=STRING "@/
32994 @t\qquad@>"\t set interaction mode (STRING=batchmode/\n"@/
32995 @t\qquad@>"\t\t\t nonstopmode/scrollmode/errorstopmode)\n"@/
32996 " -kpathsea-debug=NUMBER"@/
32997 @t\qquad@>"\t set path searching debugging flags according\n"@/
32998 @t\qquad@>"\t\t\t to the bits of NUMBER\n"@/
32999 " -recorder"@/
33000 @t\qquad@>"\t\t enable filename recorder\n"@/
33001 " [-no]-parse-first-line"@/
33002 @t\qquad@>"\t disable/enable parsing of the first line of\n"@/
33003 @t\qquad@>"\t\t\t the input file\n"@/
33004 " [-no]-file-line-error"@/
33005 @t\qquad@>"\t disable/enable file:line:error style\n"@/
33006 " -cnf-line=STRING"@/
33007 @t\qquad@>"\t process STRING like a line in texmf.cnf\n"@/
33008 " -compress "@/
33009 @t\qquad@>"\t enable compression of section 1 and 2\n"@/
33010 " [-no]-subset "@/
33011 @t\qquad@>"\t disable/enable the embedding of font subsets\n"@/
33012 " [-no]-empty-page "@/
33013 @t\qquad@>"\t disable/enable empty pages\n"@/
33014 " [-no]-hyphenate-first-word "@/
33015 @t\qquad@>"\t disable/enable hyphenation of\n"@/
33016 @t\qquad@>"\t\t\t the first word of a paragraph\n"@/
33017 " -resolution=NUMBER "@/
33018 @t\qquad@>"\t set the resolution to NUMBER dpi\n"@/
33019 " -mfmode=MODE "@/
33020 @t\qquad@>"\t set the METAFONT mode to MODE\n"@/
33021 #ifdef DEBUG
33022 " -hint-debug=FLAGS "@/
33023 @t\qquad@>"\t set flags to control hint debug output\n"@/
33024 " -hint-debug-help "@/
33025 @t\qquad@>"\t give help on hint debugging\n"@/
33026 #endif
33027 );
33028
33029 @ The processing of command line options is controlled by the |long_options|
33030 \def\SP{{\tt\char`\ }}% restore the visible space in a string
33031 array. Each entry in this array contains first the name of the option,
33032 then a flag that tells whether the option takes an argument or not.
33033 If next the (optional) address of a flag variable is given,
33034 it is followed by the value to store in the flag variable.
33035 In this case, setting the flag variable is handled by
33036 the |getopt_long_only| function.
33037
33038 Besides the flag variables that occur in the table,
33039 a few string variables may be set using the options.
33040 The following is a complete list of these variables.
33041 Variables are initialized with |-1| to indicate an undefined value;
33042 string variables are initialized with |NULL|.
33043
33044 @<Global...@>=
33045 static int iniversion=false, etexp=false, ltxp=false, recorder_enabled=false;
33046 static int parsefirstlinep=-1, filelineerrorstylep=-1, interaction_option=-1;
33047 static const char *user_progname=NULL, *output_directory=NULL, *c_job_name=NULL,
33048 *dump_name=NULL;@#
33049 static int option_no_empty_page=true, option_hyphen_first=true;
33050 static int option_dpi=600;
33051 static const char *option_mfmode="ljfour", *option_dpi_str="600";
33052 extern int option_compress;
33053 extern unsigned int debugflags;
33054 static int option_subset=true;
33055
33056 static struct option long_options[] = {@/
33057 { "help", 0, 0, 0 },@/
33058 { "version", 0, 0, 0 },@/
33059 { "interaction", 1, 0, 0 },@/
33060 { "mktex", 1, 0, 0 },@/
33061 { "no-mktex", 1, 0, 0 },@/
33062 { "kpathsea-debug", 1, 0, 0 },@/
33063 { "progname", 1, 0, 0 },@/
33064 { "fmt", 1, 0, 0 },@/
33065 { "output-directory", 1, 0, 0 },@/
33066 { "jobname", 1, 0, 0 },@/
33067 { "cnf-line", 1, 0, 0 },@/
33068 { "ini", 0, &iniversion, 1 },@/
33069 { "etex", 0, &etexp, 1 },@/
33070 { "ltx", 0, &ltxp, 1 },@/
33071 { "recorder", 0, &recorder_enabled, 1 },@/
33072 { "parse-first-line", 0, &parsefirstlinep, 1 },@/
33073 { "no-parse-first-line", 0, &parsefirstlinep, 0 },@/
33074 { "file-line-error", 0, &filelineerrorstylep, 1 },@/
33075 { "no-file-line-error", 0, &filelineerrorstylep, 0 },@/
33076 { "compress", 0, &option_compress, 1 },@/
33077 { "no-subset", 0, &option_subset, 0 },@/
33078 { "subset", 0, &option_subset, 1 },@/
33079 { "no-empty-page", 0, &option_no_empty_page, 1 },@/
33080 { "empty-page", 0, &option_no_empty_page, 0 },@/
33081 { "hyphenate-first-word", 0, &option_hyphen_first, 1 },@/
33082 { "no-hyphenate-first-word", 0, &option_hyphen_first, 0 },@/
33083 { "resolution", 1, 0, 0 },@/
33084 { "mfmode", 1, 0, 0 },@/
33085 #ifdef DEBUG
33086 { "hint-debug", 1, 0, 0 },@/
33087 { "hint-debug-help", 0, 0, 0 },@/
33088 #endif
33089 { 0, 0, 0, 0 }@+}@+;
33090
33091
33092 @ Parsing the command line options is accomplished with the
33093 |parse_options| function which in turn uses the |getopt_long_only|
33094 function from the \CEE/ library. This function returns 0 and sets the
33095 |option_index| parameter to the option found, or it returns $-1$ if
33096 the end of all options is reached.
33097 @<\TeX\ Live functions@>=
33098 static void parse_options (int argc, char *argv[])
33099 {@+ while (true) {
33100 int option_index;
33101 int g = getopt_long_only (argc, argv, "+", long_options, &option_index);
33102 if (g==0)
33103 { @<handle the options@>@;@+ }
33104 else if (g == '?')
33105 { fprintf(stderr,"Try '%s --help' for more information\n",argv[0]);
33106 exit(1);
33107 }
33108 else if (g == -1) break;
33109 }
33110 @<Check the environment for extra settings@>@;
33111 }
33112
33113 @ @<Forward declarations@>=
33114 static void parse_options (int argc, char *argv[]);
33115
33116 @ Before we can call the |parse_options| function,
33117 we might need some special preparations for Windows.
33118
33119 @<parse options@>=
33120 #if defined(WIN32)
33121 {@+ char* enc;
33122 kpse_set_program_name (argv[0], NULL);
33123 enc = kpse_var_value("command_line_encoding");
33124 get_command_line_args_utf8(enc, &argc, &argv);@/
33125 parse_options (argc, argv);
33126 @<record {\tt texmf.cnf}@>@;
33127 }
33128 #else
33129 parse_options (ac, av);
33130 #endif
33131
33132
33133 @ To handle the options, we compare the name at the given |option_index| with
33134 the different option names. This is not a very efficient method, but the
33135 impact is low and it's simple to write.
33136
33137 Comparing the name of the argument with the |name| field in the |option|
33138 structure is done in the auxiliary function |argument_is|.
33139 Unfortunately the |name| field is in conflict with the |name| macro
33140 defined by \TeX. To avoid the conflict, the |argument_is| function
33141 goes just after the \.{kpathsea.h} header file that defines
33142 the option structure.
33143
33144
33145 @<Header files and function declarations@>=
33146 #include <kpathsea/kpathsea.h>
33147 static int argument_is(struct option *opt, char * s)
33148 {@+ return STREQ(opt->name, s); @+}
33149 #define ARGUMENT_IS(S) argument_is(long_options+option_index,S)
33150
33151 @ Now we can handle the first two options:
33152
33153 @<handle the options@>=
33154 if (ARGUMENT_IS("help")) usage_help();
33155 else if (ARGUMENT_IS("version")){@+
33156 printf(banner@, "\n"@/
33157 #ifdef eTeX_version_string
33158 "eTeX version "@,eTeX_version_string@,"\n"@/
33159 #endif
33160 #ifdef HINT_VERSION_STRING
33161 "HINT version "@,HINT_VERSION_STRING@,"\n"@/
33162 #endif
33163 #ifdef Prote_version_string
33164 "Prote version "@, Prote_version_string@, "\n"
33165 #endif
33166 );
33167 exit(0);@+
33168 }
33169
33170
33171 @ The ``interaction'' option sets the |interaction_option| variable
33172 based on its string argument contained in the |optarg| variable.
33173 If defined, the |interaction_option| will be used to set \TeX's
33174 |interaction| variable in the |initialize| and the |undump| functions.
33175
33176 @<handle the options@>=
33177 else @+if (ARGUMENT_IS ("interaction"))@t\2@> {
33178 if (STREQ (optarg, "batchmode")) interaction_option = batch_mode;
33179 else if (STREQ (optarg, "nonstopmode")) interaction_option = nonstop_mode;
33180 else if (STREQ (optarg, "scrollmode")) interaction_option = scroll_mode;
33181 else if (STREQ (optarg, "errorstopmode")) interaction_option = error_stop_mode;
33182 else WARNING1 ("Ignoring unknown argument `%s' to --interaction", optarg);
33183 }
33184
33185 @ The next two options pass the string argument to the
33186 \.{kpathsearch} library.
33187
33188 @<handle the options@>=
33189 else @+if (ARGUMENT_IS ("mktex")) @t\2@> kpse_maketex_option (optarg, true);
33190 else if (ARGUMENT_IS ("no-mktex")) kpse_maketex_option (optarg, false);
33191
33192
33193 @ To debug the searching done by the \.{kpathsearch} library,
33194 the following option can be used.
33195 The argument value 3 is a good choice to start with.
33196
33197 @<handle the options@>=
33198 else @+if (ARGUMENT_IS ("kpathsea-debug")) @t\2@>
33199 kpathsea_debug |= atoi (optarg);
33200
33201
33202
33203 @ The next set of options take a string argument
33204 and assign it to the corresponding string variable.
33205
33206 @<handle the options@>=
33207 else @+if (ARGUMENT_IS ("progname"))@t\2@>
33208 user_progname = normalize_quotes(optarg,"program name");
33209 else if (ARGUMENT_IS ("fmt"))
33210 dump_name = normalize_quotes(optarg,"format name");
33211 else if (ARGUMENT_IS ("output-directory"))
33212 output_directory = normalize_quotes(optarg,"output directory");
33213 else if (ARGUMENT_IS ("jobname"))
33214 c_job_name = normalize_quotes (optarg, "job name");
33215
33216 @ When string arguments specify files or directories,
33217 special care is needed if arguments are quoted and/or contain spaces.
33218 The function |normalize_quotes| makes sure that arguments containing
33219 spaces get quotes around them and it checks for unbalanced quotes.
33220
33221
33222 @<\TeX\ Live auxiliary functions@>=
33223 static char *normalize_quotes (const char *nom, const char *mesg)
33224 {@+ int quoted = false;
33225 int must_quote = (strchr(nom, ' ') != NULL);
33226 char *ret = xmalloc(strlen(nom)+3);/*room for two quotes and NUL*/
33227 char *p=ret;
33228 const char *q;
33229
33230 if (must_quote)
33231 *p++ = '"';
33232 for (q = nom; *q; q++)
33233 if (*q == '"')
33234 quoted = !quoted;@+
33235 else
33236 *p++ = *q;
33237
33238 if (must_quote)
33239 *p++ = '"';
33240 *p = '\0';
33241 if (quoted) {
33242 fprintf(stderr, "! Unbalanced quotes in %s %s\n", mesg, nom);
33243 exit(1);
33244 }
33245 return ret;
33246 }
33247
33248 @ If the output directory was specified on the command line,
33249 we save it in an environment variable so that subprocesses can
33250 get the value. If on the other hand the environment specifies
33251 a directory and the command line does not, save the value from
33252 the environment to the global variable so that it is used in the
33253 rest of the code.
33254
33255 @<Check the environment for extra settings@>=
33256 if (output_directory)
33257 xputenv ("TEXMF_OUTPUT_DIRECTORY", output_directory);
33258 else if (getenv ("TEXMF_OUTPUT_DIRECTORY"))
33259 output_directory = getenv ("TEXMF_OUTPUT_DIRECTORY");
33260
33261 @*1 Passing a file name as a general text argument.
33262
33263 |scan_file_name| uses the following code to parse a file name given
33264 as a general text argument. Such an argument can be any token list
33265 starting with a left brace and ending with a right brace.
33266 This token list is then expanded (without the leading and trailing braces)
33267 and printed into the string pool without making it yet an official string.
33268 After removing all double quotes, because this is current practice
33269 for \TeX\ engines that are part of \TeX\ Live,
33270 and setting the area and extension delimiters,
33271 all temporary garbage used so far is freed.
33272
33273 Due to the expansion of the token list, this code and hence the
33274 |scan_file_name| procedure is recursive.
33275 One can provide the name of a file as the content of an other file.
33276
33277
33278 % Thierry Laronde
33279 @<Define a general text file name and |goto done|@>=
33280 {@+back_input();name_in_progress=false; /*this version is recursive...*/
33281 cur_cs=input_loc; /*|scan_toks| will set |warning_index| from it*/
33282 scan_general_x_text();
33283 old_setting=selector;selector=new_string;
33284 token_show(link(garbage));selector=old_setting;
33285 @<Suppress double quotes in braced input file name@>@;
33286 j=pool_ptr-1;while ((j >= str_start[str_ptr])&&(area_delimiter==0))
33287 {@+
33288 if ((str_pool[j]=='/'))
33289 area_delimiter=j-str_start[str_ptr]+1;
33290 if ((ext_delimiter==0)&&(str_pool[j]=='.'))
33291 ext_delimiter=j-str_start[str_ptr]+1;
33292 decr(j);
33293 }
33294 flush_list(link(garbage));
33295 goto done;
33296 }
33297
33298 @ A simple loop removes the double quotes and adjusts the |pool_ptr|.
33299
33300 @<Suppress double quotes in braced input file name@>=
33301 for (k=j=str_start[str_ptr]; k < pool_ptr; k++) {@+
33302 if (str_pool[k]!='"') {@+str_pool[j]=str_pool[k];incr(j);}
33303 }
33304 pool_ptr=j;
33305
33306 @*1 The {\tt -recorder} Option.
33307 The recorder option can be used to enable the file name recorder.
33308 It is crucial for getting a reliable list of files used in a given run.
33309 Many post-processors use it, and it is used in \TeX\ Live for
33310 checking the format building infrastructure.
33311
33312 When we start the file name recorder,
33313 we would like to use mkstemp, but it is not portable,
33314 and doing the autoconfiscation (and providing fallbacks) is more
33315 than we want to cope with. So we have to be content with using a
33316 default name. We throw in the pid so at least parallel builds might
33317 work. Windows, however, seems to have no |pid_t|, so instead of storing the
33318 value returned by |getpid|, we immediately consume it.
33319
33320 @<\TeX\ Live auxiliary functions@>=
33321 static char *recorder_name=NULL;
33322 static FILE *recorder_file=NULL;
33323 static void
33324 recorder_start(void)
33325 { char *cwd;
33326 char pid_str[MAX_INT_LENGTH];
33327 sprintf (pid_str, "%ld", (long) getpid());
33328 recorder_name = concat3(kpse_program_name, pid_str, ".fls");
33329 if (output_directory) {
33330 char *temp = concat3(output_directory, DIR_SEP_STRING, recorder_name);
33331 free(recorder_name);
33332 recorder_name = temp;
33333 }
33334 recorder_file = xfopen(recorder_name, FOPEN_W_MODE);
33335 cwd = xgetcwd();
33336 fprintf(recorder_file, "PWD %s\n", cwd);
33337 free(cwd);
33338 }
33339
33340 @ After we know the log file name, we have used |recorder_change_filename|
33341 to change the name of the recorder file to the usual thing.
33342 @<Forward declarations@>=
33343 static void recorder_change_filename (const char *new_name);
33344
33345 @ Now its time to define this function.
33346 Unfortunately, we have to explicitly take
33347 the output directory into account, since the new name we are
33348 called with does not; it is just the log file name with {\tt .log}
33349 replaced by {\tt .fls}.
33350
33351 @ @<\TeX\ Live auxiliary functions@>=
33352 static void
33353 recorder_change_filename (const char *new_name)
33354 { char *temp = NULL;
33355 if (!recorder_file)
33356 return;
33357 #if defined(_WIN32)
33358 fclose (recorder_file); /* An open file cannot be renamed. */
33359 #endif /* |_WIN32| */
33360 if (output_directory) {
33361 temp = concat3(output_directory, DIR_SEP_STRING, new_name);
33362 new_name = temp;
33363 }
33364
33365 #if defined(_WIN32)
33366 remove (new_name); /* A file with the |new_name| must not exist. */
33367 #endif /* |_WIN32| */
33368 rename(recorder_name, new_name);
33369 free(recorder_name);
33370 recorder_name = xstrdup(new_name);
33371 #if defined(_WIN32)
33372 recorder_file = xfopen (recorder_name, FOPEN_A_MODE); /* A closed file must be opened. */
33373 #endif /* |_WIN32| */
33374 if (temp)
33375 free (temp);
33376 }
33377
33378 @ Now we are ready to record file names. The prefix INPUT is added
33379 to an input file and the prefix OUTPUT to an output file.
33380 But both functions for recording a file name use the same
33381 function otherwise, which on first use will start the recorder.
33382
33383 @<\TeX\ Live auxiliary functions@>=
33384 static void
33385 recorder_record_name (const char *pfx, const char *fname)
33386 { @+if (recorder_enabled) {
33387 if (!recorder_file)
33388 recorder_start();
33389 fprintf(recorder_file, "%s %s\n", pfx, fname);
33390 fflush(recorder_file);
33391 }
33392 }
33393
33394
33395 static void
33396 recorder_record_input (const char *fname)
33397 { recorder_record_name ("INPUT", fname);
33398 }
33399
33400 static void
33401 recorder_record_output (const char * fname)
33402 { recorder_record_name ("OUTPUT", fname);
33403 }
33404
33405 @ Because input files are also recorded when writing the optional sections,
33406 we need the following declaration.
33407
33408 @<Forward declarations@>=
33409 static void recorder_record_input (const char *fname);
33410
33411 @ In WIN32, texmf.cnf is not recorded in
33412 the case of {\tt -recorder}, because |parse_options| is executed
33413 after the start of kpathsea due to special initializations.
33414 Therefore we record {\tt texmf.cnf} with the following code:
33415
33416 @<record {\tt texmf.cnf}@>=
33417 if (recorder_enabled) {
33418 char **p = kpse_find_file_generic ("texmf.cnf", kpse_cnf_format, 0, 1);
33419 if (p && *p) {
33420 char **pp = p;
33421 while (*p) {
33422 recorder_record_input (*p);
33423 free (*p);
33424 p++;
33425 }
33426 free (pp);
33427 }
33428 }
33429
33430
33431
33432
33433 @*1 The {\tt -cnf-line} Option.
33434 With the \.{-cnf-line} option it is possible to specify
33435 a line of text as if this line were part of \TeX's configuration
33436 file---even taking precedence over conflicting lines in the configuration
33437 file. For example it is possible to change \TeX's
33438 \.{TEXINPUTS} variable by saying \.{--cnf-line=TEXINPUTS=/foo}.
33439 The configuration lines are temporarily stored in the variable
33440 |cnf_lines| and counted in |cnf_count| because we can send them
33441 to the \.{kpathsearch} library only after the library has been
33442 initialized sufficiently.
33443
33444 @<Global...@>=
33445 static char **cnf_lines=NULL;
33446 static int cnf_count=0;
33447
33448 @ @<handle the options@>=
33449 else @+if (ARGUMENT_IS ("cnf-line"))
33450 add_cnf_line(optarg);
33451
33452 @ The function |add_cnf_line| stores the
33453 given command line argument in the variable |cnf_lines|.
33454
33455 @<\TeX\ Live auxiliary functions@>=
33456 static void add_cnf_line(char *arg)
33457 {@+ cnf_count++;
33458 cnf_lines=xrealloc(cnf_lines,sizeof(char*)*cnf_count);
33459 cnf_lines[cnf_count-1]=arg;
33460 }
33461
33462 @ To activate the configuration lines they are passed to the
33463 \.{kpathsearch} library.
33464
33465 @<activate configuration lines@>=
33466 #if 1 /* this function does not exists always */
33467 {@+ int i;
33468 for (i=0;i<cnf_count;i++)
33469 kpathsea_cnf_line_env_progname (kpse_def, cnf_lines[i]);
33470 free(cnf_lines);
33471 }
33472 #endif
33473
33474
33475 @*1 Hi\TeX\ specific command line options.
33476 Hi\TeX\ provides options to set the \MF\ mode and the resolution if
33477 {\tt .pk} fonts must be rendered and/or included in the {\tt .hnt}
33478 output file. Further, a lot of debug output can be generated if
33479 Hi\TeX\ was compiled with debugging enabled. The {\tt -hint-debug-help}
33480 option gives a short summary of what to expect.
33481 @<handle the options@>=
33482 else @+if (ARGUMENT_IS("resolution")) @t\2@>
33483 { option_dpi_str=optarg;
33484 option_dpi=strtol(option_dpi_str,NULL,10);
33485 }
33486 else if (ARGUMENT_IS("mfmode"))
33487 option_mfmode=optarg;
33488 #ifdef DEBUG@t\1@>
33489 else @+if (ARGUMENT_IS("hint-debug"))@t\2@>
33490 debugflags=strtol(optarg,NULL,16);
33491 else @+if (ARGUMENT_IS("hint-debug-help"))
33492 { fprintf(stderr,@/
33493 "To generate HINT format debug output use the option\n"
33494 " -hint-debug=XX"@/
33495 @t\qquad@>"\t\t XX is a hexadecimal value. OR together these values:\n");@/
33496 fprintf(stderr,"\t XX=%04X \t basic debugging\n", DBGBASIC);@/
33497 fprintf(stderr,"\t XX=%04X \t tag debugging\n", DBGTAGS);@/
33498 fprintf(stderr,"\t XX=%04X \t node debugging\n",DBGNODE);@/
33499 fprintf(stderr,"\t XX=%04X \t definition debugging\n", DBGDEF);@/
33500 fprintf(stderr,"\t XX=%04X \t directory debugging\n", DBGDIR);@/
33501 fprintf(stderr,"\t XX=%04X \t range debugging\n",DBGRANGE);@/
33502 fprintf(stderr,"\t XX=%04X \t float debugging\n", DBGFLOAT);@/
33503 fprintf(stderr,"\t XX=%04X \t compression debugging\n", DBGCOMPRESS);@/
33504 fprintf(stderr,"\t XX=%04X \t buffer debugging\n", DBGBUFFER);@/
33505 fprintf(stderr,"\t XX=%04X \t TeX debugging\n", DBGTEX);@/
33506 fprintf(stderr,"\t XX=%04X \t page debugging\n", DBGPAGE);@/
33507 fprintf(stderr,"\t XX=%04X \t font debugging\n", DBGFONT);@/
33508 #if 0 /* currently not used in hitex */
33509 fprintf(stderr,"\t XX=%04X \t render debugging\n", DBGRENDER);@/
33510 #endif
33511 fprintf(stderr,"\t XX=%04X \t label debugging\n", DBGLABEL);@/
33512 exit(0);
33513 }
33514 #endif
33515
33516 @*1 The Input File.
33517 After we are done with the options,
33518 we inform the \.{kpathsearch} library about the program name.
33519 This is an important piece of information for the library
33520 because the library serves quite different programs
33521 and its behavior can be customized for each program
33522 using configuration files.
33523 After the program and engine name is set,
33524 the library is ready to use.
33525 @<set the program and engine name@>=
33526 if (!user_progname)
33527 user_progname = dump_name;
33528 #if defined(WIN32)
33529 if (user_progname)
33530 kpse_reset_program_name (user_progname);
33531 #else
33532 kpse_set_program_name (argv[0], user_progname);
33533 #endif
33534 xputenv ("engine", "hitex");@/
33535
33536
33537 @ After the options, the command line usually continues with the name of the input
33538 file. Getting a hold of the input file name can be quite complicated,
33539 but the \.{kpathsearch} library will help us to do the job.
33540
33541 We start by looking at the first argument after the options:
33542 If it does not start with an
33543 ``\.{\AM}'' and neither with a ``\.{\BS}'', it's a simple file name.
33544 Under Windows, however, filenames might start with a drive letter
33545 followed by a colon and a ``\.{\BS}'' which is used to separate
33546 directory names. Finally, if the filename is a quoted string, we need
33547 to remove the quotes before we use the \.{kpathsearch} library to find it
33548 and reattach the quotes afterward.
33549
33550 @<\TeX\ Live auxiliary functions@>=
33551 #ifdef WIN32
33552 static void clean_windows_filename(char *filename)
33553 {@+if (strlen (filename) > 2 && isalpha (filename[0]) &&
33554 filename[1] == ':' && filename[2] == '\\')
33555 { char *pp;
33556 for (pp = filename; *pp; pp++)
33557 if (*pp == '\\')
33558 *pp = '/';
33559 }
33560 }
33561 #endif
33562
33563 static char *find_file(char *fname, kpse_file_format_type t, int mx)
33564 {@+char *filename;
33565 int final_quote=(int)strlen(fname)-1;
33566 int quoted = final_quote>1 && fname[0] == '"' && fname[final_quote]=='"';
33567 if (quoted) {
33568 /* Overwrite last quote and skip first quote. */
33569 fname[final_quote] = '\0';
33570 fname++;
33571 }
33572 filename = kpse_find_file(fname, t, mx);
33573 if (full_name_of_file!=NULL)
33574 { free(full_name_of_file); full_name_of_file=NULL;}
33575 if (filename!=NULL)
33576 full_name_of_file=strdup(filename);
33577 if (quoted) {
33578 /* Undo modifications */
33579 fname--;
33580 fname[final_quote] = '"';
33581 }
33582 return filename;
33583 }
33584
33585 static char *get_input_file_name (void)
33586 {@+
33587 char *input_file_name = NULL;
33588
33589 if (argv[optind] && argv[optind][0] != '&' && argv[optind][0] != '\\')
33590 {
33591 #ifdef WIN32
33592 clean_windows_filename(argv[optind]);
33593 #endif
33594 argv[optind] = normalize_quotes(argv[optind], "input file");
33595 input_file_name=find_file(argv[optind],kpse_tex_format, false);
33596 }
33597 return input_file_name;
33598 }
33599
33600
33601 @ After we called |get_input_file_name|, we might need to look at |argv[argc-1]|
33602 in case we run under Windows.
33603
33604 @<set the input file name@>=
33605 main_input_file = get_input_file_name ();
33606
33607 #ifdef WIN32
33608 /* Were we given a simple filename? */
33609 if (main_input_file == NULL) {
33610 char *file_name=argv[argc-1];
33611 if (file_name && file_name[0] != '-' && file_name[0] != '&' && file_name[0] != '\\') {
33612 clean_windows_filename(file_name);
33613 file_name = normalize_quotes(file_name, "argument");
33614 main_input_file=find_file(file_name,kpse_tex_format, false);
33615 argv[argc-1] = file_name;
33616 }
33617 }
33618 #endif
33619
33620
33621 @ After we have an input file, we make an attempt at filling in options
33622 from the {\tt texmf.cfg} file.
33623
33624 @<set defaults from the {\tt texmf.cfg} file@>=
33625 if (filelineerrorstylep < 0)
33626 filelineerrorstylep = texmf_yesno ("file_line_error_style");
33627 if (parsefirstlinep < 0)
33628 parsefirstlinep = texmf_yesno ("parse_first_line");@/@t~@>
33629
33630 @ We needed:
33631 @<\TeX\ Live auxiliary functions@>=
33632 static int texmf_yesno(const char *var)
33633 {@+
33634 char *value = kpse_var_value (var);
33635 return value && (*value == 't' || *value == 'y' || *value == '1');
33636 }
33637
33638 @ We need a stack, matching the |line_stack| that
33639 contains the source file names. For the full source filenames we use
33640 pointers to |char| because these names are just used for output.
33641
33642 @<Global...@>=
33643 static char * @!source_filename_stack0[max_in_open]={NULL}, **const @!source_filename_stack = @!source_filename_stack0-1;
33644 static char * @!full_source_filename_stack0[max_in_open]={NULL}, **const @!full_source_filename_stack = @!full_source_filename_stack0-1;
33645 static char *full_name_of_file=NULL;
33646
33647 @ The function |print_file_line|
33648 prints ``file:line:error'' style messages using
33649 the |source_filename_stack|. If it fails to find the file name, it
33650 falls back to the ``non-file:line:error'' style.
33651
33652 @<Basic printing...@>=
33653 static void print_file_line(void)
33654 {@+int level=in_open;
33655 while (level>0 && full_source_filename_stack[level]==NULL) level--;
33656 if (level==0) print_nl("! ");
33657 else
33658 { print_nl(""); print(full_source_filename_stack[level]); print_char(':');
33659 if (level==in_open) print_int(line);
33660 else print_int(line_stack[level]);
33661 print(": ");
33662 }
33663 }
33664
33665 @*1 The Format File.
33666 Most of the time \TeX\ is not running as \.{initex} or \.{virtex},
33667 but it runs with a format file preloaded.
33668 To set the format name, we first check if the format name was given on the
33669 command line with an ``\.{\AM}'' prefix,
33670 second we might check the first line of the input file,
33671 and last, we check if the program is an initex or virtex program.
33672
33673 If we still don't have a format,
33674 we use a plain format if running as a virtex, otherwise the program
33675 name is our best guess.
33676 There is no need to check for an extension, because the
33677 \.{kpathsearch} library will take care of that.
33678 We store the format file name in |dump_name| which is
33679 used in the function |w_open_in| below.
33680
33681 @<set the format name@>=
33682 if (parsefirstlinep && !dump_name)
33683 parse_first_line (main_input_file);
33684 if (!main_input_file && argv[1] && argv[1][0] == '&')
33685 dump_name = argv[1] + 1;
33686 if (strcmp(kpse_program_name, "hinitex")==0) iniversion = true;
33687 else if (strcmp(kpse_program_name, "hvirtex")==0 && !dump_name)
33688 dump_name = "hitex";
33689 if (!dump_name)
33690 dump_name = kpse_program_name;
33691 if (!dump_name)
33692 { fprintf(stderr,"Unable to determine format name\n");
33693 exit(1);
33694 }
33695 if (ltxp) etexp=1;
33696 if (etexp && !iniversion)
33697 { fprintf(stderr,"-etex and -ltx require -ini\n");
33698 exit(1);
33699 }
33700
33701 @ Here is the function |parse_first_line |. It searches the first line of
33702 the file for a \TeX\ comment of the form ``\%\AM format''\footnote{${}^1$}{The idea of using this format came from Wlodzimierz Bzyl.}.
33703 If found, we will use the format given there.
33704
33705 @<\TeX\ Live auxiliary functions@>=
33706 static void parse_first_line(char*filename)
33707 {@+ FILE *f=NULL;
33708 if (filename==NULL) return;
33709 f = open_in(filename,kpse_tex_format,"r");
33710 if (f!=NULL)
33711 { char *r,*s,*t=read_line (f);
33712 xfclose (f, filename);
33713 if (t==NULL) return;
33714 s=t;
33715 if (s[0] == '%' && s[1] == '&') {
33716 s = s+2;
33717 while ( ISBLANK(*s)) ++s;
33718 r=s;
33719 while (*s!=0 && *s!=' ' && *s!='\r' && *s!='\n') s++;
33720 *s=0;
33721 if (dump_name==NULL) {
33722 char *f_name = concat (r, ".fmt");
33723 char *d_name = kpse_find_file (f_name,kpse_fmt_format, false);
33724 if (d_name && kpse_readable_file (d_name)) {
33725 dump_name = xstrdup (r);
33726 kpse_reset_program_name (dump_name);
33727 }
33728 free (f_name);
33729 }
33730 }
33731 free (t);
33732 }
33733 }
33734
33735 @*1 Commands.
33736 In the old days, \TeX\ was a \PASCAL\ program, and standard \PASCAL\
33737 did say nothing about a command line. So \TeX\ would open the terminal
33738 file for input and read all the information from the terminal.
33739 If you don't give \TeX\ command line arguments, this is still true today.
33740 In our present time, people got so much used to control the behavior
33741 of a program using command line arguments---especially when writing
33742 scripts---that \TeX\ Live allows the specification of commands on
33743 the command line which \TeX\ would normally expect on
33744 the first line of its terminal input.
33745
33746 So our next task is
33747 writing a function to add the remainder of the
33748 command line to \TeX's input buffer.
33749 The main job is done by the |input_add_str| function
33750 which duplicates part of the |input_ln| function.
33751 Further it skips initial spaces and replaces trailing spaces
33752 and line endings by a single space.
33753
33754 @<\TeX\ Live auxiliary functions@>=
33755 static void input_add_char(unsigned int c)
33756 {@+ if (last >= max_buf_stack)
33757 {@+max_buf_stack=last+1;
33758 if (max_buf_stack==buf_size)
33759 @<Report overflow of the input buffer, and abort@>;
33760 }
33761 buffer[last]=c;incr(last);
33762 }
33763
33764 static void input_add_str(const char *str)
33765 {@+ int prev_last;
33766 while (*str==' ') str++;
33767 prev_last=last;
33768 while (*str!=0)
33769
33770 input_add_char(*str++);
33771 for (--last; last >= first ; --last)
33772 { char c =buffer[last];
33773 if ((c) != ' ' && (c) != '\r' && (c) != '\n') break;
33774 }
33775 last++;
33776 if (last>prev_last) input_add_char(' ');
33777 }
33778
33779 static int input_command_line(void)
33780 {@+
33781 last=first;
33782 while (optind < argc) input_add_str(argv[optind++]);
33783 loc=first;
33784 return (loc < last);
33785 @+ }
33786
33787 @ @<Forward declarations@>=
33788 static int input_command_line(void);
33789
33790
33791 @*1 Opening Files.
33792 When we open an output file, there is usually no searching necessary.
33793 In the best case, we have an absolute path and can open it.
33794 If the path is relative, we try in this order:
33795 the |file_name| prefixed by the |output_directory|,
33796 the |file_name| as is, and
33797 the |file_name| prefixed with the environment variable |TEXMFOUTPUT|.
33798
33799 If we were successful with one of the modified names, we update
33800 |name_of_file|.
33801
33802 @<\TeX\ Live functions@>=
33803 static FILE *open_out(const char *file_name, const char *file_mode)
33804 {@+ FILE *f=NULL;
33805 char *new_name=NULL;
33806 int absolute = kpse_absolute_p(file_name, false);
33807 if (absolute)
33808 { f=fopen(file_name,file_mode);
33809 if (f!=NULL) recorder_record_output (file_name);
33810 return f;
33811 }
33812 if (output_directory)
33813 { new_name = concat3(output_directory, DIR_SEP_STRING, file_name);
33814 f = fopen(new_name,file_mode);
33815 if (f==NULL) {@+ free(new_name); new_name=NULL;@+}
33816 }
33817 if (f==NULL)
33818 f = fopen(file_name,file_mode);
33819 if (f==NULL)
33820 { const char *texmfoutput = kpse_var_value("TEXMFOUTPUT");
33821 if (texmfoutput!=NULL && texmfoutput[0]!=0)
33822 { new_name = concat3(texmfoutput, DIR_SEP_STRING, file_name);@/
33823 f = fopen(new_name,file_mode);
33824 if (f==NULL) {@+ free(new_name); new_name=NULL; @+}
33825 }
33826 }
33827 if (f!=NULL && new_name!=NULL)
33828 update_name_of_file(new_name,(int)strlen(new_name));
33829 if (f!=NULL) recorder_record_output ((char*)name_of_file+1);
33830 if (new_name!=NULL) free(new_name);
33831 return f;
33832 }
33833
33834 static bool a_open_out(alpha_file *f) /*open a text file for output*/
33835 {@+f->f=open_out((char*)name_of_file+1,"w");
33836 return f->f!=NULL && ferror(f->f)==0;@+
33837 }
33838
33839 #ifdef @!INIT
33840 static bool w_open_out(word_file *f) /*open a word file for output*/
33841 {@+f->f=open_out((char *)name_of_file+1,"wb");
33842 return f->f!=NULL && ferror(f->f)==0;@+
33843 }
33844 #endif
33845
33846
33847 @ Format file names must be scanned
33848 before \TeX's string mechanism has been initialized.
33849 The function |update_name_of_file| will set |name_of_file| from
33850 a \CEE/ string.
33851
33852 We dare not give error messages here, since \TeX\ calls this routine before
33853 the |error| routine is ready to roll. Instead, we simply drop excess characters,
33854 since the error will be detected in another way when a strange file name
33855 isn't found.
33856 @^system dependencies@>
33857
33858 @<\TeX\ Live auxiliary functions@>=
33859 static void update_name_of_file(const char *@!s, int @!k)
33860 {@+ int j;
33861 if (k <= file_name_size) name_length=k;@+
33862 else name_length=file_name_size;
33863 for (j=0; j<name_length;j++) name_of_file[j+1]=s[j];
33864 name_of_file[name_length+1]=0;
33865 }
33866
33867 @ In standard \TeX, the |reset| macro is used to open input files.
33868 The \.{kpathsearch} library uses different search paths for
33869 different types of files and therefore different functions are needed to
33870 open these files. The common code is in the function |open_in|.
33871
33872 @<\TeX\ Live auxiliary functions@>=
33873 static FILE*open_in(char*filename,kpse_file_format_type t,const char*rwb)
33874 {@+ char *fname=NULL;
33875 FILE*f= NULL;
33876 fname= find_file(filename,t,true);
33877 if(fname!=NULL)
33878 {@+
33879 f= fopen(fname,rwb);
33880 if (f!=NULL) recorder_record_input(fname);
33881 if (full_name_of_file!=NULL) free(full_name_of_file);
33882 full_name_of_file=fname;@+
33883 }
33884 return f;
33885 }
33886
33887 static bool a_open_in(alpha_file *f) /*open a text file for input*/
33888 {@+f->f= open_in((char *)name_of_file+1,kpse_tex_format,"r");
33889 if (f->f!=NULL) get(*f);
33890 return f->f!=NULL && ferror(f->f)==0;
33891 }
33892
33893 static bool b_open_in(byte_file *f, char *fname) /*used only for .tfm files*/
33894 {@+FILE*tfm= NULL;
33895 tfm= fopen(fname,"rb");
33896 if (tfm!=NULL) recorder_record_input(fname);
33897 if (full_name_of_file!=NULL) free(full_name_of_file);
33898 full_name_of_file=fname;@+
33899 f->f= tfm;
33900 get(*f);
33901 return f->f!=NULL && ferror(f->f)==0;
33902 }
33903
33904 static bool w_open_in(word_file *f) /*open a word file for input*/
33905 {@+
33906 f->f=NULL;
33907 if (name_of_file[1]!=0)
33908 f->f= open_in((char*)name_of_file+1,kpse_fmt_format,"rb");
33909 if (f->f!=NULL) get(*f);
33910 return f->f!=NULL && ferror(f->f)==0;
33911 }
33912
33913 @ \TeX's |open_fmt_file| function will call the following function
33914 either with the name of a format file as given with an ``\.{\AM}''
33915 prefix in the input or with |NULL| if no such name was specified.
33916 The function will try |dump_name| as a last resort before returning |NULL|.
33917
33918
33919
33920 @<\TeX\ Live functions@>=
33921 static bool open_fmt_file(void)
33922 {@+int j=loc;
33923 if (buffer[loc]=='&')
33924 {@+incr(loc);j=loc;buffer[last]=' ';
33925 while (buffer[j]!=' ') incr(j);
33926 update_name_of_file((char *)buffer+loc,j-loc);
33927 if (w_open_in(&fmt_file)) goto found;
33928 }
33929 update_name_of_file(dump_name,(int)strlen(dump_name));
33930 if (w_open_in(&fmt_file)) goto found;
33931 name_of_file[1]=0;
33932 wake_up_terminal;
33933 wterm_ln("I can't find a format file!");
33934 return false;
33935 found: loc=j;return true;
33936 }
33937
33938
33939 @ The \TeX\ Live infrastructure is able to generate format files,
33940 font metric files,
33941 and even some tex files, if required.
33942
33943 @<enable the generation of input files@>=
33944 kpse_set_program_enabled (kpse_tfm_format, MAKE_TEX_TFM_BY_DEFAULT,
33945 kpse_src_compile);@/
33946 kpse_set_program_enabled (kpse_tex_format, MAKE_TEX_TEX_BY_DEFAULT,
33947 kpse_src_compile);@/
33948 kpse_set_program_enabled (kpse_fmt_format, MAKE_TEX_FMT_BY_DEFAULT,
33949 kpse_src_compile);@/
33950 kpse_set_program_enabled (kpse_pk_format, MAKE_TEX_PK_BY_DEFAULT,
33951 kpse_src_compile);@/
33952 xputenv("MAKETEX_BASE_DPI", option_dpi_str);
33953 xputenv("MAKETEX_MODE", option_mfmode);
33954
33955
33956
33957 @*1 Date and Time.
33958 We conclude this chapter using \.{time.h} to provide a function
33959 that is used to initialize
33960 \TeX's date and time information. Because |time| is one of \TeX's
33961 macros, we add the function |tl_now| before including \TeX's macros
33962 to wrap the call to the |time| function.
33963 It sets the variable |start_time| and returns a pointer to a |tm| structure
33964 to be used later in |fix_date_and_time|.
33965
33966 To support reproducible output, the environment variable |SOURCE_DATE_EPOCH|
33967 needs to be checked. If it is set, it is an ASCII representation of
33968 a UNIX timestamp, defined as the number
33969 of seconds, excluding leap seconds, since 01 Jan 1970 00:00:00 UTC.
33970 Its value is then used to initialize the |start_time| variable.
33971
33972 The \TeX\ Live conventions further require that setting the
33973 |FORCE_SOURCE_DATE| environment variable to $1$ will cause also \TeX's primitives
33974 \.{\\year}, \.{\\month}, \.{\\day}, and \.{\\time} to use this value
33975 as the current time. Looking at the \TeX\ Live code also reveals that
33976 these primitives use the local time instead of the GMT if this variable is
33977 not set to~1.
33978
33979 @<Header files and function declarations@>=
33980 #include <time.h>
33981 static time_t start_time = ((time_t)-1);
33982 static char *source_date_epoch,*force_source_date;
33983
33984 #if defined(_MSC_VER) && _MSC_VER < 1800
33985 #define strtoull _strtoui64
33986 #endif
33987
33988 static struct tm *tl_now(void)
33989 {@+struct tm *tp;
33990 time_t t;
33991 source_date_epoch= getenv("SOURCE_DATE_EPOCH");
33992 force_source_date= getenv("FORCE_SOURCE_DATE");
33993 if (force_source_date!=NULL &&
33994 (force_source_date[0]!='1' || force_source_date[1]!=0))
33995 force_source_date=NULL;
33996
33997 if (source_date_epoch!=NULL)
33998 { start_time= (time_t)strtoull(source_date_epoch, NULL, 10);
33999 if (force_source_date!=NULL)
34000 t=start_time;
34001 else
34002 t=time(NULL);
34003 }
34004 else
34005 t=start_time=time(NULL);
34006 if (force_source_date)
34007 tp=gmtime(&t);
34008 else
34009 tp=localtime(&t);
34010 return tp;
34011 }
34012
34013 @*1 Retrieving File Properties.
34014 To support \LaTeX, a few more time related functions are needed.
34015 @<Header files and function declarations@>=
34016 #define TIME_STR_SIZE 30
34017 static char time_str[TIME_STR_SIZE];
34018 static void get_creation_date(void);
34019 static void get_file_mod_date(void);
34020 static int get_file_size(void);
34021
34022 #include <md5.h>
34023 #define DIGEST_SIZE 16
34024 #define FILE_BUF_SIZE 1024
34025 static md5_byte_t md5_digest[DIGEST_SIZE];
34026
34027 static int get_md5_sum(int s, int file);
34028
34029 @ The code that follows was taken from the \.{texmfmp.c} file of
34030 the \TeX\ Live distribution and slightly modified.
34031
34032
34033 @<\TeX\ Live auxiliary functions@>=
34034
34035 static void
34036 make_time_str(time_t t, bool utc)
34037 {
34038 struct tm lt, gmt;
34039 size_t size;
34040 int off, off_hours, off_mins;
34041
34042 /* get the time */
34043 if (utc) {
34044 lt = *gmtime(&t);
34045 }
34046 else {
34047 lt = *localtime(&t);
34048 }
34049 size = strftime(time_str, TIME_STR_SIZE, "D:%Y%m%d%H%M%S", &lt);
34050 /* expected format: |"D:YYYYmmddHHMMSS"| */
34051 if (size == 0) {
34052 /* unexpected, contents of |time_str| is undefined */
34053 time_str[0] = '\0';
34054 return;
34055 }
34056
34057 /* correction for seconds: S can be in range 00 to 61,
34058 the PDF reference expects 00 to59,
34059 therefore we map |"60"| and |"61"| to |"59"| */
34060 if (time_str[14] == '6') {
34061 time_str[14] = '5';
34062 time_str[15] = '9';
34063 time_str[16] = '\0'; /* for safety */
34064 }
34065
34066 /* get the time zone offset */
34067 gmt = *gmtime(&t);
34068
34069 /* this calculation method was found in exim's tod.c */
34070 off = 60 * (lt.tm_hour - gmt.tm_hour) + lt.tm_min - gmt.tm_min;
34071 if (lt.tm_year != gmt.tm_year) {
34072 off += (lt.tm_year > gmt.tm_year) ? 1440 : -1440;
34073 } else if (lt.tm_yday != gmt.tm_yday) {
34074 off += (lt.tm_yday > gmt.tm_yday) ? 1440 : -1440;
34075 }
34076
34077 if (off == 0) {
34078 time_str[size++] = 'Z';
34079 time_str[size] = 0;
34080 } else {
34081 off_hours = off / 60;
34082 off_mins = abs(off - off_hours * 60);
34083 snprintf(&time_str[size], TIME_STR_SIZE-size, "%+03d'%02d'", off_hours, off_mins);
34084 }
34085 }
34086
34087 static void get_creation_date(void)
34088 { make_time_str(start_time,source_date_epoch!=NULL);
34089 }
34090
34091 /* static structure for file status set by |find_input_file| */
34092 #ifdef WIN32
34093 static struct _stat file_stat;
34094 #define GET_FILE_STAT _stat(fname,&file_stat)
34095 #else
34096 static struct stat file_stat;
34097 #define GET_FILE_STAT stat(fname,&file_stat)
34098 #endif
34099
34100
34101 static char* find_input_file(void)
34102 { char *fname;
34103 int r;
34104 if (output_directory&&!kpse_absolute_p((char*)name_of_file0, false))
34105 { int r=-1;
34106 fname = concat3(output_directory, DIR_SEP_STRING, (char*)name_of_file0);
34107 r=GET_FILE_STAT;
34108 if (r==0)
34109 return fname;
34110 free(fname);
34111 }
34112 fname = kpse_find_tex((char*)name_of_file0);
34113 if (fname!=NULL)
34114 { r=GET_FILE_STAT;
34115 if (r==0)
34116 return fname;
34117 free(fname);
34118 }
34119 fname=(char*)name_of_file0;
34120 r=GET_FILE_STAT;
34121 if (r==0)
34122 return strdup(fname);
34123 return NULL;
34124 }
34125
34126
34127 static void get_file_mod_date(void)
34128 { char *fname=NULL;
34129 fname= find_input_file();
34130 time_str[0]=0;
34131 if(fname!=NULL)
34132 { make_time_str(file_stat.st_mtime,source_date_epoch!=NULL && force_source_date!=NULL);
34133 free(fname);@+
34134 }
34135 }
34136
34137 static int get_file_size(void)
34138 { int s=-1;
34139 char *fname=NULL;
34140 fname= find_input_file();
34141 if(fname!=NULL)
34142 {s=file_stat.st_size;
34143 free(fname);@+
34144 }
34145 return s;
34146 }
34147
34148
34149 static int get_md5_sum(int s, int file)
34150 { md5_state_t st;
34151 memset(md5_digest,0,DIGEST_SIZE);
34152 if (file)
34153 { char *fname;
34154 pack_file_name(s,empty_string,empty_string,NULL);
34155 fname= find_input_file();
34156 if(fname!=NULL)
34157 { FILE *f;
34158 f = fopen(fname, "rb");
34159 if (f != NULL)
34160 { int r;
34161 char file_buf[FILE_BUF_SIZE];
34162 recorder_record_input(fname);
34163 md5_init(&st);
34164 while ((r = fread(&file_buf, 1, FILE_BUF_SIZE, f)) > 0)
34165 md5_append(&st, (const md5_byte_t *) file_buf, r);
34166 md5_finish(&st, md5_digest);
34167 fclose(f);
34168 }
34169 free(fname);
34170 }
34171 else
34172 return 0;
34173 }
34174 else
34175 { md5_init(&st);
34176 md5_append(&st,(md5_byte_t *)&str_pool[str_start[s]],
34177 str_start[s + 1] - str_start[s]);
34178 md5_finish(&st, md5_digest);
34179 }
34180 return DIGEST_SIZE;
34181 }
34182
34183
34184 @* UTF8 processing.
34185
34186 The first function we need is the function that inputs one character |cur_chr|
34187 from an input buffer |b| at index |i|. We advance |i| for each byte
34188 read from the buffer and check that |i<=k|.
34189 Character codes less than |0x80| are stored as a single byte. This is the easy case.
34190
34191 @<input a single byte utf8 code@>=
34192 cur_chr=b[i]; incr(i);
34193 if (cur_chr<0x80 || i>=k) return i;
34194
34195 @ Values in the range |0x80| to |0x7ff| are encoded using two byte
34196 with the first byte having three high bits |110|, indicating a two byte sequence,
34197 and the lower five bits equal to the five high bits of |c|.
34198 It is followed by a continuation byte. having two high bits |10|
34199 and the lower six bits equal to the lower six bits of |c|.
34200
34201 @<input a two byte utf8 code@>=
34202 if ((cur_chr&0xE0)==0xC0)
34203 { @<input a continuation byte |d|@>@;
34204 cur_chr= ((cur_chr&0x1F)<<6)+(d&0x3F);
34205 return i;
34206 }
34207
34208 @ Reading a continuation byte is simple, but all error conditions need to be
34209 checked. Some \TeX\ input files test for UTF8 aware engines and skip
34210 parts of the input file that a considered to be read by 8-bit \TeX\ engines.
34211 So when the |scanner_status| is |skipping|, we should not produce errors.
34212
34213 @<input a continuation byte |d|@>=
34214 if (i < k)
34215 { d=b[i]; incr(i);
34216 if ((d&0xC0)!=0x80 && scanner_status!=skipping)
34217 { print_err("Invalid UTF8 continuation byte in the input");
34218 int_error(d);
34219 return i;
34220 }
34221 }
34222 else if (scanner_status!=skipping)
34223 { print_err("Missing UTF8 continuation byte in the input");
34224 error();
34225 return i;
34226 }
34227
34228 @ Values in the range |0x800| to |0xFFFF| are encoded in three byte
34229 with the first byte having the high bits |1110| indicating a three
34230 byte sequence followed by two continuation bytes.
34231
34232 @<input a three byte utf8 code@>=
34233 if ((cur_chr&0xF0)==0xE0)
34234 { @<input a continuation byte |d|@>@;
34235 cur_chr= ((cur_chr&0x0F)<<6)+(d&0x3F);
34236 @<input a continuation byte |d|@>@;
34237 cur_chr= (cur_chr<<6)+(d&0x3F);
34238 return i;
34239 }
34240
34241 @ Values in the range |0x1000| to |0x1FFFFF| are encoded in four byte
34242 with the first byte having the high bits |11110| indicating a four byte
34243 sequence followed by three continuation bytes.
34244 This range is far greater than the actual range of UTF8 codes which
34245 ends with |0x10FFFF|.
34246
34247 @<input a four byte utf8 code@>=
34248 if ((cur_chr&0xF8)==0xF0)
34249 { @<input a continuation byte |d|@>@;
34250 cur_chr= ((cur_chr&0x07)<<6)+(d&0x3F);
34251 @<input a continuation byte |d|@>@;
34252 cur_chr= (cur_chr<<6)+(d&0x3F);
34253 @<input a continuation byte |d|@>@;
34254 cur_chr= (cur_chr<<6)+(d&0x3F);
34255 if (cur_chr>0x10FFFF && scanner_status!=skipping)
34256 { print_err("UTF8 code out of range in the input");
34257 int_error(cur_chr);
34258 cur_chr=biggest_char;
34259 }
34260 return i;
34261 }
34262
34263
34264 @ The following function combines all the cases considered before.
34265 The parameters are a pointer |b| into an array of byte where
34266 the next characters is expected at index |i|, and a maximum value for
34267 the index |k|. The function advances the index |i| for each byte taken from the
34268 buffer and returns the updated value.
34269
34270
34271
34272 @p static int utf8_get_cur_chr(unsigned char *b, int i, int k)
34273 { uint8_t d;
34274 @<input a single byte utf8 code@>@;
34275 @<input a two byte utf8 code@>@;
34276 @<input a three byte utf8 code@>@;
34277 @<input a four byte utf8 code@>@;
34278 print_err("Malformed UTF8 code in the input; character ignored");
34279 cur_chr=biggest_char;
34280 return i;
34281 }
34282
34283 @ This process can be reverted by printing an UTF8 character
34284 assuming the user's terminal and log file are UTF8 capable.
34285 The parameters of |utf8_put_char| are a pointer |b| into an array of byte where
34286 the next characters is inserted at index |i|, and a maximum value for
34287 the index |k|. The function advances the index |i| for each byte put into the
34288 buffer and returns the updated value.
34289 A slightly simpler version is |print_utf8| which writes the character
34290 to the output.
34291
34292 @d append_utf8(A) /*put UTF8 codes \# at the end of |str_pool|*/
34293 {@+int i=utf8_put_char(str_pool,pool_ptr,pool_size,A); pool_ptr=i;
34294 }
34295
34296 @p
34297 static int utf8_put_char(unsigned char *b, int i, int k, uint32_t c)
34298 { if (i+4 > k) /*put a multibyte character in the buffer*/
34299 overflow("utf8 buffer size", k);
34300 if (c<0x80)
34301 { b[i++]=c; }
34302 else if (c<0x800)@/
34303 { b[i++]=0xC0|(c>>6); b[i++]=0x80|(c&0x3F); }
34304 else if (c<0x10000)@/
34305 { b[i++]=(0xE0|(c>>12)); b[i++]=(0x80|((c>>6)&0x3F));
34306 b[i++]=(0x80|(c&0x3F)); }
34307 else if (c<0x180000)@/
34308 { b[i++]=(0xF0|(c>>18)); b[i++]=(0x80|((c>>12)&0x3F));
34309 b[i++]=(0x80|((c>>6)&0x3F)); b[i++]=(0x80|(c&0x3F)); }
34310 return i;
34311 }
34312
34313 static void print_utf8(uint32_t c)
34314 {@+ if (c<0x80)
34315 { print_char(c); }
34316 else if (c<0x800)@/
34317 { print_char(0xC0|(c>>6)); print_char(0x80|(c&0x3F)); }
34318 else if (c<0x10000)@/
34319 { print_char(0xE0|(c>>12)); print_char(0x80|((c>>6)&0x3F));
34320 print_char(0x80|(c&0x3F)); }
34321 else if (c<0x180000)@/
34322 { print_char(0xF0|(c>>18)); print_char(0x80|((c>>12)&0x3F));
34323 print_char(0x80|((c>>6)&0x3F)); print_char(0x80|(c&0x3F)); }
34324 else
34325 print("???");
34326 }
34327
34328
34329 @ All the information about utf characters comes from a generated file.
34330
34331 @p
34332
34333 #include "hitex.dat.c"
34334
34335 @ The functions defined there replace the definitions of the
34336 \.{\\catcode}, \.{\\mathcode}, \.{\\uccode}, \.{\\lccode}, and \.{\\delcode}
34337 tables. \TeX's way to access such information was (and is) to provide an index
34338 into a table where the index is the sum of a base index depending on the
34339 type of information desired and an offset depending on the character code.
34340 The following function requires both parameters to deliver the requested result.
34341
34342 @p static int utf_lookup(pointer b, int i )
34343 {if (b==utf_lc_code_base) return utf_lccode(i);
34344 else if (b==utf_uc_code_base) return utf_uccode(i);
34345 else if (i<0x100)
34346 { if (b==utf_cat_code_base) return equiv(cat_code_base+i);
34347 else if (b==utf_sf_code_base) return equiv(sf_code_base+i);
34348 else if (b==utf_del_code_base) return equiv(del_code_base+i);
34349 else if (b==utf_math_codenum_base) return equiv(math_code_base+i);
34350 else if (b==utf_math_code_base) return equiv(math_code_base+i);
34351 else return 0;
34352 }
34353 else if (b==utf_cat_code_base) return utf_catcode(i);
34354 else if (b==utf_sf_code_base) return utf_sfcode(i);
34355 else if (b==utf_math_code_base) return utf_mathcode(i);
34356 else if (b==utf_math_codenum_base) return utf_mathcode(i);
34357 else if (b==utf_del_code_base) return utf_delcode(i);
34358 else return 0;
34359 }
34360
34361 @ Using |utf_base_mask| and |utf_cp_mask| it is easy to separate base
34362 and utf code point from the sum.
34363
34364 @<Show equivalent |n|, in the utf tables@>=
34365 switch (n&utf_base_mask)
34366 {@+case utf_cat_code_base:
34367 print_esc("catcode");print_int(n&utf_cp_mask);
34368 print_char('=');print_int(cat_code(n&utf_cp_mask));
34369 break;
34370 case utf_lc_code_base:
34371 print_esc("lccode");print_int(n&utf_cp_mask);
34372 print_char('=');print_int(utf_lccode(n&utf_cp_mask));
34373 break;
34374 case utf_uc_code_base:
34375 print_esc("uccode");print_int(n&utf_cp_mask);
34376 print_char('=');print_int(utf_uccode(n&utf_cp_mask));
34377 break;
34378 case utf_sf_code_base:
34379 print_esc("sfcode");print_int(n&utf_cp_mask);
34380 print_char('=');print_int(sf_code(n&utf_cp_mask));
34381 break;
34382 case utf_del_code_base:
34383 print_esc("delcode");print_int(n&utf_cp_mask);
34384 print_char('=');print_int(del_code(n&utf_cp_mask));
34385 break;
34386 case utf_math_code_base:
34387 print_esc("mathcode");print_int(n&utf_cp_mask);
34388 print_char('=');print_int(math_code(n&utf_cp_mask));
34389 break;
34390 case utf_math_codenum_base:
34391 print_esc("mathcodenum");print_int(n&utf_cp_mask);
34392 print_char('=');print_int(math_code(n&utf_cp_mask));
34393 break;
34394 }
34395
34396 @ The definition of math codes with \.{\\mathcode} requires a single number.
34397 In its four digit hexadecimal form the most significant digit is the class,
34398 the next digit the font family and the lowest two digits the glyph number in the font.
34399 For the extended range of utf characters, a bit packed format can be used
34400 where the most significant 8 bits contain the font family, and the lower 24 bits
34401 are split between the top 3 bit for the class and the low 21 bit for the glyph number.
34402 Since this bit packed format is not very convenient, there are now two primitives
34403 to specify math codes: \.{\\Umathcodenum} expects a single
34404 number in bit packed format; while \.{\\Umathcode} expects three numbers in the order
34405 class, family, and glyph number. The three numbers are then converted to the bit packed
34406 format which is used for internal storage.
34407
34408 @<Read the arguments of \.{\\Umathcode}@>=
34409 { int fam, class;
34410 scan_int(); class=cur_val; scan_int();fam=cur_val; scan_int();
34411 if (fam<0||fam>0xff)
34412 { print_err("Invalid family (");print_int(fam);
34413 print("), should be in the range 0..255");
34414 error();fam=1;
34415 }
34416 if (class<0||class>7)
34417 { print_err("Invalid class (");print_int(class);
34418 print("), should be in the range 0..7");
34419 error();class=7;
34420 }
34421 cur_val=(((fam<<3)|class)<<21)|cur_val;
34422 }
34423
34424 @ Since now all math codes are stored in the bit packed format,
34425 also the argument of \.{\\mathcode} is converted to the new format.
34426 The special value |0x8000| is now represented as |0xFFFFFFFF|.
34427 Fortunately the 64bit memory words used in Hi\TeX\ are big enough
34428 to store these values in the available halfword (32 bit) of |eqtb|.
34429
34430 @d active_math_character_code 0xFFFFFFFF
34431 @d math_code_fam(A) (((A)>>24)&0xFF)
34432 @d math_code_class(A) (((A)>>21)&0x7)
34433 @d math_code_char(A) ((A)&0x1FFFFF)
34434 @d Umath_to_math(A) { int fam=math_code_fam(A); int class=math_code_class(A); int cp=math_code_char(A);
34435 if (cp<=0xFF && fam<=0xF && class<=0xF) A =(((class<<4)|fam)<<8)|cp; else A=0; }
34436 @d math_to_Umath(A) { int class = (A>>12)&0xF, fam = (A>>8)&0xF, cp = A&0xFF; A =(((fam<<3)|class)<<21)|cp;}
34437
34438
34439
34440 @ Changing values in the utf tables is delegated to the following function
34441 that combines the function of |eq_define| and |geq_define|.
34442 We use two new |save_type|s: |restore_utf| and |restore_utf_none|.
34443 Changing the |save_type| from |restore_utf| to |restore_utf_none|
34444 means, that the entry is invalid and must no longer be used to restore a value
34445 because it was superseded by the assignment of a global value.
34446 We implement global assignments by going down the |save_stack|
34447 and invalidate all corresponding local assignments.
34448 We do this because we do not want to store assignment levels
34449 which would need extra data fields in the utf tables that would
34450 not be compatible with the table compression.
34451 For now we use two entries on the save stack,
34452 but with 64 bits of memory in a memory word, a single entry could suffice.
34453 To find all relevant entries in the save stack, we use the |save_level|
34454 to link together all entries of |restore_utf| or |restore_utf_none|
34455 keeping the index to the top level entry in |utf_restore_list|.
34456
34457 @d restore_utf_none (restore_sa+1)
34458 @d restore_utf (restore_utf_none+1)
34459
34460 @p
34461 static int utf_unsave_list=0;
34462 static void utf_save(pointer p,int cp, int e)
34463 { if (cur_level>level_one)
34464 { check_full_save_stack;
34465 save_stack[save_ptr].i=e;
34466 incr(save_ptr);
34467 save_type(save_ptr)=restore_utf;
34468 save_level(save_ptr)=utf_unsave_list;
34469 utf_unsave_list=save_ptr;
34470 save_index(save_ptr)=p+cp;
34471 incr(save_ptr);
34472 }
34473 }
34474
34475 static void utf_unsave(pointer p)
34476 { int cp, e;
34477 utf_unsave_list=save_level(save_ptr);
34478 decr(save_ptr);
34479 e= save_stack[save_ptr].i;
34480 cp=p&utf_cp_mask;
34481 p=p&utf_base_mask;
34482 if (p==utf_cat_code_base) utf_set_catcode(cp,e);
34483 else if (p==utf_lc_code_base) utf_set_lccode(cp,e);
34484 else if (p==utf_uc_code_base) utf_set_uccode(cp,e);
34485 else if (p==utf_sf_code_base) utf_set_sfcode(cp,e);
34486 else if (p==utf_del_code_base) utf_set_delcode(cp,e);
34487 else if (p==utf_math_codenum_base) utf_set_mathcode(cp,e);
34488 }
34489
34490 static void utf_global(pointer p)
34491 { /* mark matching save stack entries as |restore_utf_none| */
34492 int i=utf_unsave_list;
34493 while (i>0)
34494 { if (save_type(i)==restore_utf && save_index(i)==p)
34495 save_type(i)=restore_utf_none;
34496 i=save_level(i);
34497 }
34498 }
34499
34500
34501 static void utf_define(pointer p,int cp, int e,bool g)
34502 { if (g) assign_trace(p,"globally changing")@;
34503 else assign_trace(p,"changing")@;
34504 if (p==utf_cat_code_base) e=utf_set_catcode(cp,e);
34505 else if (p==utf_lc_code_base) e=utf_set_lccode(cp,e);
34506 else if (p==utf_uc_code_base) e=utf_set_uccode(cp,e);
34507 else if (p==utf_sf_code_base) e=utf_set_sfcode(cp,e);
34508 else if (p==utf_del_code_base) e=utf_set_delcode(cp,e);
34509 else if (p==utf_math_codenum_base) e=utf_set_mathcode(cp,e);
34510 if (g) utf_global(p+cp);
34511 else utf_save(p,cp,e);
34512 assign_trace(p,"into")@;@/
34513 }
34514
34515 @ For characters below |0x100| all codes, except the lower- and uppercase codes
34516 are still stored in the |eqtb|. The following function is called with an |utf_|\dots|_base|
34517 and returns the correct base pointer to |eqtb| for character codes below |0x100|.
34518
34519 @p static pointer utf_adjust_base(pointer p)
34520 { if (p==utf_cat_code_base) p=cat_code_base;
34521 else if (p==utf_sf_code_base) p=sf_code_base;
34522 else if (p==utf_math_codenum_base) p=math_code_base;
34523 else if (p==utf_math_code_base) p=math_code_base;
34524 else if (p==utf_del_code_base) p=del_code_base;
34525 return p;
34526 }
34527
34528
34529 @ @p
34530 #if 0 /* currently not used */
34531 static void utf_restore(pointer p, int e)
34532 { if (p<utf_lc_code_base) utf_set_catcode(p-utf_cat_code_base,e );
34533 else if (p<utf_uc_code_base) utf_set_lccode(p-utf_lc_code_base,e);
34534 else if (p<utf_sf_code_base) utf_set_uccode(p-utf_uc_code_base,e);
34535 else if (p<utf_code_limit) utf_set_sfcode(p-utf_sf_code_base,e) ;
34536 #ifdef @!STAT
34537 if (tracing_restores > 0) restore_trace(p,"retaining");
34538 #endif
34539 }
34540 #endif
34541
34542 @ While most character codes for UTF are in the tables just defined
34543 some are still in the |eqtb| table. These are fixed when in init mode
34544 using the following code:
34545
34546 @<Fix some character code assignments for UTF@>=
34547 /* changes to make hitex match luatex */
34548 /* 125/007D: RIGHT CURLY BRACKET */
34549 equiv(sf_code_base+'}')=0;
34550 /*170/00AA: FEMININE ORDINAL INDICATOR */
34551 equiv(cat_code_base+170)=11;equiv(math_code_base+170)=31457450;
34552 /*181/B5: MICRO SIGN */
34553 equiv(cat_code_base+181)=11;equiv(math_code_base+181)=31457461;
34554 /*186/BA: MASCULINE ORDINAL INDICATOR */
34555 equiv(cat_code_base+186)=11;equiv(math_code_base+186)=31457466;
34556 /*187/BB: RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK */
34557 equiv(sf_code_base+187)=0;
34558 /*192/C0: LATIN CAPITAL LETTER A WITH GRAVE to 214/D6 LATIN CAPITAL LETTER O WITH DIAERESIS*/
34559 for (k=192; k<=214; k++)
34560 { equiv(cat_code_base+k)=11;
34561 equiv(sf_code_base+k)=999;
34562 equiv(math_code_base+k)=0x1E00000+k;
34563 }
34564 /*216/D8: LATIN CAPITAL LETTER O WITH STROKE to 222/DE LATIN CAPITAL LETTER THORN*/
34565 for (k=216; k<=222; k++)
34566 { equiv(cat_code_base+k)=11;
34567 equiv(sf_code_base+k)=999;
34568 equiv(math_code_base+k)=0x1E00000+k;
34569 }
34570 /*223/DF LATIN SMALL LETTER SHARP S to 246/F6 LATIN SMALL LETTER O WITH DIAERESIS*/
34571 for (k=223; k<=246; k++)
34572 { equiv(cat_code_base+k)=11;
34573 equiv(math_code_base+k)=0x1E00000+k;
34574 }
34575 /* 248/F8 LATIN SMALL LETTER O WITH STROKE to 255/FF LATIN SMALL LETTER Y WITH DIAERESIS */
34576 for (k=248; k<=255; k++)
34577 { equiv(cat_code_base+k)=11;
34578 equiv(math_code_base+k)=0x1E00000+k;
34579 }
34580
34581
34582 @ For multibyte UTF8 active characters $x$ we look up the position $y$ in |eqtb|
34583 by searching in a hashtable with key $x$.
34584
34585 @<Glob...@>=
34586 static uint32_t @!active_hash0[active_hash_size]={0},
34587 *const @!active_hash = @!active_hash0-active_hash_base; /*the hash table*/
34588 static int active_used=0;
34589
34590 @ The function |active_lookup| is a simplified version of |id_lookup|
34591 using Fibonacci hashing.
34592
34593 @d fibonacci_factor 0x9F406BB9 /* See ``The MMIX Supplement'' */
34594 @d active_h1(A) (((A*fibonacci_factor)>>(32-active_hash_bits))|1)
34595 @d active_h2(A) (((A*fibonacci_factor)>>(32-2*active_hash_bits))|1)
34596 @d active_mask (active_hash_size-1)
34597
34598
34599 @p
34600 static pointer active_lookup(uint32_t key) /*search the hash table*/
34601 {@+int h, h2; /*hash codes*/
34602 pointer @!p; /*index in |active_hash| array*/
34603 h=active_h1(key);
34604 p=h+active_hash_base; /*we start searching here; note that |0 <= h < active_hash_size|*/
34605 if (active_hash[p] == key) return p;
34606 else if (active_hash[p] == 0) goto insert_key;
34607 h2=active_h2(key);
34608 loop@+{@+
34609 h=(h+h2)&active_mask;
34610 p=h+active_hash_base;
34611 if (active_hash[p] == key) return p;
34612 else if (active_hash[p] == 0) goto insert_key;
34613 }
34614 insert_key:
34615 active_used++;
34616 if (active_used>=active_hash_size)
34617 overflow("active characters hash size", active_hash_size);
34618 active_hash[p]=key;
34619 return p;
34620 }
34621
34622
34623 @ Finaly we have to dump and undump the |active_hash| table. We do not expect
34624 to be too many active characters in the table when dumping or undumping.
34625 So we just dump the number of used entries and pack the distance to the next used
34626 entry together with the entry into a single integer, assuming that the distance
34627 fits into a single byte. If the distance to the next used entry is greater than
34628 255, we dump an empty entry, which is of course not counted in |active_used|
34629
34630 @<Dump the |active_hash| table@>=
34631 dump_int(active_used);
34632 j=active_used;
34633 k=0;
34634 p=0;
34635 while (j>0)
34636 { if (active_hash0[k]!=0)
34637 { dump_int((k<<24)|active_hash0[k]);
34638 j--;
34639 p=k;
34640 }
34641 else if (k-p>=0xFF)
34642 { dump_int(0xFF<<24);
34643 p=k;
34644 }
34645 k++;
34646 if (k>=active_hash_size) break; /*this should not happen*/
34647 }
34648
34649 @ @<Undump the |active_hash| table@>=
34650 undump_int(active_used);
34651 j=active_used;
34652 k=0;
34653 p=0;
34654 while (j>0)
34655 { unsigned int x;
34656 undump_int(x);
34657 k=k+((x>>24)&0xFF);
34658 x=x&0x1FFFFF;
34659 if (x!=0)
34660 { if (k>=active_hash_size) break; /*this should not happen*/
34661 active_hash0[k]=x;
34662 j--;
34663 }
34664 }
34665
34666
34667 @ @<Forward declarations@>=
34668 static int utf8_get_cur_chr(unsigned char *b, int i, int k);
34669 static int utf8_put_char(unsigned char *b, int i, int k, uint32_t c);
34670 static void print_utf8(uint32_t c);
34671 static uint8_t utf_catcode(uint32_t i);
34672 static uint32_t utf_set_catcode(uint32_t i, uint8_t cat);
34673 static uint32_t utf_lccode(uint32_t i);
34674 static uint32_t utf_set_lccode(uint32_t i, uint32_t lc);
34675 static uint32_t utf_uccode(uint32_t i);
34676 static uint32_t utf_set_uccode(uint32_t i, uint32_t uc);
34677 static uint16_t utf_sfcode(uint32_t i);
34678 static uint32_t utf_set_sfcode(uint32_t i, uint16_t sf);
34679
34680 static uint32_t utf_set_delcode(uint32_t i, uint32_t dc);
34681 static int utf_delcode(uint32_t i);
34682 static uint32_t utf_set_mathcode(uint32_t i, uint32_t mc);
34683 static uint32_t utf_mathcode(uint32_t i);
34684 static void utf_unsave(pointer p);
34685 static int utf_lookup(pointer b, int i );
34686 static void utf_define(pointer p,int c,int e,bool g);
34687 static pointer utf_adjust_base(pointer p);
34688 static int utf_b_used, utf_i_used, utf_unsave_list;
34689 static scaled x_char_width(internal_font_number g, int c);
34690 static scaled x_char_height(internal_font_number g, int c);
34691 static scaled x_char_depth(internal_font_number g, int c);
34692 static scaled x_char_italic(internal_font_number g, int c);
34693 static pointer active_lookup(uint32_t k);
34694
34695
34696
34697 @* Fonts revisited.
34698 To use a font for typesetting, \TeX\ needs only a very limited amount
34699 of information. The required information is found in a font metric
34700 file or \.{TFM} file as described before.
34701 @:TFM files}{\.{TFM} files@>
34702 @^font metric files@>
34703 For a typical font used on a modern computer, a \.{TFM} is usually not
34704 available. While it is possible to create \.{TFM} files, for example
34705 with \.{otftotfm}, this is not the best solution, because modern font
34706 files contain much more information about the best way to typeset a
34707 given text than what would fit into a \.{TFM} file. This is
34708 especially true for ``non-latin'' texts. For this reason, modern \TeX\
34709 engines, like \LuaTeX\ or \XeTeX, load and use the font files
34710 directly.
34711
34712 To convert a unicode encoded text into a list of glyphs and
34713 their positions, Hi\TeX\ like other engines uses an other
34714 specialized library called \.{harfbuzz}.
34715
34716
34717 @ Finding the height and depth of a character is
34718 slightly more complex. It requires loading the glyph
34719 and retrieving its bounding box.
34720 Since most of the time we need the height and the depth
34721 together, we provide one function for both.
34722 We use |FT_Glyph_Get_CBox| to get the control box which is supposed to be fast.
34723 Because the glyph has been loaded with |FT_LOAD_NO_SCALE| we call
34724 |FT_Glyph_Get_CBox| with mode |FT_GLYPH_BBOX_UNSCALED| and
34725 get unscaled font units in 26.6 pixel format.
34726
34727
34728
34729
34730
34731
34732
34733 @ The functions just defined are listed here:
34734
34735 @<Forward declarations@>=
34736 static bool x_char_exists(internal_font_number g, int c);
34737 static bool x_glyph(internal_font_number g, int c, hb_codepoint_t *glyph);
34738 static scaled x_char_height(internal_font_number g, int c);
34739 static scaled x_glyph_width(internal_font_number g, hb_codepoint_t glyph);
34740 static scaled x_glyph_italic(internal_font_number g, hb_codepoint_t glyph);
34741 static void x_glyph_height_depth(internal_font_number g, hb_codepoint_t glyph, scaled *h, scaled *d);
34742 static void x_char_height_depth(internal_font_number g, int c, scaled *h, scaled *d);
34743 #if 0
34744 static FT_UInt ft_glyph(FT_Face ft_face, int c);
34745 static bool ft_exists(FT_Face ft_face, int c);
34746 static scaled ft_glyph_width(FT_Face ft_face, FT_UInt ft_gid, scaled s);
34747 static scaled ft_width(FT_Face ft_face, int c, scaled s);
34748 static FT_Error ft_glyph_bbox(FT_Face ft_face, FT_UInt ft_gid, FT_BBox *ft_bbox);
34749 static void ft_glyph_height_depth(FT_Face ft_face, FT_UInt ft_gid,
34750 scaled *h, scaled *d, scaled s);
34751 static void ft_height_depth(FT_Face ft_face, int c,
34752 scaled *h, scaled *d, scaled s);
34753 static int ft_last(FT_Face ft_face);
34754 static int ft_first(FT_Face ft_face);
34755 #endif
34756
34757 @ To move the functions to the program:
34758
34759 @p
34760 @<harfbuzz font metric functions@>@;
34761
34762
34763
34764 @ Here is the code to get the basic font parameters for an extended font.
34765 Let us start with the x-height: the size of one ex in the font.
34766 |x_height(A)| is defined as |font_info[param_base[g]+x_height_code].sc| with |x_height_code==5|.
34767
34768 @<get the extended fonts parameters@>=
34769 param_base[f]=fmem_ptr;
34770 fmem_ptr=fmem_ptr+font_params[f]+1;
34771 font_info[param_base[f]].sc =0;
34772 { hb_position_t h;
34773 hb_ot_metrics_get_position_with_fallback(x_font[f]->f,HB_OT_METRICS_TAG_X_HEIGHT,&h);
34774 /* if this is not working, I could use |x_char_height(f,'x')| */
34775 x_height(f)= HB_TO_SCALED(h);
34776 }
34777
34778
34779 @ The slant value, as needed by \TeX\ is the horizontal extent to the right for a
34780 character 1pt high.
34781
34782 @<get the extended fonts parameters@>=
34783 { double r;
34784 r= hb_style_get_value (x_font[f]->f, HB_STYLE_TAG_SLANT_RATIO);
34785 slant(f)=(ONE*r+0.5);
34786 }
34787
34788
34789 @ We call the fonts that Hi\TeX\ will handle by using harfbuzz
34790 ``extended fonts'', and variables or functions dealing with
34791 such fonts will often have an |x_|\dots\ prefix in their name.
34792
34793 While Hi\TeX\ wants to be compatible with other \TeX\ engines, its
34794 implementation of the \.{\\font} primitive still uses a simplified
34795 version of the extended syntax used in \XeTeX. The procedure is
34796 called |scan_font_name| and is a modified version of |scan_file_name|.
34797
34798 @<Declare procedures that scan font-related stuff@>=
34799 static void begin_name(void);
34800 static bool more_name(uint32_t @!c);
34801 static void end_name(void);
34802 static void scan_font_name(void)
34803 {@+pool_pointer @!j, k; /*index into |str_pool|*/
34804 int @!old_setting; /*holds |selector| setting*/
34805 char *f_name=NULL;
34806 name_in_progress=true;begin_name();
34807 @<Get the next non-blank non-relax...@>;
34808 if (cur_cmd==left_brace)
34809 @<Define a general text file name and |goto done|@>@;
34810 loop@+{@+if ((cur_cmd > other_char)||(cur_chr > biggest_char)) /*not a character*/
34811 {@+back_input();goto done;
34812 }
34813 if (!more_name(cur_chr)) goto done;
34814 get_x_token();
34815 }
34816 done:
34817 @<Split the font name into its components@>@;
34818 end_name();
34819 name_in_progress=false;
34820 }
34821
34822 @ @<Glob...@>=
34823 int f_index;
34824 int f_delimiter;
34825
34826
34827 @ When we try to split the font name into its components,
34828 the users input string is in |str_pool| starting at |str_start[str_ptr]|
34829 up to |pool_ptr-1| its lenght is |cur_length|.
34830 We have |area_delimiter==0| or equal to the string length up to the
34831 last |DIR_SEP| character.
34832 We have |ext_delimiter==0| or equal to the string length up to the
34833 last |'.'| character.
34834 We look for brackets and prefixes
34835 then try to get the right file path using the |kpse_find_file| function.
34836 Finaly, we put the area, the name and the extension back into the
34837 string pool and set |cur_area|, |cur_name|, and |cur_ext| using
34838 |end_name|. The font index and the font options will go into
34839 separate global variables.
34840
34841
34842 @<Split the font name into its components@>=
34843 { int l = cur_length;
34844 int i=0;
34845 int d;
34846 f_name= (char *)str_pool+str_start[str_ptr];
34847 if (f_name[i]=='[')
34848 { d=1;
34849 @<Find a bracketed file name@>@;
34850 }
34851 else if (strncmp("file:",f_name,5)==0)
34852 { d=5;
34853 @<Find a non-bracketed file name@>@;
34854 }
34855 else if (strncmp("name:",f_name,5)==0)
34856 { d=5;
34857 @<Find a font by name@>@;
34858 }
34859 else
34860 { /* Assuming a missing file: prefix*/
34861 d=0;
34862 @<Find a non-bracketed file name@>@;
34863 }
34864 if (i<l && f_name[i]=='(')
34865 { i++;
34866 @<Find font selector@>@;
34867 }
34868 else
34869 f_index=0;
34870 if (i<l && f_name[i]==':')
34871 { begin_diagnostic();
34872 print_nl("Font features not yet implemented!");
34873 end_diagnostic(false);
34874 }
34875 pool_ptr=str_start[str_ptr]+f_delimiter; /*flush the remaining string*/
34876 }
34877
34878 @ A bracketed file name starts and ends with a \.{[}.
34879 Since at this point |name_of_file| does not contain the extention,
34880 the closing bracket might be missing if it was after the extension.
34881 @<Find a bracketed file name@>=
34882 {
34883 i+=d;
34884 f_delimiter=area_delimiter=ext_delimiter=0;
34885 while (i<l)
34886 { f_name[i-d]=f_name[i];
34887 if (f_name[i]==']')
34888 { f_delimiter=i-d;
34889 d=2;
34890 i++;
34891 break;
34892 }
34893 else if (IS_DIR_SEP(f_name[i])) {@+area_delimiter=i+1-d;ext_delimiter=0; }
34894 else if (f_name[i]=='.') ext_delimiter=i+1-d;
34895 i++;
34896 }
34897 if (d!=2)
34898 { begin_diagnostic();
34899 print_nl("Bracketed font file name with missing ']'");
34900 end_diagnostic(false);
34901 }
34902 }
34903
34904 @ A non bracketed file name is terminated either by the opening parenthesis
34905 that starts the font selector, or by the colon that starts the font features,
34906 or by the end of the string
34907 @<Find a non-bracketed file name@>=
34908 { i+=d;
34909 f_delimiter=area_delimiter=ext_delimiter=0;
34910 while (i<l)
34911 { f_name[i-d]=f_name[i];
34912 if (f_name[i]=='(' || f_name[i]==':')
34913 break;
34914 else if (IS_DIR_SEP(f_name[i])) {@+area_delimiter=i+1-d;ext_delimiter=0; }
34915 else if (f_name[i]=='.') ext_delimiter=i+1-d;
34916 i++;
34917 }
34918 f_delimiter=i-d;
34919 }
34920
34921
34922 @ A font selector is enclosed in parentheses and currently is allways in integer.
34923 It would be nice, if \HiTeX\ could use |scan_int|, but that would need a completely
34924 different syntay for font specifications.
34925
34926
34927 @<Find font selector@>=
34928 { char *end_ptr=NULL;
34929 f_index=strtol((char *)f_name+i,&end_ptr,10);
34930 i=(end_ptr-f_name);
34931 if (*end_ptr==')')
34932 i++;
34933 else
34934 {@+begin_diagnostic();
34935 print_nl("Missing ]): There is no ) to terminate the font selector!");
34936 @.Missing ]@>
34937 end_diagnostic(false);
34938 }
34939 }
34940
34941
34942
34943 @ The name based font lookup needs to be implemented.
34944 @<Find a font by name@>=
34945 { i+=d;
34946 fatal_error("Finding fonts by name not yet implemented");
34947 }
34948
34949 @ If a file name was given, we use the kpathsearch library to find the file.
34950 The use of type1 fonts with harfbuzz requires the use of \.{.afm} files
34951 and this does not work well and is deprecated. For type1 fonts,
34952 one should use \.{afm2tfm} to convert the \.{.afm} files to \.{tfm}
34953 files and put the new \.{tfm} files in a place where the \.{kpathsearch} library
34954 can find them. Then run \.{mktexls}.
34955
34956 The following code ignores a given file extension. So if a font
34957 is available in both formats, it will find the OpenType font even
34958 if ``.ttf'' was given as an extension.
34959
34960 @<Open an extended font file for input@>=
34961 { pack_file_name(cur_name, cur_area, empty_string,""); /* \TeX\ Live */
34962 path=kpse_find_file((char *)name_of_file+1, kpse_opentype_format, 0);
34963 if (path == NULL)
34964 path = kpse_find_file((char *)name_of_file+1, kpse_truetype_format, 0);
34965 }
34966
34967
34968 @ Since specifying, finding, and loading a font can be quite complex process,
34969 the primitive \.{\\tracingfonts} is almost a necessity.
34970 After reading the font specification, we use this code:
34971
34972 @<Trace the font specification@>=
34973 if (tracing_fonts>0)
34974 {@+
34975 begin_diagnostic();
34976 print_nl("Requested font \"");
34977 printn(cur_area);printn(cur_name);printn(cur_ext);
34978 print_char('"');
34979 if (s < 0) {@+
34980 print(" scaled ");
34981 print_int(-s);
34982 } else{@+
34983 print(" at ");
34984 print_scaled(s);
34985 print("pt");
34986 }
34987 end_diagnostic(false);
34988 }
34989
34990 @ After a font file was found, we trace it with this code:
34991
34992 @<Trace the new extended font@>=
34993 if (tracing_fonts>0)
34994 {@+begin_diagnostic();
34995 print_nl(" -> ");
34996 if (path!=NULL)
34997 { print(path);
34998 if (g==null_font) print_nl("Not loadable: font file not found");
34999 }
35000 else
35001 print("no matching file found.");
35002 if (g==null_font) print_nl("Font not found, using \"nullfont\"");
35003 end_diagnostic(false);
35004 }
35005 #if 0
35006 if (IS_X_FONT(g))
35007 { int x_scale, y_scale;
35008 unsigned int x_ppem,y_ppem;
35009 hb_codepoint_t glyph, cp;
35010 hb_glyph_extents_t e;
35011 hb_font_t *f;
35012 float x_ptem ;
35013 hb_position_t ax;
35014
35015 fprintf(stderr,"\n");
35016 fprintf(stderr,"%s at %fpt\n",path, font_size[g]/(double)ONE);
35017 f=x_font[g]->f;
35018 hb_font_get_scale(f,&x_scale,&y_scale);
35019 fprintf(stderr,"given scale %d/%d\n",x_scale,y_scale);
35020 hb_font_get_ppem(f,&x_ppem,&y_ppem);
35021 fprintf(stderr,"given ppem %d/%d\n",x_ppem,y_ppem);
35022 x_ptem=hb_font_get_ptem(f);
35023 fprintf(stderr,"given ptem %f\n",x_ptem);
35024 { hb_set_t *uset= hb_set_create ();
35025 hb_face_t *face=hb_font_get_face(f);
35026 hb_face_collect_unicodes (face,uset);
35027 fprintf(stderr,"Unicode range %d - %d\n",hb_set_get_min (uset),hb_set_get_max (uset));
35028 }
35029 cp='A'; @<debug font |f| and codepoint |cp|@>@;
35030 cp='g'; @<debug font |f| and codepoint |cp|@>@;
35031 cp='T'; @<debug font |f| and codepoint |cp|@>@;
35032
35033 fprintf(stderr,"\n");
35034 }
35035 #endif
35036
35037 @ For debugging hitex creates some more output. This part will be deleted after
35038 the code has stabilized.
35039
35040 @<debug font |f| and codepoint |cp|@>=
35041 { scaled h,d,w;
35042 hb_font_get_nominal_glyph (f,cp, &glyph);
35043 hb_font_get_glyph_extents (f,glyph,&e);
35044 fprintf(stderr,"char= %c/%d id=%d\n", cp,cp,glyph);
35045 fprintf(stderr,"\thb: height=y_bearing=%0.2fpt, depth= %0.2fpt, bbox height= %0.2fpt\n",
35046 HB_TO_PT(e.y_bearing),HB_TO_PT(-(e.height+e.y_bearing)),HB_TO_PT(e.height)
35047 );
35048 h=x_char_height(g,cp);
35049 d=x_char_depth(g,cp);
35050 fprintf(stderr,"\tft: height=0x%x (%0.2fpt), depth=0x%x (%0.2fpt)\n",
35051 h,h/(double)ONE,d,d/(double)ONE
35052 );
35053 ax=hb_font_get_glyph_h_advance (f, glyph);
35054 fprintf(stderr,"\thb: width=0x%x (%0.2fpt)\n", ax, HB_TO_PT(ax));
35055 w=x_char_width (g, cp);
35056 fprintf(stderr,"\tft: width=0x%x (%0.2fpt)\n", w, w/(double)ONE);
35057 ax=e.width;
35058 fprintf(stderr,"\thb: bbox width=0x%x (%0.2fpt)\n", ax, HB_TO_PT(ax));
35059 ax=e.x_bearing;
35060 fprintf(stderr,"\thb: bbox x_bearing=0x%x (%0.2fpt)\n", ax, HB_TO_PT(ax));
35061 ax=hb_font_get_glyph_h_advance (f, glyph);
35062 ax= e.x_bearing+e.width-ax;
35063 if (ax<0) ax=0;
35064 fprintf(stderr,"\thb: italics=0x%x (%0.2fpt)\n", ax, HB_TO_PT(ax));
35065 ax=x_char_italic(g,cp);
35066 fprintf(stderr,"\tft: italics=0x%x (%0.2fpt)\n",
35067 ax, ax/(double)ONE);
35068 }
35069
35070
35071
35072
35073
35074 @* Font subsets.
35075 Very often only a small subset of the glyphs in a font are used in the
35076 document at hand. For example, this program is part of the \HINT\
35077 project, and if the project name is typeset using a special font, only
35078 4 glyphs are actually used. In such cases, it is a waste of memory to
35079 embed the entire font in the \HINT\ document. Instead it is desirable to
35080 construct from a font a subset font, that contains only a subset of
35081 all glyphs in the font. This can be done easily using the Harfbuzz
35082 library.
35083
35084 Embedding only subsets is the default for Hi\TeX. This can be changed
35085 by using the option \.{-no-subset} on the command line setting the
35086 |option_subset| variable to |false|.
35087
35088
35089 @<Initialize font |g| for subsetting@>=
35090 if (option_subset)
35091 { x_font[g]->sub=hb_subset_input_create_or_fail ();
35092 if (x_font[g]->sub!=NULL)
35093 { x_font[g]->subset = hb_subset_input_unicode_set (x_font[g]->sub);
35094 hb_subset_input_set_flags ( x_font[g]->sub, HB_SUBSET_FLAGS_NO_HINTING);
35095 }
35096 else
35097 x_font[g]->subset=NULL;
35098 if (x_font[g]->subset!=NULL)
35099 hb_set_clear(x_font[g]->subset);
35100 }
35101 else x_font[g]->subset=NULL;
35102
35103
35104 @ Whenever a character node |p| is written to the output, either in the
35105 content section or in the definition section, \HiTeX registers the
35106 character in the font subset.
35107
35108
35109 @<Register character node |p| in the font subset@>=
35110 if (x_font[font(p)]!=NULL && x_font[font(p)]->subset!=NULL)
35111 hb_set_add (x_font[font(p)]->subset, character(p));
35112
35113
35114 @ After content and definition section are written to the output
35115 and before the directory section can be written,
35116 the font subsets are computed and the directory is updated appropriately.
35117
35118 @<Compute subset fonts if requested@>=
35119 { int i;
35120 for (i=0;i<=font_ptr;i++)
35121 if (IS_X_FONT(i) && x_font[i]->f!=NULL )
35122 { hb_blob_t *blob=NULL;
35123 const char *buf=NULL;
35124 unsigned int size;
35125 bool is_subset=false;
35126
35127 if (x_font[i]->sub!=NULL)
35128 { hb_face_t *fin, *fout=NULL;
35129 fin= hb_font_get_face(x_font[i]->f);
35130 if (fin!=NULL)
35131 fout= hb_subset_or_fail (fin, x_font[i]->sub);
35132 if (fout==NULL)
35133 { print_err("Unable to compute subset for font "); printn_esc(font_id_text(i));print_ln();
35134 error();
35135 }
35136 else
35137 { blob = hb_face_reference_blob (fout);
35138 }
35139 hb_subset_input_destroy(x_font[i]->sub);
35140 x_font[i]->sub=NULL;
35141 x_font[i]->subset=NULL;
35142 }
35143 if (blob!=NULL)
35144 is_subset=true;
35145 else
35146 blob = x_font[i]->blob;
35147 if (blob!=NULL)
35148 buf = hb_blob_get_data (blob, &size);
35149 if (buf!=NULL && size>0 )
35150 { int g;
35151 g=hmap_font[i];
35152 if (g>=0 && hfonts[g]!=NULL && hfonts[g]->y>2)
35153 { int y= hfonts[g]->y;
35154 dir[y].size=size;
35155 dir[y].buffer=(uint8_t*)buf;
35156 if (is_subset)
35157 { DBG(DBGFONT,"Creating subset for font %s (size %d)",dir[y].file_name,size);
35158 @<mark the file name by appending ``.subset''@>@;
35159 }
35160 }
35161 }
35162 }
35163 }
35164
35165
35166 @ Because programs like {\tt stretch} that unpack binary \HINT\ files can copy auxiliar files to disk,
35167 it is important not to confuse a possibly very small subset of a font file with the original font file.
35168 Therefore the string ``.subset'' is appended to the file name just before the file extension.
35169 Whe \HiTeX\ makes a subset from a subset, the marking is not duplicated.
35170
35171 @<mark the file name by appending ``.subset''@>=
35172 { char *n =dir[y].file_name;
35173 int i, k;
35174 i=k=strlen(n);
35175 while (k>0)
35176 { k--;
35177 if (n[k]=='.') break;
35178 }
35179 if (k<7 || strncmp(".subset",n+k-7,7)!=0)
35180 { ALLOCATE(dir[y].file_name,i+7+1,char); /*|file_name|,|".subset"|,zero byte*/
35181 strncpy(dir[y].file_name,n,k);
35182 strncpy(dir[y].file_name+k,".subset",8);
35183 strncpy(dir[y].file_name+k+7,n+k,i-k);
35184 free(n);
35185 }
35186 }
35187
35188
35189 @* Harfbuzz.
35190 Harfbuzz is a library that can determine the correct positions of characters in a word
35191 or line of text. This is called ``layout'' and
35192 Hi\TeX\ is using harfbuzz to do just that for OpenType fonts or TrueType fonts.
35193 The function prototypes used are found in these header files. We use
35194 |#include "..."| instead of |<...>| because we need to prefer the
35195 HarfBuzz that is included in \TeX\ Live when doing a ``native'' build there.
35196
35197 @<Header files and function declarations@>=
35198 #include "hb.h"
35199 #include "hb-ot.h"
35200 #include "hb-subset.h"
35201
35202 @ When we define an extended font, we allocate an |x_font_info| record
35203 for the necessary data and store a pointer to it in the |x_font| array
35204 indexed by the font number. This array can then be used to decide
35205 whether a font is an extended font or a traditional \TeX\ font.
35206
35207 The \.{\\dump} primitive will not store the contents of the
35208 |x_font_info| records in the format file. So extended fonts can not be
35209 preloaded using a format file but must be loaded by \TeX\ each time
35210 \TeX\ runs. This decision was made because keeping OpenType or FreeType
35211 fonts in a format file would make formats very big. And there is
35212 no benefit in loading a font from a format compared to loading a font
35213 directly from the font file. To enforce this rule, the \.{\\dump}
35214 primitive will issue an error message if it encounters an extended font.
35215
35216 @d IS_X_FONT(F) (x_font[F]!=NULL)
35217
35218
35219 @<Glob...@>=
35220 typedef struct {
35221 hb_blob_t *blob; /* can be shared for different faces */
35222 hb_subset_input_t *sub;
35223 hb_set_t *subset;
35224 hb_font_t *f;
35225 int i; /* index */
35226 } x_font_info;
35227 typedef x_font_info *x_font_ptr;
35228
35229 static x_font_ptr @!x_font0[font_max-font_base+1]={NULL},
35230 *const @!x_font = @!x_font0-font_base;
35231
35232 @ @<load an extended font@>=
35233 { hb_face_t *face;
35234 hb_font_t *f;
35235 ALLOCATE(x_font[g],1,x_font_info);
35236 @<Search for a font with the same |path| or load the |path|@>@;
35237 face = hb_face_create(x_font[g]->blob, f_index);
35238 if (face==NULL) fatal_error("Unable to open extended font face!");
35239 f = hb_font_create(face);
35240 if (f==NULL)
35241 fatal_error("Unable to open extended font!");
35242 x_font[g]->f=f;
35243 x_font[g]->i=f_index;
35244 @<determine the design size@>@;
35245 @<adjust the extended font for the given scale factor@>@;
35246 }
35247
35248 @ It is quite common to create several font faces from the same
35249 font file. For example using the font at different sizes.
35250 In the \HINT\ file, we do not want to include the file multiple times,
35251 so here is the place to look for an exiting font using the same
35252 file.
35253
35254 @<Search for a font with the same |path| or load the |path|@>=
35255 { int i;
35256 int l;
35257 x_font[g]->blob=NULL;
35258 x_font[g]->sub=NULL;
35259 x_font[g]->subset=NULL;
35260 l=strlen(path);
35261 for (i=1; i<=font_ptr; i++)
35262 if (i!=g && length(font_area[i])==l && str_eq_buf(font_area[i],(unsigned char *)path))
35263 { font_area[g]=font_area[i];
35264 if (x_font[i]!=NULL)
35265 { x_font[g]->blob=x_font[i]->blob;
35266 x_font[g]->subset=x_font[i]->subset;
35267 break;
35268 }
35269 }
35270 if (x_font[g]->blob==NULL)
35271 { x_font[g]->blob = hb_blob_create_from_file(path);
35272 if (x_font[g]->blob==NULL) fatal_error("Unable to open extended font file!");
35273 font_name[g]=nom;
35274 if (font_area[g]==0)
35275 font_area[g]=s_no(path);
35276 @<Initialize font |g| for subsetting@>@;
35277 }
35278 }
35279
35280 @ Most of the info in \TeX's font tables is not needed for extended fonts.
35281 Hi\TeX\ uses the |font_name| and |font_area|, as well as the |font_size|
35282 and the |font_dsize|.
35283
35284 @<Initialize the font tables for the extended font |f|@>=
35285 hyphen_char[f]='-';skew_char[f]=-1;
35286 bchar_label[f]=non_address;
35287 font_bchar[f]=non_char;font_false_bchar[f]=non_char;
35288 char_base[f]=extended_base;width_base[f]=0;
35289 height_base[f]=0;depth_base[f]=0;
35290 italic_base[f]=0;lig_kern_base[f]=0;
35291 kern_base[f]=0;exten_base[f]=0;
35292 font_glue[f]=null;
35293 font_params[f]=7;
35294 if ((font_ptr==font_max)||(fmem_ptr+font_params[f]+1 > font_mem_size))
35295 @<Apologize for not loading the font, |goto done|@>;
35296 @<get the extended fonts parameters@>;
35297
35298 @ We start with finding the first and the last character in the font:
35299 @<get the extended fonts parameters@>=
35300 { hb_set_t *uset= hb_set_create ();
35301 hb_face_t *face=hb_font_get_face(x_font[f]->f);
35302 hb_face_collect_unicodes (face,uset);
35303 font_bc[f]=hb_set_get_min (uset);
35304 font_ec[f]=hb_set_get_max (uset);
35305 hb_set_destroy(uset);
35306 }
35307
35308 @ Last, we look at the space character.
35309 @<get the extended fonts parameters@>=
35310 { space(f)=x_char_width(f,' ');
35311 space_stretch(f)=space(f)/2;
35312 space_shrink(f)=space(f)/3;
35313 extra_space(f)=space(f)/3;
35314 quad(f)=font_size[f];
35315 }
35316
35317
35318 @ Harfbuzz has no fixed units like point, meter, or millimeter to work with,
35319 and since the variables that hold a position or width are integer variables,
35320 it might be necessary for any unit to use fractions of it.
35321 For a given font, you can choose a unit and the relation of this unit to the
35322 integer value used to represent it.
35323 For example, we can use the unit pt and represent 1pt by the integer
35324 value 100. This would allow a precision of $1/100$pt because the smallest
35325 non zero difference between two integers is 1 and this represents $1/100$pt.
35326 When working with TeX, the natural choice for the unit is a printers point
35327 and its integer representation is a scaled point (sp)with one scaled point equal to
35328 $2^{-16}$ printer's points, or |0x10000|sp equal to 1pt.
35329 Unfortunately Harfbuzz will allow scale values only in the range
35330 $2^4$ to $2^{13}$ and typical values are in the range 1000 to $2^{11}$.
35331 So we use $2^{11}$ which means that we need to shift the values returned
35332 by harfbuzz by another 5 bits to obtain \TeX's scaled points.
35333
35334 @d HB_PT_BITS 11 /*Bits of Harfbuzz binary fraction*/
35335 @d HB_ONE_PT (1<<HB_PT_BITS) /*1pt in Harfbuzz*/
35336 @d HB_EPS (1<<(16-HB_PT_BITS-1)) /*$\epsilon$ is $1/2$ of smallest Harfbuzz value*/
35337 @d HB_TO_SCALED(A) ((A)<<(16-HB_PT_BITS)) /*Convert Harfbuzz to scaled point*/
35338 @d HB_FROM_SCALED(A) (((A)+HB_EPS)>>(16-HB_PT_BITS)) /*Convert scaled to Harfbuzz*/
35339 @d HB_TO_PT(A) (HB_TO_SCALED(A)/(double)ONE)
35340
35341 @<adjust the extended font for the given scale factor@>=
35342 if (s<0)
35343 { if (s==-1000) s=font_dsize[g];
35344 else s= xn_over_d(font_dsize[g],-s, 1000);
35345 }
35346 font_size[g]=s;
35347 hb_font_set_scale(f,HB_FROM_SCALED(s), HB_FROM_SCALED(s));
35348 hb_font_set_ptem(f,(72.0/72.27)*s/(double)ONE);
35349
35350
35351 @ The function |hb_ot_layout_get_size_params| can be used to obtain the
35352 design size of the font face in units of $1/10$ of a point with 72 points per inch.
35353
35354 @<determine the design size@>=
35355 { unsigned int designSize, minSize, maxSize, subFamilyID, nameCode;
35356 scaled f_dsize;
35357 hb_ot_layout_get_size_params(face, &designSize, &subFamilyID,
35358 &nameCode, &minSize, &maxSize);
35359 if (designSize==0)
35360 f_dsize=10*ONE; /*use 10pt instead of zero*/
35361 else
35362 f_dsize=(((designSize/72.0)*72.27)/10.0)*ONE+0.5; /* round to a scaled value */
35363 font_dsize[g]=f_dsize;
35364 }
35365
35366
35367 @ To get glyph specific information, for example a characters width,
35368 we first need to obtain the glyph number that belongs to the character in
35369 the given font.
35370
35371 @<harfbuzz font metric functions@>=
35372
35373 static bool x_glyph(internal_font_number g, int c, hb_codepoint_t *glyph)
35374 {
35375 return hb_font_get_nominal_glyph (x_font[g]->f,c, glyph);
35376 }
35377
35378 static bool x_char_exists(internal_font_number g, int c)
35379 { if (font_bc[g]>c || c>font_ec[g])
35380 return false;
35381 else
35382 { hb_codepoint_t glyph;
35383 return x_glyph(g,c, &glyph);
35384 }
35385 }
35386
35387
35388 static scaled x_glyph_width(internal_font_number g, hb_codepoint_t glyph)
35389 { return HB_TO_SCALED(hb_font_get_glyph_h_advance (x_font[g]->f, glyph));
35390 }
35391
35392 static scaled x_char_width(internal_font_number g, int c)
35393 { hb_codepoint_t glyph;
35394 if (x_glyph(g,c,&glyph))
35395 return x_glyph_width(g, glyph);
35396 else
35397 return 0;
35398 }
35399
35400 @ Finding the height and depth of a character is
35401 slightly more complex. It requires retrieving its bounding box.
35402 Since most of the time we need the height and the depth
35403 together, we provide one function for both.
35404
35405
35406 @<harfbuzz font metric functions@>=
35407 static void x_glyph_height_depth(internal_font_number g, hb_codepoint_t glyph,
35408 scaled *h, scaled *d)
35409 { hb_glyph_extents_t e;
35410 hb_font_get_glyph_extents (x_font[g]->f,glyph,&e);
35411 *h=HB_TO_SCALED(e.y_bearing);
35412 *d=HB_TO_SCALED(-(e.height+e.y_bearing));
35413 }
35414
35415
35416 static void x_char_height_depth(internal_font_number g, int c,
35417 scaled *h, scaled *d)
35418 { hb_codepoint_t glyph;
35419 if (x_glyph(g,c,&glyph))
35420 x_glyph_height_depth(g,glyph,h,d);
35421 else
35422 *h=*d=0;
35423 }
35424
35425
35426 static scaled x_char_height(internal_font_number g, int c)
35427 { hb_glyph_extents_t e;
35428 hb_codepoint_t glyph;
35429 if (x_glyph(g,c,&glyph))
35430 { hb_font_get_glyph_extents (x_font[g]->f,glyph,&e);
35431 return HB_TO_SCALED(e.y_bearing);
35432 }
35433 else
35434 return 0;
35435 }
35436
35437 static scaled x_char_depth(internal_font_number g, int c)
35438 { hb_glyph_extents_t e;
35439 hb_codepoint_t glyph;
35440 if (x_glyph(g,c,&glyph))
35441 { hb_font_get_glyph_extents (x_font[g]->f,glyph,&e);
35442 return HB_TO_SCALED(-(e.height+e.y_bearing));
35443 }
35444 else
35445 return 0;
35446 }
35447
35448
35449
35450 static scaled x_glyph_italic(internal_font_number g, hb_codepoint_t glyph)
35451 { hb_position_t a,b;
35452 hb_glyph_extents_t e;
35453 hb_font_get_glyph_extents (x_font[g]->f,glyph,&e);
35454 b=hb_font_get_glyph_h_advance (x_font[g]->f, glyph);
35455 a= e.x_bearing+e.width-b;
35456 if (a<0) a=0;
35457 return HB_TO_SCALED(a);
35458 }
35459
35460 static scaled x_char_italic(internal_font_number g, int c)
35461 { hb_codepoint_t glyph;
35462 if (x_glyph(g,c,&glyph))
35463 { return x_glyph_italic(g,glyph);
35464 }
35465 else
35466 return 0;
35467 }
35468
35469
35470 @ Harfbuzz is used to insert kerns and liatures in the input stream.
35471
35472 We start easy without any extra processing. The following code
35473 is called if the main loop has just started.
35474 It has adjusted the space factor and called |fix_language| if necessary.
35475 |main_f| is initialized to |cur_font|. If then |main_f| happens to be
35476 an extended font, the following code comes to life.
35477
35478 @d tail_append_char(A) { pointer p; fast_get_avail(p); font(p)=main_f; character(p)=A; tail_append(p);}
35479
35480 @<Append characters from an extended font; |goto reswitch| when done@>=
35481 { hb_buffer_t *buf;
35482 unsigned int glyph_count;
35483 hb_glyph_info_t *glyph_info;
35484 hb_glyph_position_t *glyph_pos;
35485 int i,len;
35486 hb_codepoint_t cp[256];
35487 hb_feature_t features[4] =
35488 { {HB_TAG('l','i','g','a'), 0, HB_FEATURE_GLOBAL_START, HB_FEATURE_GLOBAL_END},
35489 {HB_TAG('c','l','i','g'), 0, HB_FEATURE_GLOBAL_START, HB_FEATURE_GLOBAL_END},
35490 {HB_TAG('d','l','i','g'), 0, HB_FEATURE_GLOBAL_START, HB_FEATURE_GLOBAL_END},
35491 {HB_TAG('c','a','l','t'), 0, HB_FEATURE_GLOBAL_START, HB_FEATURE_GLOBAL_END}
35492 };
35493 buf = hb_buffer_create();
35494 for (len=0;len<256;len++) {
35495 if (!x_char_exists(main_f,cur_chr))
35496 {@+char_warning(cur_font, cur_chr);goto big_switch;
35497 }
35498 cp[len]=cur_chr;
35499 get_next(); /*set only |cur_cmd| and |cur_chr|, for speed*/
35500 if (cur_cmd==letter || cur_cmd==other_char || cur_cmd==char_given)
35501 continue;
35502 x_token(); /*now expand and set |cur_cmd|, |cur_chr|, |cur_tok|*/
35503 if (cur_cmd==letter || cur_cmd==other_char || cur_cmd==char_given)
35504 continue;
35505 else if (cur_cmd==char_num)
35506 {@+scan_char_num();cur_chr=cur_val; continue; }
35507 else
35508 { len++; break;}
35509 }
35510 if (len==256)
35511 { print_err("Long word cut to 256 characters");
35512 error();
35513 }
35514 hb_buffer_add_codepoints(buf,cp,len,0,len);
35515 hb_buffer_set_direction(buf, HB_DIRECTION_LTR);
35516 hb_buffer_set_script(buf, HB_SCRIPT_LATIN);
35517 hb_buffer_set_language(buf, hb_language_from_string("en", -1));
35518 /* set shaper level probably 2 0r 1, set features */
35519
35520
35521 hb_shape(x_font[main_f]->f, buf, features, 4);
35522 glyph_info = hb_buffer_get_glyph_infos(buf, &glyph_count);
35523 glyph_pos = hb_buffer_get_glyph_positions(buf, &glyph_count);
35524
35525 for (i = 0; i < glyph_count; i++) {
35526 uint32_t cluster = glyph_info[i].cluster;
35527 hb_position_t x_advance = glyph_pos[i].x_advance;
35528 scaled w, a, delta;
35529 tail_append_char(cp[cluster]);
35530 w = x_char_width(main_f,cp[cluster]);
35531 a= HB_TO_SCALED(x_advance);
35532 delta= a-w;
35533 if (delta!=0)
35534 tail_append(new_kern(delta));
35535 }
35536 hb_buffer_destroy(buf);
35537
35538 goto reswitch;
35539 }
35540
35541 @* Index.
35542 Here is where you can find all uses of each identifier in the program,
35543 with underlined entries pointing to where the identifier was defined.
35544 If the identifier is only one letter long, however, you get to see only
35545 the underlined entries. {\sl All references are to section numbers instead of
35546 page numbers.}
35547
35548 This index also lists error messages and other aspects of the program
35549 that you might want to look up some day. For example, the entry
35550 for ``system dependencies'' lists all sections that should receive
35551 special attention from people who are installing \TeX\ in a new
35552 operating environment. A list of various things that can't happen appears
35553 under ``this can't happen''. Approximately 40 sections are listed under
35554 ``inner loop''; these account for about 60\pct! of \TeX's running time,
35555 exclusive of input and output.